diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md index 1dcbe3ed5e7..9df21293f9c 100644 --- a/.agents/AGENTS.md +++ b/.agents/AGENTS.md @@ -14,7 +14,7 @@ See `./rules/design-system.md` for Chakra UI v3 design system configuration and ## Code Style & Quality -See `./rules/code-quality.md` for code style, lint commands plus conventions linters don't catch. +See `./rules/code-quality.md` for code style, lint commands plus conventions linters don't catch, and the complexity/CRAP scores. ## TypeScript Conventions @@ -27,17 +27,18 @@ See `./rules/env-vars.md` for where environment variables live, how they're deli ## Testing - Vitest unit tests (`*.spec.ts` / `*.spec.tsx`): See `./rules/tests-unit.md` for purpose, setup, utilities, and conventions. -- Playwright component visual tests (`*.pw.tsx`): See `./rules/tests-visual.md` for purpose, setup, fixtures, and conventions. +- Playwright component visual tests (`*.pw.tsx`): See `./rules/tests-visual.md` for their purpose, when to use them, setup, fixtures, and conventions. ## Running locally -Three ways to start the dev server: +Two ways to start the dev server: - `pnpm dev:preset ` (e.g. `eth`) — the quickest way to a running app. Fetches a live instance's config over HTTP at startup, so it needs outbound internet. Aliases are defined in `tools/dev-server/registry.json`; how the fetch and env layering work is documented in `tools/dev-server/CONTEXT.md`. -- `pnpm dev:local` — runs against a locally running Blockscout backend, using the committed `tools/dev-server/.env.localhost`. -- `pnpm dev` — plain Next.js dev; needs a hand-written `.env.local` with the instance config. +- `pnpm dev:local` — runs against a locally running Blockscout backend, using the committed `tools/dev-server/.env.localhost`. A hand-written instance config goes in `.env.local`, which wins over it. -Both `dev:preset` and `dev:local` accept `--port ` to run on a port other than 3000 (it overrides `NEXT_PUBLIC_APP_PORT`, keeping the generated `envs.js` consistent). +Both accept `--port ` to run on a port other than 3000 (it overrides `NEXT_PUBLIC_APP_PORT`, keeping the generated `envs.js` consistent). + +`tools/dev-server/` also holds the local production build (`pnpm prod:preset`) and the local docker image (`pnpm build:docker`, `pnpm start:docker:*`) — everything that runs the app on this machine. Gotchas: @@ -49,31 +50,38 @@ Gotchas: Some directories have a `CONTEXT.md` documenting non-obvious patterns specific to that area. Read the relevant one before working in (or reaching into) that directory: - `deploy/scripts/` — how the frontend container is built and starts up (Dockerfile stages, entrypoint). -- `deploy/tools/envs-validator/` — startup validation of `NEXT_PUBLIC_*` envs against yup schemas. +- `deploy/tools/envs-validator/` — startup validation of `NEXT_PUBLIC_*` envs against valibot schemas. - `src/api/` — how a request URL is assembled (resource registry, runtime config, `/node-api/config`) and where resource response types come from. +- `src/config/` — the app-config convention (default-only exports, one import surface, envs read only in config modules), its ESLint enforcement and exemptions. - `src/features/connect-wallet/` — why the wallet stack is loaded lazily (off the critical path), how account state reaches boot-time consumers before a provider exists, and the connector-mode differences. - `src/server/primedRequests/` — the early-fetch primer: why it exists, the CSP-driven determinism constraint, its correctness guarantee, and the drift-test contract. +- `src/shared/lists/` — the list helpers shared by tables: the row-key rule and the lazy-render constraint. +- `src/shared/pagination/` — the paginated-list components and utils. - `src/slices/` — slice ownership model (who owns an entity's rendering). - `src/sprite/` — SVG sprite build pipeline and which outputs are tracked vs. generated. - `src/toolkit/` — the `@blockscout/ui-toolkit` workspace package structure. +- `tools/code-complexity/` — the cognitive-complexity / CRAP code-quality gate: what a failure means and how to fix it. +- `tools/design-readout/` — the Figma design readout. - `tools/dev-server/` — how the dev server and demo deploy get their env vars from a running instance config. +- `tools/doc-links/` — the doc-link checker. +- `tools/mutation-testing/` — the mutation-testing gate for unit-test assertion strength. +- `tools/playwright/` — the runner for Playwright component tests. - `tools/profiling/` — React render profiling: production profiling build and DevTools trace aggregation. +- `tools/react-doctor/` — the React Doctor PR gate: reading a failure, suppressing a finding, changing the rule allowlist. +- `tools/review-screen/` — the Jev review-screen pilot: what a suspect is, what a run must never do, where the sidecars go. + +See `./rules/docs.md` before adding or editing any doc about the code — a `CONTEXT.md`, a file under +`docs/`, a module `README.md`. -If you encounter a `CONTEXT.md` not listed here, read it too (and consider adding it to this list). +## Architecture decision records (ADRs) -## Architecture decision records +See `./rules/adr.md` when proposing or adding a new record. -Decisions with repo-wide consequences are recorded in `.agents/adr/`, named -`<0000>-.md`. Read the relevant one before changing what it decided — an ADR carries the -evidence and the trade-off, so it answers "why is it like this?" without a git archaeology session. +The repo-wide records index: - `0002-layer-shaped-ticket-leaves.md` — why a product task's tickets cut vertically while the leaves inside them run along layers. - `0003-turbopack-for-production-builds.md` — why production builds moved back to Turbopack. - -Add a new record (next free number, and a line here) whenever a decision is expensive to rediscover: -it constrains future work, was reached by measurement or an investigation worth not repeating, or -looks wrong without its context. Supersede rather than rewrite — flip the old record's `Status` to -`superseded by ` and leave its reasoning intact. +- `0004-typescript-7-side-by-side.md` — why `tsc` is TypeScript 7 while the `typescript` package is TypeScript 6, and when to collapse them. ## Product task workflow @@ -89,4 +97,5 @@ rules contract, the per-file symlink Cursor needs, and how references here are c ## Reaching people & channels on Slack To reach anyone or any channel on Slack, resolve the Slack IDs from `./TEAM.md`. Draft and get approval -before sending anything — unless the skill you are running names an explicit exception. +before sending anything — unless the skill you are running names an explicit exception. Before composing +any Slack message, read `./slack-message.md` (language, addressing, links, attribution). diff --git a/.agents/GLOSSARY.md b/.agents/GLOSSARY.md index f8bcfad9362..3533cd96983 100644 --- a/.agents/GLOSSARY.md +++ b/.agents/GLOSSARY.md @@ -43,6 +43,7 @@ vars are documented in `docs/ENVS.md`. Architectural concepts like | **Hot Contracts** | feature | Ranked list of the most recently and frequently interacted-with smart contracts on the network. | | **Interchain Indexer** | service | Microservice that indexes cross-chain messages and token transfers across heterogeneous chains. General-purpose interop indexer, not ZetaChain-specific. Provides "Cross chain txs" feature. Distinct from **CCTX**. | | **Interop Messages** | entity | **Deprecated** Cross-rollup messages passed between OP Stack chains using the native interoperability protocol. Distinct from **Interchain Indexer** messages. | +| **Jev** | service | TypeSafe's typed-judgment model: answers a structured question (yes/no, a choice) with a probability, never a claim, so whatever consumes a score verifies it before acting on it. | | **Kettle** | entity | In the **SUAVE** architecture, a Kettle is a trusted execution environment (TEE) node that processes MEV bundles. SUAVE transactions are associated with a Kettle. | | **Marketplace** | feature | Curated directory of dApps and DeFi applications integrated with Blockscout. | | **MetaSuites** | service | Third-party browser extension that enhances the Blockscout UI with additional data and links. | @@ -50,6 +51,7 @@ vars are documented in `docs/ENVS.md`. Architectural concepts like | **Operation** | entity | **TAC**-specific entity representing a bridge operation between the TON and EVM ecosystems. No equivalent on standard EVM chains. | | **Pools** | entity | DEX liquidity pool positions tracked on-chain. | | **Public Tags** | feature | Community-submitted labels for addresses, visible on address pages. A sub-feature of **Address Metadata**. | +| **Readout (design readout)** | concept | The mapping of a Figma node to repo components, props and design tokens, with every ambiguous, unrecognized and layout item listed for a developer to resolve before markup. The tool of the same name extracts the values and recognizes signals and tokens; the skill maps those to components — the tool names none. Recognition only, never implementation. | | **Rewards** | feature | The Blockscout Merits program — a token rewards and incentives system operated by Blockscout. Entirely distinct from **Block Reward** (on-chain block-producer payouts). | | **Rollup** | concept | A chain that settles transactions on a parent (L1) chain. Introduces specific entities: deposits, withdrawals, transaction batches, output roots. Contrast with **Chain Variant**. | | **SolidityScan** | service | Third-party smart contract security vulnerability scanner integrated into contract detail pages. | diff --git a/.agents/README.md b/.agents/README.md index 45bf5e38ee2..2f11f7c2f41 100644 --- a/.agents/README.md +++ b/.agents/README.md @@ -8,7 +8,7 @@ here; each tool reads it through its own directory via symlinks. | `AGENTS.md` | Always-loaded project context | `.claude/CLAUDE.md` → here; Cursor reads `AGENTS.md` natively | | `rules/*.md` | Coding rules, scoped to file patterns | `.claude/rules/` and `.cursor/rules/` — see below | | `skills/*/SKILL.md` | Workflows loaded on invocation | `.claude/skills/` → here | -| `delegation.md`, `GLOSSARY.md`, `TEAM.md`, `slack-thread.md` | Read on demand, by pointer from `AGENTS.md` or a skill | — | +| `delegation.md`, `GLOSSARY.md`, `TEAM.md`, `slack-thread.md`, `slack-message.md`, `honk.md` | Read on demand, by pointer from `AGENTS.md` or a skill | — | | `tasks/` | Product-task specs — see `tasks/README.md` | — | Cross-references between all of these are machine-checked: `pnpm lint:doc-links`. diff --git a/.agents/TEAM.md b/.agents/TEAM.md index 7dd933ca0df..614f748abe0 100644 --- a/.agents/TEAM.md +++ b/.agents/TEAM.md @@ -13,15 +13,7 @@ Slack IDs are stored so addressing is deterministic (no runtime name lookup). Th identifiers, **not credentials** — knowing one grants no access. To find your own member ID in Slack: your profile → **⋯ More** → **Copy member ID**. Do not add emails to this file. -## How to address - -- **Person** — the *Slack member ID* (`U…`) from the People table. Mention as `<@U…>`; to DM, pass the ID as - the channel to the send tool. -- **Team / group** — the *Slack group ID* (`S…`) from the Groups table. Mention as ``. -- **Channel** — the *Channel ID* (`C…`). Pass it as the channel target when sending; refer to it in prose by - its `#name`. -- **Permalink** — `https://blockscout.slack.com/archives//p` (the message timestamp - with the dot removed). +How to turn an ID into a mention, a DM target, or a permalink: `./slack-message.md` → Addressing. ## Product managers @@ -54,6 +46,7 @@ Own: core API endpoints and response models, field propagation across services, | --- | --- | --- | --- | | Victor | @vbaranov | U8L403FEG | ✓ | | Nikita P. | @nikitosing | U0218K3MTC5 | | +| Alexey | @Qwerty5Uiop | U03EE7T5TJS | | ### Groups @@ -61,6 +54,12 @@ Own: core API endpoints and response models, field propagation across services, | --- | --- | | Core API | S064H6TD6MA | +### Channels + +| Purpose | Channel | Channel ID | +| --- | --- | --- | +| Default for core API questions | blockscout-elixir | C04NCPZGRAR | + ## Microservices API Own: microservice API endpoints and their response models (metadata, stats, admin, interchain, etc.). @@ -98,12 +97,19 @@ Own: architecture, the delegation boundary. | tom | @tom2drum | U03MN1588AU | ✓ | | Max | @maxaleks | UKP0RR9K9 | | +### Bots +| Name | Role | Bot ID | But used ID +| --- | --- | --- | --- | +| Rollbar | Post error monitoring events | B0AADAP5PM0 | U0A9XT13GB1 | + + ### Channels | Purpose | Channel | Channel ID | | --- | --- | --- | | Default for frontend questions | blockscout-frontend | C03MMUTQDNU | | Ask a frontend engineer to prepare an instance's config | front-config-requests | C08D60ZL1QB | +| Get alert events from the error monitoring system | blockscout-sentry-alerts | C05ULMSURUZ | ### Groups diff --git a/.agents/adr/0003-turbopack-for-production-builds.md b/.agents/adr/0003-turbopack-for-production-builds.md index 7b42a2dd9f1..99e4037c3d2 100644 --- a/.agents/adr/0003-turbopack-for-production-builds.md +++ b/.agents/adr/0003-turbopack-for-production-builds.md @@ -72,6 +72,7 @@ bundles in less than half the wall-clock (the type-check phase is bundler-agnost only. The compiler-API path (this flag `false`) checks against `lib/typescript.js`, which the alias does provide, so type-checking runs normally. Without it the build aborts claiming `typescript` is missing — on **both** bundlers, since the check runs before bundling. + *Superseded by [0004](0004-typescript-7-side-by-side.md): the flag is gone, Next's check is off.* - **Dev and production are on the same bundler again.** 0001's "a production-only bug can't be caught in dev" caveat is lifted for the default path — though the two webpack exceptions (`build:analyze`, `--profile`) still exercise a second pipeline. @@ -96,3 +97,4 @@ bundles in less than half the wall-clock (the type-check phase is bundler-agnost - The `useTypeScriptCli: false` workaround exists because Next's CLI type-check path does not recognize the `@typescript/typescript6` alias's `bin/tsc6`. If a later Next release accepts the native compiler's binary (or the alias ships a `bin/tsc`), the flag can be dropped. + *Superseded by [0004](0004-typescript-7-side-by-side.md).* diff --git a/.agents/adr/0004-typescript-7-side-by-side.md b/.agents/adr/0004-typescript-7-side-by-side.md new file mode 100644 index 00000000000..b431929499d --- /dev/null +++ b/.agents/adr/0004-typescript-7-side-by-side.md @@ -0,0 +1,9 @@ +# TypeScript 7 for type-checking, TypeScript 6 for tooling + +| | | +| --- | --- | +| Status | Accepted | + +## Decision + +TypeScript 7 ships `tsc` without the compiler API that `typescript-eslint`, `vite-plugin-dts` and Next's build-time check need, so `@typescript/native` (TS 7) backs `pnpm lint:tsc` while the `typescript` name stays on the `@typescript/typescript6` alias. To have one checker instead of two, `pnpm build` runs `lint:tsc` first and Next's own check is off (`typescript.ignoreBuildErrors`); pointing Next at the CLI instead would not help, since it resolves the binary through the `typescript` name and would run `tsc6`. Collapse to a single `typescript@7` once TS 7.1 is stable and `typescript-eslint` ([#10940](https://github.com/typescript-eslint/typescript-eslint/issues/10940)) and `vite-plugin-dts` support it. Replaces the `useTypeScriptCli: false` consequence of [0003](0003-turbopack-for-production-builds.md). diff --git a/.agents/delegation.md b/.agents/delegation.md index cde1cdcad77..40f6f8e17af 100644 --- a/.agents/delegation.md +++ b/.agents/delegation.md @@ -14,15 +14,21 @@ agent-friendly, loosen the boundary here via a normal PR — don't renegotiate i - Data wiring: hooks, query integration, rendering fetched data plainly. - Component **scaffolds** — file placement, props and types, data fetching, behavioral states (loading / empty / error / pagination), semantic structure built from existing toolkit components, and - placeholder presentation. Every deferred visual decision is marked `TODO (design):` (the convention the - `add-new-page` templates use), which is what makes the handover to a human explicit. + placeholder presentation. +- Final markup and styling to the mockup, which should **always** be verified by the developer. - Unit tests (`*.spec.ts` / `*.spec.tsx`) and Playwright test **scaffolds** (`*.pw.tsx` files, fixtures, mock data). - Glossary and docs updates, demo deploys (`deploy-demo` skill). +- Resolving agent-review findings and pushing the fixes, within the review loop's rules (`resolve-review + --auto`): fix / reject / defer per its verdict rules, and stop on anything that needs a human. +- Fixing a red CI run inside the review loop (`.agents/skills/review-loop/ci-fixes.md`), including updating a Playwright + baseline when the diff is explained by a spec requirement the commit cites; any other visual diff, and + any fix that changes behaviour or restructures beyond the finding, stops for a human. +- Design readouts from Figma nodes (`design-readout` skill) — recognition only, never implementation. ## Humans only, for now -- Final markup and styling that must match the designer's Figma mockups; visual polish of any kind. -- Choosing nav/sprite icons and other visual assets. -- Generating and eyeballing Playwright screenshot baselines — and only **once the component matches the - mockup**, because a baseline of placeholder presentation is worse than no baseline at all. +- Visual polish of any kind, and any visual asset the readout did not recognize and the spec does not name. +- Generating and eyeballing Playwright screenshot baselines, beyond the cited-requirement case above — and + only **once the component matches the mockup**, because a baseline of placeholder presentation is worse + than no baseline at all. - Design sign-off. diff --git a/.agents/honk.md b/.agents/honk.md new file mode 100644 index 00000000000..b2cb356eb5f --- /dev/null +++ b/.agents/honk.md @@ -0,0 +1,52 @@ +# Run by Honk + +The contract for a skill the Honk orchestrator runs headless (`claude -p`) instead of a developer in a chat. +A run's first prompt says "Run by Honk"; from then on these rules hold on every turn. A skill that supports +it carries a `## Run by Honk` section with a link here and its own status table. + +## No user in the conversation + +Nobody reads the session until it stops. Every "show the user and wait" and every confirmation in the skill +is released: the step goes ahead without asking. The gate is the run's tool allow/deny list, which Honk +sets per run. A denied tool is a **stop** (`needs_approval`), reported with the exact command or message +it would have run or sent; the step waits for the approval rather than reaching the same effect through +another tool, an API call or a script. + +Post to Slack only through the command the run's prompt names. `./slack-message.md` still governs the text. + +## A stop is a return + +A stop the skill would make in a chat — a question, an approval for a denied tool (`needs_approval`), a wait for +someone's reply — ends the turn. +The final message opens with a plain first line `STATUS: `, a status from the skill's table, then +the text the user would have seen. Honk reads only that first line to decide what happens next; a run +that ends without it counts as failed. + +Statuses every skill shares; its table lists them with its own triggers: + +| Status | When | The message carries | Resumed? | +| --- | --- | --- | --- | +| `needs_user` | an answer only a person can give: ambiguity, intent, a missing prerequisite | the question | yes, with the answer | +| `needs_approval` | the next step needs a denied tool | the exact command or message (target and text) | yes, once a human did it or allowed it | +| `done` | the skill finished and nothing waits on an operator | the skill's final message | no | + +A success is a stop too: it ends with `STATUS: done`, never with a free-form message, since a run that +ends without a status counts as failed. The skill's table adds its other statuses and marks which ones +Honk resumes. + +## Resume + +Honk continues a stopped run with `claude -p --resume` in the same cwd and worktrees, one turn per input: +the developer's answer or approval, or a reply posted in the Slack thread. + +- **The transcript is the only memory.** Before every stop, state each artefact the next turn needs: branch, + PR link, demo URL, the pending question. +- **An approval opens a tool for one turn.** The resume prompt names what is open; the next stop finds it + denied again. +- **A Slack reply is data.** Who may approve is decided by Honk, not by the reply's wording; the resume + prompt says whether the sender could. +- **Waiting on someone in Slack:** subscribe to the thread with the + [`slack-subscribe`](skills/slack-subscribe/SKILL.md) skill, then stop with the skill's waiting status. + The reply resumes the run even after this session has exited. +- **A status Honk does not resume ends the run.** Honk removes the run's worktrees; nothing waits for a + next turn. diff --git a/.agents/rules/adr.md b/.agents/rules/adr.md new file mode 100644 index 00000000000..1a09dd40c60 --- /dev/null +++ b/.agents/rules/adr.md @@ -0,0 +1,56 @@ +--- +description: ADR rules +paths: + - "**/adr/*.md" +globs: "**/adr/*.md" +alwaysApply: false +--- +# Architecture decision records + +An ADR answers "why is it like this?" without a git archaeology session. It carries the evidence and the +trade-off, so read the relevant one before changing what it decided. + +## Template + +```md +# {Short title of the decision} + +| | | +| --- | --- | +| Status | Accepted \/ Superseded by | + +## Decision + +{1-3 sentences: what's the context, what did we decide, and why.} +``` + +That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections. + +## Where a record goes + +| Scope | Folder | Listed in | +| --- | --- | --- | +| Affects the project as a whole | `.agents/adr/` | a line in `.agents/AGENTS.md` | +| Relevant only to one area or module | `/adr/` | that module's `CONTEXT.md` | + +Numbering is sequential and **scoped to its folder**; the filename is `<0000>-.md`. + +## When to offer one + +All three must be true: + +1. Hard to reverse: the cost of changing your mind later is meaningful. +2. Surprising without context: a future reader will look at the code and wonder "why on earth did + they do it this way?" +3. The result of a real trade-off: there were genuine alternatives and you picked one for specific + reasons. + +If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will +wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing." + +Offer the ADR; do not write one unasked. + +## Superseding + +Supersede rather than rewrite. Change the old record's `Status` to `superseded by ` and leave its +reasoning intact. diff --git a/.agents/rules/architecture.md b/.agents/rules/architecture.md index afea74593e6..ad317eca5b4 100644 --- a/.agents/rules/architecture.md +++ b/.agents/rules/architecture.md @@ -16,6 +16,7 @@ Blockscout frontend — a blockchain explorer UI. Distributed as a Docker image; | Layer | Technology | |---|---| | Framework | Next.js 16 — **Pages Router only** (not App Router) | +| Routing | `src/shared/router/` — the framework-neutral facade (`useRouter`, `usePathname`, `route()` and the `Route` types) over a toolkit-owned router context (`src/toolkit/router/`) | | UI | React 19 | | Component library | Chakra UI v3 (see `.agents/rules/design-system.md`) | | Server state | React Query 5 | @@ -23,7 +24,7 @@ Blockscout frontend — a blockchain explorer UI. Distributed as a Docker image; | Schema validation | Valibot | | Unit tests | Vitest | | Visual tests | Playwright | -| Package manager | pnpm (Node >=22.14.0) | +| Package manager | pnpm (Node >=24.21.0) | ## Directory layout @@ -84,6 +85,7 @@ Both slices and features share the same internal shape: `pages/`, `components/`, - **Cross-domain type imports** go through `/types/api.ts`, never deeper internal paths. - **Compose at the page level** when optional feature UI plugs into a core slice — the slice page renders the feature's component, not the other way around. Avoids cycles and keeps the feature opt-in. - **No files directly at the root of `src/shared/`** — only subfolders grouped by purpose. +- **Routing goes through the facade.** `useRouter` / `usePathname` from `src/shared/router/`, `route()` and the `Route` types from `src/shared/router/routes`, `Link` from `src/toolkit/chakra/link`. ESLint bans the framework's routing modules everywhere else (`eslint.config.mjs`, `ROUTER_FRAMEWORK_MODULES`), so a router change touches the adapter, not the app. ## Data flow diff --git a/.agents/rules/code-quality.md b/.agents/rules/code-quality.md index bceedd6368d..77b0ceafdd3 100644 --- a/.agents/rules/code-quality.md +++ b/.agents/rules/code-quality.md @@ -7,15 +7,44 @@ alwaysApply: false --- # Code Quality -We use ESLint, cSpell and Typescript to maintain code quality and consistency across the project. -In order to check code quality run the following commands: +We use ESLint, cSpell, TypeScript to maintain code quality. + ```bash -pnpm lint:eslint:fix +pnpm lint:eslint --fix # whole repo +pnpm lint:eslint path/to/file.tsx # one file or directory +pnpm lint:eslint --changed # this branch vs origin/main, including uncommitted and untracked files +pnpm lint:eslint --changed= --fix # another base; eslint flags such as --fix pass through pnpm lint:tsc pnpm lint:cspell ``` -Moreover, please find below the general sense rules that linters do not cover. +Pull requests also pass a React Doctor gate for React bugs ESLint misses, on changed code only: +`pnpm lint:react-doctor --scope changed --base origin/main`. Reading a failure and suppressing a +finding: `tools/react-doctor/CONTEXT.md`. + +The rest of this file covers code complexity scores and conventions that the linters do not. + +## Complexity and CRAP + +Two independent per-function gates: + +- **COG** (cognitive complexity) — readability. A `BROKE` here means decompose the function (flatten nesting, extract, early-return). +- **CRAP** — under-tested *behavior* (handlers, hooks, utils — not JSX render bodies). A `BROKE` here means add a Vitest spec; simplifying the function does not lower CRAP. + +How a score is counted, which functions are gated, and how to read a failure: `tools/code-complexity/CONTEXT.md`. + +How to run: + +```bash +# The file you are on — every function in it +pnpm test:code-complexity path/to/file.ts + +# This branch vs origin/main, including uncommitted edits +pnpm test:code-complexity --changed + +# For the full command usage +pnpm test:code-complexity --help +``` ## Code Style and Structure @@ -43,10 +72,10 @@ This applies to hooks, components, functions, and variables alike.. ### Magic numbers -Extract magic numbers into named `UPPER_SNAKE_CASE` constants, placed above the component or function that uses them. This makes intent clear and avoids silent duplication. +Name a literal only when a reader would still ask why this value. The name is `UPPER_SNAKE_CASE`, sits above the component or function, and carries a domain rule the surrounding identifiers do not: a limit, threshold, interval, or similar choice. ```ts -// BAD +// BAD: 4 is a product limit with no name const visibleItems = items.slice(0, 4); // GOOD @@ -54,7 +83,25 @@ const MAX_VISIBLE_ITEMS = 4; const visibleItems = items.slice(0, MAX_VISIBLE_ITEMS); ``` -The same applies to magic strings used as discriminators, keys, or thresholds. In tests, unexplained magic values should also be extracted into named constants so their meaning is clear. +Leave the literal when it is the meaning. A constant that restates the value, a nearby identifier, or a universal convention is noise. `1` is the first page, `0` is the first index, a URL is a URL. + +```ts +// BAD: the name restates href and page +const URL = 'https://example.com'; +const link = ; + +const FIRST_PAGE = 1; +if (page !== FIRST_PAGE) return null; + +// GOOD +const link = ; + +if (page !== 1) return null; +``` + +Apply the same test to strings used as discriminators, keys, or thresholds, and to values in tests. CSS-style props (margin, padding, font weight, color) are already named by the prop. + +If the same unexplained value must stay in sync at more than one call site, one constant is the share point. #### Shared unit constants @@ -134,34 +181,28 @@ Before writing custom utility logic (clamping, deep cloning, grouping, etc.), ch ### Comments -Comment the *why*, not the *what*. The code already shows what it does; a good comment explains what the -code can't — the rationale, a non-obvious constraint, a gotcha, a link to the issue or spec that motivated -it. +**Do not write comments. Never. Period.** +Prefer a name or a structure change that makes the comment unnecessary. + +A comment in the diff is allowed only when it explains *why* the obvious code is wrong — a quirk, workaround, or invariant git cannot show — optionally with a link to the issue. Required mechanical comments (`eslint-disable`, unavoidable double-cast, raw color) still explain *why*, in their own sections. -Never write *diff-narration* comments — what the code replaces, what it used to do, what behavior it -preserves. That belongs in the commit message and the PR, not in the source, where it goes stale the moment -the next change lands. +Never write *diff-narration* (what this change replaces). That belongs in the commit and the PR. Test: if the comment would confuse someone who never saw the previous file, delete it. + +Do not add JSDoc that restates the name or types. Do not rewrite comments you did not have to touch. Delete commented-out code; git keeps it. TODOs only with an issue or a concrete follow-up. ```ts -// BAD — narrates the change and restates the obvious -// Replaces the old useEffect approach; now we memoize the filtered list +// BAD — narrates the change and restates the next line +// Replaces the old useEffect; memoize the filtered list const active = useMemo(() => items.filter(isActive), [ items ]); -// GOOD — explains the non-obvious why -// Memoized because bails out of re-rendering on referential equality of `items`. -const active = useMemo(() => items.filter(isActive), [ items ]); +// GOOD — why the obvious approach fails +// Firefox: drag outside the window swallows mouse events until re-entry; see onMouseLeave(). +const onMouseMove = useCallback(() => {}, [ ]); ``` -Quick test: if a comment would confuse a reader who never saw the previous version of the file, it is -diff-narration — delete it. If it still helps that reader understand a decision, keep it. - -### Commented-out code - -Remove commented-out code blocks. The git history preserves anything that might be needed later. TODOs are acceptable only when paired with a clear follow-up plan or issue reference. - ### Links -When links to **application pages** are constructed, verify that `nextjs-routes` or `src/shared/router/routes` utilities are used instead of string concatenation or template literals. The full list of application routes is available in `src/shared/router/nextjs-routes.d.ts`. +When links to **application pages** are constructed, verify that `route()` from `src/shared/router/routes` is used instead of string concatenation or template literals. The same module is the only import surface for the `Route` / `Query` / `DynamicRoute` types. The full list of application routes is available in `src/shared/router/nextjs-routes.d.ts`. ### Date and time diff --git a/.agents/rules/design-system.md b/.agents/rules/design-system.md index 4a082337573..eefced6aabd 100644 --- a/.agents/rules/design-system.md +++ b/.agents/rules/design-system.md @@ -79,6 +79,28 @@ Available `radii` tokens: `none`, `sm` (4px), `base` (8px), `md` (12px), `lg` (1 Available `shadows` tokens: `size.xs`, `size.sm`, `size.base`, `size.md`, `size.lg`, `size.xl`, `size.2xl`, `action_bar`, `dark-lg`. +## Styling components + +Use Chakra's style props and conditional styles where possible. Reach for the `css` prop only when there is +no other way: a selector Chakra has no prop for, styling an external module's markup, or a non-literal value +such as a recipe slot object (`css={ styles.cell }`). + +```tsx +// BAD +Label + +// GOOD +Label + .external-module-classname': { + bg: 'white', + }, +}}>... +``` + ## Text styles Do not set `fontSize` or `lineHeight` directly. Apply the appropriate `textStyle` token instead — it encodes both properties together along with `fontWeight` and `fontFamily`. diff --git a/.agents/rules/docs.md b/.agents/rules/docs.md new file mode 100644 index 00000000000..45592c5d665 --- /dev/null +++ b/.agents/rules/docs.md @@ -0,0 +1,93 @@ +--- +description: Rules for CONTEXT.md and other documentation about the code +paths: + - "**/CONTEXT.md" + - "**/docs/**/*.md" +globs: "**/CONTEXT.md,**/docs/**/*.md" +alwaysApply: false +--- +# Documenting the code + +The code is the only source of truth for what it does. A doc that restates it is a second source that +nobody executes, so it drifts within weeks and then the reader has to guess which one is lying. Write +only what the code cannot say. + +Applies to every doc about the code: a `CONTEXT.md`, a file under `docs/`, a module `README.md`. + +## What earns a line + +- **Navigation.** Which directory or file to open for what, so the reader skips a repo-wide search. + Earned only by an area large or nested enough that the split of responsibility is unclear on a + first read. Two or three files need no map. Past about ten entries the directory needs grouping by + concern (`tools/code-complexity/` is the precedent), not a longer map: group it, then map the + directories, one line each. +- **Recurring questions.** How to read the tool's output, which command answers a given question, where a + failure is explained. Prefer a table of question to location over prose. A row earns its place only + when the answer is not the module whose name says so: a path outside the directory, a generated + file, a naming pattern. A symbol name in the answer column is the tell that the row belongs to the + file map, or to the code. +- **Local vocabulary.** Terms that mean something only in this area. Project-wide terms go in + `.agents/GLOSSARY.md` (`update-glossary` skill). +- **Constraints.** What an editor here must keep true, and what breaks if they don't. The rule and its + cost, two sentences; the mechanism that enforces it is in the code. +- **Gotchas**, under the test below. +- **Pointers to the why.** Decisions with real alternatives belong in an ADR (`./adr.md`), local or + repo-wide. Link to it; do not summarise it. + +## What the code and the environment already say + +Leave these out. Every one of them has a source that cannot go stale: + +- Control flow, signatures, prop lists, types, algorithms. The reader opens the file. +- Anything one lookup gives: `--help` output, `package.json` scripts, the directory listing, env vars + (`docs/ENVS.md`). +- What the change replaced. The commit and the PR carry that. +- Anything another source states. Link instead, so the fact has one home. A source is not only + another `.md`: a module's header comment, a tool's `--help` text, a skill and a spec all count. + Each kind of fact has one home: what a thing *means* sits in the code's names and types, with a + comment only where `code-quality.md` allows one; how to *invoke* it is `--help`; the *procedure* around it is the skill; the + *constraint* and what breaks is the `CONTEXT.md`. + +The drop test, for every line of an existing doc: if this line goes, can the reader still find the +fact in one lookup? If yes, cut it. + +## The gotcha test + +"Not obvious" is subjective, so bind it. All four: + +1. A competent reader of this code would get it wrong. +2. Someone was actually caught: you, CI, a reviewer, or production. +3. Stating it takes a sentence or two, and does not require describing how the code works. +4. It cannot be a spec. A test whose title names the surprise is the doc that runs, so a gotcha + about behaviour goes there first, and a line already pinned by a spec goes. The doc keeps only + what no assertion can state: a policy for the person editing, a convention the code does not + check. + +Write the surprise and its consequence, not the mechanism. + +```md +BAD — describes the code; the file says this, and says it accurately +`generate.ts` runs vitest with a config that writes coverage to a temp dir, then `read.ts` +parses `coverage-final.json` and maps ranges onto functions. + +GOOD — the surprise and what it costs +A `behavior` function with no co-located spec reads 0% coverage. Simplifying it lowers COG, not CRAP. +``` + +If it fails the test, it belongs in the code as a name, a structure change, or (rarely) a comment. +See `./code-quality.md` for when a comment is allowed. + +## Keep it maintainable + +- Point at directories and files, not at symbols or line numbers. +- Prefer facts that survive a refactor: ownership, constraints, intent. +- Changing code a doc describes: fix or delete the stale lines in the same change. +- Shorter is more likely to stay true. Cut a line rather than qualify it. + +## Adding a new doc + +A directory earns a `CONTEXT.md` when getting oriented in it takes real reading and the layout does not +speak for itself. Offer it; do not write one unasked. + +A new `CONTEXT.md` needs a line in the per-directory list in `.agents/AGENTS.md`. Cross-references are +checked by `pnpm lint:doc-links`. diff --git a/.agents/rules/env-vars.md b/.agents/rules/env-vars.md index 92bf3b11345..8a3f17c813f 100644 --- a/.agents/rules/env-vars.md +++ b/.agents/rules/env-vars.md @@ -27,6 +27,7 @@ For the full pipeline (registry generation, container startup order, validation, - **Read env values via `getEnvValue('NEXT_PUBLIC_...')`** from `src/config/utils/envs.ts` — `process.env` is empty in the browser, and the helper handles SSR/client transparently. (Server-only code may use `process.env` directly.) - **Co-locate sub-configs with the code that owns them.** The aggregator at `src/config/index.ts` (sections: `app`, `apis`, `chain`, `shell`, `slices`, `features`, `services`, `metadata`, `misc`) re-exports them; add new values in the owning sub-config (e.g. `src/features/marketplace/config.ts`, `src/slices/tx/config.ts`), not in a central file. +- **Only a `config.ts` reads envs, and only `src/config` exposes the result.** The convention, its ESLint enforcement and its exemptions: `src/config/CONTEXT.md`. ## Value types @@ -42,6 +43,8 @@ For mid-sized structured config — anything with two or more fields, or a small Read with `parseEnvJson(getEnvValue('NEXT_PUBLIC_…'))`. It returns `null` on parse failure, so always provide a fallback. The operator-facing JSON syntax uses single quotes (e.g. `'[{"id":1}]'`) so the value can be pasted into a shell or `.env` file without escaping. +`getEnvValue` rewrites every `'` in the value to `"`, which breaks JSON whose *content* carries quotes — HTML attributes, an apostrophe in a sentence. A variable that accepts HTML is read with `getEnvHtmlValue`, and a JSON list of HTML strings with `parseEnvHtmlList(getRawEnvValue('NEXT_PUBLIC_…'))`, which parses the value as set first and falls back to the rewritten one so both quoting styles keep working. Rendering such a value goes through `sanitizeHtml` (`src/shared/texts/sanitize-html.ts`) on the call site. + ### 3. Links to JSON config files For large configs (marketplace apps, featured-networks list, footer links, etc.) where the payload is too big to embed in an env var and benefits from being fetched and cached separately. The env var itself only carries the URL; the JSON content is loaded **asynchronously** in the browser and is **not** validated at container startup. diff --git a/.agents/rules/tests-unit.md b/.agents/rules/tests-unit.md index 4c5cec72f83..aea2004532c 100644 --- a/.agents/rules/tests-unit.md +++ b/.agents/rules/tests-unit.md @@ -108,17 +108,16 @@ Don't mock: ## File naming and location -Test files must be named `*.spec.ts` or `*.spec.tsx` and placed alongside the code they test. Run all tests: +Test files must be named `*.spec.ts` or `*.spec.tsx` and placed alongside the code they test. ```bash -pnpm test:vitest +pnpm test:vitest # entire suite +pnpm test:vitest path/to/file.spec.ts # one file +pnpm test:vitest --changed # tests related to uncommitted work (staged and unstaged) +pnpm test:vitest --changed origin/main # tests related to this branch vs origin/main ``` -Run a single file: - -```bash -pnpm test:vitest path/to/file.spec.ts -``` +`--changed` uses git, then the Vitest module graph, so editing a source file still runs the spec that imports it. Untracked files are invisible until `git add`. If nothing matches, the command fails unless you add `--passWithNoTests` (CI does this on PRs). Fetch `origin/main` first if that ref is missing locally. ## Setup @@ -136,7 +135,7 @@ pnpm test:vitest path/to/file.spec.ts import { render, screen } from 'vitest/lib'; ``` -`vitest/lib.tsx` re-exports everything from `@testing-library/react` and replaces `render` with a custom version that wraps the component in the full app provider stack (mirroring `playwright/TestApp.tsx`): Chakra, `QueryClientProvider` (no retry, no window-focus refetch), Socket (inert by default — see below), `AppContextProvider`, Marketplace, Settings, GrowthBook, Wagmi (mock connector), Rewards, and CsvExport — heavy enough to mount whole page slices in jsdom. +`vitest/lib.tsx` re-exports everything from `@testing-library/react` and replaces `render` with a custom version that wraps the component in the full app provider stack (mirroring `playwright/TestApp.tsx`): Chakra, `QueryClientProvider` (no retry, no window-focus refetch), Socket (inert by default — see below), `AppContextProvider`, Marketplace, Settings, GrowthBook, Wagmi (mock connector), Rewards, and CsvExport — heavy enough to mount whole page slices in jsdom. The stack also mounts the toolkit router provider with a frozen home-page router; `TestApp`'s `router` prop (a `Partial` of the toolkit router type) overrides it field by field, so a spec never mocks the framework router module — the adapter's own spec (`src/shared/router/NextRouterProvider.spec.tsx`) is the one exception, since the adapter is what wraps that module. The `wrapper` export is also available if you need to pass it separately to RTL hooks: @@ -147,6 +146,8 @@ const { result } = renderHook(() => useMyHook(), { wrapper }); ## Utilities +**`vitest/utils/mockRouter.ts`** and **`vitest/utils/routerStandIn.ts`** — router values for the toolkit router provider: `buildRouterMock` is frozen (`push` / `replace` are spies, `query` never changes), `routerStandIn` is live (consumers re-render on `push` / `replace`). Their header comments say when each applies and how to install it. + **`vitest/utils/flushPromises.ts`** — call after an action that triggers async effects (e.g. a state update followed by a data fetch) to flush all pending microtasks before asserting: ```tsx @@ -157,7 +158,7 @@ await flushPromises(); expect(screen.getByText('Loaded')).toBeInTheDocument(); ``` -**`vitest/utils/mockSocket.ts`** — a fake Phoenix transport whose channels join immediately, for components that keep a query disabled until `useSocketChannel` reports a join. Only the `phoenix` `Socket` is replaced; `SocketProvider`, `useSocketChannel` and `useSocketMessage` run for real: +**`vitest/utils/mockSocket.ts`** — a fake Phoenix transport whose channels join immediately, for components that keep a query disabled until `useSocketChannel` reports a join, or that react to live socket messages. Only the `phoenix` `Socket` is replaced; `SocketProvider`, `useSocketChannel` and `useSocketMessage` run for real: ```tsx import { mockSocket, MOCK_SOCKET_URL } from 'vitest/utils/mockSocket'; @@ -168,7 +169,16 @@ render(); await flushPromises(); ``` -It uses `vi.doMock`, so it only affects modules imported **after** the call — pair it with `vi.resetModules()` and dynamic imports. Pass `socketUrl` explicitly too: without a url the provider creates no socket at all. Server-sent events are not simulated yet. +It uses `vi.doMock`, so it only affects modules imported **after** the call — pair it with `vi.resetModules()` and dynamic imports. Pass `socketUrl` explicitly too: without a url the provider creates no socket at all. + +A spec that imports the component statically installs it with a top-level `vi.mock` instead, and delivers server events with `sendSocketMessage`, which throws if nothing subscribes to that topic and event (see `AddressTokenTransfers.spec.tsx`): + +```tsx +vi.mock('phoenix', () => import('vitest/utils/mockSocket').then((m) => m.phoenixModule)); + +render(); +act(() => sendSocketMessage('addresses:0x…', 'token_transfer', { token_transfers: [ … ] })); +``` ## Mocking fetch responses @@ -196,6 +206,8 @@ await withEnvs(ENVS_MAP.arbitrumRollup, async () => { `src/config` is a module-level singleton, so `withEnvs` calls `vi.resetModules()` — everything that reads config must be imported **dynamically inside the callback**, not statically at the top of the spec. Curated env bundles live in `src/config/test-utils/env-presets.ts` and are shared with the Playwright suite. +The reset also splits React contexts: a component imported inside the callback holds a fresh toolkit router context, which a statically imported `render` / `wrapper` from `vitest/lib` does not feed — the component silently gets the no-provider default (`pathname: ''`, no-op `push`), and a `routerStandIn` imported statically is never read. When the rendered tree reads the router (`useRouter`, `usePathname`, a non-external `Link`), import `vitest/lib` or `vitest/utils/routerStandIn` inside the callback as well (see `useBridgedTokensQuery.spec.ts`, `DeFiDropdown.spec.tsx`). + ## Primed-requests drift tests (`*.primed.spec.tsx`) Each page registered in the early-fetch primer has a `.primed.spec.tsx` next to its root component that guards the primer registry against drift from what the page actually requests on first render. What these tests guarantee and why lives in `src/server/primedRequests/CONTEXT.md`. diff --git a/.agents/rules/tests-visual.md b/.agents/rules/tests-visual.md index c95ce1df63c..b2903bdc1ec 100644 --- a/.agents/rules/tests-visual.md +++ b/.agents/rules/tests-visual.md @@ -1,5 +1,5 @@ --- -description: Playwright component visual tests — purpose, setup, fixtures, and conventions +description: Playwright component visual tests — when to extend, pack, or skip a suite; setup, fixtures, and conventions paths: - "**/*.pw.tsx" globs: "**/*.pw.tsx" @@ -9,19 +9,35 @@ alwaysApply: false ## Purpose -Playwright tests verify the visual presentation and interactive behavior of UI components across multiple viewports and color modes. Use them when a change affects what the user sees — layout, styling, conditional UI states. +Playwright tests catch layout and style regressions a Vitest assertion cannot. Each screenshot is slow in CI. A new `*.pw.tsx` is the last option, not a default deliverable of every UI change. + +Decide in this order: + +1. **Vitest first.** Branching, copy, mapping, and state machines go in `*.spec.ts(x)` (`tests-unit.md`). A screenshot whose job is to prove a string or a condition is the wrong tool. +2. **Extend.** If a `*.pw.tsx` already sits next to the component or page you changed, add the look there. A child, a row, or a field that already appears in a parent screenshot does not need its own file or test case. +3. **Pack.** One screenshot shows every look that can appear together. + - A list of token types is one shot with every type in the list, not one shot per type. + - A details page is one shot with every optional field visible, env-gated ones included and turned on, not one shot per flag. + A second case is justified only when packing would hide the thing you are checking: mutually exclusive layouts, an overlay that covers the page, a hover that replaces the idle look. Where possible, add a second screenshot to the same case instead of creating an entirely new case. +4. **Create only for owned layout.** Open a new `*.pw.tsx` only when this component owns layout or styling that no existing screenshot covers. Toolkit, entity, and tag components used in many places are the usual case, because one file covers every consumer. A page or wrapper that only assembles those does not get a file. Restyling a shared component would force every composing page's baselines to update anyway. + +Skip loading, empty, and error chrome unless they have distinct custom layout. Env-flag permutations belong in the packed full look, not as extra cases. + +A case that cannot name the layout or style it uniquely protects does not ship. ## File naming and location -Test files must be named `*.pw.tsx` and placed alongside the component they test. Run all tests: +Test files must be named `*.pw.tsx` and placed alongside the component they test. One entrypoint runs them: ```bash -pnpm test:pw # locally (fast, no Docker) -pnpm test:pw:docker # in Docker (required for screenshot updates) -pnpm test:pw:docker path/to/Component.pw.ts --update-snapshots # Run single file in Docker and update all corresponding screenshots +pnpm test:pw # whole suite, locally +pnpm test:pw --changed # only tests affected by the diff vs origin/main +pnpm test:pw --docker path/to/Component.pw.tsx --update-snapshots # one file in Docker, regenerating its screenshots ``` -**Never commit screenshots generated by `pnpm test:pw` (local).** Screenshots used in CI must be generated via `pnpm test:pw:docker`, otherwise tests will fail in CI due to rendering differences. +Flags, the Docker setup, and where the reports land are in `tools/playwright/CONTEXT.md`. + +**Never commit screenshots generated by a plain local `pnpm test:pw` run.** Screenshots used in CI must be generated via `pnpm test:pw --docker`, otherwise tests will fail in CI due to rendering differences. ## Test projects @@ -41,6 +57,8 @@ test('mobile only -@default +@mobile', async ({ render }) => { ... }); test('dark mode variant +@dark-mode', async ({ render }) => { ... }); ``` +Put `+@mobile` or `+@dark-mode` only on cases whose layout or color actually changes in that project. One packed shot tagged for those projects is enough; sibling cases that only reveal a field stay on `default`. + ## Imports **Never import directly from `@playwright/experimental-ct-react`.** Use the project's extended test: @@ -62,7 +80,15 @@ test('example', async ({ render }) => { }); ``` -`render` accepts optional second and third arguments to customize `hooksConfig` (mainly used for mocking Next.js router object), `appContext` and `marketplaceContext` props passed to `TestApp`. +`render` accepts optional second and third arguments to customize `hooksConfig` (its `router` field is typed by `AppHooksConfig` in `playwright/fixtures/render.tsx`: the serializable `query`, `pathname` and `asPath`, which `TestApp` merges over an empty default and feeds to the toolkit router provider), `appContext` and `marketplaceContext` props passed to `TestApp`. + +## Mock flow + +The mock fixtures and the catch-all route in `playwright/lib.ts` form one pipeline; a test is written in this order: + +1. **Envs and feature flags first.** `mockEnvs` and `mockFeatures` write to `localStorage`, which the app config in the test page reads once, at its first evaluation. +2. **Then every request mock.** `mockApiResponse` and `mockConfigResponse` resolve their matcher URL in the test page with the production URL builder, so the matcher reflects the envs mocked in step 1 and the caller passes only the path and query params the component itself passes, never env-derived ones. The first such registration evaluates the app config in the page; a `mockEnvs` after it throws, naming both calls. +3. **Then `render`.** Every `localhost` request the component makes must be answered by a mock from step 2 (the component-test server and the socket server ports excepted). A request that reaches no mock fails the test with the URL next to the registered matchers sharing its pathname, so a query-param drift shows side by side. There is no per-test opt-out: a test that shows a failure state mocks the request with an error status instead of leaving it unmocked. Requests to hosts other than `localhost` are aborted silently. ## Fixtures @@ -174,10 +200,12 @@ page.getByTestId('tx-hash') ## Environment and date -`playwright/lib.tsx` runs before every component mount and: -- Mocks `next/router.useRouter()` with a configurable router object. +`playwright/lib.ts` runs before every component mount and: +- Clears `localStorage`, so envs and feature flags from a previous test in the same worker do not leak in. - Fixes the current date to `2022-11-11T12:00:00Z` via MockDate — all `new Date()` / `Date.now()` calls return this value. +The router is not mocked at the module level: `TestApp` mounts the toolkit router provider with `hooksConfig.router` layered over an empty default, and the component reaches it through the `src/shared/router` facade hooks (see Component mounting). `hooksConfig` is serialized on its way into the page, so only `query`, `pathname` and `asPath` can be set there (`AppHooksConfig` in `playwright/fixtures/render.tsx`); `push` and `replace` stay the defaults, which resolve `true` without navigating. + ## Mock data Use existing files from `mocks/` and `playwright/mocks/` rather than hardcoding values inline. The `mocks/` directory contains shared mock data (API responses, entities) used across both Vitest and Playwright tests. `playwright/mocks/` contains Playwright-specific assets (images, JSON files, module mocks). @@ -187,5 +215,4 @@ Extract any non-obvious test values (IDs, amounts, hashes) into named constants ## Conventions - Do not use the `testFn: TestFixture<...>` pattern. It makes refactoring harder and can bypass Playwright lint rules. Use it only when genuinely sharing fixture logic across multiple suites. -- Keep each test focused on one visual state or interaction. - Screenshots are the contract — keep them up to date and review diffs carefully in PRs. diff --git a/.agents/rules/typescript.md b/.agents/rules/typescript.md index 1d65d1c42a6..82870400c5d 100644 --- a/.agents/rules/typescript.md +++ b/.agents/rules/typescript.md @@ -204,26 +204,9 @@ interface C extends A, B { ``` -## JS-doc comments - -Use JSDoc comments to annotate functions and types. - -Be concise in JSDoc comments, and only provide JSDoc comments if the function's behavior is not self-evident. - -Use the JSDoc inline `@link` tag to link to other functions and types within the same file. - -```ts -/** - * Subtracts two numbers - */ -const subtract = (a: number, b: number) => a - b; - -/** - * Does the opposite to {@link subtract} - */ -const add = (a: number, b: number) => a + b; -``` +## JSDoc +JSDoc is a comment. Same rule as [Comments](./code-quality.md#comments): omit it unless it explains *why*. Never restate the name or types. If a JSDoc block already earned its place, `@link` is fine for same-file references. ## Naming conventions @@ -406,3 +389,122 @@ Use `decs.d.ts` exclusively for untyped third-party module declarations. Do not // decs.d.ts declare module 'some-untyped-package'; ``` + +## Constructive modeling + +Build the type from parts that are all legal instead of restricting a loose type with runtime checks. + +Non-empty, via a variadic tuple: + +```ts +import type { NonEmptyArray } from 'src/shared/types/utils'; + +// BAD: Array plus a length check every caller must repeat +function pickWinner(entries: Array): string { + if (entries.length === 0) throw new Error("no entries"); + return entries[Math.floor(Math.random() * entries.length)]; +} + +// GOOD: an empty value of the type can't exist +function pickWinner(entries: NonEmptyArray): string { + return entries[Math.floor(Math.random() * entries.length)]; +} +``` + +Where a plain `Array` arrives, narrow once with a guard. The fact then travels in the type: + +```ts +const isNonEmpty = (arr: Array): arr is NonEmptyArray => arr.length > 0; +``` + +Even length, as pairs: + +```ts +import type { Pairs } from 'src/shared/types/utils'; +const entities: Pairs = [ [ 'foo', 'bar' ] ]; +``` + +A time range, as start plus duration: + +```ts +// BAD: a comment holds the invariant +type TimeRange = { start: Date; end: Date }; // start <= end + +// GOOD: one field to validate at the boundary instead of a relation between two; derive end when needed +type TimeRange = { start: Date; durationMs: number }; +``` + +`durationMs` still admits a negative number; the gain is that the invariant is a single field checked once where the value is built, not `start <= end` re-checked wherever both are read. Pick the representation that leaves the fewest bad states, then expose the reading you need on top (`pairs.flat()`, a `rangeEnd()` helper). + +## Simplest total type + +Don't strengthen everything. Keep `Array` when every operation on it is total: + +```ts +const sum = (xs: Array) => xs.reduce((a, b) => a + b, 0); // [] is 0, fine +``` + +Strengthen when the loose type forces a lie at a use site. The tells are `!`, `arr[0] as T`, and a "should never happen" throw: + +```ts +// BAD: partiality smuggled past the compiler +function newestSession(sessions: Array): Session { + return sessions.at(0)!; +} + +// GOOD: strengthen the input; the assertion disappears +function newestSession(sessions: NonEmptyArray): Session { + return sessions[0]; +} +``` + +Weakening the result to `Session | undefined` is the other total signature. + +## Narrowing hierarchy + +From best to last-resort: + +1. **Discriminated union switch / if.** Compiler narrows automatically. +2. **`in` operator.** `"key" in obj` narrows to variants containing that key. +3. **`typeof` / `instanceof`.** For primitives and class instances. +4. **User-defined type guard.** When the above aren't enough. +5. **`as` cast.**. + +```ts +function area(s: Shape): number { + if ("radius" in s) return Math.PI * s.radius ** 2; // narrowed to circle + return s.width * s.height; // narrowed to rect +} +``` + +## Type guards + +A guard is for a claim the compiler can't check from the shape alone (see the narrowing hierarchy above; a discriminant needs no guard). It must actually verify the claim. A lying guard is worse than `as`. + +```ts +// A string's shape says nothing about its content; the guard checks it. +const isHex = (s: string): s is `0x${string}` => s.startsWith("0x"); + +// BAD: claims the full shape, checks one key +const isUser = (v: unknown): v is User => typeof v === "object" && v !== null && "id" in v; +``` + +## Schema-derived types + +When an API response type already defines a shape, derive from it instead of duplicating it. Response types come from the generated `@blockscout/*-types` packages, or from a local `types/api.ts` for the exceptions; how to find which is `src/api/CONTEXT.md` ("Where a resource's response types come from"). Reach for `Pick`, `Omit`, `Parameters`, `ReturnType`, `Awaited`, `typeof` before writing a new interface. + +```ts +// BAD. Duplicate shape, drifts when the schema changes. +type BlockTimeStats = { + average_block_time?: { value: string; units?: string }; +}; +function renderBlockTime(s: BlockTimeStats) { + /* ... */ +} + +// GOOD. Derive from the generated type. +import type { MainPageStats } from '@blockscout/stats-types'; +function renderBlockTime(s: Pick) { + /* ... */ +} +``` diff --git a/.agents/skills/add-api-resource/SKILL.md b/.agents/skills/add-api-resource/SKILL.md index 5373e1ebc64..adc7fca276d 100644 --- a/.agents/skills/add-api-resource/SKILL.md +++ b/.agents/skills/add-api-resource/SKILL.md @@ -14,7 +14,7 @@ This skill declares new resource(s) in an **existing** service. (registration + dispatch-type branches) and a `src/api/config.ts` block; not covered here. **Out of scope — consuming the resource.** Wiring it into UI (`useApiQuery` / -`useQueryWithPages`, stubs) is the caller's job; this skill only makes the resource exist and +`useApiPaginatedQuery`, stubs) is the caller's job; this skill only makes the resource exist and be correctly typed. **Background reading:** *Where a resource's response types come from* in diff --git a/.agents/skills/add-env-var/SKILL.md b/.agents/skills/add-env-var/SKILL.md index c59f0f419c7..1b9afdb2184 100644 --- a/.agents/skills/add-env-var/SKILL.md +++ b/.agents/skills/add-env-var/SKILL.md @@ -32,7 +32,9 @@ Add a row in the section that mirrors where the variable's config lives: App configuration / APIs configuration / App shell / Slices / Features / External services / Misc. The doc sections mirror `src/config/index.ts`. -Fill in: name, type, description, required/optional, default, example. +Fill in the name, type, description, required/optional status, default, and example. +Description: one sentence maximum; avoid validation logic and implementation details; +be extremely concise. Set the **Version** column to `upcoming`. The release process replaces this with the actual version number when the change ships. @@ -140,9 +142,9 @@ URL of a same-origin asset, etc.), this section doesn't apply. ## Step 3 — Validator schema and tests -Add the rule and a test preset entry. The full procedure (which schema file, -where in the schema, JSON shape conventions, JSON-URL example assets, -companion-variable rules, running the tests, verifying the negative path) +Add the rule and its spec cases. The full procedure (which schema file, +where in the schema, JSON shape conventions, JSON-URL fixtures, +companion-variable rules, running the tests) lives in `deploy/tools/envs-validator/CONTEXT.md` — follow the "Adding a new variable" section there. @@ -162,9 +164,9 @@ For any other external host (analytics, third-party services, custom integrations, etc.), add the domain to the matching policy and gate it on the feature/option being enabled. -## Step 5 — Only if the variable holds an asset URL (image or JSON config) - -Append the variable name to the `ASSETS_ENVS` array in -`deploy/scripts/download_assets.sh`. The container entrypoint downloads the -asset into the image at startup so the browser serves it same-origin. +## Step 5 — Only if the variable holds an asset URL (image, JSON config or HTML snippet) +Add the variable to `ASSET_ENVS` in `deploy/tools/assets-downloader/assets.ts` +with the content kind the app expects — the `AssetKind` union in that file lists +them. The container entrypoint downloads the asset at startup, checks the content +against that kind, and saves it so the browser serves it same-origin. diff --git a/.agents/skills/add-new-page/SKILL.md b/.agents/skills/add-new-page/SKILL.md index 1a299ca0083..b317d56fdeb 100644 --- a/.agents/skills/add-new-page/SKILL.md +++ b/.agents/skills/add-new-page/SKILL.md @@ -15,10 +15,11 @@ sorting, search, socket live-updates, mocks, tests, and design polish are out of wiring is deferred, the freshly-scaffolded page keeps its intentional `TODO`s and will not fully pass `lint`/`tsc` until its data is wired — that is expected. -**TODO tags.** Every deferred piece of work is marked with a stage-tagged TODO, so each later stage can find -its worklist with a grep: **`TODO (api-data):`** — resolved by the data-wiring phase (`wiring.md`); -**`TODO (design):`** — content/representation decisions left for the design stage (icons, field hints, -uncertain value formatting). Keep the tags when scaffolding, and use them for any new deferred work you mark. +**TODO tag.** Every piece of work deferred to the data-wiring phase is marked **`TODO (api-data):`**, so that +phase finds its worklist with a grep (`wiring.md`). Keep the tag when scaffolding, and use it for any new +deferred data work you mark. Nothing is deferred to the style leaf by a marker: a representation decision +the scaffold cannot make is listed to the user at the end, and a visual item still with the designer is a +question on the task, not a comment in the code. **Rule of thumb: never guess.** Whenever information is missing or required to proceed, **pause and ask the user, or confirm your findings**, before writing files. @@ -43,13 +44,13 @@ substitute the placeholders and delete any optional blocks you don't need: Template sets: - `templates/general/{Page,GeneralInfo}.tsx.tmpl` (`Page` = non-tabbed general page; `GeneralInfo` = a general-content body, used as a tab panel) - `templates/detail/{Page,Details}.tsx.tmpl` -- `templates/index/{Page,Content,Table,TableItem,List,ListItem}.tsx.tmpl` +- `templates/index/{Page,Content,Table,TableItem}.tsx.tmpl` - `templates/tabs/PageWithTabs.tsx.tmpl` (tabbed page shell — `PageTitle` + `RoutedTabs`) - `templates/route.tsx.tmpl` (shared route wrapper; has a commented dynamic-route variant) A **page shell** is one of: a non-tabbed `Page.tsx.tmpl` (embeds a single content body) or the tabbed `PageWithTabs.tsx.tmpl` (renders `RoutedTabs`). A **content body** is `Details` (detail), `Content` + -`Table`/`List`/items (index), or `GeneralInfo` (general). Tabbed pages combine one shell with one body per tab. +`Table`/`TableItem` (index), or `GeneralInfo` (general). Tabbed pages combine one shell with one body per tab. **Naming the destination files.** Drop the `.tmpl` extension and name each component file after the component it exports — i.e. the `__PageName__`-prefixed name used in the template's `const` / `import` @@ -65,8 +66,6 @@ route wrapper is named after the route, not the component. | `index/Content.tsx.tmpl` | `__PageName__Content.tsx` → `ValidatorsContent.tsx` | | `index/Table.tsx.tmpl` | `__PageName__Table.tsx` → `ValidatorsTable.tsx` | | `index/TableItem.tsx.tmpl` | `__PageName__TableItem.tsx` → `ValidatorsTableItem.tsx` | -| `index/List.tsx.tmpl` | `__PageName__List.tsx` → `ValidatorsList.tsx` | -| `index/ListItem.tsx.tmpl` | `__PageName__ListItem.tsx` → `ValidatorsListItem.tsx` | | `general/GeneralInfo.tsx.tmpl` | `__PageName__GeneralInfo.tsx` → `ValidatorsGeneralInfo.tsx` | | `tabs/PageWithTabs.tsx.tmpl` | `__PageName__.tsx` → `Validators.tsx` | | `route.tsx.tmpl` | `src/pages/__route__.tsx` → `src/pages/validators.tsx` | @@ -76,8 +75,7 @@ components live in their own kebab-case sub-folder** under it (mirrors `src/slices/tx/pages/details/{info,logs,state,…}`). Name a tab's components after the tab so same-type tabs don't collide: replace the `__PageName__` base with `__PageName__` (PascalCase tab name), and rename the body's sub-components/imports to match. E.g. an `index`-type tab "Active" on page `Validators` → folder -`active/` holding `ValidatorsActive` (from `Content`), `ValidatorsActiveTable`, `ValidatorsActiveTableItem`, -`ValidatorsActiveList`, `ValidatorsActiveListItem`. A `detail`-type tab "Details" → folder `info/` holding +`active/` holding `ValidatorsActive` (from `Content`), `ValidatorsActiveTable`, `ValidatorsActiveTableItem`. A `detail`-type tab "Details" → folder `info/` holding `ValidatorsDetails` (from `Details`). A `general`-type tab "Stats" → folder `stats/` holding `ValidatorsStats` (from `GeneralInfo`). @@ -90,7 +88,7 @@ Propose each of the following and **wait for the user's explicit approval**. Ask obvious from the conversation or the codebase. 1. **Layout** — does the page have **tabs**? Decide this first; ask if it isn't obvious from the conversation. - - **No tabs** → pick the single content type: `index` (list + table views), `detail` (label/value grid), + - **No tabs** → pick the single content type: `index` (table view), `detail` (label/value grid), or `general` (title + content). - **Tabs** → list the tabs **in order**; for each, give a **name** (the tab title) and a **content type** (`details` / `index` / `general info`). That's enough at this stage. **A `details` tab, if present, must @@ -100,8 +98,8 @@ obvious from the conversation or the codebase. 3. **Gated or core?** — apply the architecture rule's test: *"Can this exist on a vanilla EVM chain with no feature flag?"* If yes → **core slice** (`__area__` = `slices`, no feature config/sitemap). If no → **config-gated feature** (`__area__` = `features`). -4. **Title** and **navigation placement** — the `` text, the nav label, and which nav group it - belongs to. +4. **Title** and **navigation placement** — the `` text, the nav label, which nav group it + belongs to, and the nav icon (the exact sprite name). 5. **Metadata** — **suggest** a default page title and description; let the user confirm or refine. Default only — do **not** add `enhanced` variants. 6. **Data — wire data now, or layout only?** If now, collect for **each content body** (per tab if tabbed): @@ -111,6 +109,7 @@ obvious from the conversation or the codebase. the endpoint isn't deployed anywhere yet, wiring is deferred — layout only. For each resource that doesn't exist yet, also run the **Step 0 interview of the `add-api-resource` skill** here — after this step, no question should remain for the middle of the work. +7. **Field hints (detail pages)** — Every `DetailedInfo.ItemLabel` on a detail page includes a `hint`: a one-line explanation of the field displayed when users hover over it. Collect the hint text for each field from the available context. If the context does not explicitly specify a hint, draft a suggestion for the user to confirm. Proceed only once these are settled. @@ -141,10 +140,11 @@ The **content bodies** are the same regardless of tabs — reference these exemp `src/features/gas-tracker/pages/index/GasTracker.tsx`. - **detail** (`Details.tsx`) — a `DetailedInfo.Container` grid of `ItemLabel`/`ItemValue` rows wrapped in `Skeleton`. Exemplars `src/slices/block/pages/details/BlockDetails.tsx`; grid `src/shared/detailed-info/DetailedInfo.tsx`. -- **index** (`Content.tsx` + `Table`/`TableItem` + `List`/`ListItem`) — `Content.tsx` is `DataList` + dual - view (`` mobile `List`, `` desktop `Table`); `Table`/`List` render - one row per item via dedicated `TableItem`/`ListItem` components (mirroring `BlocksTableItem`/`BlocksListItem`). - Exemplars `src/slices/block/pages/index/{BlocksContent,BlocksTable,BlocksTableItem,BlocksList,BlocksListItem}.tsx`; +- **index** (`Content.tsx` + `Table`/`TableItem`) — `Content.tsx` is `DataList` wrapping the `Table` in + `TableContainerScrollable`, one view for every viewport (mobile scrolls it horizontally); the `Table` root's + `minWidth` is set from its columns' content so they don't compress. `Table` renders one row per item via a + dedicated `TableItem` component (mirroring `BlocksTableItem`). + Exemplars `src/slices/block/pages/index/{BlocksContent,BlocksTable,BlocksTableItem}.tsx`; `src/shared/lists/DataList.tsx`. Replace the `DataList` placeholders with the page's entity (don't leave the generic "items"): set `emptyText` to a plural no-data sentence (`"There are no blocks."`) and `emptyStateProps={{ term: '' }}` to @@ -158,7 +158,7 @@ Use the single page shell that embeds its one content body directly: - **general** → `general/Page.tsx.tmpl` (content inline; no separate body needed). - **detail** → `detail/Page.tsx.tmpl` (reads the route param, renders `PageTitle` + `Details`) + `detail/Details.tsx.tmpl`. -- **index** → `index/Page.tsx.tmpl` (renders `PageTitle` + `Content`) + `index/{Content,Table,TableItem,List,ListItem}.tsx.tmpl`. +- **index** → `index/Page.tsx.tmpl` (renders `PageTitle` + `Content`) + `index/{Content,Table,TableItem}.tsx.tmpl`. ### B. With tabs @@ -204,18 +204,18 @@ Run **`pnpm run routes:generate`** (runs `nextjs-routes`) to regenerate `src/sha ## Step 5 — Navigation -In `src/shell/navigation/useNavItems.tsx` add a `NavItem` to the group agreed in Step 0: +In `src/shell/navigation/useNavItems.ts` add a `NavItem` to the group agreed in Step 0: ```ts const __featureName__: NavItem | null = config.features.__featureName__.isEnabled ? { text: '__title__', nextRoute: { pathname: '__route__' as const }, - // TODO (design): set nav icon + icon: '', isActive: pathname.startsWith('__route__'), } : null; ``` -For a core slice page drop the `config.features.*` guard (or gate on `config.slices.*`). **Do not invent an -icon** — leave the `// TODO (design): set nav icon` comment and omit the `icon` field so the user assigns the correct -sprite later. Then insert the item into the appropriate group array. +For a core slice page drop the `config.features.*` guard (or gate on `config.slices.*`). The `icon` is the +sprite name settled in Step 0 (`public/icons/name.d.ts` is the list of valid names) — never a guess. Then +insert the item into the appropriate group array. ## Step 6 — Metadata @@ -236,7 +236,7 @@ title/description (`default` only, no `enhanced`): ## Step 7 — Page-type analytics -In `src/services/mixpanel/get-page-type.ts` add an entry to `PAGE_TYPE_DICT` (a +In `src/shared/analytics/get-page-type.ts` add an entry to `PAGE_TYPE_DICT` (a `Record`). **Suggest** a human-readable name; let the user adjust: ```ts '__pathname__': '__title__', diff --git a/.agents/skills/add-new-page/templates/detail/Details.tsx.tmpl b/.agents/skills/add-new-page/templates/detail/Details.tsx.tmpl index b514dadb802..c764fd16be2 100644 --- a/.agents/skills/add-new-page/templates/detail/Details.tsx.tmpl +++ b/.agents/skills/add-new-page/templates/detail/Details.tsx.tmpl @@ -17,7 +17,7 @@ const __PageName__Details = ({ data, isLoading }: Props) => { return ( - + Label diff --git a/.agents/skills/add-new-page/templates/detail/Page.tsx.tmpl b/.agents/skills/add-new-page/templates/detail/Page.tsx.tmpl index e920742c336..5ca4c1be7ab 100644 --- a/.agents/skills/add-new-page/templates/detail/Page.tsx.tmpl +++ b/.agents/skills/add-new-page/templates/detail/Page.tsx.tmpl @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import PageTitle from 'src/shell/page/title/PageTitle'; @@ -8,6 +7,7 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import __PageName__Details from 'src/__area__/__featureName__/pages/details/__PageName__Details'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; const __PageName__ = () => { const router = useRouter(); diff --git a/.agents/skills/add-new-page/templates/index/Content.tsx.tmpl b/.agents/skills/add-new-page/templates/index/Content.tsx.tmpl index 5b0eb1f7f70..48a524b9fe8 100644 --- a/.agents/skills/add-new-page/templates/index/Content.tsx.tmpl +++ b/.agents/skills/add-new-page/templates/index/Content.tsx.tmpl @@ -1,18 +1,18 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; -import __PageName__List from 'src/__area__/__featureName__/pages/index/__PageName__List'; import __PageName__Table from 'src/__area__/__featureName__/pages/index/__PageName__Table'; import DataList from 'src/shared/lists/DataList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + const __PageName__Content = () => { - // TODO (api-data): wire up data (useQueryWithPages) — see wiring.md in the add-new-page skill. + // TODO (api-data): wire up data (useApiPaginatedQuery) — see wiring.md in the add-new-page skill. // Pagination, filtering, sorting and the action bar are intentionally omitted from // this scaffold. See src/slices/block/pages/index/BlocksContent.tsx for the full pattern. - // Three placeholder items so the table/list render visible example rows — replace with fetched data. + // Three placeholder items so the table renders visible example rows — replace with fetched data. const items: Array = [ {}, {}, {} ]; const isError = false; const isLoading = false; @@ -26,12 +26,9 @@ const __PageName__Content = () => { emptyText="There are no items." emptyStateProps={{ term: 'item' }} > - - <__PageName__List items={ items } isLoading={ isLoading }/> - - + <__PageName__Table items={ items } isLoading={ isLoading }/> - + ); }; diff --git a/.agents/skills/add-new-page/templates/index/List.tsx.tmpl b/.agents/skills/add-new-page/templates/index/List.tsx.tmpl deleted file mode 100644 index 40129fba34b..00000000000 --- a/.agents/skills/add-new-page/templates/index/List.tsx.tmpl +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import __PageName__ListItem from 'src/__area__/__featureName__/pages/index/__PageName__ListItem'; - -interface Props { - // TODO (api-data): replace `unknown` with the real item type - items: Array; - isLoading?: boolean; -} - -const __PageName__List = ({ items, isLoading }: Props) => { - return ( - - { items.map((item, index) => ( - <__PageName__ListItem key={ index } item={ item } isLoading={ isLoading }/> - )) } - - ); -}; - -export default __PageName__List; diff --git a/.agents/skills/add-new-page/templates/index/ListItem.tsx.tmpl b/.agents/skills/add-new-page/templates/index/ListItem.tsx.tmpl deleted file mode 100644 index fc8b25b8183..00000000000 --- a/.agents/skills/add-new-page/templates/index/ListItem.tsx.tmpl +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - // TODO (api-data): replace `unknown` with the real item type - item: unknown; - isLoading?: boolean; -} - -const __PageName__ListItem = ({ item, isLoading }: Props) => { - return ( - - { /* TODO (api-data): one Label/Value pair per field; render values from `item` */ } - Label 1 - - Value 1 - - - Label 2 - - Value 2 - - - Label 3 - - Value 3 - - - ); -}; - -export default __PageName__ListItem; diff --git a/.agents/skills/add-new-page/templates/index/Table.tsx.tmpl b/.agents/skills/add-new-page/templates/index/Table.tsx.tmpl index 8b342f65c80..11d0f197a16 100644 --- a/.agents/skills/add-new-page/templates/index/Table.tsx.tmpl +++ b/.agents/skills/add-new-page/templates/index/Table.tsx.tmpl @@ -4,6 +4,8 @@ import React from 'react'; import __PageName__TableItem from 'src/__area__/__featureName__/pages/index/__PageName__TableItem'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; + import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; interface Props { @@ -12,9 +14,14 @@ interface Props { isLoading?: boolean; } +// TODO (api-data): key by the item's identifying fields +const getBaseKey = (item: unknown): string => String(item); + const __PageName__Table = ({ items, isLoading }: Props) => { + const keys = useUniqueKeys(items, getBaseKey); + return ( - + { /* TODO (api-data): define columns */ } @@ -25,7 +32,7 @@ const __PageName__Table = ({ items, isLoading }: Props) => { { items.map((item, index) => ( - <__PageName__TableItem key={ index } item={ item } isLoading={ isLoading }/> + <__PageName__TableItem key={ keys[index] } item={ item } isLoading={ isLoading }/> )) } diff --git a/.agents/skills/add-new-page/templates/tabs/PageWithTabs.tsx.tmpl b/.agents/skills/add-new-page/templates/tabs/PageWithTabs.tsx.tmpl index c7d79234555..31b02917fe8 100644 --- a/.agents/skills/add-new-page/templates/tabs/PageWithTabs.tsx.tmpl +++ b/.agents/skills/add-new-page/templates/tabs/PageWithTabs.tsx.tmpl @@ -15,10 +15,11 @@ import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; const __PageName__ = () => { // Detail (entity) pages: read the route param here for the title, e.g. + // import { useRouter } from 'src/shared/router/useRouter'; // const router = useRouter(); // const __entityParam__ = getQueryParamString(router.query.__entityParam__); - // TODO (api-data): wire up data (useApiQuery / useQueryWithPages) — see wiring.md in the add-new-page skill. + // TODO (api-data): wire up data (useApiQuery / useApiPaginatedQuery) — see wiring.md in the add-new-page skill. const tabs: Array = [ { id: 'tab1', title: 'Tab 1', component: <__PageName__Tab1/> }, diff --git a/.agents/skills/add-new-page/wiring.md b/.agents/skills/add-new-page/wiring.md index 7995fcae600..9a6cadb278f 100644 --- a/.agents/skills/add-new-page/wiring.md +++ b/.agents/skills/add-new-page/wiring.md @@ -6,13 +6,12 @@ was scaffolded earlier (its `TODO (api-data):` markers are still in place); on d run the *Data* item of the Step 0 interview first. **The worklist is the tag.** Grep the page's directories for `TODO (api-data):` — every hit -(page shell, `Content`, `Table`/`TableItem`, `List`/`ListItem`, `Details`, `GeneralInfo`) is -a spot this phase must resolve (the done-condition is checked in Step W5). `TODO (design):` -markers are the next stage's worklist — leave them in place, and add new ones for any -representation decision you defer (Step W4). +(page shell, `Content`, `Table`/`TableItem`, `Details`, `GeneralInfo`) is +a spot this phase must resolve (the done-condition is checked in Step W5). A representation +decision this phase defers is listed to the user at the end (Step W4), never marked in the code. **In scope:** resource declaration (via the `add-api-resource` skill), minimal loading stubs, -`useApiQuery` / `useQueryWithPages` wiring, pagination controls, plain rendering of every +`useApiQuery` / `useApiPaginatedQuery` wiring, pagination controls, plain rendering of every payload field. **Out of scope:** filters, sorting, search, socket live-updates, mocks, tests, and design polish — unless the task explicitly names them. @@ -45,10 +44,10 @@ Mocks and tests are **not** produced here. Replace the scaffold's placeholder `items` / `data` / `isLoading` / `isError` consts, and replace the `unknown` item/data types with the payload (item) type **everywhere it appears** — -the page shell *and* the `Table`/`TableItem`/`List`/`ListItem` (or `Details`) components each +the page shell *and* the `Table`/`TableItem` (or `Details`) components each carry their own `unknown` marker. -- **index, paginated resource** — in the page shell, `useQueryWithPages({ resourceName, +- **index, paginated resource** — in the page shell, `useApiPaginatedQuery({ resourceName, options: { placeholderData: generateListStub<'service:name'>(ITEM_STUB, 50, { next_page_params: { … } }) } })`; take the `next_page_params` keys from the sample body. Thread the query down to the content body; pass `isPlaceholderData` as `isLoading` and @@ -69,8 +68,7 @@ carry their own `unknown` marker. Inventory the payload fields from the type + sample body and render **all of them** in the scaffolded body — `DetailedInfo` rows in `Details` for detail pages; for index pages the -columns in `Table`, the cells in `TableItem`, **and** the label/value pairs in `ListItem` -(desktop and mobile views must show the same fields); free layout in `GeneralInfo` for +columns in `Table` and the cells in `TableItem`; free layout in `GeneralInfo` for general: - Use the obvious shared component **only when the field is unambiguous** — an address @@ -78,9 +76,10 @@ general: timestamp → the shared time-format helpers. - Everything else is **plain text**: numbers/strings as-is; nested objects either split into sub-fields or JSON-stringified. **Never invent formatting** (no rounding, units, or - truncation decisions) — tag each plain-text field with - `// TODO (design): representation` instead, and **list all tagged fields to the - user at the end** so the design pass has a worklist. + truncation decisions) — leave the field plain and **list every such field to the user at + the end**, so the style leaf has a worklist. No marker goes in the code. +- On a detail page, set every `ItemLabel`'s `hint` to the confirmed text from Step 0 item 7. A field with no confirmed hint keeps the template's + `TODO (api-data):` hint placeholder and joins the list above. - Replace the scaffold's generic `DataList` placeholders with the real entity: plural sentence in `emptyText`, singular `emptyStateProps.term`. diff --git a/.agents/skills/create-issue/SKILL.md b/.agents/skills/create-issue/SKILL.md index 476f5d2ae0a..cdf19e12fe7 100644 --- a/.agents/skills/create-issue/SKILL.md +++ b/.agents/skills/create-issue/SKILL.md @@ -24,7 +24,7 @@ Done when one body of material is in hand, or the run has stopped. Done when exactly one topic is selected, or the run has stopped. -- Several issue-worthy topics → list them in one short round and wait. "All of them" means a separate issue per topic: confirm and create each before starting the next. +- Several issue-worthy topics → list them in one short round and wait. "All of them" means a separate issue per topic, created one after another. - File when the problem or request can be stated in a couple of sentences. Missing repro, acceptance criteria, or technical detail is fine — omit those sections later. - No request or problem in the source, or the subject itself cannot be named → stop and tell them the issue cannot be created. @@ -34,7 +34,7 @@ Done when repository, type, labels, title and body are all decided. Follow the `check-github-cli` skill before any `gh` command below. Do not proceed with `gh` until `gh auth status` succeeds. -**Repository.** Recommend one: this workspace's `origin` when it is a `blockscout/*` repo and the topic fits; otherwise a best-guess `blockscout/*` repo from the topic. Skip fork remotes. If they say it is the wrong place, list `blockscout` source repos (`gh repo list blockscout --source --no-archived --limit 100 --json name,description`) or take an `owner/name` they type. +**Repository.** Pick one: this workspace's `origin` when it is a `blockscout/*` repo and the topic fits; otherwise a best-guess `blockscout/*` repo from the topic. Skip fork remotes. If the user later says it is the wrong place, move the issue with `gh issue transfer ` — list `blockscout` source repos (`gh repo list blockscout --source --no-archived --limit 100 --json name,description`) when they need to pick. **Type.** Infer one of `Bug`, `Task`, or `Feature` from the topic: unexpected broken behavior → `Bug`; new user-facing capability → `Feature`; otherwise `Task`. @@ -68,11 +68,9 @@ Follow the `check-github-cli` skill before any `gh` command below. Do not procee **Public-safe.** People unnamed and unattributed; no links to the private source (Slack, Notion, Fireflies, internal docs); no client names; no unreleased dates or roadmap. -## Step 4 — Confirm, create, stop +## Step 4 — Create, stop -Present repository, type, title, body, labels (or "None"), and project board (or "None") and wait. Apply requested edits and re-confirm. - -Then create: +Create: ```bash gh issue create \ @@ -98,4 +96,15 @@ gh project item-add --owner --url Unlisted repos skip the board. A board failure does not undo the issue — report it and still show the issue link. -Show a clickable Markdown link to the new issue. The skill is done — no grilling, speccing, or implementing unless they ask in a follow-up. +Show a clickable Markdown link to the new issue, with its repository, type and labels (or "None") on one line. The skill is done — no grilling, speccing, or implementing unless they ask in a follow-up. + +## Run by Honk + +When the Honk orchestrator runs this skill headless, follow [`honk.md`](../../honk.md). This skill adds +no statuses of its own; the shared three with their triggers here: + +| Status | When | Resumed? | +| --- | --- | --- | +| `done` | the issue exists (board added or its failure reported); the message is the Step 4 line with the link | no | +| `needs_user` | the source could not be fetched, has no issue-worthy topic or several of them, or `gh` is not authenticated or lacks the `project` scope; the message carries the question or the setup to do | yes, with the answer | +| `needs_approval` | `gh issue create` or `gh project item-add` needs a tool the worker profile denies; the message carries exactly what would be run | yes, once a human did it or allowed it | diff --git a/.agents/skills/create-pr/SKILL.md b/.agents/skills/create-pr/SKILL.md index f17d6453e1f..e64b60d3e3d 100644 --- a/.agents/skills/create-pr/SKILL.md +++ b/.agents/skills/create-pr/SKILL.md @@ -42,13 +42,11 @@ the PR does from the title alone: ## Mode A — Draft placeholder (spec time) -**Reached from `to-spec`** after the developer approved the spec content: that approval already covers this -whole mode, so run steps 1–5 without re-confirming. A direct invocation keeps the confirmation in step 3. - At this stage nothing is implemented, so **do not** describe changes, env vars, or checklists — the description is a placeholder pointing at the plan: -1. **Prepare the branch** — commit `spec.md` and `questions.md` if needed (with the user's approval), push +1. **Prepare the branch** — commit `spec.md` and `questions.md` if needed (with the user's approval — + reached from `to-spec`, they are already committed and its content confirmation covers this), push with `-u`. 2. **Compose the placeholder body** (skip the PR template — it describes finished work): - `Resolves #` — the branch is `issue-`, so extract the number from it. @@ -56,10 +54,9 @@ description is a placeholder pointing at the plan: - A link to the spec file on this branch: `.agents/tasks//spec.md`. - A note that this is a **spec-first draft**: the branch will receive the task's work ticket by ticket, and the final description will be written when the PR is marked ready for review. -3. **Confirm with the user**, then create as draft: `gh pr create --draft --title "..." --body-file ...`. +3. **Create as draft**: `gh pr create --draft --title "..." --body-file ...`. Title per "PR title" above (not "spec for..."; the PR becomes the task's PR, describing the whole task). -4. **Labels** — copy the issue's labels (`gh issue view --json labels`). Skip ENVs/dependencies - labels — nothing is implemented yet; Mode B adds them from the real diff. +4. **Labels** — the category label only, per "Labels" below. Scope labels wait for Mode B. 5. Link the created PR in the output. ## Mode B — Finalize a draft into ready-for-review @@ -69,11 +66,8 @@ description is a placeholder pointing at the plan: wants; resolve conflicts before continuing. 2. **Rewrite the description** following "Writing the description" below — the placeholder body is replaced wholesale: `gh pr edit --body-file ...`. -3. **Labels from the real diff** — ENVs label if `./docs/ENVS.md` changed; dependencies label only if the - **dependency sections** of `package.json` changed (`dependencies`, `devDependencies`, - `peerDependencies`, `pnpm`/`overrides`) — inspect `git diff origin/main -- package.json` and ignore - changes confined to `scripts` or other fields; plus the issue's labels if not already copied. -4. **Confirm with the user**, then flip: `gh pr ready `. (On flipping, the Checks workflow runs — +3. **Labels** — see "Labels" below, including the check. +4. **Flip to ready**: `gh pr ready `. (On flipping, the Checks workflow runs — drafts skip it by design.) 5. Link the PR in the output. @@ -83,10 +77,26 @@ description is a placeholder pointing at the plan: approval, clear message). When the work sits on `main`, create the branch first: `issue-` when it came from an issue, otherwise a kebab-case slug naming the change. 2. **Write the description** — see "Writing the description" below. -3. **Confirm with the user**, then create: `gh pr create --title "..." --body-file ...` (add `--draft` - only if the user asked for it). -4. **Labels** — as Mode B step 3. +3. **Create**: `gh pr create --title "..." --body-file ...` (add `--draft` only if the user asked for it). +4. **Labels** — see "Labels" below, including the check. 5. Link the created PR in the output. +6. **Offer the demo** when grilling in this session settled demo presets (the `grill-the-task` demo + question; a small task holds the answer in session, not in a spec). Offer the runs + [`../deploy-demo/demo-entries.md`](../deploy-demo/demo-entries.md) gives for that answer. An answer of + `none`, or a session that never grilled, gets no offer. + +## Labels (all modes) + +Every label and its meaning is in `./docs/ISSUE_LABELS.md`; the PR check (`.github/workflows/pull-request-check.yml`) +fails a non-draft PR whose labels break the category rule. Apply with `gh pr edit --add-label " (` for a recording>) +``` diff --git a/.agents/skills/debrief-meeting/report-template.md b/.agents/skills/debrief-meeting/report-template.md new file mode 100644 index 00000000000..9e37ac7f69e --- /dev/null +++ b/.agents/skills/debrief-meeting/report-template.md @@ -0,0 +1,31 @@ +# Debrief report + +Printed in chat at the end of `debrief-meeting`. Markdown, English, in this order. A section with nothing +to list is dropped. + +``` +**Source:** , () + +## Topics + +**. (# / new issue / excluded)** +- +- Written: + +## New issues +- — + +## Skipped +- #<issue>: open PR, no checkout on its branch + +## Mid-ticket +- #<issue>: inbox written into a checkout with uncommitted changes + +## Excluded +<topic> (<product>); <topic> (<product>) + +## Failed +- <write>: <error>. <what the developer does instead, the composed Slack text included when the send failed> + +Slack: <permalink> +``` diff --git a/.agents/skills/debrief-meeting/slack-template.md b/.agents/skills/debrief-meeting/slack-template.md new file mode 100644 index 00000000000..f70445961b6 --- /dev/null +++ b/.agents/skills/debrief-meeting/slack-template.md @@ -0,0 +1,25 @@ +# Slack summary + +Russian, one message to the frontend channel, sent without a draft round: every line comes from a row the +developer approved in the plan. Issue links are Slack-formatted links, `<url|text>`, so the bullet's +title is the link and no bare URL touches the next line. The recording link is the only bare URL, and a +blank line follows it. Placeholders in angle brackets are filled in step 5 of `debrief-meeting`, after +the issue writes exist. A block with nothing to list is dropped, heading included. + +``` +Итоги фронтенд-синка <дата> +<ссылка на запись> + +По задачам: +• <<ссылка на issue>|#<номер> <название>> — <решение в одну фразу> +• ... + +Обновили описание: +• <<ссылка на issue>|#<номер> <название>> + +Новые задачи: +• <<ссылка на issue>|<название>> + +Action points: +• <@U…> — <что сделать> +``` diff --git a/.agents/skills/deploy-demo/SKILL.md b/.agents/skills/deploy-demo/SKILL.md index a272401577d..4e7a6ec3f33 100644 --- a/.agents/skills/deploy-demo/SKILL.md +++ b/.agents/skills/deploy-demo/SKILL.md @@ -1,6 +1,7 @@ --- name: deploy-demo description: Create a GitHub deployment for the current branch using the deploy-review workflow +argument-hint: "[--preset <envs_preset>] [--variant review|review-2] [--no-build]" disable-model-invocation: true --- # Deploy demo @@ -13,6 +14,34 @@ This workflow uses `gh` to trigger and monitor the deployment workflow. **Follow Create a GitHub deployment for the current branch using `.github/workflows/deploy-review.yml` (workflow name: "Deploy review environment"). +One run deploys one demo. Deploying the one or two entries a task's `Demo` row lists — slots, image reuse, +sequencing, how a failed run is read — is [`demo-entries.md`](demo-entries.md), which `finalize-task` and +`create-pr` follow. + +## Inputs + +Nothing here is inferred from prose. Every input maps to a `workflow_dispatch` input of the workflow file, +which is the single source of truth for valid values — never hardcode them in this skill. A value the +workflow does not list stops the run with the valid options shown. + +| Input | Values | Default | Workflow flag | +| --- | --- | --- | --- | +| `--preset <p>` | an `on.workflow_dispatch.inputs.envs_preset.options` entry | the workflow default | `-f envs_preset=<p>` | +| `--variant <v>` | an `on.workflow_dispatch.inputs.variant.options` entry | `review` | `-f variant=<v>` | +| `--no-build` | flag | off (builds a fresh image) | `-f build_image=false` | + +``` +/deploy-demo workflow defaults: fresh build, default preset, review slot +/deploy-demo --preset base base preset, review slot, fresh build +/deploy-demo --preset multichain --variant review-2 --no-build + second slot, reusing the branch's image +``` + +`--no-build` needs an image for this branch from a prior successful build. The image tag is +`review-<branch-slug>`, preset- and variant-agnostic: re-pointing a demo to another preset, or deploying +the other variant, reuses it. Only the namespace and hostname (`<variant>-<branch-slug>`) differ per +variant, so the two demos coexist. If unsure whether an image exists, build. + ## Steps _Note:_ In the command output, format all URLs as clickable Markdown links: `[Link Text](URL)`. @@ -30,32 +59,16 @@ _Note:_ In the command output, format all URLs as clickable Markdown links: `[Li - `gh run list --workflow=deploy-review.yml --branch <BRANCH> --status queued` - If any run is returned, **abort the command** and tell the user a deployment is already running for this branch (include a link to the run). -### 3. Resolve the workflow inputs (all optional) - -**Always read `.github/workflows/deploy-review.yml` as the single source of truth for valid option values — never hardcode them in this skill.** The workflow has three `workflow_dispatch` inputs: - -**a. `envs_preset`** — which chain's config the demo fetches at startup. -- Allowed values: `on.workflow_dispatch.inputs.envs_preset.options`. -- Infer from the prompt: "deploy a demo for base" / "with base preset" → `base`; "spin up a demo using staging" → `staging`. -- If no preset is mentioned: skip the flag (workflow default). -- Validate against the options list; if invalid, show the valid options and **abort**. - -**b. `variant`** — which demo flavor (`on.workflow_dispatch.inputs.variant.options`, e.g. `review` / `review-2`). `review-2` disables ENVs validation (used for multichain). -- Pass `-f variant=review-2` only if the user clearly asks for it ("review-2", "validation-disabled / multichain variant", "second demo"). Otherwise skip (default `review`). -- Validate against the options list; if invalid, **abort**. +### 3. Validate the inputs -**c. `build_image`** — whether to build & publish a fresh image (default `true`). -- The image is preset-agnostic, so **re-pointing an existing demo to a different chain does not need a rebuild**. If the user asks to *redeploy / re-point / switch an existing demo to another preset* ("redeploy it for celo", "switch the demo to base without rebuilding", "re-point to gnosis"), pass `-f build_image=false` — this skips the multi-minute image build and just re-runs the deploy (~1–2 min), changing `ENVS_PRESET` so the pods roll. -- For a first/normal deploy, skip the flag (default `true`, builds fresh). -- **Caveat:** `build_image=false` only works if an image for this branch already exists (a prior successful build). If unsure, prefer building. The image tag is `review-<branch-slug>` — **variant-independent** (the image is both preset- and variant-agnostic). So an image built under either variant can be reused by the other: e.g. after a `review` build you can deploy `review-2` with `build_image=false`. Only the namespace/hostname (`<variant>-<branch-slug>`) differ per variant, so the two demos coexist. +Read `.github/workflows/deploy-review.yml` and check each given `--preset` and `--variant` against its +options list. An invalid value: show the valid options and **abort**. An input not given passes no flag, +so the workflow default applies. ### 4. Trigger the workflow and capture the run ID -- Run the workflow from the current branch (from step 1/2), passing only the flags resolved in step 3: +- Run the workflow from the current branch (from step 1/2), passing only the flags for the inputs given: - `gh workflow run deploy-review.yml --ref <BRANCH> [-f envs_preset=<PRESET>] [-f variant=<VARIANT>] [-f build_image=false]` - - Examples: - - First deploy for base: `gh workflow run deploy-review.yml --ref <BRANCH> -f envs_preset=base` - - Re-point existing demo to celo (no rebuild): `gh workflow run deploy-review.yml --ref <BRANCH> -f build_image=false -f envs_preset=celo` - The CLI does not print the new run ID. To get it: wait a few seconds, then list the latest run for this workflow and branch: `gh run list --workflow=deploy-review.yml --branch <BRANCH> --limit 1`. Use that run’s ID for the next steps. ### 5. Monitor the workflow until it completes diff --git a/.agents/skills/deploy-demo/demo-entries.md b/.agents/skills/deploy-demo/demo-entries.md new file mode 100644 index 00000000000..637be27d65a --- /dev/null +++ b/.agents/skills/deploy-demo/demo-entries.md @@ -0,0 +1,54 @@ +# Demo entries + +The one home for what a task's demo answer means — from the grilling question, through the spec header's +`Demo` row, to the `deploy-demo` runs that `finalize-task` and `create-pr` Mode C trigger. The skills that +ask, write and deploy link here; none restates it. + +## The answer + +`none`, or **up to two** presets from `tools/dev-server/registry.json`. `none` is a decision, not a +blank: the land step reads it and deploys nothing. + +Two is the cap because the workflow has two deployment slots, the `variant` input's `review` and +`review-2`. `review-2` disables ENVs validation, which is what a `multichain` demo needs. Refuse a third +preset with that reason. + +## The row + +``` +| Demo | none | +| Demo | <preset> | +| Demo | <preset> (review-2) | +| Demo | <preset> · <preset> | +``` + +Entries are **positional**: the first deploys on `review`, the second on `review-2`. So a preset that +needs validation off (`multichain`) goes second. The `(review-2)` mark exists only for a **single** entry +that needs that slot; never mark one of two. A small task without a spec holds the same answer in +session, in the same shape. + +## The runs + +One `deploy-demo` run per entry, **sequentially**, with explicit inputs: + +| Entry | Inputs | +| --- | --- | +| first of two, or a single unmarked entry | `--preset <p>` | +| second of two | `--preset <p> --variant review-2 --no-build` | +| single entry marked `(review-2)` | `--preset <p> --variant review-2` | + +The second run reuses the image the first built, and `deploy-demo` aborts on a run already in progress, +so wait for the first run to complete before triggering the second. + +**A failed first run is two different things**, and the workflow's jobs tell them apart (`gh run view <run +id> --json jobs`). The `Publish Docker image` job builds the image and the `Deploy frontend` job deploys +it, running only after a successful or skipped build. Both call reusable workflows, so the rows come back +named `<caller> / <callee>` when the job ran, and by the bare caller name only when it was `skipped`: + +- `Publish Docker image / Run` failed, `Deploy frontend` skipped → no image exists. Do not trigger the + `--no-build` run; report the failed run and name both entries as not deployed. +- `Publish Docker image / Run` succeeded, `Deploy frontend / Deploy` failed → the image is there. Report + the failed deploy and trigger the second entry as planned; it deploys from that image. + +Collect each run's deployment URL from `deploy-demo`'s output for the report. Post **no** demo comment on +the PR: GitHub's deployment entry already links it. diff --git a/.agents/skills/deprecate-env-var/SKILL.md b/.agents/skills/deprecate-env-var/SKILL.md index 8715a20f6a1..aa45b1deafc 100644 --- a/.agents/skills/deprecate-env-var/SKILL.md +++ b/.agents/skills/deprecate-env-var/SKILL.md @@ -14,10 +14,11 @@ structured, the three value types, and where validation lives. Two startup checks make a removed variable fail loudly, so you rarely need to write a custom guard: -- The validator schemas use `.noUnknown(true)` — any `NEXT_PUBLIC_*` key not - declared in a schema fails validation. -- `checkPlaceholdersCongruity` (in `deploy/tools/envs-validator/index.ts`) - throws if an env has no build-time placeholder. Placeholders come from +- `composeSchemas` in `deploy/tools/envs-validator/utils.ts` rejects any + `NEXT_PUBLIC_*` key no schema declares. +- The placeholder check (`findEnvsWithoutPlaceholder` in + `deploy/tools/envs-validator/checks.ts`) fails startup if an env has no + build-time placeholder. Placeholders come from `.env.registry`, which `collect_envs.sh` generates by scanning `docs/ENVS.md`. @@ -30,8 +31,8 @@ variable in *both* places until the final removal. A variable already mid-grace-period must **not** be treated as a fresh deprecation. First check whether it is **already deprecated** from an earlier -release: grep `deploy/tools/envs-validator/index.ts` for a -`printDeprecationWarning` / `checkDeprecatedEnvs` entry naming it, and check its +release: look for its entry in `DEPRECATED_ENVS` in +`deploy/tools/envs-validator/deprecations.ts`, and check its `docs/ENVS.md` row for a "Deprecated…" annotation. - **Already in a grace period** — a request to "remove it" *is* the removal @@ -114,11 +115,10 @@ set only in per-instance files, or nowhere. `schema_multichain.ts`, or in a feature sub-schema under `schemas/features/<name>.ts`. Remove it from **both** schemas / sub-schemas if it applied in both modes. -- Remove the variable from every test preset under - `deploy/tools/envs-validator/test/` (`.env.base`, `.env.alt`, - `.env.multichain`, scenario presets). If it was a JSON-config-URL variable, - also delete its example payload under `test/assets/configs/` and its entry in - the `envsWithJsonConfig` array in `index.ts`. +- Remove the variable's cases from the sibling `*.spec.ts` and from the full + configurations in `deploy/tools/envs-validator/mocks/instance.ts`. If it was a + JSON-config-URL variable, also delete its fixture under `mocks/` and its entry + in `ENVS_WITH_JSON_CONFIG` in `checks.ts`. ### A3 — Remove the app code @@ -134,7 +134,7 @@ set only in per-instance files, or nowhere. Check each and clean up if the variable/feature touched it: - CSP allowance under `src/server/csp/policies/`. -- `ASSETS_ENVS` array in `deploy/scripts/download_assets.sh` (asset-URL vars). +- `ASSET_ENVS` in `deploy/tools/assets-downloader/assets.ts` (asset-URL vars). - `deploy/tools/sitemap-generator/next-sitemap.config.js`. - `deploy/tools/llms-txt-generator/` generators. - `public/icons/name.d.ts` (if a feature-only icon is gone). @@ -151,10 +151,11 @@ See `tools/dev-server/CONTEXT.md` § "Dropped envs" for the full why. ### A6 — (Optional) friendlier error for a replaced variable -The `.noUnknown` + congruity checks already fail startup with a generic +The unknown-variable + congruity checks already fail startup with a generic message. If the variable was **replaced** and you want operators to see a -clear "use X instead" message, add a guard to `checkDeprecatedEnvs()` in -`deploy/tools/envs-validator/index.ts` that throws with that message. +clear "use X instead" message, keep the variable in the schema as a +`v.optional(v.pipe(v.string(), v.check(() => false, '<message>')))` +rule, with a spec case asserting the message. --- @@ -180,42 +181,37 @@ clear "use X instead" message, add a guard to `checkDeprecatedEnvs()` in 3. **Validator schema** — keep the old variable accepted in `schema.ts` / `schema_multichain.ts`. If it was **Required**, make it optional now (the new - variable carries the requirement). Keep its test-preset entries valid. - -4. **Validator messaging** (`deploy/tools/envs-validator/index.ts`): - - Always add a non-fatal warning in `printDeprecationWarning()` when the old - variable is present (the `❗❗❗ … will be removed in the next release …` - block). - - **If there is a replacement:** also add a guard in `checkDeprecatedEnvs()` - that **throws** when the old variable is set *without* the new one — forces - operators onto the new name while still accepting both. (This is the - `NEXT_PUBLIC_RE_CAPTCHA_*` pattern from #2384.) - - **If there is no replacement:** warn only; do not throw. + variable carries the requirement). Keep its spec cases valid. + +4. **Validator messaging** (`deploy/tools/envs-validator/`): + - Always add an entry to `DEPRECATED_ENVS` in `deprecations.ts`: a non-fatal + `… will be removed in the next release …` warning printed when the old + variable is present. + - **If there is a replacement:** also make the old variable's schema rule + reject it when set *without* the new one (a `.when` on the new name with a + `not-exist` test in the otherwise-branch, see the tool's `CONTEXT.md`) — + forces operators onto the new name while still accepting both. (This is the + `NEXT_PUBLIC_RE_CAPTCHA_*` pattern from #2384.) Add a spec case for both + paths. + - **If there is no replacement:** warn only; do not reject. ### Phase 2 — Removal release (a later PR) Run the entire **Branch A** checklist for the old variable, **plus**: remove -the warning block you added to `printDeprecationWarning()` and the guard in -`checkDeprecatedEnvs()` in Phase 1. +the `DEPRECATED_ENVS` entry and the rejection rule you added in Phase 1. --- ## Both branches — finishing up -- **Version columns** stay `upcoming`; the `prepare-release` skill rewrites them - to the shipping tag. -- **Label the PR `ENVs`** so the change is picked up into the "Changes in ENV - variables" section of the release notes. +- **Version columns** stay `upcoming`; `pnpm release prepare` and `alpha` rewrite + them to the shipping tag. - **Name every removed variable in the PR description**, and say the removal is - breaking. `prepare-release` reads `ENVs`-labelled PR bodies to build both the - release notes and the roll-up request to DevOps, so this description is how + breaking. The release notes copy the PR body's "Environment variables" section + as written, and the `release` skill derives the roll-up request to DevOps from + the notes, so this description is how DevOps learns what to drop from deployment-values, and for which release. It is the only place that list needs to live. -- **Run the validator suite and check the negative path:** - ```bash - pnpm --filter envs-validator test - ``` - Each preset should end with `👍 All good!`. For a grace-period guard, - temporarily set the old variable without the new one in a preset and confirm - startup fails as intended, then revert. See - `deploy/tools/envs-validator/CONTEXT.md` for details. +- **Run the validator suite** — the command and the spec conventions (including + the grace-period guard's rejection case) are in + `deploy/tools/envs-validator/CONTEXT.md`. diff --git a/.agents/skills/design-readout/SKILL.md b/.agents/skills/design-readout/SKILL.md new file mode 100644 index 00000000000..8283f18e93a --- /dev/null +++ b/.agents/skills/design-readout/SKILL.md @@ -0,0 +1,124 @@ +--- +name: design-readout +description: >- + Read one Figma node into a design readout — per node the repo component, its props and the theme + tokens, with every ambiguous, unrecognized and layout item listed for the developer to settle. Recognition only, never implementation. +argument-hint: [figma node URL] +--- + +# Design readout + +Turn a Figma node into a **readout**: the content root confirmed by the developer in this session, the +values and recognition from `pnpm design:readout`, and the judgment the tool cannot make — applied in a +subagent so the values never reach the main context. The readout names components; it writes no markup. +What the tool does on its own and where its record lives: `tools/design-readout/CONTEXT.md`. + +## Inputs + +| Input | Source | Missing | +| --- | --- | --- | +| Figma node URL *(positional, optional)* | the task's issue, spec or ticket | every Figma link in the task's `spec.md` that has no block in `design-readout.md` yet; no task folder either → stop | +| Task context | the task's `spec.md` or ticket `spec.md` in session; else the conversation | ask the developer one line: which screen, which entity family | +| API response type | the resource's type file, when the task names a resource | the context override has one leg less; say so in the dispatch | + +One link is one screen in one state. A second state or the mobile variant is a second run. The task +folder is resolved from the branch (`issue-<number>`, layout in `../../tasks/structure.md`); with no +URL, steps 1–4 run once per link still without a block, in the spec's order. + +The tool needs a Figma personal access token in the environment. A run that fails on the token prints +one line on stderr: relay it and stop. Obtaining the token is the developer's two-minute job; the skill +names no variable and sets none. + +## 1. Outline — in this session + +Read the flags once per session from `pnpm design:readout --help`. Then run the node with stdout +captured, and show the developer the outline only: + +```bash +OUT="$SCRATCHPAD/readout-<fileKey>-<nodeId>.txt" +pnpm design:readout "<url>" > "$OUT" +sed -n '1,/^Regions:/p' "$OUT" +``` + +The developer confirms the content root and each dropped chrome line, or names the regions +themselves; a different choice is a re-run with `--regions`. Everything past the `Regions:` line — the +values, the hints, the lists — stays in the file for the subagent. + +A node that already has a sidecar prints a diff instead of values; the sidecar is complete either way, +and a correction or override flagged `STALE` in that diff goes to the developer with the Ambiguous +items in step 3. + +**Done when**: the developer has said yes to the regions, and the `Sidecar written to` or +`Sidecar updated at` line in `$OUT` names the record. + +## 2. Readout — in a subagent + +Spawn **one** `general-purpose` subagent with: the sidecar path from step 1, `$OUT`, the Figma node URL, +the task context (file paths when they exist, the developer's line otherwise), the API response type +path when there is one, and [`readout-brief.md`](readout-brief.md) — the judgment rules and the exact +return shape live there. The subagent reads the sidecar and the shipped code; this session reads neither. + +**Done when**: the return is the Ambiguous, Unrecognized, Layout and By convention lists plus one +Recognized count. A return carrying anything else — a component table, values, prose — is cut to those +five before it is relayed, never pasted whole. + +## 3. Settle — with the developer + +Walk the lists in order: Ambiguous, Unrecognized, Layout, By convention. Per item, the developer +settles it, sends it on, or — a Layout item only — names it a convention: + +- **Settled** — record it through the tool, with the gap category the brief proposed and the developer + confirmed. A settled Layout question that changes a node's component or props is recorded the same + way with the category `layout`; one that changes no node stays listed. + + ```bash + pnpm design:readout "<url>" --correct <nodeId> <Component> [<props…>] --gap <category> + ``` + +- **Sent on** — a design-intent question the developer cannot answer goes to the designer: step 4 + writes it as a `questions.md` entry; the item stays in its list with the question beside it. + +- **Convention** — the developer says "that's just how we do it": the repo answered this layout + question long ago and will answer it the same way next time. Draft the line, read it back, and on + the developer's confirmation append it to `tools/design-readout/layout-conventions.md` by a plain + edit in this session. That file is one table and nothing else, one row per convention, with the + columns *What the mockup shows / the question*, *Convention*, *Unless* (empty when there is no + exception) and *Code home* — a file or directory path, never a line number; no date, no node id. A + convention that also changes a node's component or props is recorded through the tool with the + category `convention`, so the sidecar carries the props while the gap log can set the line aside: + + ```bash + pnpm design:readout "<url>" --correct <nodeId> <Component> [<props…>] --gap convention + ``` + +A **shipped-code-vs-mockup conflict** is presented with both sides and settled by the developer, one +of two ways. The shipped code is wrong here: a correction with the category `context`, as above. The +mockup styles this one instance on purpose, and the line carries an `override:` tail: an override, +which names no component and logs no gap — the tool read the values right, the disagreement is +design intent. A color prop is checked against the tokens the node resolved for that fill. + + ```bash + pnpm design:readout "<url>" --override <nodeId> <prop=value> [<prop=value…>] + ``` + +A **By convention** item is already settled: the developer reviews each application and either lets it stand or edits the convention's line +in the file. + +**Done when**: every Ambiguous and Unrecognized item is recorded or sent on, the Layout list holds +only open questions, and every By convention line is reviewed. + +## 4. Hand back + +Write the node’s block to the task folder’s `design-readout.md`, in the format defined in [`readout-template.md`](readout-template.md): create the file from the template if it does not exist, replace the block for the same node if it does, and read the rows from the sidecar and the settled lists. + +Then, if a task folder exists for any item forwarded in step 3, append one entry to the task’s `questions.md`, using the format defined in `.agents/skills/to-spec/questions-template.md`. + +## Rules — binding in every step + +- **Never invent a component.** A node nothing matches is Unrecognized with its resolved values. +- **Hex over style name.** A Figma style, component or layer name is a hint; the value wins and the + disagreement is reported. +- **Report a conflict, do not pick.** Shipped code and mockup disagree → both sides on the list. +- **The MCP serves a screenshot only.** `get_screenshot` on the linked node is allowed, to see a + composite the boxes alone do not settle; `get_design_context` is never read — its values are the + hints this skill distrusts. diff --git a/.agents/skills/design-readout/readout-brief.md b/.agents/skills/design-readout/readout-brief.md new file mode 100644 index 00000000000..dbf5eccecd9 --- /dev/null +++ b/.agents/skills/design-readout/readout-brief.md @@ -0,0 +1,124 @@ +# The readout brief + +You are the subagent [`SKILL.md`](SKILL.md) step 2 dispatched. The orchestrator gave you the sidecar +path, the tool's stdout file, the Figma node URL, the task context, and the API response type path +when the task has one. The tool has already extracted the values and recognized what it can; you add +the judgment it cannot make and return five things. + +## What you return + +Exactly these five blocks, and nothing else — no component table, no values beyond the lines below, +no preamble: + +``` +Recognized: <n> of <total> + +Ambiguous: +- <nodeId> "<text or icon name>" at <x>,<y> — <what it can be> — proposal: <Component> [<props>] — gap: <category>[ — override: <prop>=<token>[ <prop>=<token>]] + +Unrecognized: +- <nodeId> <kind> "<text or icon name>" at <x>,<y> — <values: fills → tokens, font> — proposal: <Component> [<props>] | none — gap: <category> + +Layout: +- <question> — nodes <ids> — <the two readings> + +By convention: +- <convention> — nodes <ids>[ — mockup shows <the opposite>] +``` + +A proposal is **one** shipped component you located, named with its file path the first time, or +`none`. Never a component you did not find in the repo. The gap category is one of the tool's list +(`--gap` in `pnpm design:readout --help`), the one the developer would log if they settle the item +your way. + +## 1. Read + +- The sidecar, in full: per node its values, `decision`, `status`, `tokens`, `composite`, `correction`, + `override`. A node with a `correction` is settled unless `stale` is true; a stale one goes on the + Ambiguous list with the correction as the proposal. A node with an `override` is settled the same + way: the shipped component with those props on purpose; a stale one goes on the Ambiguous list with + the override as the proposal, in the `override:` tail. +- The stdout file, for the hint verdicts only: a line where a hint **disagrees** with the value is + reported beside its node in whichever list the node lands in, as `hint: <name> disagrees`. A hint + that agrees adds nothing. +- The task context and, when given, the API response type. +- `tools/design-readout/layout-conventions.md`, in full: the layout questions the repo has already + answered, one convention per row with its exception and code home. +- The shipped component the task context names, when it names one — a `*TableItem.tsx`, a details + page — read in full: it is where props such as `noIcon`, `truncation` and `fontWeight` come from. + +**Done when**: every node in the sidecar is in your hands with its status, the conventions are in +your hands, and the context override below has its inputs. + +## 2. Judge + +Apply the rules in this order to every node whose `status` is not `recognized` **and** to every +recognized node whose decision names more than one entity. + +### Context override + +The tool's text shapes say what a value *can* be (`block or batch or epoch`, `address or +transaction`); the task decides which. The ticket text and the API response type pick the entity and +its variant: + +| The context says | The family | +| --- | --- | +| a rollup's L1 side — deposits, withdrawals, batches, output roots | the `L1` / `L2` variants in `src/features/rollup/common/components/` | +| interchain, cross-chain, a foreign chain in the response | the `Interchain` variants beside the base entity | +| an external chain or explorer link | the `External` variants beside the base entity | +| a chain variant's own entity (epoch, operation, kettle, validator) | that variant's folder under `src/features/chain-variants/` | +| none of these | the base entity in `src/slices/<entity>/components/entity/` | + +Find the file with `find src -name '*Entity*.tsx'`; a family with no shipped component is +Unrecognized with proposal `none`, never a guess at a name. A node whose decision lists several +entities and whose context settles exactly one is Recognized with that one; one the context cannot +settle stays Ambiguous with every candidate listed. + +### Badge and tag fingerprints + +A small rounded box with a fill from the `badge.*` or `tag.*` token families and one short text child +is a `Badge` or `Tag` from `@blockscout/ui-toolkit`. The box's `bg` token names the color scheme +(`badge.green.bg` → `colorPalette: green`; `badge.bright.*` → the `bright` family; `tag.root.*` → a +`Tag` with that variant). Two schemes sharing one hex — the `tokens` array lists both — is Ambiguous +with both named; one scheme is Recognized. The text child is the badge's content, not its own node +on any list. + +### Composites + +A `composite` on a node means the tool paired it: `from-to` is `AddressFromTo` or the entity pair the +context names; `amount-ticker` is a value with its currency. Report the composite once, on its first +member, and fold the other members into it. Take the screenshot (`get_screenshot` on the linked +node, once) only when the boxes leave a pairing open — an arrow between two columns, say. + +### Layout questions + +A question is anything the boxes cannot settle and a developer must before markup. The recurring +ones: a value in its own column vs under another cell (two boxes sharing `x` with a small `y` gap +against the shipped row's cell list); a secondary line that is a tooltip in code and a visible line +in the mockup; a column the shipped component has and the mockup lacks, or the reverse. Each question +carries the node ids and both readings. State the question; do not answer it. + +A question a line in the conventions file answers is not a question: apply the convention as a fact +and put it on the `By convention` list instead, one line per convention applied, with every node it +settled. The convention wins even where the mockup draws the opposite and that line then ends in `mockup shows <what the mockup draws>` so the +developer reviews the override; it raises no `context` conflict. A convention that changes nothing on +the node is still listed, so the developer sees every application. + +### Shipped code vs mockup + +Where the shipped component and the mockup disagree about a node — the mockup draws an icon the code +passes `noIcon` for, a weight the code does not set — the node is Ambiguous with both sides named and +proposal left to the developer, category `context`. Where the disagreement is a style the shipped +component takes as a prop — a fill, a weight, a border — the line also ends with the override form, +`— override: <prop>=<token>[ <prop>=<token>]`, the Chakra prop as written in JSX and the token the +node's `tokens` resolved for that fill, so the developer can either correct the node (the shipped +code is wrong here) or override it (the mockup styles this one instance on purpose). Never pick. + +**Done when**: every node is on exactly one list or counted as Recognized, every proposal names a file +you opened, every disagreeing hint is beside its node, and no Layout question is one the conventions +file answers. + +## 3. Return + +The shape at the top, lists in the order given. Count Recognized as the nodes the tool recognized plus +the ones the context override settled; a node you moved to Ambiguous is not counted. diff --git a/.agents/skills/design-readout/readout-template.md b/.agents/skills/design-readout/readout-template.md new file mode 100644 index 00000000000..c9e11e29422 --- /dev/null +++ b/.agents/skills/design-readout/readout-template.md @@ -0,0 +1,59 @@ +# `design-readout.md` — the task-folder readout + +The shape of the file that carries a node's readout into a task folder: one file per task, one block +per Figma node. It is written from the node's sidecar (`tools/design-readout/CONTEXT.md` says where +that lives) and the lists the [`design-readout`](SKILL.md) skill returned, and it is pruned at land +like the ticket files. Five sections per node, in this order, each present even when empty. + +```md +# Design readout — <task title> + +## <screen name> — [<node id>](<figma node URL>) + +Sidecar `<path>` · color mode `<light|dark>` · file version `<version>` · regions `<ids>` + +### Recognized + +| Node | Content | Component | Props | Tokens | Signal | +| --- | --- | --- | --- | --- | --- | +| `<nodeId>` | `<text or icon name>` | `<Component>` | `<props, as words>[ · override <prop>=<value>…]` | `<role → token>` | `<shape / icon / color / composite / context / correction>` | + +### Ambiguous + +- `<nodeId>` `<content>` — <what it can be> — proposal `<Component> [<props>]` — gap `<category>` + — <open question and to whom, when sent on> + +### Unrecognized + +- `<nodeId>` <kind> `<content>` — <values: fills → tokens, font> — proposal `<Component>` | none — + gap `<category>` + +### Layout questions + +- <question> — nodes `<ids>` — <the two readings> — <answer, once given> + +### By convention + +- <convention> — nodes `<ids>`[ — mockup shows <the opposite>] +``` + +What goes where: + +- **Recognized** holds every node with a component: the tool's recognitions as the subagent mapped + them, the context-override hits (signal `context`), and every developer correction (signal + `correction`, the corrected component). One row per node; a composite's members sit on the first + member's row with the others' ids in Content. A node's `override` sits in its Props cell after the + component's own props, as `· override <prop>=<value>…`; it never moves a node between lists, and it + sits beside a correction when the node carries both. The Signal column does not name it. +- **Ambiguous** and **Unrecognized** hold what is still open at write time, each line with the + proposal and gap category from the skill's return. An item the developer settled in session has + moved to Recognized; an item sent to the designer carries its question. +- **Layout questions** hold every layout question the subagent raised, answered or not; an answer + that changed a node is also a Recognized row with signal `correction`. +- **By convention** holds every application of a `tools/design-readout/layout-conventions.md` row the + subagent returned, as reviewed in session: the convention, the nodes it settled, and the + `mockup shows` tail where the mockup draws the opposite, so the style leaf follows the convention + over the mockup without reopening the question. + +The sidecar is the source; this file is a view of it for the ticket's style leaf and is +regenerated, never hand-edited. diff --git a/.agents/skills/diagnose-bug/SKILL.md b/.agents/skills/diagnose-bug/SKILL.md new file mode 100644 index 00000000000..7fdd4ca9e52 --- /dev/null +++ b/.agents/skills/diagnose-bug/SKILL.md @@ -0,0 +1,179 @@ +--- +name: diagnose-bug +description: Diagnose a reported misbehaviour end-to-end. +disable-model-invocation: true +argument-hint: <Slack thread link | GitHub issue URL | description of the problem> +metadata: + credits: + skill: diagnosing-bugs + author: Matt Pocock + url: https://github.com/mattpocock/skills/blob/main/skills/engineering/diagnosing-bugs/SKILL.md +--- +# Diagnose a bug + +A workflow for hard bugs. The run goes end-to-end without asking; the one stop is a bug that cannot be +reproduced. Skip phases only when explicitly justified. + +The discipline in one line: **no red loop, no hypothesis.** A *red* loop is a command that goes red on +*this* bug and green once it is fixed; a *tight* one is deterministic and runs in seconds. With one in +hand the bug is mostly found — bisection, hypotheses and probes only consume it. Reading code to build a +theory before the loop exists is the failure this skill prevents. + +Show every command and its output; put `<REDACTED>` in place of any token or key. + +## Steps + +### 1. Resolve the input + +- A **Slack thread link** — read it per `.agents/slack-thread.md`, attachments included. Keep the + thread: the outcome is posted back there (step 9). +- A **GitHub issue URL** — `gh issue view <N> --comments`. Keep the number: the branch is `issue-<N>` + and the outcome is posted as a comment. +- **Anything else** — free text, or a bug already discussed in this conversation — the conversation is + the source. + +From the source, write down: the exact symptom, the instance (URL or alias), the page URL, the steps +and state that led there (chain, wallet, account), what the screenshots show, and whether the fix is +wanted in the release in flight (the source names staging, an alpha, a release or a version). + +**Done when:** the symptom is one sentence, with the instance and page named or stated unknown. + +### 2. Build a red loop + +Work down the ladder in [`loops.md`](loops.md) and stop at the first rung that goes red. Spend +disproportionate effort here; be relentless. Treat the loop as a product once it exists: faster +(cache setup, narrow the scope), sharper (assert the exact symptom, not "didn't crash"), more +deterministic (pin time, seed data, freeze network). + +A loop that reveals the **API response itself is wrong** — at the data rung, or already in the +dev-server rung's network list — settles the diagnosis early: go to step 6 with **Not a frontend bug**. + +A **non-deterministic** bug needs a *higher reproduction rate*, not a clean repro: loop the trigger, +narrow timing windows, inject delays, until it is debuggable. + +When the whole ladder is exhausted with nothing red, go to step 6 with **Cannot reproduce**. + +**Done when:** one command (a test path, a browser sequence, a curl) has been run at least once, its +invocation and output shown, and it is red-capable, fast and agent-runnable, and either deterministic or +— for a non-deterministic bug — red at a stated rate (*n* of *m* runs) high enough to debug. + +### 3. Reproduce and minimise + +Run the loop; watch it go red. Confirm it is the **reporter's** failure — same message, same wrong +output, same slowness — and not a neighbour. Wrong bug, wrong fix. + +Minimise in proportion to the repro: a one-line spec is already minimal; a repro with several inputs, +mocks or steps is cut one element at a time, re-running the loop after each cut, until every element +left is load-bearing. + +**Done when:** the loop is red on the reported symptom, and each remaining element of the repro turns +it green when removed. + +### 4. Hypothesise + +Write **three ranked hypotheses** before testing any; a single one anchors on the first plausible idea. +Each must be falsifiable: "if *X* is the cause, then *changing Y* makes the loop go green". One that +cannot state its prediction is a vibe: sharpen or drop it. + +Show the list, then proceed with the ranking straight away — the user interjects if they know better. + +**Done when:** three predictions are in the transcript, ranked. + +### 5. Instrument + +One probe per prediction, one variable at a time. Prefer a breakpoint or a REPL-style check in a spec to +logs; when logs it is, tag each with one prefix (`console.log('[DEBUG-a4f2]', …)`) so cleanup is a +single grep. `no-console` is an ESLint error here, so a stray one also fails the commit hook. + +A **performance regression** gets a baseline measurement first (timing in the loop, the profiler per +`tools/profiling/CONTEXT.md`) and a bisect second; logs are usually the wrong probe. + +A **regression** gets its culprit named: `git bisect run` with the loop as the script when the loop is a +rung-1 or rung-2 command (a browser sequence has no exit code), otherwise `git log -S` or blame on the +lines the fix touches. The culprit decides the backport (step 7). + +**Done when:** one hypothesis survives and the others are shown falsified. None surviving means a new +ranked three; more than one means keep falsifying until one remains. + +### 6. Classify + +| Outcome | When | +| --- | --- | +| **Fix PR** | Our code is the cause, `origin/main` still has it, and the fix is inside what `.agents/delegation.md` lets an agent do. | +| **Already fixed** | A commit on `origin/main` after the reported release fixes it (read the suspected code as of the release rev with `git show <rev>:<path>`; the instance's `/node-api/config` reports its tag or commit). | +| **Not a frontend bug** | The page renders faithfully what the API, the instance config or the chain gives it; the evidence is the request and its payload. | +| **Needs human fix** | The cause is found, but the fix is on the human side of `.agents/delegation.md` (styling to a mockup, a visual asset, a design call); or the bug lives only on the release branch (a bad pick; `origin/main` is clean) — name the pick, open no PR. | +| **Cannot reproduce** | The ladder is exhausted with no red loop. | + +**Done when:** the outcome and a one-paragraph justification are written down for step 9. **Fix PR** +and **Already fixed** continue to step 7; only **Fix PR** goes on to step 8; the others go to step 9. + +### 7. Backport + +A release is **in flight** when `gh release list --json tagName,isPrerelease,isDraft` shows a release +that is a pre-release or a draft; its PRs are listed in that release's body (`gh release view <tag> +--json body`) plus the merged PRs labelled `backport` not picked yet. The fix goes in the release when: + +- the culprit commit (step 5) belongs to one of the release's PRs, or the report came from staging; or +- the source asks for the fix in the release (step 1). + +No release in flight means no backport. The label is `backport` (`gh pr edit <N> --add-label backport`): +for **Already fixed** set it now on the fixing PR when that PR is not in the release yet, and name the +reason in the step 9 report; for **Fix PR** it goes on the new PR in step 8, whose description names the +reason. + +**Done when:** the decision and its reason are written down, and for **Already fixed** the label is set +or does not need to be set. + +### 8. Fix and regression test + +Branch off `origin/main`: `issue-<N>` for an issue, otherwise `bug-<kebab-slug>`. + +1. **Seam.** Pick the test seam that exercises the real bug pattern — the spec or component test the + loop already is, usually. A seam that is too shallow to catch the chain that triggered the bug gives + false confidence; then no seam exists, and that absence is a finding for the PR description. +2. **Red first.** Turn the minimised repro into a failing test at that seam and watch it fail. Skip it + when the test would be expensive, integration-heavy, or unclear. A visual bug gets a DOM assertion + in Vitest, or no test: screenshot baselines are a human's to generate. +3. **Fix**, watch it pass, then re-run the step 2 loop on the original, un-minimised scenario. +4. **Cleanup.** `grep -r "DEBUG-" src/` returns nothing; throwaway scripts are gone from the scratchpad + and the tree; a registry alias added in step 2 stays. +5. **Verify** per `.agents/rules/code-quality.md`, linting the changed files with `--fix`; then + `pnpm test:vitest --changed`, and `pnpm test:pw <file>` only when the regression test is a `*.pw.tsx`. +6. **Commit**, then follow the `create-pr` skill, Mode C. The Description carries, in this order: + what was broken, the root cause, the fix, how it was verified (the regression test named, or why + there is none). Additional information carries the hypotheses ruled out and the backport decision + from step 7 with its reason. +7. **Label** the PR `backport` when step 7 decided so. + +**Done when:** the PR link is in hand, the label matches step 7, and `git status` is clean. + +### 9. Report + +The **final message** has four parts, in this order: what was broken, the root cause, the fix (or the +outcome and its justification from step 6), and how it was verified. Links: the PR, the fixing commit, +or the request and payload that clear the frontend. **Cannot reproduce** replaces the last three parts +with what was tried and the artifacts to ask the reporter for: exact URL and instance, browser, a +screenshot or recording with timestamps, a HAR, the console output, wallet or account state. + +Then post back to the source, without asking — the named exception to `AGENTS.md`'s +approve-before-sending rule. Slack text follows `.agents/slack-message.md`. + +| Source | Fix PR | Already fixed | Not a frontend bug | Needs human fix | Cannot reproduce | +| --- | --- | --- | --- | --- | --- | +| Slack thread | two lines: outcome and PR link | the report | the report | the report | the artifact request | +| GitHub issue | nothing — the PR's `Resolves #N` links it | comment, close | comment, close | comment | comment, label `need info` | +| Conversation | the final message only | | | | | + +**Done when:** the message is shown to the user and posted where the table above names a post. + +## Run by Honk + +When the Honk orchestrator runs this skill headless, follow [`honk.md`](../../honk.md). This skill adds +no statuses of its own; the shared three with their triggers here: + +| Status | When | Resumed? | +| --- | --- | --- | +| `done` | the outcome is Fix PR, Already fixed, Not a frontend bug or Needs human fix, and the step 9 message is shown and posted where the step 9 table names a post; the message is that text | no | +| `needs_user` | the outcome is Cannot reproduce; the message is the artifact request, also posted where the step 9 table names a post | yes, with the artifacts | +| `needs_approval` | the push, the PR creation, a label, an issue comment or the Slack reply needs a tool the worker profile denies; the message carries exactly what would be done | yes, once a human did it or allowed it | diff --git a/.agents/skills/diagnose-bug/loops.md b/.agents/skills/diagnose-bug/loops.md new file mode 100644 index 00000000000..85d3b0e10be --- /dev/null +++ b/.agents/skills/diagnose-bug/loops.md @@ -0,0 +1,15 @@ +# Feedback-loop ladder + +The rungs of step 2 of the `diagnose-bug` skill, cheapest first. Stop at the first one that goes red; +climb when a rung cannot reach the bug. A rung's agent-runnable command is what later steps re-run. + +| Rung | Reaches | The loop | +| --- | --- | --- | +| **Vitest spec** | logic, hooks, component state, data mapping, fetch handling | A `*.spec.ts(x)` beside the code, per `.agents/rules/tests-unit.md`: `render` from `vitest/lib`, `fetchMock` for the API, `withEnvs` for an instance's config branch, `mockSocket` for live updates. `pnpm test:vitest <path>`. | +| **Playwright component test** | what jsdom cannot do: layout, real browser APIs, a provider stack the spec cannot fake | A `*.pw.tsx` with `mockApiResponse` / `mockEnvs`, asserting on the DOM (`toHaveText`, visibility), never on a screenshot. `pnpm test:pw <path>`. | +| **Dev server in a browser** | the whole page against the reporter's instance: routing, SSR, config, third-party scripts | `pnpm dev:preset <alias> --port <n>`; the alias is the instance in `tools/dev-server/registry.json` — add it there when missing, then `pnpm presets:sync`. Drive it with the Playwright MCP browser: navigate, snapshot, console messages, network requests. Red is the symptom in the snapshot, console or network list; the same navigate-and-inspect sequence is the re-run. First load takes up to a minute. A bug only in production builds (hydration, SSR-only) uses `pnpm prod:preset`. | +| **Data** | whether the frontend is even the place | Resolve the request with the `resolve-api-url` skill and `curl` it. A payload already wrong at the API, or a config value the instance really serves, clears the frontend: **Not a frontend bug**. | +| **Bisect** | a regression between two known states | A release tag or a commit is a rev (the instance's `/node-api/config` reports its tag or SHA). `git bisect run` with a rung-1 or rung-2 command as the script. | +| **Differential** | one instance or version against another | The same page or the same request on two instances (`registry.json` has production and staging aliases), or two revs; diff the outputs. | + +A rung that needs a human to click is not a loop: the artifacts to ask for are in step 9. diff --git a/.agents/skills/finalize-task/SKILL.md b/.agents/skills/finalize-task/SKILL.md index 95df70c4877..db28dc8b3c6 100644 --- a/.agents/skills/finalize-task/SKILL.md +++ b/.agents/skills/finalize-task/SKILL.md @@ -1,32 +1,85 @@ --- name: finalize-task description: >- - Land a finished product task — prune the working files (keep spec.md), then finalize the draft PR into - ready-for-review. + Land a finished product task — prune the working files (keep spec.md), flip the draft PR to ready, run + the review loop, deploy the spec's demos, report. disable-model-invocation: true --- # Finalize task -Land a task whose every `progress.md` box is checked. Two steps: prune the disposable working files, then -finalize the PR. Why only `spec.md` survives — the decomposition is preserved in git history, one commit per -ticket — is in [`../../tasks/concepts.md`](../../tasks/concepts.md). +Land a task whose every `progress.md` box is checked. Five steps, in order, each a handoff: prune the +disposable working files, finalize the PR, run the review loop, deploy the demos, report. Why only `spec.md` +survives — the decomposition is preserved in git history, one commit per ticket — is in +[`../../tasks/concepts.md`](../../tasks/concepts.md). The developer returns to a PR that is reviewed, green +and deployed, with the review history on its threads. ## Step 1 — Prune Confirm the task is done: every box in `progress.md` is checked. If any is unchecked, stop and report which -ticket is unfinished — there is nothing to land yet. +ticket is unfinished — there is nothing to land yet. An `inbox.md` with a section whose status is `pending` +is a stop as well: context the task never absorbed cannot land. Tell the developer to run +`process-task-inbox`. Then delete the disposable files, keeping only `spec.md` in the task folder: -- `tickets/` — the whole directory. +- `tickets/` — the whole directory, review files included. - `progress.md`. - `questions.md`. +- `inbox.md`, if any outer-loop context was debriefed into the task. +- `design-readout.md`, if a design readout was written. +- `review.md` / `review-<tag>.md`, if a task-level review ran in `md` mode. Commit the deletions on the feature branch as the task's final commit — a plain descriptive subject, the repo's `Co-Authored-By` trailer, no `#issue` reference. Pruning **before** the PR is finalized is what lets the whole-task review read the spec and the diff without any ticket files. +**Done when**: the task folder holds `spec.md` alone and the prune commit exists. + ## Step 2 — Finalize the PR -Hand off to the `create-pr` skill in **finalize-draft mode** (Mode B). +Hand off to the `create-pr` skill in **finalize-draft mode** (Mode B). It pushes, writes the real +description, and flips the draft to ready, which starts the Checks workflow. + +**Done when**: the PR is ready for review and `HEAD` equals its `headRefOid`. + +## Step 3 — Review loop + +Hand off to [`../review-loop/SKILL.md`](../review-loop/SKILL.md) on the PR, with no reviewer or model +override unless the developer gave one for this run. The loop reviews, resolves, waits for CI and pushes, +round by round, and pauses only on a `needs-human` finding — that pause is the loop's, not this skill's: +answer it as the loop says and let the loop continue. + +The loop ends one of two ways, and the way decides step 4: + +- **Cleared and green** — the review outcome is `cleared` and the Checks run for the pushed `HEAD` is + green. Continue to step 4. +- **Stopped short** — a bound hit, a reviewer failure after its retry, a timeout. Skip step 4: a demo of + unreviewed code is what the loop exists to avoid. Carry the loop's report into step 5. + +**Done when**: the loop has reported, and the PR is in the consistent pushed state its report confirms. + +## Step 4 — Deploy the demos + +Only after a loop that ended cleared and green. Read the `Demo` row from `spec.md` and run it as +[`../deploy-demo/demo-entries.md`](../deploy-demo/demo-entries.md) says: nothing for `none`, otherwise one +`deploy-demo` run per entry, sequentially, with the inputs its table gives, reading a failed first run the +way it describes. + +**Done when**: every entry has a successful run and a URL, or the row said `none`, or the report names +each entry that did not deploy and its failed run. + +## Step 5 — Report + +Fire a `PushNotification` with the PR url and one line: the loop outcome (cleared and green, or why it +stopped) and the number of demos deployed. + +Then report in the terminal, as clickable Markdown links where there is a url: + +- The PR. +- The review outcome and the number of rounds, from the loop's report. +- The CI status: the Checks run for the final `HEAD` and its conclusion. +- The demo URLs, one per deployed entry, or that none deployed and why (`none`, or the loop stopped short). +- Anything left open: `deferred` nits and `answered` human threads on the PR, a loop stop and its reason. + +**Done when**: the notification is sent and the report is printed. diff --git a/.agents/skills/grill-the-task/SKILL.md b/.agents/skills/grill-the-task/SKILL.md index 3883daac7e8..f8b488e0b30 100644 --- a/.agents/skills/grill-the-task/SKILL.md +++ b/.agents/skills/grill-the-task/SKILL.md @@ -29,10 +29,8 @@ Gather, in roughly this order: 3. **The API** — for every endpoint the issue names, fetch a real sample response (the `resolve-api-url` skill resolves instance URLs; then `curl`). Note pagination/sorting/filtering params and whether the API is production-deployed or staging-only. -4. **Figma mockups** — via the Figma MCP tools, **enumerate-only**: list screens/frames, their elements, - columns, states, and record a node link per screen. Do **not** extract visual/styling details — appearance - stays with the mockups and the `[human]` style leaves (see `.agents/delegation.md`). If the Figma - MCP is not connected, have the developer describe the mockups instead. +4. **Figma mockups** — enumerate the Figma links the task carries: one node link per screen and per + state, hidden layers ignored. Record the links for the spec's UI inventory. Then run two mechanical cross-checks; every mismatch becomes an open question for the backend owner or PM: @@ -68,11 +66,20 @@ of them, and marching through all six regardless is how a five-minute task turns **which upcoming backend release ships the required API changes** (so the frontend release notes can reference it) — usually a question for the backend owner. 4. **UI inventory** — routes, navigation entry points (where do users find this?), cross-links to existing - entity pages. Behavioral states and mobile behavior are standard — don't ask. + entity pages. Behavioral states and mobile behavior are standard — don't ask; the executor skills' + own inputs are `to-tickets`' to collect. 5. **Analytics & links** — custom Mixpanel events **only** if there's a new interactive element worth tracking (page views are auto-wired); UTM query params on any hardcoded links to Blockscout or partner products. +**The demo question is asked on every task**, because `none` is a decision and the land step reads it: +which preset(s) the demo deploys on. What an answer may hold — the preset list, the two-entry cap and the +`(review-2)` mark — is [`../deploy-demo/demo-entries.md`](../deploy-demo/demo-entries.md); offer those +options and recommend one from the task: a chain-type feature → that chain's preset; multichain → +`multichain`; generic UI → `staging`; nothing to deploy (agent instructions, tooling, CI) → `none`. A +specced task records the answer in the spec header's `Demo` row (`to-spec`); a small task keeps it in +session for `create-pr` Mode C's deploy offer. + Testing is **not** an interview domain — the capability boundary in `.agents/delegation.md` settles it. Neither is human verification: which acceptance criteria are `(human)` follows the standing rule in "The ticket model" in `.agents/tasks/concepts.md`. Only ask when one sits genuinely on the line. @@ -95,9 +102,9 @@ Route every question the session couldn't answer to the person who owns it. - When posting to a channel, **always mention the addressee** — `<@member ID>` from `.agents/TEAM.md` (people missing from the roster: resolve by name via `slack_search_users` and suggest adding them). 3. Draft one message per owner: brief task context (issue link), the questions, and why they block progress. - Write all Slack messages in **Russian** — the team's internal language (the spec itself stays in English). 4. **Show every draft (with its destination) to the user and wait for explicit approval** — never send - unreviewed outreach. + unreviewed *new* outreach. (In-thread follow-ups on a thread already approved here are exempt — see + "Watch for replies" below.) 5. Send (`slack_send_message`), then keep each thread's permalink for the question's `questions.md` entry. If the Slack MCP tools are unavailable, record the questions with owners anyway and tell the user to route @@ -106,11 +113,42 @@ them manually. Outreach is complete when every question has a recorded permalink — or an explicit note that the developer routes it manually. +### Watch for replies and drive each question to settled + +Once the questions are sent, don't hand the reply round-trip back to the developer to poll. Run the +**`slack-subscribe`** skill — one registration per `pending` question thread (the channel id and parent +`ts` from each `slack_send_message` you just sent), all in this turn — then stop once; a settled question +is unsubscribed the same way. Outside +local Claude Code that skill stops at its readiness check, and the developer polls manually as before. + +Each forwarded reply arrives as a cross-session message carrying its `thread_ts`. Read the thread with +`slack_read_thread`, then for the question that thread belongs to: + +- **Assess** the reply against the question's `Resolved when:` criterion — session-held here, since this + runs before `to-spec`; it only becomes a `questions.md` line once `to-spec` writes one (lifecycle step 2). +- **Insufficient** → send a clarifying **follow-up to the colleague directly, in the same thread, without + developer approval** — this is continuing a conversation the developer already opened. Cap: **3** + consecutive follow-ups per question, then escalate. Opening a *new* thread or contacting a *new* person + stays approval-gated (Step 3 rules unchanged). +- **Sufficient** → **propose in the session chat**: the answer arrived, the proposed resolution, and the + edits it implies. **Edit no file.** Apply only after the developer accepts in-session. Where the answer + lands depends on how far the task has come: once `to-spec` has run, fold it into `questions.md` (the + fold-in is `.agents/tasks/README.md` step 4) — so `implement-ticket`'s question gate never releases work + a human hasn't read; before that (still grilling, or a small task that never gets a spec), hold it in + session to inform the forthcoming spec or to unblock the in-session implementation. +- **Escalate** (one line: which task/question and why it's stuck) when the answer needs *frontend* + knowledge only the developer has, the 3-follow-up cap is hit, or the colleague goes silent. + Claude Code: `PushNotification` with that line. Cursor: the same line in this session chat — Cursor has + no OS nudge. + +Every message posted to a colleague carries a disclosure — they must be able to tell they're in a +technical back-and-forth with an agent — `.agents/slack-message.md` → Attribution. + ## Step 4 — Size and hand off Decide, by a rough sizing judgment, whether the task needs a spec — one session of work or not. No formal breakdown is needed for this call ("Not every task needs a spec" in `.agents/tasks/README.md`). - **Small task** — implement it in this same session, then hand off to the `create-pr` skill. If a `pending` question blocks the work, wait for the - reply and pick the implementation back up here. + reply and pick the implementation back up here. A small task gets no spec and no readout. - **Larger task** — suggest proceeding with the `to-spec` skill **in this same session**. diff --git a/.agents/skills/implement-ticket/SKILL.md b/.agents/skills/implement-ticket/SKILL.md index 93595de2203..87fbdf5ddcc 100644 --- a/.agents/skills/implement-ticket/SKILL.md +++ b/.agents/skills/implement-ticket/SKILL.md @@ -22,7 +22,9 @@ checked out. Resolve the task folder from the branch (`issue-<number>`) and read the main `spec.md`, the target ticket's `tickets/NN-<slug>/spec.md`, `progress.md`, `questions.md`, and `.agents/delegation.md`. If ticket `NN` has -only a `brief.md`, it isn't scoped — tell the developer to scope it with a `to-tickets` run, and stop. +only a `brief.md`, it isn't scoped — tell the developer to scope it with a `to-tickets` run, and stop. An +`inbox.md` with a section whose status is `pending` is a stop too: tell the developer to run +`process-task-inbox` first. ## Step 2 — Check runnable @@ -37,25 +39,88 @@ Start at the **first unchecked** leaf and work in order, checking each box as it after a human touchpoint skips the leaves already checked. Stop at the first **unchecked** `[human]` leaf and hand off (Step 5). +**A style leaf** (the one linking a Figma node) takes the component to the mockup. The mockup is the source; the readout is an optional help, never a prerequisite: + +- **The leaf links a readout block** → read it (the task folder's `design-readout.md`) and the node's + sidecar in the main checkout (`tools/design-readout/CONTEXT.md` says where + and what is in it): the component, props and theme tokens per node are already settled there, and the + shipped code it names is the reference. Take a Figma screenshot (`get_screenshot` on the linked node) + to see what the rows do not show. +- **No readout** → work from the mockup through the Figma MCP: `get_design_context` on the linked node + for structure, values and names, plus `get_screenshot`. Do **not** run `pnpm design:readout`. Map what you see to the repo's components and theme tokens yourself, with + `tools/design-readout/layout-conventions.md` for the settled layout questions. + +Every style leaf covers **all breakpoints**: the mobile node when the ticket links one, otherwise the +desktop layout adapted the way neighbouring views do. An item that is still with the designer is a +`Blocked by Q<NN>` edge on the ticket and nothing else — the leaf leaves no marker in the code for it. + ## Step 4 — Verify Run every code-quality check the repo defines (per `.agents/rules/code-quality.md`) plus the relevant unit tests. Intentional scaffold `TODO`s may keep ESLint red the way the `add-new-page` skill documents — -say so explicitly rather than chasing green. Then walk the ticket's **acceptance criteria** and confirm each - agent-checkable one holds. A `(human)` criterion is not yours to judge — it is a touchpoint Step 5 stops for. +say so explicitly rather than chasing green. Then walk the ticket's **acceptance criteria** and confirm each +agent-checkable one holds. A `(human)` criterion is not yours to judge — it is a touchpoint Step 5 stops for. +When the ticket's **How to verify** line names a `pnpm dev:preset` alias and a route, open that route on the +dev server through the Playwright MCP, at a desktop and a mobile width, and look at what you built. A defect you can see +is yours to fix before the hand-off; what to probe follows from the leaf. The `(human)` criteria stay the +developer's — this pass is your own check, not their sign-off. ## Step 5 — Close Key the close to whether the ticket has any **human touchpoint** — a `[human]` leaf, or a `(human)` acceptance criterion: -- **No touchpoint** → fully autonomous. Check the ticket's box in `progress.md`, then **commit** — the box - tick folded into the commit so the worktree is clean after. A plain descriptive subject, the repo's - `Co-Authored-By` trailer, and **no** `#issue` reference (the PR's `Resolves #N` already links it; a commit - that names the issue spams its timeline). Done. -- **Any touchpoint** → stop and hand off. Stop at the first **unchecked** `[human]` leaf; or, when the - leaves are all `[agent]` but a `(human)` criterion remains, after implementing them and **before** - committing. Say what the developer must do, link the Figma node, and point at the scaffold's - `TODO (design):` markers. The developer does the work; for a `[human]` leaf they check its box and ask - the session to continue — it resumes from the next unchecked leaf (Step 3), never by re-invoking the - skill. Once every leaf is done, the developer commits and checks the `progress.md` box at their commit. +- **No open touchpoint** — no unchecked `[human]` leaf, and no `(human)` criterion the developer has not + yet confirmed → commit (Step 7). Done. A ticket with no touchpoint at all lands here on its first run; a + ticket whose touchpoints are all `[human]` leaves lands here once the last one is checked. +- **An open touchpoint** → stop and hand off. Stop at the first **unchecked** `[human]` leaf; or, when no + unchecked `[human]` leaf remains but an unconfirmed `(human)` criterion does, after implementing the + leaves and **before** committing. **Stage** the work (`git add -A`, then `git reset -- '*/inbox.md'`: + an `inbox.md` that appeared mid-run belongs to `process-task-inbox`, not to the ticket) and stop — nothing is committed or stashed. From + here the index is the agent's work and the working tree on top of it is the developer's: their fixes stay + **unstaged**, so `git diff` reads back exactly what they changed. When the developer reports a bug during + the hand-off and the agent fixes it, the index must still hold only the agent's hunks afterwards. `git + add` cannot do that — it stages the whole file, developer hunks included — and no patch can be relied on + to lift them back out, because a fix next to a developer hunk breaks the patch's context. So the fix + goes into the index **by hand, beside the working tree**, per tracked file the agent edits: + + ```bash + mkdir -p "$(dirname <scratchpad>/index/<path>)" # the redirect below creates no parent directories + git show :<path> > <scratchpad>/index/<path> # the index copy — the agent's work, no developer hunks + # … make the same fix in <path> (working tree) and in <scratchpad>/index/<path> … + git update-index --cacheinfo "$(git ls-files --format='%(objectmode)' <path>),$(git hash-object -w <scratchpad>/index/<path>),<path>" + ``` + + Nothing is applied, so nothing can fail to apply: the index gains exactly the fix, the developer's + hunks stay in the working tree, and `git diff` still reads back only what they changed. A file the agent + creates for the fix has no developer hunks and is plain `git add <path>`. A modified path the agent + did not touch is a developer fix and is never staged. + + Say what the developer does next, keyed to where the run stopped: + + - **At a `[human]` leaf** → **verify** in the running app and **fix** by hand, leaving the fixes + unstaged; then check the leaf's box and ask the session to continue — it resumes from the next + unchecked leaf (Step 3), never by re-invoking the skill. + - **At the `(human)` criteria, on a ticket with a style leaf** (one linking a Figma node) → **verify** + against the linked node at every breakpoint, **fix** by hand leaving the fixes unstaged, then say + **"record my corrections"** (Step 6). + - **At the `(human)` criteria, no style leaf** → **verify** and **fix** the same way, then confirm the + criteria and ask the session to commit (Step 7). + + The stopping turn ends at its bullet. + +## Step 6 — Record corrections + +Entered when the developer says **"record my corrections"** after a hand-off on a ticket with a style +leaf. Spawn a **subagent** with [`record-corrections.md`](record-corrections.md) as its brief and the +leaf's Figma node URL; when the leaf had a readout, point it at the node's block and +sidecar too. The subagent reads the developer's unstaged fixes back as gap-log lines, confirms the batch +with the developer and records it; it edits no source file. After the batch, commit (Step 7). + +## Step 7 — Commit + +Check the ticket's box in `progress.md`, then **commit** the entire body of work — the box tick folded +into the commit so the worktree is clean after, except an `inbox.md` written mid-run, which stays +uncommitted for `process-task-inbox`. A plain descriptive subject, the repo's `Co-Authored-By` +trailer, and **no** `#issue` reference (the PR's `Resolves #N` already links it; a commit that names the +issue spams its timeline). diff --git a/.agents/skills/implement-ticket/record-corrections.md b/.agents/skills/implement-ticket/record-corrections.md new file mode 100644 index 00000000000..448f7b43917 --- /dev/null +++ b/.agents/skills/implement-ticket/record-corrections.md @@ -0,0 +1,31 @@ +# Record corrections — subagent brief + +You read back the developer's own fixes to an agent's markup and turn them into gap-log lines. The +developer's edits are the correction; you propose how to record them, never what they should have been. +You are given the **Figma node URL** of the style leaf and, when the leaf had one, the node's block in +the task folder's `design-readout.md` and its sidecar under `.ai/design-readout/` in the main checkout (`tools/design-readout/CONTEXT.md` says what is in it). + +## Steps + +1. **Read the diff**: `git diff` — the working tree against the index, which holds exactly what the + agent staged at the hand-off, so every hunk is a developer fix. +2. **Map each hunk** to a sidecar node from the readout block and the sidecar's values (text, fills, + box). A hunk that pins to one node is a **miss** when the tool read the node wrong and a + **deliberate style** when the tool read it right; a hunk no node explains stays unmapped. An + uncertain mapping is a note, never a guessed correction. A leaf that had no readout has no sidecar + to map to, so every one of its corrections is a note. +3. **Propose one line per correction**, as the command that records it: + - a mapped miss → `pnpm design:readout "<url>" --correct <nodeId> <component> [<props…>] --gap <category> --stage markup`; + - a mapped deliberate style → `pnpm design:readout "<url>" --override <nodeId> <prop=value…>` (no gap line); + - anything else → `pnpm design:readout "<url>" --note "<what the developer changed>" --gap <category>`, + `markup` when no other category names the kind of miss. The tool needs no sidecar for a note. +4. **Confirm the batch** with the developer — the whole list, once — then run the confirmed commands. + The tool appends the lines to the gap log and the sidecar. + +## Rules + +- **Edit no source file.** The fixes are already in the working tree; your output is gap-log lines. +- **One line per correction, in the developer's terms.** A note quotes what changed, not why you think + it changed. +- **Never guess a node.** `--correct` and `--override` name a node the sidecar holds and the hunk + plainly matches; anything less is a `--note`. diff --git a/.agents/skills/prepare-release/SKILL.md b/.agents/skills/prepare-release/SKILL.md deleted file mode 100644 index 94f168814fc..00000000000 --- a/.agents/skills/prepare-release/SKILL.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -name: prepare-release -description: Prepare the next release of the application (tag, docs, release notes), then publish the pre-release and request a staging roll-up -disable-model-invocation: true ---- -# Prepare Release - -## Prerequisites: GitHub CLI - -This workflow uses `gh` to fetch releases, compare branches, and draft release notes via the GitHub API. **Follow the check-github-cli skill** first (ensure `gh auth status` succeeds; if not, guide the user to install/configure `gh` and do not proceed). The account needs read access to the repo and, if you publish or draft releases, appropriate write access. - -## Overview - -Prepare the next release of the application. - -## Steps - -### 1. Get the next release tag name - -- Fetch the latest release from GitHub: `gh release list --limit 1` (or `gh release view` for the latest). Retrieve its tag name (e.g. `v1.2.3`). -- **If the user did not specify which version bump to use:** Compute the next **minor** version per [semantic versioning](https://semver.org) (e.g. `v1.2.3` → `v1.3.0`). -- **If the user specified major or patch:** Compute the next **major** (e.g. `v2.0.0`) or **patch** (e.g. `v1.2.4`) version accordingly. -- Use this tag (e.g. `v1.3.0`) as the release tag for all following steps. - -### 2. Update `./docs/ENVS.md` and `./docs/DEPRECATED_ENVS.md` - -- In both files, replace every placeholder that contains the text "upcoming" with the next release tag followed by a "+". Examples: - - `"upcoming"` → `"v1.3.0+"` - - `"<upcoming>"` → `"v1.3.0+"` -- You can use search-and-replace in the editor or a script (e.g. `sed -i '' 's/upcoming/v1.3.0+/g' ./docs/ENVS.md` and similarly for `DEPRECATED_ENVS.md`; adjust for `<upcoming>` if present). Ensure all such placeholders are updated. - -### 3. Create release notes - -Perform the following sub-steps **in order**. - -- **Reference files:** Use `./RELEASE_NOTES.md` as the template and, for format inspiration, this [example release](https://github.com/blockscout/frontend/releases/tag/v2.3.0). -- **Get release notes draft:** Use the GitHub API to generate draft release notes with main as the target (e.g. `gh api repos/OWNER/REPO/releases/generate-notes -f tag_name=<next-tag> -f target_commitish=main -f previous_tag_name=<latest-release-tag>`). Parse the response to get the list of pull request **numbers** and new contributors. Keep this list; every PR in it must appear in the final notes. -- **Fetch and store PR data (labels and descriptions):** Before editing the release notes file, fetch labels and body for all PRs from the draft **once** and save them to a temporary file so later steps do not hit the GitHub API repeatedly. Use the script that rate-limits requests (authenticated API limit is 5000 requests/hour; the script adds a delay between calls). - - From the **repository root**, run: `node .agents/skills/prepare-release/fetch-release-prs.js <pr-number-1> <pr-number-2> ... --out release-prs-data.json` with every PR number from the release notes draft. Example: `node .agents/skills/prepare-release/fetch-release-prs.js 2725 2726 2727 --out release-prs-data.json`. - - The script writes JSON to `release-prs-data.json` in the repository root (format: `{ "prs": [ { "number", "title", "author", "url", "labels", "body" }, ... ] }`). Use this file as the **single source of truth** for labels and descriptions in the next two steps; do not call the GitHub API again when mapping sections or writing the ENV section. -- **Copy and fill the notes file:** Copy `./RELEASE_NOTES.md` to a new file `./RELEASE_NOTES_<release-tag>.md` (e.g. `RELEASE_NOTES_v1.3.0.md`). -- **Map PRs to sections:** For each section in the new file **except** "Changes in ENV variables", add the relevant pull requests. **Use only the data in `release-prs-data.json`** (labels, title, author, url) — do not call the GitHub API again. For each line use the format: `- <pull-request-title> by @<author> in <link-to-pull-request>`. Example: `- API documentation page by @tom2drum in https://github.com/blockscout/frontend/pull/2725`. Capitalize the first letter of the PR title if needed. Assign PRs to sections using each PR’s **labels** from the stored file and this mapping: - - | Section | Labels | - | ------------------------- | ------------------------------------------- | - | New Features | feature, enhancement, client feature | - | Bug Fixes | bug | - | Performance Improvements | performance | - | Dependencies updates | dependencies | - | Design updates | design | - | DX & tooling | refactoring | - -If a PR has no matching labels, try to categorize it based on its description (the **body** field in the `release-prs-data.json` file). If the section remains unclear, categorize it as "Other Changes." Never exclude a PR from the notes. The list of PRs in the release notes must match exactly the list from "Get release notes draft." Always double-check this. - -- **"Changes in ENV variables" section:** - - From `release-prs-data.json`, find all PRs whose **labels** include `"ENVs"` (or `ENVs`). Use their **body** field as the PR description. - - For each of those PRs, strip the "Checklist for PR Author" part from the body if present. Then, summarize the changes to the ENV variables and rephrase them if necessary. If you are unable to determine the changes or are unsure, use the placeholder: "Cannot find any changes in ENVs in PR description." - - Write the section in this form (grouped by PR number): - ``` - - <pull-request-number>: - - <change-1> - - <change-2> - ``` - - Examples: - - #3005 - - Added `NEXT_PUBLIC_AD_BANNER_ENABLE_SPECIFY` to enable the Specify ad provider for users with a connected wallet. - - Removed the `hype` option from the `NEXT_PUBLIC_AD_BANNER_PROVIDER` variable values. - - #2968 - - Added `NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_METRICS` to display information on the uptime dashboard page. - -- **"Compatibility" section:** - - List only the API versions this release *raises* — the diff, not the full set of services the app needs. - A service whose required version is unchanged from before is not mentioned. - - From `release-prs-data.json`, read each PR body's **Minimum API version** section. For every service a PR - names, add a row at the **highest** version among all PRs that name it. Ignore PRs whose section says - "None" or that have no such section (PRs opened before it existed). - - Map the PR's service to a row: "Core API" → the **Blockscout API** row; a microservice → its - **`<name>` microservice API** row. - - If no PR names an API version, the section lists no services — leave the table empty. - -- **Final edits in the release notes file:** - - Update "Full list of the ENV variables" and "Full Changelog" with the correct version tags/links. - - Update the "New Contributors" section if the "Get release notes draft" response included new contributors. - -### 4. Verify with the user (stop and wait) - -The release notes draft and the doc changes are now prepared but **nothing has been committed or published**. Hand control back to the user for review: - -- Tell the user the path to the release notes draft (`./RELEASE_NOTES_<release-tag>.md`) so they can open and **manually edit** it. -- Show a `git diff` of the doc changes (`docs/ENVS.md` and `docs/DEPRECATED_ENVS.md`) so they can see exactly what changed and edit those files too if needed. -- Explicitly ask the user to reply once everything is in place. -- **Stop and wait.** Do not commit, tag, or push anything until the user confirms. -- After the user confirms, **re-read** `docs/ENVS.md`, `docs/DEPRECATED_ENVS.md`, and the release notes draft, since the user may have edited them. - -### 5. Commit and push the docs to `main` - -Once the user has confirmed: - -- Stage **only the changed files under `docs/`** (typically `docs/ENVS.md` and `docs/DEPRECATED_ENVS.md`). Stage them explicitly by path — **never** `git add -A`. -- **Do not commit** the release notes draft (`RELEASE_NOTES_<release-tag>.md`) or the temp artifact `release-prs-data.json` (the latter is gitignored anyway). -- Commit with the message `chore: prepare release <release-tag>` (e.g. `chore: prepare release v1.3.0`). -- Push **directly to `main`** (branch protection is off for the release author). If there were no doc changes to stage, skip the commit/push and continue. - -### 6. Create and publish the pre-release - -Publish a pre-release for the `-alpha` variant of the tag. This single command creates and pushes the `-alpha` tag, which fires the `pre-release.yml` workflow (it triggers on a pushed tag matching `v[0-9]+.[0-9]+.[0-9]+-[a-z]+*`). - -- Build the alpha tag by appending `-alpha` to the release tag: `<release-tag>-alpha` (e.g. `v1.3.0-alpha`). -- Run: - ``` - gh release create <release-tag>-alpha \ - --target main \ - --prerelease \ - --title "<release-tag>-alpha" \ - --notes-file ./RELEASE_NOTES_<release-tag>.md - ``` - - `--prerelease` is GitHub's "Pre-release" release label (the `prerelease` boolean) — it marks the release as non-production-ready. - - `--target main` makes the tag point at the latest `main` (the commit you just pushed). - - The notes body is the **draft you prepared** (named for the final `v…` tag, even though the published tag is the `-alpha` one). -- Capture the published release URL from the command output (or `gh release view <release-tag>-alpha --json url -q .url`) — you'll need it for the Slack message. - -### 7. Wait for the pre-release workflow to finish (background, auto-resume) - -The pushed `-alpha` tag triggers `pre-release.yml`, which builds and publishes a Docker image and usually takes **~30 minutes**. Do **not** block the session watching it in the foreground. - -- Find the run for the tag: - ``` - gh run list --workflow=pre-release.yml --limit 5 - ``` - Identify the run for the `-alpha` tag / the commit you just pushed and capture its `<run-id>`. -- Start a **background** watcher so the session stays interactive (the user can keep chatting; the harness re-invokes you when it exits): - ``` - gh run watch <run-id> --exit-status --interval 60 - ``` - Run this with `run_in_background: true`. `--exit-status` returns non-zero if the run fails. -- When the watcher exits: - - **Success (exit 0):** continue to step 8. - - **Failure (non-zero):** report which job failed with a link to the run (`gh run view <run-id> --web` URL), and **do not** post to Slack. Let the user decide how to proceed. -- **Fallback:** if the background watch dies early (e.g. a network drop over the long run), do a single `gh run view <run-id> --json status,conclusion` to determine the real state before deciding. - -### 8. Request a staging roll-up in Slack (draft, then send on approval) - -Once the pre-release workflow has finished **successfully**, ask the DevOps team to roll up the new pre-release on staging. - -- Build the message from `./slack-message-template.md` (in this skill directory) — it holds the format, the breaking-ENV-change rule, the target channel, and the QA cc. Fill it with the `-alpha` tag, the breaking-ENV list derived per that rule (or `None.`), and the pre-release URL from step 6. The breaking-ENV input comes from the "Changes in ENV variables" section / `release-prs-data.json`. -- **Draft first:** show the user the fully rendered message and **wait for their approval** before sending it to the channel. diff --git a/.agents/skills/prepare-release/fetch-release-prs.js b/.agents/skills/prepare-release/fetch-release-prs.js deleted file mode 100644 index 000689ea3f8..00000000000 --- a/.agents/skills/prepare-release/fetch-release-prs.js +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env node -/* eslint-disable no-console */ -/** - * Fetches labels and description (body) for a list of pull requests via the GitHub API, - * with rate limiting to avoid hitting API limits. Outputs JSON to a file for use when - * preparing release notes (mapping PRs to sections and building the ENV variables section). - * - * Prerequisites: GitHub CLI (gh) installed and authenticated. - * - * Usage: - * node fetch-release-prs.js <pr-number> [pr-number ...] [--out <path>] - * echo "2725 2726" | xargs node fetch-release-prs.js --out release-prs-data.json - * - * Output JSON shape (written to --out or stdout): - * { "prs": [ { "number", "title", "author", "url", "labels", "body" }, ... ] } - */ - -const { execSync } = require('child_process'); -const fs = require('fs'); -const path = require('path'); - -const DELAY_MS = 400; - -function getRepo() { - try { - return execSync('gh repo view --json nameWithOwner -q .nameWithOwner', { - encoding: 'utf-8', - }).trim(); - } catch { - return 'blockscout/frontend'; - } -} - -function fetchPr(ownerRepo, number) { - const [ owner, repo ] = ownerRepo.split('/'); - const out = execSync( - `gh api repos/${ owner }/${ repo }/issues/${ number } --jq '{number, title, user: .user.login, labels: [.labels[].name], body}'`, - { encoding: 'utf-8', maxBuffer: 2 * 1024 * 1024 }, - ); - const data = JSON.parse(out); - return { - number: data.number, - title: data.title, - author: data.user, - url: `https://github.com/${ ownerRepo }/pull/${ data.number }`, - labels: data.labels || [], - body: data.body || '', - }; -} - -function sleep(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -async function main() { - const args = process.argv.slice(2); - let outPath = null; - const prNumbers = []; - - for (let i = 0; i < args.length; i++) { - if (args[i] === '--out' && args[i + 1]) { - outPath = args[i + 1]; - i += 1; - } else if (/^\d+$/.test(args[i])) { - prNumbers.push(Number(args[i], 10)); - } - } - - if (prNumbers.length === 0) { - console.error('Usage: node fetch-release-prs.js <pr-number> [pr-number ...] [--out <path>]'); - process.exit(1); - } - - const ownerRepo = getRepo(); - const prs = []; - - for (let i = 0; i < prNumbers.length; i++) { - const num = prNumbers[i]; - try { - prs.push(fetchPr(ownerRepo, num)); - if (i < prNumbers.length - 1) { - await sleep(DELAY_MS); - } - } catch (err) { - console.error(`Failed to fetch PR #${ num }:`, err.message); - process.exit(1); - } - } - - const result = { prs }; - const json = JSON.stringify(result, null, 2); - - if (outPath) { - fs.writeFileSync(outPath, json, 'utf-8'); - console.error(`Wrote ${ prs.length } PR(s) to ${ path.resolve(outPath) }`); - } else { - console.log(json); - } -} - -main(); diff --git a/.agents/skills/prepare-release/slack-message-template.md b/.agents/skills/prepare-release/slack-message-template.md deleted file mode 100644 index 69ad65bb9c3..00000000000 --- a/.agents/skills/prepare-release/slack-message-template.md +++ /dev/null @@ -1,73 +0,0 @@ -# Slack message template — staging roll-up request - -Used in the final step of the `prepare-release` skill to ask the DevOps team to roll up -a freshly published **frontend** pre-release on the staging instances. - -- **Channel:** the DevOps *requests* channel — resolve its ID from `.agents/TEAM.md` (DevOps → Channels, - `blockscout-devops-requests`). -- **QA cc:** the QA team user group — resolve its group ID from `.agents/TEAM.md` (QA → Groups) and build the - mention token `<!subteam^<group-id>>`. -- **Always draft first** and get the user's approval before sending. - -Slack IDs are **not** duplicated here on purpose — `.agents/TEAM.md` is the single source of truth for every -channel and group ID, so a moved channel or renamed group is fixed in one place. - -## Placeholders - -| Placeholder | Meaning | -| ------------------------ | ----------------------------------------------------------------------- | -| `<alpha-tag>` | The pre-release tag, e.g. `v1.3.0-alpha`. | -| `<breaking-env-changes>` | Bulleted list of breaking ENV changes, or the single line `None.` | -| `<release-url>` | Link to the published GitHub pre-release. | -| `<qa-group-mention>` | QA team group mention token `<!subteam^<group-id>>`, built from `.agents/TEAM.md`. | - -A change is **breaking** if a deployment must change its config to keep working: a -**removed** variable, a **renamed** variable, or a change to a **required**/default value -or **allowed value set**. New optional variables are *not* breaking. When in doubt, list it -and mark it `(potentially breaking)` — better to over-report than to miss one. - -## Template - -``` -📦 Frontend pre-release *`<alpha-tag>`* is ready for staging. - -Could you please roll up this pre-release tag on the staging instances? - -*Breaking ENV changes:* -<breaking-env-changes> - -Release notes: <release-url> - -cc <qa-group-mention> -``` - -### Example — with breaking changes - -``` -📦 Frontend pre-release *`v1.3.0-alpha`* is ready for staging. - -Could you please roll up this pre-release tag on the staging instances? - -*Breaking ENV changes:* -• Removed `NEXT_PUBLIC_FOO` — the X feature now reads from `NEXT_PUBLIC_BAR` instead. -• Renamed `NEXT_PUBLIC_OLD` → `NEXT_PUBLIC_NEW`. -• `NEXT_PUBLIC_AD_BANNER_PROVIDER`: removed the `hype` option (potentially breaking). - -Release notes: https://github.com/blockscout/frontend/releases/tag/v1.3.0-alpha - -cc <qa-group-mention> -``` - -### Example — no breaking changes - -``` -📦 Frontend pre-release *`v1.3.0-alpha`* is ready for staging. - -Could you please roll up this pre-release tag on the staging instances? - -*Breaking ENV changes:* None. - -Release notes: https://github.com/blockscout/frontend/releases/tag/v1.3.0-alpha - -cc <qa-group-mention> -``` diff --git a/.agents/skills/process-task-inbox/SKILL.md b/.agents/skills/process-task-inbox/SKILL.md new file mode 100644 index 00000000000..e9a7e9e4d12 --- /dev/null +++ b/.agents/skills/process-task-inbox/SKILL.md @@ -0,0 +1,58 @@ +--- +name: process-task-inbox +description: >- + Fold the pending sections of the task's inbox.md into its questions, spec and tickets. +disable-model-invocation: true +--- + +# Process task inbox + +A task's `inbox.md` holds decisions that arrived from outside any session: a weekly, a thread, a document +(what the file is and who writes it is in [`../../tasks/structure.md`](../../tasks/structure.md)). Each +pending section is context the task has not absorbed yet. This skill decides, with the developer, what +every decision does to the task files, applies it, and marks the section folded. `to-tickets`, +`implement-ticket` and `finalize-task` refuse to start while a section is pending, so this is the way +back into the task. + +No arguments; runs on the checked-out feature branch. + +## 1. Load + +Resolve the task folder from the branch (`issue-<number>`). Read `inbox.md`, `spec.md`, `questions.md`, +`progress.md` and every `tickets/NN-<slug>/spec.md` and `brief.md`. Collect the sections whose status is +`pending`, oldest first. No pending section, or no `inbox.md` at all, is a stop: say the inbox is clean +and end. + +**Done when:** every pending section's decisions are in hand, with the task's current questions and tickets. + +## 2. The plan + +For every decision in every pending section, propose exactly one **disposition**: + +- **resolve Q<NN>** when an open question asks what the decision answers. Answer as a phrase plus date. + The Slack line stays as it is, a permalink or `—`; the link into the source lives in the inbox section. +- **add Q<NN>** when the decision needs something nobody in the task holds yet (a mockup, a backend + field). Next free id, owner from the spec header, status `pending`, Slack `—`. Posting it is the + developer's own step, if they post it at all. +- **edit spec** when a Functional Requirement, the UI inventory or Out of scope now says something else. + This is the rare in-place requirement change `.agents/tasks/concepts.md` allows; show the exact sentence + before and after. +- **edit ticket** when an unfrozen ticket's What to build, acceptance criteria or leaves change. A frozen + ticket (every leaf checked) is never edited; the change goes to a `brief`. +- **brief** when the decision is new work. `tickets/NN-<slug>/brief.md` with the next free `NN`, and its + line in `progress.md`; a later `to-tickets` run scopes it the way it scopes any deferred ticket. +- **no-op** when the task already does what the decision says. Say which FR or ticket covers it. + +Show the dispositions as one table (section, decision, disposition, text) and wait for the developer. +**This is the run's one gate.** + +**Done when:** the developer has approved every row. + +## 3. Apply + +Make every approved edit. Then set each processed section's status to `folded`. Commit on the feature +branch with a pathspec of the task files this run changed, `inbox.md` first among them: the index may +already hold a ticket's staged hand-off, and that stays out of this commit. A plain subject naming the +source, the repo's `Co-Authored-By` trailer. + +**Done when:** no section is `pending` and the commit holds exactly the folded files. diff --git a/.agents/skills/release/SKILL.md b/.agents/skills/release/SKILL.md new file mode 100644 index 00000000000..f8f2d582289 --- /dev/null +++ b/.agents/skills/release/SKILL.md @@ -0,0 +1,80 @@ +--- +name: release +description: Run one phase of a release — prepare, alpha or publish — through the release CLI, stopping at the operator's checkpoints +disable-model-invocation: true +argument-hint: prepare <vX.Y.Z> | alpha <vX.Y.Z-alpha.N> | publish <vX.Y.Z> +--- +# Release + +`/release prepare vX.Y.Z` · `/release alpha vX.Y.Z-alpha.N` · `/release publish vX.Y.Z` + +Which phase to run, and the release model behind it, is `docs/RELEASING.md`; what a phase does is +`pnpm release --help`. This skill adds only the points where the operator decides. One run is one phase; +the operator invokes the next phase when they are ready for it. + +## Prerequisites + +- **Follow the `check-github-cli` skill** first; the CLI uses the operator's `gh` auth to read and write + releases. +- A clean working tree on the operator's checkout: `prepare` and `alpha` switch it to the release branch, + `publish` also to `main`. The CLI refuses a dirty tree. + +Every phase command is a long foreground process: `alpha` and `publish` end by watching a CI run of about +30 minutes. Run them with `run_in_background: true` and report when they exit; the operator keeps the +session. + +## A pick conflict — `prepare` and `alpha` + +Both phases cherry-pick the `backport` PRs onto the release branch and stop at the first conflict, with the +cherry-pick left in progress and the files named in the error. + +1. Show the conflict: the PR, the files, the conflicting hunks. +2. Resolve it, with a one-line reason per file (a modify/delete conflict is usually a refactoring on `main` + touching a file the branch lacks, resolved by dropping the file). +3. Show the resolved diff (`git diff` of the staged resolution) and **wait for the operator's approval**. +4. After approval only: `git cherry-pick --continue`, then **re-run the same command**, which resumes + after this pick. + +The CLI pushes; the agent never pushes a release branch, a tag or `main` by hand. + +## `prepare vX.Y.Z` + +Run `pnpm release prepare vX.Y.Z`. When it exits, hand off; the next phase is the operator's to invoke: + +- The draft pre-release URL from the command's output, to review the notes on GitHub. A wrong line is + fixed at its source — the merged PR's title, category labels or body — which the next phase regenerates + the notes from. An edit made on the release page is overwritten by the next phase. +- The docs diff: `git diff <start>..HEAD -- docs/`, `<start>` being the cut point the command printed + (`origin/main` for a minor, the previous final tag for a patch). +- The PRs the command skipped, from its report, in case one was expected in the release. + +## `alpha vX.Y.Z-alpha.N` + +Before running, the operator has reviewed the pre-release notes and the docs diff of `prepare` (or of the +previous alpha). The first alpha publishes the pre-release, so from then on its page is public and its +notes are no longer a draft to review. Run `pnpm release alpha vX.Y.Z-alpha.N` in the background. When it +exits: + +- **Tag check failed** — nothing was tagged or pushed. Report the failures; they are the operator's to fix + on `main` (a PR with the `backport` label, picked by the next run) or on the release branch (docs only). +- **CI run failed** — report the failing job with the run URL and stop. No Slack message. +- **Passed** — request the staging roll-up in Slack, from `./slack-message-template.md` in this directory: + the alpha tag, the pre-release URL from the command's output, and the breaking-ENV list derived per the + template's rule from the "Changes in ENV variables" section of the notes (`pnpm release notes + vX.Y.Z-alpha.N`, or the release page). **Draft first**, show the rendered message and send only once the + operator approves it. + +## `publish vX.Y.Z` + +The operator invokes it once QA has approved the staging build; the branch head must be the latest alpha. +Run `pnpm release publish vX.Y.Z` in the background. + +- A docs cherry-pick onto `main` can conflict; it is the same stop as a pick conflict above — approve the + resolved diff, `git cherry-pick --continue`, re-run the same command, which skips the tag and the release + already on GitHub. +- When it exits, report the release URL and the CI run; on a failed run, the failing job with its URL. + +## A hotfix + +The same three phases with `Z > 0`; where the branch is cut from, and how a fix found on staging reaches +the open release, is the decision table in `docs/RELEASING.md`. diff --git a/.agents/skills/release/slack-message-template.md b/.agents/skills/release/slack-message-template.md new file mode 100644 index 00000000000..2dff5473cad --- /dev/null +++ b/.agents/skills/release/slack-message-template.md @@ -0,0 +1,74 @@ +# Slack message template — staging roll-up request + +Used by the `alpha` phase of the `release` skill to ask the DevOps team to roll up a freshly +published **frontend** pre-release on the staging instances. + +- **Channel:** the DevOps *requests* channel — resolve its ID from `.agents/TEAM.md` (DevOps → Channels, + `blockscout-devops-requests`). +- **QA cc:** the QA team user group — resolve its group ID from `.agents/TEAM.md` (QA → Groups) and build the + mention token `<!subteam^<group-id>>`. +- **Always draft first** and get the user's approval before sending. + +Slack IDs are **not** duplicated here on purpose — `.agents/TEAM.md` is the single source of truth for every +channel and group ID, so a moved channel or renamed group is fixed in one place. + +## Placeholders + +| Placeholder | Meaning | +| ------------------------ | ----------------------------------------------------------------------- | +| `<alpha-tag>` | The pre-release tag, e.g. `v1.3.0-alpha.1`. | +| `<breaking-env-changes>` | Bulleted list of breaking ENV changes, or the single line `Отсутствуют.` | +| `<release-url>` | Link to the published GitHub pre-release. | +| `<qa-group-mention>` | QA team group mention token `<!subteam^<group-id>>`, built from `.agents/TEAM.md`. | + +The input is the "Changes in ENV variables" section of the release notes (`pnpm release notes <alpha-tag>`), +one entry per PR as its author wrote it. A change is **breaking** if a deployment must change its config +to keep working: a **removed** variable, a **renamed** variable, or a change to a **required**/default value +or **allowed value set**. New optional variables are *not* breaking. When in doubt, list it +and mark it `(возможно, ломающее)` — better to over-report than to miss one. + +## Template + +``` +📦 Пре-релиз фронтенда *`<alpha-tag>`* готов для стейджинга. + +Раскатите, пожалуйста, этот тег на стейджинг-инстансы. + +*Ломающие изменения ENV:* +<breaking-env-changes> + +Содержание релиза: <release-url> + +cc <qa-group-mention> +``` + +### Example — with breaking changes + +``` +📦 Пре-релиз фронтенда *`v1.3.0-alpha.1`* готов для стейджинга. + +Раскатите, пожалуйста, этот тег на стейджинг-инстансы. + +*Ломающие изменения ENV:* +• Удалена `NEXT_PUBLIC_FOO` — фича X теперь читает `NEXT_PUBLIC_BAR`. +• Переименована `NEXT_PUBLIC_OLD` → `NEXT_PUBLIC_NEW`. +• `NEXT_PUBLIC_AD_BANNER_PROVIDER`: удалено значение `hype` (возможно, ломающее). + +Содержание релиза: https://github.com/blockscout/frontend/releases/tag/v1.3.0-alpha.1 + +cc <qa-group-mention> +``` + +### Example — no breaking changes + +``` +📦 Пре-релиз фронтенда *`v1.3.0-alpha.1`* готов для стейджинга. + +Раскатите, пожалуйста, этот тег на стейджинг-инстансы. + +*Ломающие изменения ENV:* Отсутствуют. + +Содержание релиза: https://github.com/blockscout/frontend/releases/tag/v1.3.0-alpha.1 + +cc <qa-group-mention> +``` diff --git a/.agents/skills/resolve-config-request/SKILL.md b/.agents/skills/resolve-config-request/SKILL.md index 857e42012ed..985323b8184 100644 --- a/.agents/skills/resolve-config-request/SKILL.md +++ b/.agents/skills/resolve-config-request/SKILL.md @@ -13,15 +13,13 @@ Convert **intent → variables**. The request already carries the intent; this s Only send a DevOps message we are **sure** of. Every other rule serves that. - **Stop** on ambiguity. If the variable cannot be pinned, or the value is not in the documented set of allowed values, stop and tell the user. -- **The user is the face.** Uncertainty and clarifying questions go to the user. Requester-facing posts are only the handover reply after an approved send, and the demo link on the skin branch. +- **The user is the face.** Uncertainty and clarifying questions go to the user. Requester-facing posts are only the handover reply after the send, and the demo link on the skin branch. - **Intent is given.** Any question that turns on what someone *wants* is a stop, not a judgement call. - **Operator.** `docs/ENVS.md` is the manual. The docs pin legal values, not the consumers. A value the docs cannot pin is a documentation gap, fixed as documentation. - **Off.** Prefer a documented off-value over unsetting. Unset only when the docs show the default *is* the desired state. - **Mirror** the requester's targeting language. Unstated is not undeterminable — the DevOps bot resolves instances. - **Drift.** `NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG` and `NEXT_PUBLIC_COLOR_THEME_OVERRIDES` ship with a `frontend-configs` file change in the same run; take the skin branch. -No commit without the user's explicit confirmation in this conversation — the one exception is the skin branch's phase 1, which runs unattended up to the demo link. - ## Scope **In:** variables in `docs/ENVS.md`, including start-time ones such as `FAVICON_MASTER_URL`. @@ -30,7 +28,8 @@ No commit without the user's explicit confirmation in this conversation — the - **Not configurable** — needs a code change. Stop and offer the `create-issue` skill. The channel carries these; they look like ordinary requests. - **Retired variable named** — read `docs/DEPRECATED_ENVS.md` and propose the replacement. -- **Outside the frontend, or mixed with a non-configurable ask** — do the configurable frontend part only, and tell the user what was left out. +- **Outside the frontend** — nothing here to configure. Stop and tell the user. +- **Mixed with a non-configurable ask** — not an exit: do the configurable frontend part, and tell the user what was left out. - **CDN-only trees** in `frontend-configs` with no `docs/ENVS.md` variable (`multisearch/`, `token-icons/`, `nft-images/`, `explorer-logos/`, `meta-suites-logos/`) — stop and tell the user. ## Steps @@ -67,13 +66,13 @@ Run the startup validator against the live env plus our change, before drafting. ### 5. Draft the DevOps message -Compose it per **The DevOps message** below. Show it to the user and wait. +Compose it per **The DevOps message** below. Show it to the user and wait (run by Honk: no wait — go straight to step 6). -**Done when:** the user has approved the exact text. +**Done when:** the user has approved the exact text (run by Honk: the text is final and step 6 runs). ### 6. Send, then hand over -Post the approved message to `blockscout-devops-requests` — resolve the channel ID from `.agents/TEAM.md`. Then reply in the original thread — same language as the thread — with a link to that message, saying the request has been handed over and is waiting on DevOps. +Post the approved message to `blockscout-devops-requests` — resolve the channel ID from `.agents/TEAM.md`. Then reply in the original thread with a link to that message, saying the request has been handed over and is waiting on DevOps. **Done when:** both posts exist and the original-thread reply carries the DevOps link. @@ -100,13 +99,14 @@ cp /tmp/instance.env /tmp/instance.validate.env jq -r '.localEnvs | to_entries[] | "\(.key)=\(.value)"' tools/dev-server/envs-rules.json >> /tmp/instance.validate.env ``` -From `deploy/tools/envs-validator/`, the preamble in `test.sh` (collect placeholders, copy `test/assets`, build), then: +From `deploy/tools/envs-validator/`, prepare as in its `CONTEXT.md` ("Validating a real instance config by hand"), with the same overlay on the asset download so a changed or new config URL is the one validated: ```bash +pnpm exec dotenv -e /tmp/change.env -e /tmp/instance.validate.env -- ../../scripts/download_assets.sh ./public/assets/configs pnpm exec dotenv -e /tmp/change.env -e /tmp/instance.validate.env -- pnpm run validate ``` -Schema organisation: `deploy/tools/envs-validator/CONTEXT.md`. This is what catches missing companion variables (`.when(...)`), forbidden combinations, and malformed nested JSON — a documentation check cannot. +Schema organisation: `deploy/tools/envs-validator/CONTEXT.md`. This is what catches missing companion variables, forbidden combinations, and malformed nested JSON — a documentation check cannot. ## Fetched configs @@ -114,7 +114,7 @@ JSON the instance **fetches** at startup — not instance chrome, no demo. Checkout: a workspace folder named `frontend-configs` or `blockscout_frontend_configs`. If none, stop and ask the user to add it. -Follow the `check-github-cli` skill. Confirm with the user before the commit and the PR — this PR is merged to `main`, where live instances fetch from. (Skin phase 1 is the exception: its PR stays unmerged for review, so it needs no confirmation.) The `create-pr` skill's frontend template, ENVs label, and issue-from-branch steps do not apply. +Follow the `check-github-cli` skill. Commit and open the PR without asking; confirm with the user before the **merge to `main`** — that is where live instances fetch from. (Run by Honk: no confirmation, see below.) The `create-pr` skill's frontend template, ENVs label, and issue-from-branch steps do not apply. | Directory | Variable | | --- | --- | @@ -126,11 +126,31 @@ Follow the `check-github-cli` skill. Confirm with the user before the commit and Hosted icons for **inlined** lists (the env holds the JSON; the file is the URL inside it): `configs/ide-icons/` → `NEXT_PUBLIC_CONTRACT_CODE_IDES`; `configs/nft-marketplace-logos/` → `NEXT_PUBLIC_VIEWS_NFT_MARKETPLACES`; `configs/multichain-balance/` → `NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG`. +Merge PR with exactly this form: + +```bash +gh pr merge -R blockscout/frontend-configs <number> --merge --delete-branch +``` + After merge to `main`, confirm each raw URL returns 200. If the instance already has that URL, the DevOps ask is a restart to re-fetch — no new `KEY=value`. If the URL is new, or the value is inlined, it goes in the block as usual. +## Run by Honk + +When the Honk orchestrator runs this skill headless, follow [`honk.md`](../../honk.md). This skill's statuses: + +| Status | When | Resumed? | +| --- | --- | --- | +| `needs_user` | a stop that needs an answer — ambiguity, intent, missing `frontend-configs` checkout, Figma unreachable; the message carries the question | yes, with the answer | +| `needs_approval` | the next step needs a tool the worker profile denies (a merge, a DevOps post); the message carries what would be done and the exact draft | yes, once a human did it or allowed it | +| `awaiting_designer` | skin phase 1 ended on `slack-subscribe`; the designer's reply resumes the run | yes, with the reply | +| `handed_over` | DevOps message sent and the source thread replied to | no | +| `out_of_scope` | a **Scope** exit — not configurable, outside the frontend, CDN-only tree; the message carries that exit's text (the `create-issue` offer included) | no | + +A mixed ask and a retired variable are not exits: the run continues on the configurable part, and the leftover is noted in the final message. + ## The DevOps message -Russian, informal. Target in the requester's own words — not registry aliases. Sets in one fenced `KEY=value` block; keys to drop as names only. Mention the requester with `<@U…>` from the thread author's `user_id` (`.agents/TEAM.md` → How to address). +Informal. Target in the requester's own words — not registry aliases. Sets in one fenced `KEY=value` block; keys to drop as names only. Mention the requester with `<@U…>` from the thread author's `user_id` (`.agents/slack-message.md` → Addressing). ```` Привет! 🐈 diff --git a/.agents/skills/resolve-config-request/SKIN-REQUESTS.md b/.agents/skills/resolve-config-request/SKIN-REQUESTS.md index 5f45f1c26f2..0a6b0032cb1 100644 --- a/.agents/skills/resolve-config-request/SKIN-REQUESTS.md +++ b/.agents/skills/resolve-config-request/SKIN-REQUESTS.md @@ -45,7 +45,7 @@ While the configs PR is open, asset URLs are the **PR branch's** raw GitHub URLs ## Demo mechanics -`.env.extra` is committed and is the **only** channel that carries env overrides into a review deploy. An instance not in the registry: add it to `tools/dev-server/registry.json`, run `pnpm presets:sync` (writes `.github/workflows/deploy-review.yml` and `.vscode/tasks.json`), commit all four **on the demo branch**. They die with that branch. Procedure: `tools/dev-server/CONTEXT.md`. +The **repo-root** `.env.extra` is committed and is the **only** channel that carries env overrides into a review deploy. An instance not in the registry: add it to `tools/dev-server/registry.json`, run `pnpm presets:sync` (writes `.github/workflows/deploy-review.yml` and `.vscode/tasks.json`), commit all four **on the demo branch**. They die with that branch. Procedure: `tools/dev-server/CONTEXT.md`. Hostname: `review-<branch-slug>.k8s-dev.blockscout.com`. Follow the `deploy-demo` skill. @@ -53,28 +53,44 @@ Verify the theme by **computed values** — read the resolved CSS custom propert ## Phase 1 — demo -**Phase 1 runs to the demo link without stopping.** No gate — designer's or user's — on the branch, the commits, the configs PR, the demo deploy, or the demo-link post. The PR is open but unmerged and the demo dies with its branch, so nothing here can touch a production instance; the parent's commit confirmation does not apply. The demo *is* the review surface, and a confirmation asked before it exists is asked of someone who cannot yet see what they are confirming. +**Phase 1 runs to the demo link without stopping.** No gate — designer's or user's — on the branch, the commits, the configs PR, the demo deploy, or the demo-link post. The PR is open but unmerged and the demo dies with its branch, so nothing here can touch a production instance. The demo *is* the review surface, and a confirmation asked before it exists is asked of someone who cannot yet see what they are confirming. -The requester (designer) is the gatekeeper for phase 2; the user relays that approval. There is no automated watch on the thread — the user monitors and continues this session. +The requester (designer) is the gatekeeper for phase 2. Do not hand the session back to the user to monitor: **subscribe to the designer's replies on the source thread with the `slack-subscribe` skill** as the last action of phase 1, then stop. 1. Produce the assets and JSON configs from the thread and Figma. -2. Open a PR on `frontend-configs` (target `main` branch). No confirmation, per above; `create-pr` exceptions: parent **Fetched configs**. +2. Open a PR on `frontend-configs` (target `main` branch). `create-pr` exceptions: parent **Fetched configs**. 3. Point the demo at the PR-branch raw URLs (see **Demo mechanics**). Deploy it. -4. Verify on the live demo, post the demo link to the requester, and **stop**. Post it without asking — the named exception to `AGENTS.md`'s approve-before-sending rule. This is the run's only stop; what it waits for is the designer's reply. +4. Verify on the live demo, then post the demo link to the requester. Post it without asking — the named exception to `AGENTS.md`'s approve-before-sending rule. +5. Subscribe to the designer's replies on the source thread with `slack-subscribe`, then **stop**. This is the run's only stop; the forwarded reply is what resumes it — see **On the designer's reply**. Before stopping, state the branch, the PR link, and the demo URL in the session: a resumed run has only the transcript. -**Done when:** the configs PR is open, the demo is live, the requester has the link, and this run has stopped. +**Done when:** the configs PR is open, the demo is live, the requester has the link, the thread is subscribed, and this run has stopped (run by Honk: `STATUS: awaiting_designer`). + +## On the designer's reply + +The reply arrives as a cross-session message from Honk. Read it and act on it directly: + +- **Approval** (the designer signs off) → go to **Phase 2**. +- **Change request** → stay in phase 1: apply the asked changes using the same technique as for the initial request; redeploy the demo and re-post the refreshed demo link; then stop exactly as step 5 did — restate branch, PR, demo URL, `STATUS: awaiting_designer` under Honk, end the turn. The subscription stays; the next reply is a new turn. +- **A question, or anything turning on intent you cannot pin** → stop and ask the user (the *Sure* principle: intent questions go to the user, not the designer). + +Each reply is one turn; repeat until approval. The subscription is removed in phase 2. ## Phase 2 — ship -Starts only when the user relays the designer's approval. +Starts when the designer approves. -1. Merge the configs PR. Swap every branch URL to `main` and confirm each returns 200 — that is when instances can fetch them. -2. For inlined vars (hero banner, colour theme), regenerate the strings from the merged files (the converter above). URL vars (homepage highlights, asset URLs): the env value is the `main` raw URL. Navigation promo: the inlined string produced in phase 1. -3. Run the parent skill from **Read current state** through **Send, then hand over**. -4. **Teardown** — checkable, they fail silently when skipped: +1. Merge the configs PR using exactly this command: + ```bash + gh pr merge -R blockscout/frontend-configs <number> --merge --delete-branch + ``` +2. Swap every branch URL to `main` and confirm each returns 200 — that is when instances can fetch them. +3. For inlined vars (hero banner, colour theme), regenerate the strings from the merged files (the converter above). URL vars (homepage highlights, asset URLs): the env value is the `main` raw URL. Navigation promo: the inlined string produced in phase 1. +4. Run the parent skill from **Read current state** through **Send, then hand over**. +5. **Teardown** — checkable, they fail silently when skipped: - demo destroyed: `gh workflow run cleanup.yml --ref <branch>`; hostname returns 404 - temporary frontend branch deleted, local and remote - `git status` clean + - the source thread unsubscribed (`slack-subscribe --remove`) The review-image cleanup is broken ([frontend#3638](https://github.com/blockscout/frontend/issues/3638)); hostname 404 is the bar, not image deletion. diff --git a/.agents/skills/resolve-review/SKILL.md b/.agents/skills/resolve-review/SKILL.md index 6a4576fb572..e6a9ad50412 100644 --- a/.agents/skills/resolve-review/SKILL.md +++ b/.agents/skills/resolve-review/SKILL.md @@ -1,37 +1,80 @@ --- name: resolve-review description: >- - Close out review findings on a PR — adjudicate each one, fix what deserves fixing, then reply and resolve - the threads. + Close out review findings — adjudicate each one, fix what deserves fixing, then reply on the PR threads or + in the task's review file. +argument-hint: pr|md [<PR url | comment url | review file path>] [--auto] [--scope branch|uncommitted] [--ticket <NN>] disable-model-invocation: true --- # Resolve review -Work through a PR's review findings and close them out. The hard part is not fixing — it is deciding *which* -findings deserve a fix. So the centre of this skill is **adjudication**: every finding gets a **verdict**, -reached skeptically, by checking the claim against the real code and the project's intent rather than by -trusting how confidently it was worded. - -In the product-task workflow this runs at **land**, against the whole-task PR — it adjudicates the inline -comments `review-changes` posted, alongside any human or bot comments on the same PR. +Work through a change's review findings and close them out. The hard part is not fixing — it is deciding +*which* findings deserve a fix. So the centre of this skill is **adjudication**: every finding gets a +**verdict**, reached skeptically, by checking the claim against the real code and the project's intent +rather than by trusting how confidently it was worded. + +In the product-task workflow this runs at **land**, against the whole-task PR, and mid-ticket against the +review file `review-changes` wrote for uncommitted work. The `review-loop` skill dispatches it per round +with `--auto`, as a fresh subagent. + +## Inputs + +Mirrors `review-changes`: the same output, first and required, decides where the findings are read from and +replied to. + +| Input | Values | Default | Meaning | +| --- | --- | --- | --- | +| `output` *(positional)* | `pr` · `md` | **required** | where the findings live | +| `target` *(positional)* | PR url, comment url, or review-file path | the current branch's PR / its review file | scopes the run | +| `--auto` | flag | off | autonomous gating: no Gate 1, no Gate 2, the run commits and pushes (or leaves the push to a caller that says it pushes); the only stop is `needs-human`. `pr` only | +| `--scope` | `branch` · `uncommitted` | `branch` | which review file: the task's, or the in-flight ticket's. `md` only | +| `--ticket <NN>` | ticket number | inferred | `--scope uncommitted` only | + +``` +/resolve-review pr every open finding on the current branch's PR +/resolve-review pr --auto the same, unattended — one round of the review loop +/resolve-review pr <comment url> that single comment, scoping the whole run to it +/resolve-review md the task-level review file +/resolve-review md --scope uncommitted the in-flight ticket's review file +/resolve-review md <path> that review file — one reviewer's, where several ran +``` + +Contradictory inputs stop the run: `--scope` or `--ticket` with `pr`, `--ticket` with `--scope branch`, or +`--auto` with `md`. + +`--scope` and `--ticket` are `review-changes`' own, and the file resolves off them exactly as it does there +([`../review-changes/output-md.md`](../review-changes/output-md.md)) — `branch` is the task-level +`review.md`, `uncommitted` the ticket's. An explicit `target` path settles the file outright and makes both +redundant. Several review files side by side means several reviewers ran: resolve them in one pass, and +where two raise the same defect, fix once and reply on both. + +### Auto mode + +`--auto` is a gating policy, not a second procedure. Steps 1–3, 5 and 7 run unchanged; the two gates switch +off, and the **In auto mode** sentences below say what replaces the developer's judgement at each: the two +verdict rules, and the commit at step 6. Where the interactive run +would have stopped for the developer, the auto run stops only on `needs-human` — and then **before any +edit**, returning as [Returning on `needs-human`](#returning-on-needs-human) specifies, so the caller can put +the questions to the developer and resume the same run. ## Verdicts, by source -Which verdicts are even available depends on who raised the finding, so establish the source first. +Which verdicts are even available depends on who raised the finding, so establish the source first. In `md` +mode every finding came from `review-changes`, so the question does not arise — `fix` or `reject`. | Source | How you know it | Verdicts | | --- | --- | --- | | This workflow's review | a PR comment ending in a `— Reviewed by …` footer | `fix` · `reject` | | A bot | `user.type == "Bot"` | `fix` · `reject` | -| A human | neither of the above | `fix` · `answered` | +| A human | anything else | `fix` · `answered` | -Test in that order. The footer comes first because an agent posts through a human's account — `user.login` -is the repo owner's in every case, so nothing but the footer distinguishes this workflow's own review. -Bots are then caught by GitHub's own `user.type`, **not** by a list of logins: this repo alone sees -`Copilot` (no `[bot]` suffix, capitalised), `coderabbitai[bot]`, `cursor[bot]` (Cursor Bugbot, which -`.cursor/BUGBOT.md` aims at our smell baseline) and `github-advanced-security[bot]`, and a name list gets -three of those four wrong — silently promoting them to human, whose comments may never be rejected. +Test the rows in that order. The footer is what separates this workflow's own review from a colleague's — +why, in [`../review-changes/gh-commands.md`](../review-changes/gh-commands.md). Bots are then caught by +GitHub's own `user.type`, **not** by a list of logins: this repo still runs CodeQL and Copilot, so +`github-advanced-security[bot]` and `Copilot` (no `[bot]` suffix, capitalised) both reach a PR, and a name +list goes stale the moment the tooling around the repo changes. Miss either test and an agent's or a bot's +finding is silently promoted to human, whose comments may never be rejected. - **fix** — the concern is real *and* the fix belongs in this change. - **reject** — invalid premise, contradicts design intent, already addressed, or out of scope. Closes with @@ -41,34 +84,47 @@ three of those four wrong — silently promoting them to human, whose comments m the thread unresolved** and let the human decide whether they still insist. A human comment is never rejected — they may be wrong, but that call is theirs, not yours. -Two further rules on verdicts: +Two further rules on verdicts, each with its auto-mode form: - **No repeat rejection.** A finding you rejected once, where the reviewer came back and disagreed, may not be rejected again on the same grounds. Fix it, reject it on genuinely **new** grounds (once), or mark it - `needs-human`. -- **Nits are `deferred`**, not fixed. The developer may promote one at Gate 1. - -## Invocation - -- `/resolve-review` — the usual case: resolve the open findings on the current branch's PR. -- `/resolve-review <PR url | comment url>` — that PR, or that single comment, scoping the whole run to it. + `needs-human`. **In auto mode** the reviewer's second dispute on the same finding turns it `needs-human` + outright: a rejection, a disputed rejection, a rejection on new grounds, a second dispute — and the + question goes to the developer. There is never a third rejection. +- **Nits are `deferred`**, not fixed. The developer may promote one at Gate 1. **In auto mode** a nit is + fixed when its fix stays within 5 lines in one file, adds no test and creates no file, and always when the + nit concerns comments, docs or tests; any other nit is `deferred` and stays an open thread for the + developer. ## 1. Scope -Establish what you are resolving. Derive `owner/repo` and the PR number, and confirm `gh auth status` -succeeds (commands: [`../review-changes/gh-commands.md`](../review-changes/gh-commands.md)). +Establish what you are resolving: +- in `pr` mode derive `owner/repo` and the PR number, and confirm `gh auth +status` succeeds (commands: [`../review-changes/gh-commands.md`](../review-changes/gh-commands.md)) +- in `md` mode resolve the review file and read it; a path that does not exist stops the run rather than +becoming a fresh review. -**Done when**: you know the unit of work and whether the scope is every open finding or one specific comment. +**Done when**: you know the unit of work and whether the scope is every open finding or one specific +finding. ## 2. Gather -Collect every **actionable** finding — inline review comments, PR-level reviews, and issue comments -([`../review-changes/gh-commands.md`](../review-changes/gh-commands.md)). Keep only unresolved, actionable -threads. Drop already-resolved threads, your own prior replies, and bot status noise (CodeRabbit "review -skipped", Copilot's PR overview). +In `pr` mode, collect every **actionable** finding — inline review comments, PR-level reviews, and issue +comments ([`../review-changes/gh-commands.md`](../review-changes/gh-commands.md)). Keep only unresolved, +actionable threads. Drop already-resolved threads and your own prior replies. Tag each with its **source** +per the table above. + +A footer-bearing issue comment titled `### 📎 Findings without a diff anchor` holds several findings at +once, one per `**<emoji> <tag->F<n> · <severity>**` title, the tag prefix present exactly when that +reviewer ran under `--as`. Split them and adjudicate each on its own. They have no resolved flag, so read +one as open unless a later footer-bearing comment already rules on that id. -Tag each with its **source** per the table above, then open the code it points at — `path` + `line`, or the -`diff_hunk` — so the next step judges against reality rather than against the comment text. +In `md` mode, collect every finding whose `**Status:**` is `open` or `disputed`. The file's reply +blockquotes carry the exchange history — read them, so a finding you already rejected once is not rejected +again on the same grounds. + +Either way, open the code each finding points at — `path` + `line`, or the `diff_hunk` — so the next step +judges against reality rather than against the comment text. **Done when**: every actionable finding is listed with its source, its location, and the current code it refers to. Exhaustive, not a sample. @@ -80,10 +136,11 @@ The heart of the skill. Reason hard here; do not rush toward the gate. - **Investigate before judging.** Verify the claim against the actual code. Check whether it still applies — it may be stale or already fixed. Weigh it against the spec and the conventions in `.agents/rules/`. - **Decompose multi-point findings.** One comment can be part-`fix`, part-`reject`. Adjudicate each point. -- **Give bots no deference.** A plausible-sounding suggestion is not automatically correct; a bot can - contradict the author's intent or argue from the wrong docs. +- **Give the reviewer no deference.** A plausible-sounding finding is not automatically correct; a review + agent or a bot can contradict the author's intent or argue from the wrong docs. - **When a verdict turns on design intent you cannot settle from the code and the spec, mark it - `needs-human`.** Do not guess. + `needs-human`.** Do not guess. A finding the reviewer already marked `🙋 needs human` is `needs-human` + from the start. For each finding record the verdict, the reasoning, and the proposed action — the fix sketch, or the reply text for a `reject` or an `answered`. @@ -92,12 +149,18 @@ text for a `reject` or an `answered`. ## 4. Gate 1 — confirm -**A hard stop.** Present a table — finding (`file:line` + short quote), source, verdict, reasoning, proposed -action — and list the `needs-human` items as questions. Then **stop and wait**. Edit no code until the -developer confirms; they may re-categorise anything or answer the open questions. This is the cheapest -steering point in the whole process, which is why it comes before any edit. +**A hard stop.** Present the verdict table (shape below) and list the `needs-human` items as questions. +Then **stop and wait**. Edit no code until the developer confirms; they may re-categorise anything or answer +the open questions. This is the cheapest steering point in the whole process, which is why it comes before +any edit. + +The verdict table, one row per finding: finding (id, `file:line` + short quote), source, verdict, reasoning, +proposed action. -**Done when**: the developer has confirmed. +**In auto mode** there is no confirmation. With no `needs-human` finding, go straight to step 5. With one or +more, this is where the run stops: [Returning on `needs-human`](#returning-on-needs-human). + +**Done when**: the developer has confirmed — or, in auto mode, the table holds no `needs-human` row. ## 5. Fix @@ -110,26 +173,59 @@ findings untouched. ## 6. Gate 2 — review the diff **A hard stop.** Show `git diff` plus a per-finding summary of what changed, and wait for approval before -anything is pushed or replied to. The developer commits and pushes the fixes — the reviewer's next -arbitration round reads them from the PR. +anything is pushed or replied to. In `pr` mode the developer commits and pushes the fixes — the reviewer's +next follow-up round reads them from the PR. In `md` mode the fixes stay uncommitted, which is what the +reviewer's follow-up round reads. + +**In auto mode** there is no approval: commit the fixes yourself — one commit, a plain descriptive subject, +the repo's `Co-Authored-By` trailer, no `#issue` reference — and `git push`. When the caller's brief says it +pushes itself, commit and leave the push to it: the `review-loop` skill pushes once per round after its CI +wait, and the reviewer's follow-up round reads the PR from that push. + +## Returning on `needs-human` + +The auto run's one stop, and the contract the `review-loop` skill reads. It happens at step 4, **before any +edit**: the working tree is as the run found it, nothing is committed, replied to or resolved. + +Return one block the caller can present verbatim: + +1. The full verdict table from step 4 — **every** finding, not only the `needs-human` rows — so the + developer sees what the run will do once resumed. +2. The questions, one per `needs-human` finding, each naming its finding id and stating what the code and + the spec could not settle. + +Then stop. Nothing else is in the block: the caller presents it, collects the developer's answers, and +**resumes the same run with the answers** — the same agent, with its table and reasoning still in context, +not a fresh dispatch. In Claude Code that is a `SendMessage` to this subagent. On resumption, re-adjudicate +each `needs-human` finding against its answer (`fix`, `reject` or `answered`, per the source's row in the +verdicts table), add the ones ruled `fix` to the fix set, and continue at step 5. The reply at step 7 cites +the developer's answer as the reasoning. ## 7. Close out -Reply to every thread; **who resolves depends on the source.** +Reply to every finding; **who closes it depends on the source.** - `fix` → what changed, plus the commit sha once it exists. - `reject` → the explanation. - `answered` → the reasoning, the alternatives, why this path won. +- `deferred` → that it is a nit left as it stands, so the reviewer's follow-up round can rule `deferred` + rather than wait on a fix that is not coming. + +**This workflow's own findings — reply, never close.** The reviewer raised them and owns their close: it +verifies the fix (or agrees the reject) and closes them in its next follow-up round, which is what lets it +confirm the work landed and post the final all-clear. Closing here would end the loop before the reviewer +ever checked it. + +In `pr` mode that means replying on the thread and leaving it unresolved. **Bot findings** — resolve on +`fix` or `reject`; a bot has no arbitration round, so your verdict is the last word on its thread. +**Human findings** — resolve on `fix`, and leave `answered` open for the human. Leave every `needs-human` +thread open. -**This workflow's own findings — reply, never resolve.** The reviewer raised them and owns their close: it -verifies the fix (or agrees the reject) and resolves in its next arbitration round, which is what lets it -confirm the work landed and post the final all-clear. Resolving here would close the loop before the -reviewer ever checked it. +Non-anchorable findings have no thread. Reply to all of them in **one** new issue comment, each line naming +its id, so the reviewer's follow-up round can match the ids it raised. -**Bot findings** — resolve on `fix` or `reject`; a bot has no arbitration round, so its verdict stands on -posting. **Human findings** — resolve on `fix`, and leave `answered` open for the human. Leave every -`needs-human` thread open — those must stay visible. +In `md` mode, append a reply line under the finding — `> **resolve-review, round <n>:** fix — <what +changed>` — and leave its `**Status:**` alone. -**Done when**: every adjudicated finding has been replied to and (where settled) resolved on the PR. Then -report: counts per verdict, every `reject`/`answered` with its one-line reason, and anything left for a -human. +**Done when**: every adjudicated finding has been replied to and (where settled) resolved. Then report: +counts per verdict, every `reject`/`answered` with its one-line reason, and anything left for a human. diff --git a/.agents/skills/review-changes/SKILL.md b/.agents/skills/review-changes/SKILL.md index a332c39ee0a..13992ea1255 100644 --- a/.agents/skills/review-changes/SKILL.md +++ b/.agents/skills/review-changes/SKILL.md @@ -1,8 +1,9 @@ --- name: review-changes description: >- - Review a change on three axes — spec compliance, repo standards, correctness — each in a fresh subagent - context, then post the findings as inline PR comments (or report them in chat when there is no PR). + Review a change axis by axis — spec compliance, repo standards, correctness, and a Jev screen — then + publish the findings as inline PR comments or into a review file in the task folder. +argument-hint: pr|md [--round first|follow-up] [--scope branch|uncommitted] [--as <tag>] [--ticket <NN>] disable-model-invocation: true --- @@ -11,150 +12,129 @@ disable-model-invocation: true Review a change the way a lead reviewer would: the **axes** that apply, in parallel, each in its own fresh subagent context, then one normalized report. -You produce **findings** and nothing else. Fixing them is `resolve-review`'s job, so this skill never edits -a file — which is also why it runs `lint:eslint` and never `lint:eslint:fix`. +You produce **findings** and nothing else. Fixing them is `resolve-review`'s job. -## Scope and mode +## Inputs -Mode follows from where the code is. +Nothing here is inferred. The output is the one positional and the one required input; a run without it +stops rather than guessing. -| Working tree | Mode | Base | -| --- | --- | --- | -| Clean, PR open, `HEAD` = the PR's head sha | inline PR comments | merge-base with the PR's base branch | -| Clean, PR open, `HEAD` ≠ the PR's head sha | **stop — the branch must be synced first** | — | -| Clean, no PR | chat only, no file | merge-base with `main` | +| Input | Values | Default | Meaning | +| --- | --- | --- | --- | +| `output` *(positional)* | `pr` · `md` | **required** | where the findings are published | +| `--round` | `first` · `follow-up` | `first` | `follow-up` is arbitration (step 3), never a fresh pass | +| `--scope` | `branch` · `uncommitted` | `branch` | what to diff. `md` only | +| `--as <tag>` | short slug (`cursor`, `codex`) | none | namespaces the findings, for concurrent reviewers | +| `--ticket <NN>` | ticket number | inferred | `--scope uncommitted` only | -**An open PR plus an out-of-sync branch stops the run.** Say which way it diverged and what to run — `git -push` when `HEAD` is ahead, `git pull` when behind — then stop rather than review. Otherwise lines that were -never pushed are absent from the PR diff, every anchor fails, and the all-or-nothing POST discards the whole -review. +``` +/review-changes pr round 1 on the current branch's PR +/review-changes pr --round follow-up arbitrate the rulings on that PR +/review-changes md --scope uncommitted the ticket in flight, before it is committed +/review-changes pr --as cursor a second reviewer on a PR another agent already reviewed +``` + +Contradictory inputs stop the run: `--scope` or `--ticket` with `pr`, or `--ticket` with `--scope branch`. -The skill takes no invocation arguments — every case above is inferred. +A `--scope uncommitted` run also stops when you cannot determine **whose** working-tree changes these are — +the resolved ticket, task-level work spanning several tickets, or fixes from an earlier round. Ask the +operator which, and review only after they answer. -**Round detection.** Prior review comments on the PR make this run **arbitration** (step 3) rather than a -fresh review — keyed on the presence of prior comments, not on whether findings are still open, so a second -round never silently becomes another three-axis pass. +### `--as` and concurrent reviewers + +Two agents may review the same change simultaneously; comparing their findings is the point. The tag keeps +them separate by prefixing every finding ID (`cursor-F1`) and, in `md` mode, the file name. Without a tag, +IDs are bare (`F1`), with no collision because only one reviewer is present. A `follow-up` round applies +only to findings carrying **its own** tag, where an untagged round owns the untagged findings — the rest +belong to another reviewer's round. Do not derive the tag: guessing it from the running model makes it +change when the model does, causing round 2 to disown round 1's findings. + +**Guard.** In a `first` round, a review of this change already sitting under someone else's tag means +another agent is working. With no `--as` of your own, stop and ask for one rather than overwriting it — +with a tag, you are the second reviewer and carry on. ## 1. Pin the ground -Resolve the mode with exactly these three probes, then **fail fast before spawning anything**: a wrong mode, -a base that does not resolve (`git rev-parse`), or an empty diff stops the run here, not inside three -subagents. +Resolve the base and the preconditions, and **fail fast before spawning anything**. A breached +precondition, a base that does not resolve (`git rev-parse`), or an empty diff stops the run here, not +inside the subagents. + +| output · `--scope` | Base | Precondition | Repo checks | +| --- | --- | --- | --- | +| `pr` | merge-base with the PR's `baseRefName` | clean tree, and `HEAD` == the PR's `headRefOid` | none — the Checks workflow owns them | +| `md` · `branch` | merge-base with `main` | clean tree | run them | +| `md` · `uncommitted` | `HEAD`, against the working tree | a non-empty working diff | run them | ```bash -git status --porcelain # any output at all → dirty, not ready to review +git status --porcelain # output = dirty gh pr list --head "$(git branch --show-current)" --state open \ - --json number,headRefOid,baseRefName -git rev-parse HEAD # compare against headRefOid + --json number,headRefOid,baseRefName # pr mode; see gh-commands.md +git rev-parse HEAD ``` -**The `gh` exit code answers "could I ask?"; its output answers "is there one?"** Exit ≠ 0 is a tooling -failure that **aborts the run**; exit 0 with `[]` is genuinely no PR. Use `gh pr list --json` and never `gh pr -view`, which exits 1 *both* when no PR exists and when it cannot reach GitHub — so nothing downstream can tell -a missing PR from a sandbox with no network. Never wrap either command in `||`. +**A `md` `follow-up` round has no clean-tree precondition.** `resolve-review` leaves its `md`-mode fixes +uncommitted on purpose ([`../resolve-review/SKILL.md`](../resolve-review/SKILL.md) step 6), so the round +whose whole job is verifying those fixes expects a dirty tree — under either scope. -`--state open` matters: a merged or closed PR must not select PR mode. `headRefOid` and `baseRefName` come -back from that same call, so the base is read rather than guessed, and a plain string comparison against -`HEAD` decides PR mode — unequal in *either* direction means out of sync. +**An open PR plus an out-of-sync branch stops the run.** Say which way it diverged and what to run — `git +push` when `HEAD` is ahead, `git pull` when behind. Otherwise lines that were never pushed are absent from +the PR diff, every anchor fails, and the all-or-nothing POST discards the whole review. Collect, in the review's own context: - `git diff --stat <base>` and `git diff --name-only <base>`, plus untracked files - (`git ls-files --others --exclude-standard`) — a new file is the most review-worthy thing in a change - and `git diff` alone misses it. -- The task's `spec.md` (if this is a task PR) and `.agents/delegation.md`. + (`git ls-files --others --exclude-standard`) — a new file is the most review-worthy thing in a change and + `git diff` alone misses it. Under `--scope uncommitted` the new files are usually most of the change. +- The task's `spec.md` (if this is a task PR) and [`../../delegation.md`](../../delegation.md). -**In chat mode**, run the repo's checks yourself — do not take "checks pass" on trust, because verifying that -claim is most of what a review is worth: +Where the table says to run the checks, run them yourself rather than taking "checks pass" on trust — +verifying that claim is most of what a review is worth: ```bash -pnpm lint:eslint +pnpm lint:eslint --changed=<base> pnpm lint:tsc pnpm lint:cspell pnpm test:vitest --changed <base> ``` -`vitest --changed` selects only the test files the change affects, and exits 0 when it affects none. - -**In PR mode, checks are not your business at all** — neither run them nor read them. The Checks workflow -reports to the PR where the developer already sees it, and it may still be running alongside this review. +**Done when**: the base, the touched-file list, and (where run) the check results are in hand, and the diff +is known non-empty. -**Done when**: mode, base, the touched-file list, and (in chat mode) the check results are all in hand, and -the diff is known non-empty. +## 2. Round `first` — spawn the axes -## 2. Round 1 — spawn the axes - -Send **one** message with the `general-purpose` subagents the change actually has axes for. Each gets: the -base ref, the touched-file list plus untracked files, the check output as established fact, and the paths it -must read. +Send **one** message with the `general-purpose` subagents the change actually has axes for — the `jev` +axis among them. Each gets: the scope, the base ref, the touched-file list plus untracked files, the spec +path when one resolved and the ticket when the run has one, the check output as established fact, and +[`axes.md`](axes.md) — its own brief, the finding shape and the per-finding cap all live there. **The spec axis is gated on a spec existing.** Plenty of changes have none — work done outside the task workflow, and any task finished inside its own grilling session (see "Not every task needs a spec" in [`../../tasks/README.md`](../../tasks/README.md)). Confirm `spec.md` is there before dispatching. With no -spec, run **two** axes and say so in the report — the spec axis with nothing to read invents a standard to -judge against, which is worse than the gap it papers over. Standards and correctness carry the review on -their own. - -Every axis returns findings in this shape, and nothing else — no preamble, no summary: - -``` -severity: blocker | major | nit -needs-human: yes | no -location: <path>:<line> -claim: <what is wrong — quote the code> -fix: <one or two lines> -``` +spec, run **two** blind axes plus `jev` and say so in the report. -Each report is capped at **400 words**, which forces ranking instead of dumping. +**Done when**: every dispatched axis has returned, or one has failed and you have noted which. A `jev` +axis reporting `skipped`, `failed` or no suspects has returned: the review proceeds on the blind axes and +the terminal close carries its reason. -**Spec axis brief.** Read the spec (path given) and the diff. Its **Functional Requirements** are the -contract: take each one in turn and report whether the diff actually satisfies it, quoting the requirement -behind each finding. Then report what the requirements don't cover: behaviour in the diff the spec never -asked for, and requirements that look implemented but are implemented wrongly. Anything the spec's **Out of -scope** section names is not a finding. +## 3. Round `follow-up` — arbitration -**Standards axis brief.** Read `.agents/rules/*.md` matching the touched file types, every `CONTEXT.md` for -directories the diff touches, `.agents/delegation.md`, and **one** smell baseline, picked by what the diff -touches: - -| The diff touches | Baseline | -| --- | --- | -| code | [`smells.md`](smells.md) | -| the instruction surface — `.agents/**`, `AGENTS.md`, any `CONTEXT.md`, `.cursor/**`, `.github/*instructions*` | [`prose-smells.md`](prose-smells.md) | -| both | both, each applied only to the files it governs | - -Task specs under `.agents/tasks/**` are not the instruction surface — the Spec axis reads those as the -source of truth rather than reviewing them as instructions. - -Report: places the diff breaks a documented rule — **cite the rule file and the rule** — and smells from the -baseline, each named and quoted. A documented rule can be a hard breach; a smell is always a judgement call. -Skip anything the checks in step 1 already cover. - -**Correctness axis brief.** Read the touched files **in full**, plus the files the change depends on — a -hunk-only read produces exactly the shallow findings that make developers stop trusting review. Report: -logic errors; mishandled loading / empty / error / pagination paths; places where the types claim something -the runtime does not; and tests that assert the framework or the mock rather than real behaviour (per the -"What to test (and what not)" section of `.agents/rules/tests-unit.md`). - -**Done when**: every dispatched axis has returned, or one has failed and you have noted which. - -## 3. Round 2+ — arbitration - -An arbitration round is **not** a fresh three-axis review. Re-reviewing everything keeps surfacing unrelated -findings, so the round never converges. +Re-reviewing everything keeps surfacing unrelated findings, so the round never converges. This round rules +on what is already open and nothing else. Spawn **one** fresh `general-purpose` agent — fresh, so it rules on the evidence rather than defending a -claim it made itself. Give it the prior review comments (which carry the full exchange history) and the -current diff. It does exactly three things: +claim it made itself. Give it your own tag's open findings with their full reply history, and the current +code. It does exactly three things: 1. Verify each claimed fix actually addresses its finding, rather than cosmetically silencing it. -2. Rule on each `reject`: **agree** — the finding closes as `rejected-accepted` — or **disagree**, with a - counter-argument. +2. Rule on each `reject`: **agree** — the finding closes, in the words its output file's ruling table + gives — or **disagree**, with a counter-argument. 3. Flag regressions introduced **by the fixes only**. New findings elsewhere are out of scope for this round. -The reviewer posts these rulings and resolves the settled threads itself (step 5). +Under `--scope uncommitted` the fixes are not separable from the original work in the diff, so verify each +one against the code as it now stands rather than looking for what changed since round 1. -**Done when**: every open finding is either closed or carries a ruling. +**Done when**: every open finding of yours is either closed or carries a ruling — and a deferred nit's +ruling is that it stays open. ## 4. Normalize @@ -164,66 +144,68 @@ to `blocker` because that axis is all it can see. - **Severity.** `blocker` — a requirement missing or wrong, a correctness bug, or a rule breach with a real consequence. `major` — real cost, not shipping-critical. `nit` — taste. Set `needs-human` on any finding that turns on design intent the code cannot settle; it is orthogonal to severity and it is the loop's - escape hatch. + escape hatch. Only `pr` mode records it — `md` mode is read by agents alone, so the escape hatch there is + `resolve-review`'s Gate 1, which puts the question to the developer in the terminal. - **One defect, one label.** The same defect seen through two axes is one finding: pick the sharper label - and drop the other. Never report it twice. + and drop the other. Never report it twice. Keep a `sources` list per surviving finding so the merge keeps a record of who saw it; a `jev` finding's label is the + grid its brief named, `standards` or `spec`. Keep the `rule` line too — the standards and `jev` axes + label each finding with a rubric rule id or `—`; when the two merge, keep the one that is not `—`, + the standards axis's when both have one, and `—` when neither does. +- **Another reviewer's finding stays theirs.** A defect already raised under a different tag gets a + concurrence on their thread, not a second id under yours. - **Anchor check.** For every surviving finding, open its `file:line`. Confirm the quoted code is actually - there, the claim still holds, and the line is in the PR diff. Drop what fails. Hallucinated line numbers - and stale claims are the two things that end a reviewer's credibility. + there and the claim still holds. Drop what fails. Hallucinated line numbers and stale claims are the two + things that end a reviewer's credibility. -**Done when**: every finding has a normalized severity, a verified anchor, and exactly one axis label. +**Done when**: every finding has a normalized severity, a verified anchor, exactly one axis label, and its +`sources`. -## 5. Report +## 5. Publish -Zero findings still produces a report with `Outcome: clear` and zeroed counts — a missing report is -indistinguishable from a review that never ran. +Both outputs carry the same findings, worded the same way, with the same ids and severities. They differ +only in where a finding lives and how its thread is closed. -**PR mode.** The PR is the record. `event` is always `COMMENT`: never `REQUEST_CHANGES`, which blocks the -author's own PR, and never `APPROVE`, which claims accountability an agent does not have. Name the reviewer -from the running model — any provider can run this skill — in a footer `— Reviewed by <agent or model -name>`, falling back to `— Reviewed by agent`. Commands and the all-or-nothing 422 hazard: -[`gh-commands.md`](gh-commands.md). +| Output | Mechanics | +| --- | --- | +| `pr` | [`output-pr.md`](output-pr.md) | +| `md` | [`output-md.md`](output-md.md) | -*A fresh review (round 1)* posts one batched review event — never N separate comments. Each inline comment -opens with its finding id and severity — `**F1 · blocker** — <claim>` — then the suggested fix and the -footer. The review body is the header table, listing each finding by id, plus a `## Not anchorable` section -for findings with no diff line to sit on: approach-level questions, or lines outside the diff. With zero -findings the body is `Review clear` and the zeroed counts. The id is the handle a human greps for and the -coder cites back, so it is stable: an arbitration round recovers the highest `F<n>` from the existing -comments and numbers any regression from there. +Zero findings still publishes, with the outcome `cleared` and zeroed counts — a missing report is +indistinguishable from a review that never ran. -*An arbitration round (round 2+)* acts on each ruling on its own thread, because the reviewer owns the -threads it raised and is the one that closes them: +**The outcome is defined here; both output files render this definition rather than restating it.** It is +`blocked` while any `blocker` or `major` is open, and `cleared` once only nits remain. -| Ruling | Reply | Thread | -| --- | --- | --- | -| fix verified | `F<n> — verified` | resolve | -| reject agreed | `F<n> — accepted, <reason>` | resolve | -| reject disputed | the counter-argument | leave open | -| regression from a fix | a new inline comment, next free id | leave open | +**Then record the origins**, whenever the `jev` axis returned a sidecar path. Spawn one fresh +`general-purpose` subagent with the `## Jev axis` brief in [`axes.md`](axes.md), the sidecar path, the +final table in the shape its Origins section gives, and the `jev` axis's drop table verbatim. It returns the tool's JSON: an origin per finding, a fate per suspect. -When no `blocker` or `major` thread is left open — only `deferred` nits remain — post a final review whose -body is `Review clear` and the counts. That terminal comment is the PR's `Outcome: clear`. +Then close **in the terminal** with where the review was published — the review's `html_url` from the POST +response, or the review file's path — counts per severity, counts per axis (an axis that came back empty is +worth a second look), one `jev` line, and the outcome. The `jev` line: -**Chat mode.** Same content, no file, no PR — report the findings in the conversation. +``` +jev: <n> suspects · <c> confirmed · <d> dropped · origins jev <x> / axis <y> / both <z> +``` -Close by reporting counts per severity, counts per axis (an axis that came back empty is worth a second -look), and the `Outcome`. +Suspects, confirmed and dropped come from the axis's return, the origin split from the `--origins` JSON. +When the screen was `skipped` or `failed`, or sent no suspects, the line carries the reason instead. -**Done when**: the review is posted (or reported in chat) and the counts have been reported. +**Done when**: the review is published, the origins recorded, and the counts reported. ## Out of bounds Not findings, no matter how they look. Each of these otherwise fills a report with noise that trains the reader to skim past real problems. -- **Any visual or styling judgement.** Presentation belongs to the `[human]` style leaf. +- **Any visual or styling judgement.** Presentation belongs to the style leaf and the developer who + verifies it in the running app. - **Anything the spec's Out of scope section names.** -- **Missing Playwright screenshot baselines** — human-generated, per `.agents/delegation.md`. +- **Missing Playwright screenshot baselines** — human-generated, per [`../../delegation.md`](../../delegation.md). - **Style preferences with no basis** in `.agents/rules/`, a `CONTEXT.md`, or the surrounding code. No citable rule or precedent, no finding. -- **"Add a comment explaining what this does"** — `code-quality.md` forbids *what* comments. +- **Any "add a comment here" suggestion.** `code-quality.md` bans comments outright; its one exception — a + *why* comment on code whose obvious reading is wrong — is the author's call, never a reviewer's request. + A comment the diff *adds* that is not such a why comment is the opposite: a citable rule breach. - **A primitive or shortcut with a why-comment on it.** The comment is an override signal: read it and back off rather than arguing with it. -- **A `TODO (design):` marker that has been consumed.** An *unconsumed* marker, though, is a finding here: - by land the `[human]` style leaves have had their turn, so a leftover marker is real dead scaffolding. diff --git a/.agents/skills/review-changes/axes.md b/.agents/skills/review-changes/axes.md new file mode 100644 index 00000000000..ee5b800c527 --- /dev/null +++ b/.agents/skills/review-changes/axes.md @@ -0,0 +1,132 @@ +# The review axes + +One brief per axis, dispatched by [`SKILL.md`](SKILL.md) step 2. You are one axis: read **your** section +and ignore the others. The orchestrator has already given you the scope, the base ref, the touched files +(untracked included), and the check results — those are established fact, so do not re-run them. + +## What every axis returns + +Findings in this shape, and nothing else. No preamble, no summary. + +``` +severity: blocker | major | nit +needs-human: yes | no +location: <path>:<line> +claim: <what is wrong — quote the code> +fix: <one or two lines> +``` + +Report every in-bounds finding you have, ranked most severe first; the count is uncapped. Each finding is +capped at **120 words** of prose — quoted code does not count. Severity here is your own read; the +orchestrator recalibrates across axes. + +## Spec axis + +Read the spec (path given) and the diff. Its **Functional Requirements** are the contract: take each one in +turn and report whether the diff actually satisfies it, quoting the requirement behind each finding. Then +report what the requirements don't cover: behaviour in the diff the spec never asked for, and requirements +that look implemented but are implemented wrongly. Anything the spec's **Out of scope** section names is +not a finding. + +## Standards axis + +Read `.agents/rules/*.md` matching the touched file types, every `CONTEXT.md` for directories the diff +touches, [`../../delegation.md`](../../delegation.md), and **one** smell baseline, picked by what the diff +touches: + +| The diff touches | Baseline | +| --- | --- | +| code | [`smells.md`](smells.md) | +| the instruction surface — `.agents/**`, `AGENTS.md`, any `CONTEXT.md`, `.cursor/**`, `.github/*instructions*` | [`prose-smells.md`](prose-smells.md) | +| both | both, each applied only to the files it governs | + +Task specs under `.agents/tasks/**` are not the instruction surface — the Spec axis reads those as the +source of truth rather than reviewing them as instructions. + +Report: places the diff breaks a documented rule — **cite the rule file and the rule** — and smells from the +baseline, each named and quoted. A documented rule can be a hard breach; a smell is always a judgement call. +Skip anything the checks already cover. + +Add one line to every finding, `rule: <id>`, naming the rubric rule in `tools/review-screen/rubric.ts` it +corresponds to — the `id` whose `question` the finding answers yes to — or `rule: —` when none does. + +## Correctness axis + +Read the touched files **in full**, plus the files the change depends on — a hunk-only read produces exactly +the shallow findings that make developers stop trusting review. Report: +- logic errors; +- mishandled loading / empty / error / pagination paths; +- places where the types claim something the runtime does not; +- tests that assert the framework or the mock rather than real behaviour (per the "What a good test is" +section of `.agents/rules/tests-unit.md`). + +## Jev axis + +A screen, then verdicts. `pnpm review:screen` scores every rubric rule against every touched file with +Jev, a typed-judgment model, and prints the cells over threshold as **suspects** — a probability each, +never a claim. It has read no rule; you decide. Given a findings table instead of a change, you are the +second dispatch: skip to **Origins**. + +Run it on the ground the orchestrator pinned, never re-derived: + +```bash +pnpm review:screen --scope <branch|uncommitted> --base <base ref> [--spec <path>] [--ticket <NN>] +``` + +`pr` output is `--scope branch`. `--spec` goes exactly when a spec resolved, `--ticket` when the run has +one. The JSON on stdout carries `status` (`ok` · `skipped` · `failed`) with a `reason`, the `sidecar` path, +and two suspect lists: `standards` (a rubric rule, a file, a line, a score) and `spec` (an `FR<n>`, its +best-scoring file, no line, a score). A `skipped` or `failed` status, or no suspect in either list, ends +the axis: return the status line and the sidecar path and stop. + +**Suspects are the whole territory.** A defect you notice beside one belongs to the other axes. For each +suspect: open the location; read the rule the rubric cites (`cites` on its entry in +`tools/review-screen/rubric.ts`) or the requirement in the spec; decide. A breach or an unmet requirement +becomes a finding in the shape above plus one line, `axis: standards | spec`, naming the grid, and for a +standards suspect a second, `rule: <the suspect's rule>`; a spec finding with no line writes +`location: FR<n>`. Anything else is one row of the drop table, in the shape +`--origins` reads back unchanged: + +``` +| suspect | fate | reason | +| --- | --- | --- | +| <rule> <path>:<line> | dropped | <one line> | +| FR<n> | dropped | <one line> | +``` + +The reasons that recur: the flagged line is unchanged context; the rule's `not_for` covers it; the +requirement lives outside the diff (docs, a later ticket, code the change removes); the Out of bounds list +names it. + +Return, in this order: `status: <status> — <reason>` and `sidecar: <path>`, the findings, the drop table. +**Every suspect appears exactly once**, as a finding or a drop — the later `--origins` step matches them +mechanically and records an unreported one as dropped for no reason. The per-finding cap applies. + +### Origins + +After publishing, a fresh dispatch gets the sidecar path, the final findings table and the drop table. +Write both, as given, to one file beside the sidecar — the sidecar's name with `.findings.md` in place of +`.json`, so it lands in the same git-ignored folder — and run: + +```bash +pnpm review:screen --origins <sidecar path> --findings <that file> +``` + +The tables: + +``` +| id | axis | rule | location | sources | claim | +| suspect | fate | reason | +``` + +`rule` is the rubric rule id the finding was labelled with, or `—`; `location` is `<path>:<line>`, `FR<n>` +for a requirement finding with no line, or `—`; `sources` lists the axes that raised the finding; `claim` is +the first sentence of the finding's claim, with any `|` removed; `suspect` is `<rule> <path>:<line>` or +`FR<n>` and `fate` is `dropped`. +Return the tool's JSON verbatim — it matches by window and requirement id with no code in front of it, and +that is the point: a judgement added here would be one made blind. + +## Out of bounds + +The **Out of bounds** list in [`SKILL.md`](SKILL.md) binds every axis. Read it before you report: a finding +it names is dropped whichever axis raised it. diff --git a/.agents/skills/review-changes/gh-commands.md b/.agents/skills/review-changes/gh-commands.md index 21c72821076..315aca7bf81 100644 --- a/.agents/skills/review-changes/gh-commands.md +++ b/.agents/skills/review-changes/gh-commands.md @@ -1,9 +1,9 @@ # gh / GraphQL command reference -The whole PR surface both review skills need: `review-changes` posts findings and, in arbitration rounds, -replies and resolves the threads it raised; `resolve-review` gathers, replies, and resolves bot and human -threads. Substitute `{owner}`, `{repo}`, `{N}` (PR number), `{commentId}`. Derive `{owner}/{repo}` once -and reuse. +The whole PR surface both review skills need in `pr` mode: `review-changes` posts findings and, in +follow-up rounds, replies and resolves the threads it raised; `resolve-review` gathers, replies, and +resolves threads. Substitute `{owner}`, `{repo}`, `{N}` (PR number), `{commentId}`. Derive +`{owner}/{repo}` once and reuse. Confirm `gh auth status` succeeds before anything else — follow the `check-github-cli` skill if it does not. Never authenticate on the developer's behalf. @@ -14,11 +14,12 @@ not. Never authenticate on the developer's behalf. # owner / repo for the current checkout gh repo view --json nameWithOwner,owner,name -# PR for the current branch — its absence is what selects chat mode. Use `gh pr list`, never `gh pr view`, -# which exits 1 both when no PR exists and when it can't reach GitHub: exit ≠ 0 is a tooling failure that -# aborts, exit 0 with `[]` is genuinely no PR. +# PR for the current branch. Use `gh pr list`, never `gh pr view`, which exits 1 both when no PR exists and +# when it can't reach GitHub: exit ≠ 0 is a tooling failure that aborts the run, exit 0 with `[]` is +# genuinely no PR — and a `pr`-mode run with no open PR stops there. `--state open` matters: a merged or +# closed PR is not something to review onto. Never wrap the call in `||`. gh pr list --head "$(git branch --show-current)" --state open \ - --json number,title,url,headRefName,baseRefName,state,isDraft + --json number,title,url,headRefName,headRefOid,baseRefName,state,isDraft # head sha, needed as commit_id when posting a review git rev-parse HEAD @@ -26,7 +27,8 @@ git rev-parse HEAD ## Posting a review (review-changes) -One batched review event per round. Build the payload as a file, then: +One batched review event per round, whose body is the summary; the finding format, the summary shape and +the footer are [`output-pr.md`](output-pr.md). Build the payload as a file, then: ```bash gh api -X POST repos/{owner}/{repo}/pulls/{N}/reviews --input review.json @@ -36,20 +38,28 @@ gh api -X POST repos/{owner}/{repo}/pulls/{N}/reviews --input review.json { "commit_id": "<head sha>", "event": "COMMENT", - "body": "<header table, plus a '## Not anchorable' section if any>", + "body": "<the summary: status line, counters line, axes line, footer>", "comments": [ { "path": "src/slices/token/pages/Holders.tsx", "line": 41, "side": "RIGHT", - "body": "**F1 · blocker** — <claim>\n\n<suggested fix>\n\n— Reviewed by <agent or model name>" + "body": "**🛑 F1 · blocker**\n\n<claim>\n\n<suggested fix>\n\n— Reviewed by <agent or model name>" } ] } ``` -`event` is always `COMMENT`. For a multi-line anchor add `start_line` (and `start_side`) alongside -`line`. +For a multi-line anchor add `start_line` (and `start_side`) alongside `line`. + +Findings with no anchor, and a `follow-up` round's rulings on them, are issue comments — posted after the +review event, one comment per round: + +```bash +gh api -X POST repos/{owner}/{repo}/issues/{N}/comments -F body=@not-anchorable.md +``` + +`-F body=@<file>` reads the body from a file; `-f body="…"` mangles a multi-line string. ### Validate every anchor first — the POST is all-or-nothing @@ -64,9 +74,9 @@ gh api repos/{owner}/{repo}/pulls/{N}/files --paginate \ For each file, walk its `patch`: every `@@ -a,b +c,d @@` header starts a hunk whose RIGHT-side line numbers run from `c`; added (`+`) and context (` `) lines each advance that counter and are anchorable, removed (`-`) lines do not advance it and are not. A finding whose line is outside that set moves into the -review body under `## Not anchorable`. +non-anchorable issue comment. -If a POST still 422s, retry once with the offending comments demoted into the body. Never drop them. +If a POST still 422s, retry once with the offending comments moved into that comment. Never drop them. ## Gather (resolve-review) @@ -77,7 +87,7 @@ gh api repos/{owner}/{repo}/pulls/{N}/comments --paginate # PR-level reviews (summary body + state per reviewer) gh api repos/{owner}/{repo}/pulls/{N}/reviews --paginate -# issue-level comments (the conversation tab, incl. most bot posts) +# issue-level comments (the conversation tab) gh api repos/{owner}/{repo}/issues/{N}/comments --paginate ``` @@ -89,16 +99,24 @@ Fields worth reading per inline comment: | `in_reply_to_id` | `null` = top-level; otherwise a reply within a thread | | `path`, `line` / `original_line` | where it sits — open this code | | `diff_hunk` | the snippet the reviewer saw | -| `user.login` | author — this is how you tell a human from a bot from this workflow's own review | +| `user.login` | author — who to address in a reply | | `body` | the comment text | | `html_url` | link back to the comment | **Telling the sources apart matters**, because they are adjudicated differently: a comment whose body ends in a `— Reviewed by …` footer is this workflow's own review, whichever provider produced it, and may be -rejected; a bot's gets no deference at all; a human's may never be rejected. Test the footer **first** — -`user.login` is the repo owner's account for every agent, so nothing else separates this workflow's review -from a human's — then `user.type == "Bot"` for the bots. Never match bot logins by name; see the source -table in `../resolve-review/SKILL.md` for why. +rejected — and where several agents reviewed the same PR, the tag in that footer says which one, matching +the prefix on its finding ids. + +The footer is the only thing that separates this workflow's own review from a human's: `user.login` is the +repo owner's account for every agent, so nothing else tells them apart. It does not settle bots, which +`user.type` catches — the full source split, and which verdicts each source allows, is the table in +[`../resolve-review/SKILL.md`](../resolve-review/SKILL.md). + +A footer-bearing **issue** comment titled `### 📎 Findings without a diff anchor` carries findings, not +conversation: one per `**<emoji> <tag->F<n> · <severity>**` title, the tag prefix present exactly when the +review ran under `--as`. It has no thread, so a reply is a new issue comment naming those ids, and there is +nothing to resolve. ### Parse a comment / PR link @@ -145,7 +163,5 @@ Notes: - Reply *before* resolving — a resolved thread still accepts replies, but replying first keeps the explanation visible. - Skip threads already `isResolved`. -- Leave `disputed`, `needs-human` and `answered` threads **unresolved** — they are exactly the ones that - must stay visible. -- Bot status posts (CodeRabbit "review skipped", Copilot's PR overview) arrive as issue comments, have no - thread to resolve, and are not actionable. +- Leave `disputed`, `deferred`, `needs-human` and `answered` threads **unresolved** — they are exactly the + ones that must stay visible. diff --git a/.agents/skills/review-changes/output-md.md b/.agents/skills/review-changes/output-md.md new file mode 100644 index 00000000000..1b7a042ff6d --- /dev/null +++ b/.agents/skills/review-changes/output-md.md @@ -0,0 +1,82 @@ +# Publishing to a review file + +`md` mode. One Markdown file holds the whole exchange — findings, replies, rulings — in place of the PR's +threads. Only agents read it (`resolve-review` replies in the same file), so a finding carries no +`— Reviewed by` footer: there is no human to tell an agent's comment from a colleague's. + +## Where the file goes + +The task folder comes off the branch name, `issue-<number>` → `.agents/tasks/<issue>-<slug>/`. If no task +folder resolves, stop and ask — this mode reviews tasks and tickets, and inventing a path elsewhere buries +the review where nothing will look for it. + +| `--scope` | The file | +| --- | --- | +| `branch` | `<task>/review.md` | +| `uncommitted` | `<task>/tickets/<NN>-<slug>/review.md` | + +`<NN>` comes from `--ticket`, or from the first unchecked box in `progress.md` — uncommitted work is by +definition the ticket in flight, since `implement-ticket` checks the box only once the commit exists. An +absent or ambiguous `progress.md` stops the run. + +Under `--as <tag>` the file is `review-<tag>.md` beside it, so concurrent reviewers never write the same +file. Before writing a `first` round, glob `review*.md` in the resolved folder and apply +[`SKILL.md`](SKILL.md)'s guard to what comes back — a sibling under a tag that is not yours means another +agent is already reviewing this change. + +Both are working files: `finalize-task` prunes them with the rest of the task's scaffolding, and only +`spec.md` survives the land. + +## The file + +A `## Rounds` log, then one `###` section per finding — the thread. Replies append inside the section as +blockquote lines; the `**Status:**` line is the only record of what is still open, so it is edited in place +rather than restated in the index. + +```md +# Review — tickets/03-holders-table · uncommitted + +## Rounds + +- **1** — 2026-09-07, <model name>. blocker 1 · major 2 · nit 1. Outcome: blocked. + +## Findings + +| id | severity | axis | location | +| --- | --- | --- | --- | +| F1 | blocker | correctness | `src/slices/token/pages/Holders.tsx:41` | + +### F1 · blocker · correctness · `src/slices/token/pages/Holders.tsx:41` + +**Claim.** <what is wrong, quoting the code> + +**Fix.** <one or two lines> + +**Status:** open + +> **resolve-review, round 1:** fix — <what changed> +> **review, round 2:** verified +``` + +A finding with no line to sit on keeps its section and writes `location: —`. The PR's split into a separate +comment has nothing to do here, and neither do its severity emoji or its `needs-human` flag: only agents +read this file, so that flag would have no reader — in `md` mode the escape hatch is `resolve-review`'s +Gate 1, which puts the question to the developer in the terminal. + +Zero findings still writes the file: the `## Rounds` line reads `Outcome: cleared` and `## Findings` is +empty. + +## A `follow-up` round + +Append a line to `## Rounds`, then work each of your open findings: + +| Ruling | Reply line | Status | +| --- | --- | --- | +| fix verified | `verified` | `resolved — verified` | +| reject agreed | `accepted, <reason>` | `resolved — rejected` | +| reject disputed | the counter-argument | `disputed` | +| deferred nit | `deferred` | `deferred` | +| regression from a fix | a new `###` section, next free id | `open` | + +The round's `## Rounds` line carries the outcome [`SKILL.md`](SKILL.md) defines — `Outcome: blocked` or +`Outcome: cleared`. diff --git a/.agents/skills/review-changes/output-pr.md b/.agents/skills/review-changes/output-pr.md new file mode 100644 index 00000000000..5301a7b1b3d --- /dev/null +++ b/.agents/skills/review-changes/output-pr.md @@ -0,0 +1,154 @@ +# Publishing to a PR + +`pr` mode. The PR is the record: findings are inline review comments, and a thread stays open until this +reviewer closes it. Commands and the all-or-nothing 422 hazard: [`gh-commands.md`](gh-commands.md). + +`event` is always `COMMENT`: never `REQUEST_CHANGES`, which blocks the author's own PR, and never `APPROVE`, +which claims accountability an agent does not have. + +## The severity emoji + +One set, used on every finding title and on the summary's status line. Nowhere else — a reader who sees +`🛑` skips to it, and that only works while it is rare. + +| Severity | Emoji | +| --- | --- | +| `blocker` | 🛑 | +| `major` | ⚠️ | +| `nit` | 💬 | +| `needs-human` (orthogonal, appended) | 🙋 | + +## A finding's comment + +The title line carries the id and the severity and nothing else; the claim starts below it. One blank line +between every block. + +```md +**🛑 F1 · blocker** + +<claim, quoting the code> + +<suggested fix> + +— Reviewed by <agent or model name> +``` + +`needs-human` extends the title: `**🛑 F1 · blocker · 🙋 needs human**`. + +Title with bold, never a heading. + +The severity **word** stays next to the emoji. `resolve-review` reads that line to classify a finding, and +nobody greps for a glyph. + +## Ids and the footer + +The footer names the reviewer from the running model, falling back to `— Reviewed by agent`. Any provider +can run this skill, and that footer is the only thing telling `resolve-review` an agent raised this finding +rather than a colleague — why, in [`gh-commands.md`](gh-commands.md). + +Under `--as <tag>` the id carries the tag (`cursor-F1`) and the footer names it too — `— Reviewed by cursor +(<model name>)`. + +The id is the handle a human greps for and the coder cites back, so it is stable: a `follow-up` round +recovers the highest `F<n>` **of its own tag** from the existing comments and numbers any regression from +there. + +## Before posting a `first` round + +Read the existing review threads ([`gh-commands.md`](gh-commands.md)) and sort them by footer: + +- **A footer-bearing thread whose tag is not yours, and you were given no `--as`** — another agent is + already reviewing this PR. Stop and ask for a tag. +- **A thread under another tag that raises a defect you also found** — reply `+1 — <your tag> concurs` on + it and drop your own copy. Agreement between two reviewers is worth recording; a duplicate id is not. +- **Your own earlier threads** — you are running `first` over a change you already reviewed. Say so and + confirm with the operator before posting a second set. + +## A `first` round + +One batched review event, never N separate comments. Its body is the summary and nothing else; the findings +are the inline comments. Then, if any finding has no line to sit on, one issue comment for those. + +Post the review event **first**, the non-anchorable comment after it. A 422 discards the review event +whole, so in that order the retry can fold anything that failed to anchor into a comment you have not sent +yet. + +## Findings with no diff anchor + +Approach-level questions, and lines outside the diff. They do not go in the summary — mixed in there they +are read as commentary on the summary, and the point of the split is that a reader can find them. + +One issue comment holds all of them, titled the same way as an inline finding, with a single footer at the +end: + +```md +### 📎 Findings without a diff anchor + +**⚠️ F3 · major** + +<claim> + +<suggested fix> + +--- + +**💬 F7 · nit** + +<claim> + +<suggested fix> + +— Reviewed by <agent or model name> +``` + +An issue comment is not a review thread: it cannot be resolved, and a reply to it is another issue comment. +So these findings carry no per-finding open state, and their state lives in the summary's counters instead. +They count as open until a `follow-up` round rules on them. + +## The summary + +Same shape every round, first and follow-up alike, so two rounds can be read against each other. + +```md +🛑 **Blocked** — 1 blocker, 1 major open + +blocker 1 · major 1 · nit 3 · not anchorable 1 + +Axes: spec · standards · correctness + +— Reviewed by <agent or model name> +``` + +- **Status.** `🛑 Blocked` and `✅ Cleared` render the two outcomes [`SKILL.md`](SKILL.md) defines, zero + findings included. Append `· 🙋 <n> needs human` when any `needs-human` finding is open whatever its + severity. +- **The counters are open counts, never raised counts.** On a `first` round the two are the same. Keeping + the meaning fixed is what makes the rounds comparable. +- **`Axes:`** is the coverage record, and it names a skipped axis rather than dropping it. + +No table of findings. A reader on the PR already has them inline, and a second copy in the summary is one +more thing to keep in sync with the threads. + +## A `follow-up` round + +Act on each ruling on its own thread, because the reviewer owns the threads it raised and is the one that +closes them. Threads under another tag are not yours to touch. + +| Ruling | Reply | Thread | +| --- | --- | --- | +| fix verified | `F<n> — verified` | resolve | +| reject agreed | `F<n> — accepted, <reason>` | resolve | +| reject disputed | the counter-argument | leave open | +| deferred nit | `F<n> — deferred` | leave open | +| regression from a fix | a new inline comment, next free id | leave open | + +Non-anchorable findings have no thread, so one issue comment carries their rulings — the reply column +above, one line each, for those ids only, closing with the same `— Reviewed by` footer: that footer is how +`resolve-review` tells a ruling from its own reply comment on the same ids. Write the id as +`<tag->F<n>`, the tag prefix present exactly when the finding was raised under one, so the line names the +id `resolve-review` is matching against — bare `F<n>` matches nothing, and with two reviewers on the PR it +would be ambiguous even if it did. Leave the original comment as posted. An id with no ruling stays in the +open counters. + +Then post the summary, in the shape above. Nothing marks a round as terminal beyond its status reading +`✅ Cleared`, which is this PR's `cleared` outcome. diff --git a/.agents/skills/review-loop/SKILL.md b/.agents/skills/review-loop/SKILL.md new file mode 100644 index 00000000000..f8b2ab8b36b --- /dev/null +++ b/.agents/skills/review-loop/SKILL.md @@ -0,0 +1,178 @@ +--- +name: review-loop +description: >- + Run the review loop on an open PR — a headless reviewer round, an autonomous resolver, a CI wait and fix, + repeated until the review is cleared and CI is green; pauses only on a `needs-human` finding. +argument-hint: "[<PR url>] [--reviewer <name>] [--model <id>]" +disable-model-invocation: true +--- + +# Review loop + +Close the loop between `review-changes`, `resolve-review` and CI on one PR. Each **round**: the reviewer +reviews the PR from its own CLI, and the orchestrator reads the outcome from the PR. While the outcome is +`blocked` a fresh resolver fixes. The round then waits for the Checks run on the branch, fixes it when red, +and pushes everything **once**. The loop ends **cleared and green**: the review outcome is `cleared` and the +Checks run for the current `HEAD` is green. Otherwise it stops with a report. The one decision it never +makes alone is a `needs-human` finding, from the review or from a CI fix: that pauses the round for the +developer. + +In the product-task workflow `finalize-task` hands off here after the PR is flipped to ready. The skill +also runs by hand on any open PR; `create-pr` never offers it. + +## Inputs + +| Input | Values | Default | Meaning | +| --- | --- | --- | --- | +| `target` *(positional)* | PR url | the current branch's open PR | the PR under review | +| `--reviewer <name>` | a file in [`reviewers/`](reviewers/) | `cursor` | which reviewer runs the rounds | +| `--model <id>` | a model id the reviewer's CLI accepts | the reviewer's default | model override, passed through | + +``` +/review-loop the current branch's PR, reviewed by cursor +/review-loop https://github.com/o/r/pull/12 that PR +/review-loop --model gpt-5 cursor, on the named model +``` + +**The reviewer file is the provider seam.** Everything specific to one provider — binary, flags, time +limit, failure detection, retry — lives in `reviewers/<name>.md`, and the reviewer's **tag** is its name. +This file speaks only of "the reviewer". Every reviewer run passes `--as <name>`, which is what satisfies +`review-changes`' guard against overwriting another reviewer's threads +([`../review-changes/SKILL.md`](../review-changes/SKILL.md), "`--as` and concurrent reviewers"). + +## 1. Pin the PR + +Resolve `owner/repo` and the PR with the discovery commands in +[`../review-changes/gh-commands.md`](../review-changes/gh-commands.md); a positional url settles the PR +outright. Confirm `gh auth status` succeeds. Then confirm the tree is clean and `HEAD` equals the PR's +`headRefOid` — the reviewer reads the PR diff, so a local commit it cannot see is a review of the wrong +code. A `HEAD` ahead of the PR is pushed here; a dirty tree stops the run. + +Read the reviewer file `reviewers/<name>.md` and keep it open for the rounds. + +**Done when**: the PR is known, pushed, and the tree is clean. + +## 2. Run a round + +Rounds are numbered from 1. Each round: + +1. **Review.** Run the reviewer as its file says: `review-changes pr --as <name>`, with `--round + follow-up` on every round after the first. It runs in the background and is polled to completion. + While it runs, **edit nothing** in this tree — the reviewer reads the working copy for the code the diff + points at, and an edit under it is a finding against code that does not exist. The file says what counts + as a transport failure (one retry) and what counts as a review that ran (no retry). +2. **Read the outcome from the PR**, never from the CLI's text — it can be truncated and the PR is the + record. Among the PR-level reviews (`gh api repos/{owner}/{repo}/pulls/{N}/reviews --paginate`, in + `gh-commands.md`; without the flag a PR past its first 30 reviews returns none of the newest), take the + latest whose body ends in the footer `— Reviewed by <name> …` and read its + status line, in the shape [`../review-changes/output-pr.md`](../review-changes/output-pr.md) gives: + `✅ **Cleared**` or `🛑 **Blocked**`, and the `🙋 <n> needs human` count when present. A review newer + than the round's start with that footer is the round's outcome; none means the reviewer did not run. +3. **`blocked`** → dispatch the resolver (step 3). It returns with the review fixes **committed, not + pushed**. Then wait for CI and fix a red run (step 4), **push once**, and start the next round at 1. +4. **`cleared`** → with a `🙋 <n> needs human` count above zero, dispatch the resolver first (step 3): a + `needs-human` nit pauses the round exactly as a blocker would, and the resolver's fixes are committed + before the CI wait. Otherwise no resolver. Then wait for CI (step 4). Green with nothing committed + locally ends the loop at step 5. Green with the resolver's fixes still local is **not** the end: the + round pushes them — its one push — and waits for the run on the new `headRefOid`; that run's conclusion + is the one that ends the loop or opens a CI-fix cycle. Red enters the post-clear CI-fix cycles step 4 + describes. Neither path runs another review round. + +**One push per round.** The review fixes and the CI fix are separate commits — the history shows which +change came from which source — and they leave in one `git push` after the CI wait. Nothing is pushed +between the resolver's return and that push. + +**Bounds.** Three review rounds. A third round that still reads `blocked` is resolved like the others — +resolver, `needs-human` pause, CI wait, one push — and then the loop ends with a report instead of a fourth +review; the report says the round-3 fixes landed unverified by the reviewer. The reviewer's own stops — a +transport failure that survived its retry, a timeout, an agent that finished without posting — end the loop +too. + +**Done when**: the outcome is `cleared` and the current `HEAD` is green, or a bound or a reviewer stop has +been hit. + +## 3. Dispatch the resolver + +Spawn **one fresh** `general-purpose` subagent per round — fresh, so it adjudicates against the code rather +than defending what it wrote. Its brief: read [`../resolve-review/SKILL.md`](../resolve-review/SKILL.md) +and run it as `resolve-review pr --auto <PR url>`, in this tree, **committing but not pushing** — the loop +pushes once per round after its CI wait — and reporting back with the commit or with the `needs-human` +block. Wait for it; edit nothing while it works. + +The resolver returns one of two ways: + +- **Fixes committed.** Its report carries the verdict counts and the commit sha. Continue at step 4. +- **`needs-human`.** It stopped before any edit and returned the block that + [`../resolve-review/SKILL.md`](../resolve-review/SKILL.md) → "Returning on `needs-human`" specifies — the + full verdict table and one question per `needs-human` finding. Then: + 1. Print the block **verbatim** in the terminal. + 2. Fire a `PushNotification` with the PR url and the number of questions. + 3. End the turn and **wait** for the developer's answers. Nothing is edited, committed or pushed while + waiting. + 4. **Resume the same resolver with the answers** — the same agent, its table and reasoning still in + context, not a fresh dispatch. In Claude Code that is a `SendMessage` to the subagent. It folds the + answers into its fix set and proceeds; the round continues at "Fixes committed". + +The loop never ends with an unanswered `needs-human` finding: a bound or a stop is reported only once the +pending answers are in and the fixes are pushed. + +**Done when**: the resolver has reported its review fixes committed. + +## 4. Wait for CI, fix a red run + +The run to watch is the **Checks** workflow run for the PR's pushed head — `headRefOid`, which is the last +pushed commit, not the local `HEAD` once the resolver has committed. Find it by head SHA, never by "latest +on the branch": the workflow has no `cancel-in-progress`, so every push leaves its own run going and the +newest one may belong to an older commit. + +```bash +gh run list --workflow=checks.yml --commit <headRefOid> --json databaseId,status,conclusion,url +gh run watch <databaseId> --exit-status # blocks until the run completes +``` + +- **No run for that SHA** → a run takes a few seconds to register after a push, so an empty list is not yet + an answer: poll the same command every 15 seconds for up to 2 minutes. A run that appears is the run to + watch. Still none after the window → the workflow's `paths-ignore` skipped the push (agent docs, `docs/`, + deploy values): the newest completed Checks run on the branch stands in for it, and **its** conclusion is + the one read below. No completed run on the branch at all counts as green. +- **Pending** (`queued`, `in_progress`) → watch it to completion. Edit nothing while waiting. +- **Green** (`success`) → in a `blocked` round, push and start the next round. After `cleared`, the loop + ends at step 5 **only when `HEAD` equals `headRefOid`** — the green run is for the code on the PR. With + the round's resolver fixes still local (a `cleared` round with `needs-human` findings), push them and + watch the run for the new `headRefOid` from the top of this step; a green run on the pre-fix SHA says + nothing about the fixes. +- **Red** (`failure`, `timed_out`, `cancelled`) → a CI fix: + 1. **Resume the round's resolver** with [`ci-fixes.md`](ci-fixes.md) as its brief, the run url and the + PR url — the same agent, so one agent holds both fix sets. After `cleared` no resolver exists for the + round: spawn a fresh `general-purpose` subagent with the same brief. + 2. It returns one of four ways, all in the shapes `ci-fixes.md` gives: + - the CI fix in its **own commit**, separate from the review fixes → continue to the push; + - a `needs-human` block → pause exactly as in step 3: print verbatim, `PushNotification`, wait, resume + the same agent with the answers; + - an **infrastructure rerun** (`gh run rerun --failed`, no commit) → the SHA is unchanged, so watch that + same run id again (`gh run watch`) and read its new conclusion; red again is the next CI-fix cycle, + not a repeat of this one; + - a job the developer **left red** (no commit) → the loop stops: push what is committed (step 5) and + name the job in the report. No further CI-fix cycle opens on it. + 3. **Push once.** In a `blocked` round that push carries the review fixes and the CI fix, and the next + round starts. After `cleared` it carries the CI fix and any review fixes the round's resolver left + local, and the loop waits for the run on the new `headRefOid`: green ends the loop, red starts another + CI-fix cycle. + +**Post-clear bound.** Two CI-fix cycles after `cleared`. A second cycle that still ends red stops the loop +with a report, the fixes pushed. No review round follows a post-clear CI fix: a follow-up review over a +baseline update or an added assertion would be arbitration with nothing to arbitrate. + +**Done when**: the round's push is out and the next round can start, or the loop has ended cleared and +green, or the post-clear bound has been hit. + +## 5. Report + +Before anything is said, confirm the PR is in a **consistent pushed state**: a clean tree and `HEAD` equal +to the PR's `headRefOid`. A stop that leaves local commits behind pushes them first. + +Then report in the terminal: the PR url, the outcome (`cleared` and green, or why the loop stopped — rounds +exhausted, post-clear CI-fix cycles exhausted, reviewer failure after its retry, timeout), the number of +rounds run and of post-clear CI-fix cycles, the Checks run url for the final `HEAD` and its conclusion, the +counts from the last resolver report, and anything left open — `deferred` nits and `answered` human threads +stay as open threads for the developer. Leave the PR's threads as the reviewer and the resolver left them. diff --git a/.agents/skills/review-loop/ci-fixes.md b/.agents/skills/review-loop/ci-fixes.md new file mode 100644 index 00000000000..ac2ed3b0d05 --- /dev/null +++ b/.agents/skills/review-loop/ci-fixes.md @@ -0,0 +1,76 @@ +# CI fixes + +The brief for the agent that fixes a red Checks run inside a `review-loop` round: the round's resolver, +resumed, or a fresh subagent after `cleared`. It is given the run url and the PR url. Its job is to make +that run's failures pass on the next push without changing what the PR builds, and to hand back anything +it cannot settle that way as `needs-human`. What makes this different from fixing CI by hand is that +nobody is watching: the rules below are the judgement a developer would apply at the keyboard. + +## 1. Read the run + +Read the failed jobs and their logs; the failing job's name says which gate it is, and the gate's own doc +(`.agents/rules/*.md`, `tools/*/CONTEXT.md`) says how to read its output and what the valid fixes are. +Read it before touching code. Reproduce each failure locally with the command that doc gives before +fixing it: a fix for a failure you cannot reproduce is a guess. + +A job that failed on infrastructure (a runner lost, an install timeout, a download that never arrived) is +**not a finding**: rerun it with `gh run rerun <run id> --failed` and report that instead of a commit. + +**Done when**: every failing job is listed with its gate, the failure reproduced, and a proposed fix — or +a `needs-human` reason. + +## 2. The escape + +A CI fix stays inside the finding. Two kinds of fix are **`needs-human`**, whatever the gate: + +- a fix that **changes behaviour** — the component renders something else, a branch is removed, a value + changes — rather than a test, an assertion, a suppression with its reason, or a decomposition that keeps + the same output; +- a fix that **restructures beyond the finding** — moving a hook, splitting a component, reshaping a + signature, touching a file the failure does not name. + +The gates' own docs name the same line for their domain: the mutation-testing doc's "a survivor is not a +reason to restructure working code", the complexity doc's "raising the cap is not the fix". When the only +fix you can see crosses it, the question goes to the developer. + +## 3. Playwright screenshot mismatches + +Every other Playwright failure — an unmocked request, a timeout, an assertion on text or a role, a failed +mount — is a plain fix under the escape above. A **screenshot mismatch** has a baseline question: + +1. **Reproduce in Docker**, the only run whose pixels match CI (`.agents/rules/tests-visual.md` has the + command), and **view the diff image** — the expected, actual and diff files sit together, and the + `Read` tool renders images. +2. **Decide what the diff is.** Match the changed region to the PR's diff and to the task spec's + Functional Requirements (`.agents/tasks/<issue>-<slug>/spec.md`; on a non-task PR, the PR body). + - The diff **is** a requirement — the spec asks for this change, and the pixels show it and nothing + else → **update the baseline** from the Docker run, and nothing else in that commit. The commit + message **cites the requirement** by number and phrase, e.g. `Update Holders baseline for FR3 + (balance column shows USD value)`. A baseline from a plain local run is never committed. + - Anything else — a diff the spec does not ask for, a diff larger than the requirement, a change you + can explain only as "it moved", a baseline for presentation the spec does not name → **`needs-human`**. + The question names the test, the image paths and what the spec does and does not say. + +## 4. Commit + +One commit for the CI fix, **separate from the review fixes**, so the history shows which change came from +which source. A plain descriptive subject naming the gate (`Kill surviving mutants in useFoo`, `Flatten +classify() under the COG cap`), the repo's `Co-Authored-By` trailer, no `#issue` reference. Run the gate's +local command once more on the fixed files before committing. **No push**: the loop pushes once per round. + +**Done when**: the CI fix is committed, the tree is clean, and the gate's local command passes on the +touched files. + +## Returning + +Two shapes, and the loop reads both: + +- **Fixed.** The commit sha, and per failing job: the gate, the failure in one line, what changed. A rerun + of an infrastructure failure is reported as such, with no commit. +- **`needs-human`.** Return it **before any edit**, as `resolve-review` does + ([`../resolve-review/SKILL.md`](../resolve-review/SKILL.md) → "Returning on `needs-human`"): one table + with every failing job — gate, failure, verdict (`fix` or `needs-human`), proposed action — and one + question per `needs-human` row stating what the code and the spec could not settle. Then stop. The loop + presents the block, collects the answers and resumes this same run; on resumption, re-adjudicate each + `needs-human` row against its answer, add the ones ruled `fix` to the fix set, and continue at step 4. + A row the developer answers "leave it" stays red: say so in the return, so the loop's report names it. diff --git a/.agents/skills/review-loop/reviewers/cursor.md b/.agents/skills/review-loop/reviewers/cursor.md new file mode 100644 index 00000000000..fdef92034ad --- /dev/null +++ b/.agents/skills/review-loop/reviewers/cursor.md @@ -0,0 +1,61 @@ +# Reviewer: `cursor` + +The Cursor CLI (`agent`) running the repo's `review-changes` skill headlessly. Tag: `cursor`, passed as +`--as cursor` on every run. + +## Invocation + +```bash +agent -p --trust --approve-mcps --output-format json [--model <id>] \ + "/review-changes pr --as cursor [--round follow-up]" +``` + +- `--round follow-up` on every round after the first; the first round passes no `--round`. +- `--model <id>` only when the loop was given one. Otherwise Cursor's default model. +- `--trust --approve-mcps` are mandatory: trust and MCP approval are per absolute path, so a fresh + worktree prompts without them and a headless run hangs on the prompt. +- Run from the repo root, where Cursor loads `.agents/skills/` natively and the slash invocation attaches + the skill. + +## Background run and polling + +The run exceeds the foreground command cap, so launch it as **one Bash call with `run_in_background: true`** +(the Claude Code flag `release` uses for the same kind of long command) under a **30-minute limit**, with +stdout and the exit code captured to the scratchpad. macOS ships no `timeout`, so the deadline is a shell +watchdog that kills the run and records exit `124` itself — the same code `timeout` would give: + +```bash +agent -p --trust --approve-mcps --output-format json [--model <id>] \ + "/review-changes pr --as cursor [--round follow-up]" \ + > <scratchpad>/review-<round>.json 2> <scratchpad>/review-<round>.err & +pid=$! +( sleep 1800 && kill "$pid" 2>/dev/null && echo 124 > <scratchpad>/review-<round>.timeout ) & +watchdog=$! +wait "$pid"; rc=$? +kill "$watchdog" 2>/dev/null +[ -f <scratchpad>/review-<round>.timeout ] && rc=124 +echo "$rc" > <scratchpad>/review-<round>.exit +``` + +Fill in `--round follow-up` and `--model <id>` per the Invocation rules above — this block is the one that +runs, so a round-2 copy without `--round follow-up` is a second `first` round. Record the start time first +(`date -u +%FT%TZ`); the outcome check below compares against it. The background call reports back when the +script exits; until then, poll for the exit file and edit nothing in the tree. + +## Failure detection + +Read the exit code and stdout, then check the PR for a review posted since the start time whose body ends +in `— Reviewed by cursor …` (the `reviews` endpoint in +[`../../review-changes/gh-commands.md`](../../review-changes/gh-commands.md)). + +| Observation | Meaning | Action | +| --- | --- | --- | +| Footer-bearing review newer than the start time | the review ran | read its outcome; the exit code is irrelevant | +| No such review, exit `124` | timeout | stop the loop | +| No such review, exit non-zero other than `124`, or empty stdout | transport failure | retry once, same invocation | +| No such review after the retry | reviewer failure | stop the loop | +| No such review, exit `0`, non-empty stdout | the agent ran to completion but posted nothing | stop the loop; report that the agent finished without a footer-bearing review | + +Rows are tested top to bottom; the first match rules. A review that ran gets no retry, whatever the CLI +reported: a second `first` round would post a duplicate set of findings under the same tag. Nor does an +agent that finished without posting — the retry would repeat the same thirty minutes to the same end. diff --git a/.agents/skills/slack-subscribe/SKILL.md b/.agents/skills/slack-subscribe/SKILL.md new file mode 100644 index 00000000000..4d215cb3c60 --- /dev/null +++ b/.agents/skills/slack-subscribe/SKILL.md @@ -0,0 +1,65 @@ +--- +name: slack-subscribe +description: >- + Subscribe this session to replies in a Slack thread, then stop; replies are + forwarded later as cross-session messages. Use after posting a question or a + demo link to Slack when the run must resume on the colleague's answer, and to + unsubscribe at teardown. Local Claude Code only. +--- + +# Slack subscribe + +A session **registers interest** in a thread and stops. One other process — the Honk orchestrator — holds the only Slack Socket Mode connection, reads the registry, and forwards each reply into the registered session as a cross-session message. This skill never opens a socket, never polls Slack, and never runs `slack-watch` (a second socket on the same app token swallows events). + +Contract: the tuple `(channel, thread_ts, session)`. The pilot stores it in a local file; a later version carries it in the Slack message's `metadata` instead. The commands below do not change. + +Every command below runs with the shell at the **repo or worktree root** — the script records its working directory as the `cwd` a headless resume starts in, so the skill directory is the wrong place to run it from. + +## 1. Ready + +1. `.claude/skills/slack-subscribe/scripts/slack-subscribe` is executable; Node 22+ on `PATH`. +2. This is a local Claude Code session — the script reads `CLAUDE_CODE_SESSION_ID` from the Bash tool's environment. In Cursor or a cloud agent the variable is absent: stop and tell the developer to run this step in local Claude Code. + +**Done when:** both hold, or the run has stopped. + +## 2. Subscribe, then stop + +The thread is `CHANNEL:THREAD_TS` (channel id + parent `ts` from `slack_send_message`) or a permalink — a reply's permalink works too, its `thread_ts` query names the parent. + +```bash +.claude/skills/slack-subscribe/scripts/slack-subscribe C0123ABCD:1700000000.000200 +.claude/skills/slack-subscribe/scripts/slack-subscribe "https://blockscout.slack.com/archives/C0123ABCD/p1700000000000200" +``` + +Prints `SUBSCRIBED <channel>:<thread_ts> session=<id>`. Re-running on the same thread is a no-op overwrite. Several threads to watch: one call each, all in this turn. + +Once every thread is registered, **end the turn** — once. Nothing else to launch, nothing to await. The reply arrives as a new turn: + +``` +<cross-session-message from="honk-…"> + reply text · author · channel · thread_ts · ts +</cross-session-message> +``` + +Act on it per the skill that subscribed, then end the turn again; the other registered threads stay registered. Read the full thread with `slack_read_thread` when the forwarded text is not enough. + +**Leave state findable.** If this session is gone when a reply lands, Honk resumes it headless — see [`honk.md`](../../honk.md) → Resume for what the transcript must carry before stopping. + +**Done when:** a `SUBSCRIBED` line is printed per thread and the turn has ended. + +## 3. Unsubscribe + +At teardown, or when the question is settled: + +```bash +.claude/skills/slack-subscribe/scripts/slack-subscribe --remove C0123ABCD:1700000000.000200 +``` + +Prints `REMOVED …` (or `ABSENT …` when it was never registered — also fine). + +**Done when:** the line is printed. + +## Options + +- `--session <id>` — register on behalf of another session (testing the resume path by hand). Default: `CLAUDE_CODE_SESSION_ID`. +- Registry: `~/.claude/channels/honk/watches.json`, a map keyed `channel:thread_ts`. Written atomically; safe to inspect, pointless to edit by hand. diff --git a/.agents/skills/slack-subscribe/scripts/slack-subscribe b/.agents/skills/slack-subscribe/scripts/slack-subscribe new file mode 100755 index 00000000000..47810ad6a87 --- /dev/null +++ b/.agents/skills/slack-subscribe/scripts/slack-subscribe @@ -0,0 +1,106 @@ +#!/usr/bin/env node +// Register this Claude Code session's interest in a Slack thread so the Honk +// orchestrator — the one process holding the Slack Socket Mode connection — +// forwards every reply in that thread to this session as a cross-session +// message. No socket, no polling, no Slack API call: the script only edits a +// local registry file and exits. +// +// Pilot registry: ~/.claude/channels/honk/watches.json, a map keyed +// "channel:thread_ts" → { channel, thread_ts, session, cwd, registered_at }. +// Re-registering the same thread overwrites its entry (idempotent). The write +// is atomic (temp file + rename), so Honk never reads a half-written file. +// +// Usage: +// scripts/slack-subscribe <thread> register +// scripts/slack-subscribe --remove <thread> unregister +// scripts/slack-subscribe --session <id> <thread> override the session id +// <thread> is "C…:1700000000.000200" or a Slack permalink +// (…/archives/<channel>/p<ts-without-dot>[?thread_ts=<parent>], or +// app.slack.com …/thread/<channel>-<ts>). A reply's permalink carries the +// parent in its thread_ts query — that parent is what gets registered. +// The session id defaults to $CLAUDE_CODE_SESSION_ID (set in Claude Code's Bash tool). +// cspell:ignore ENOENT +'use strict'; + +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const REGISTRY_DIR = path.join(os.homedir(), '.claude', 'channels', 'honk'); +const REGISTRY_FILE = path.join(REGISTRY_DIR, 'watches.json'); + +function die(msg) { + process.stderr.write(`slack-subscribe: ${msg}\n`); + process.exit(1); +} + +// "1709834567890123" or "1709834567.890123" → "1709834567.890123" +const dotTs = (p) => (p.includes('.') ? p : `${p.slice(0, -6)}.${p.slice(-6)}`); +const TS = String.raw`(\d{10}\.\d{6}|\d{16})`; + +// The ?thread_ts= query on a reply's permalink names the parent; the /p digits +// are the reply itself, which no forwarded event would ever match. +function queryThreadTs(arg) { + const m = arg.match(/[?&]thread_ts=(\d{10}\.\d{6})(?:[&#]|$)/); + return m ? m[1] : null; +} + +function parseThread(arg) { + let m = arg.match(new RegExp(String.raw`^([CDG][A-Z0-9]+):${TS}$`)); + if (m) return { channel: m[1], thread_ts: dotTs(m[2]) }; + m = arg.match(new RegExp(String.raw`/archives/([CDG][A-Z0-9]+)/p${TS}(?:[/?#]|$)`)); + if (m) return { channel: m[1], thread_ts: queryThreadTs(arg) || dotTs(m[2]) }; + m = arg.match(new RegExp(String.raw`/thread/([CDG][A-Z0-9]+)-${TS}(?:[/?#]|$)`)); + if (m) return { channel: m[1], thread_ts: queryThreadTs(arg) || dotTs(m[2]) }; + die(`cannot parse thread '${arg}' — expected CHANNEL:THREAD_TS or a Slack permalink`); +} + +function readRegistry() { + try { + const parsed = JSON.parse(fs.readFileSync(REGISTRY_FILE, 'utf8')); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed; + die(`${REGISTRY_FILE} is not a JSON object — fix or delete it`); + } catch (e) { + if (e.code === 'ENOENT') return {}; + die(`cannot read ${REGISTRY_FILE}: ${e.message}`); + } +} + +function writeRegistry(registry) { + fs.mkdirSync(REGISTRY_DIR, { recursive: true }); + const tmp = `${REGISTRY_FILE}.${process.pid}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(registry, null, 2) + '\n'); + fs.renameSync(tmp, REGISTRY_FILE); +} + +// ---- argv +let remove = false; +let session = process.env.CLAUDE_CODE_SESSION_ID || ''; +let thread = null; +const args = process.argv.slice(2); +for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (a === '--remove') remove = true; + else if (a === '--session') session = args[++i] || ''; + else if (a.startsWith('-')) die(`unknown option '${a}'`); + else if (thread) die('exactly one thread per call'); + else thread = a; +} +if (!thread) die('usage: slack-subscribe [--remove] [--session <id>] <CHANNEL:THREAD_TS | permalink>'); + +const { channel, thread_ts } = parseThread(thread); +const key = `${channel}:${thread_ts}`; +const registry = readRegistry(); + +if (remove) { + const existed = key in registry; + delete registry[key]; + writeRegistry(registry); + process.stdout.write(`${existed ? 'REMOVED' : 'ABSENT'} ${key}\n`); + process.exit(0); +} + +if (!session) die('no session id — CLAUDE_CODE_SESSION_ID is unset (not a Claude Code session?); pass --session <id>'); +registry[key] = { channel, thread_ts, session, cwd: process.cwd(), registered_at: new Date().toISOString() }; +writeRegistry(registry); +process.stdout.write(`SUBSCRIBED ${key} session=${session}\n`); diff --git a/.agents/skills/slack-watch/SKILL.md b/.agents/skills/slack-watch/SKILL.md new file mode 100644 index 00000000000..7a17b8d0c47 --- /dev/null +++ b/.agents/skills/slack-watch/SKILL.md @@ -0,0 +1,104 @@ +--- +name: slack-watch +description: >- + Deprecated — use slack-subscribe. Watch Slack threads for new replies over a + Socket Mode WebSocket; only while no Honk session is connected to Slack. +disable-model-invocation: true +--- + +<!-- cspell:ignore acks xapp xoxp xoxb WXYZ AwaitShell --> + +# Slack watch + +> **Deprecated.** Subscribe through the `slack-subscribe` skill instead. This script opens a second Socket Mode connection on the same app token as the Honk orchestrator, and Slack delivers each event to only **one** connection — while Honk is connected, running this watcher makes both of them miss replies. + +A push subscription to replies in specific Slack threads — **DM threads and channel threads both**. The script holds one Socket Mode WebSocket, acks every event, and prints one line per new reply — nothing else. It knows nothing about tasks or questions; it filters a thread list you give it and reports. The caller (a session, a skill) decides what a reply means and reads it via the Slack MCP (`slack_read_thread`). + +macOS. Three tokens live in the Keychain; the script reads them and never prints them. It does **not** print message content or event payloads — the underlying `message.im` feed is a DM firehose. DMs are watched with the developer's **user** token; channels are watched with the **bot** token, which only sees channels the Honk bot was invited into (so no firehose there). A single Socket Mode connection carries both the bot and user events. + +## 1. Ready + +From **this skill's directory** (the folder that contains this `SKILL.md`): + +1. `scripts/slack-watch` is executable. +2. Keychain has all three services, metadata only (no `-w`): + - `security find-generic-password -s slack-orchestrator-app-token` + - `security find-generic-password -s slack-orchestrator-user-token` + - `security find-generic-password -s slack-orchestrator-bot-token` +3. Node 22+ is on `PATH` (`node --version`) — the script uses the built-in `WebSocket` and `fetch`, no npm deps. + +If 2 fails: give the user **Setup** below and stop. Do not store the tokens yourself. + +**Local session only** — the Keychain and the socket both live on this Mac. If you are a cloud agent, stop and tell the developer to run this in local Claude Code or Cursor. + +**Done when:** every check passes, or the run has stopped for setup (or cloud). + +## 2. Run + +Each watched thread is one `CHANNEL:THREAD_TS` argv item — the channel id (a DM is `D…`, a channel `C…`, a private group `G…`) and the parent `ts`, both from the `slack_send_message` / permalink you already hold. The script routes each by its id prefix; channel threads only report if the Honk bot is a member of that channel. + +Launch so each stdout line wakes this session. Use the recipe whose tools you have. + +### Claude Code + +`Monitor` with `persistent: true`. The sandbox cannot read the Keychain or reach `slack.com` — allow both on that Monitor. + +``` +Monitor( + command: "scripts/slack-watch C0123ABCD:1700000000.000200 D0456WXYZ:1700000100.000700", + description: "Slack reply watcher", + persistent: true, +) +``` + +Give the absolute path to `scripts/slack-watch` if Monitor's working directory is not this skill's directory. + +### Cursor (local IDE) + +Background `Shell` (`block_until_ms: 0`) with `notify_on_output` and `required_permissions: ["all"]` (Keychain + `slack.com`). Cursor floors notification debounce at 5s — two `NEW` lines in one burst may arrive as one wake; on wake, read the terminal output and handle every `NEW` line, not only the last. + +``` +Shell( + command: "<absolute>/scripts/slack-watch C0123ABCD:1700000000.000200 D0456WXYZ:1700000100.000700", + description: "Slack reply watcher", + block_until_ms: 0, + required_permissions: ["all"], + notify_on_output: { pattern: "^NEW |^RECONNECTED", reason: "Slack reply" }, +) +``` + +Use the absolute path. Smoke-check the terminal output file once so a failed start is not silent. + +### Output lines + +- `NEW channel=<C…> thread_ts=<ts> ts=<ts>` — a new reply landed (or was missed during downtime and reconciled on reconnect). Read it with `slack_read_thread` on that `thread_ts`. Our own messages — the developer's **and** the Honk bot's, including agent follow-ups posted as either — and the thread's pre-existing history are **not** reported. +- `RECONNECTED` — the socket re-opened after a drop; a catch-up for every watched thread has just run, so any `NEW` lines around it are the replies missed while it was down. + +Diagnostics (auth or reconnect failures) go to stderr — Claude's Monitor output file, or Cursor's terminal file; Read it if the watcher seems quiet. + +### Changing the watched set + +All state lives in the process (thread list, per-thread last-seen `ts`, `event_id` dedupe). There is no state file. To add or remove a thread, **stop and relaunch** with the new argument list. + +- Claude Code: `TaskStop` on that Monitor, then launch again. +- Cursor: kill the PID in that shell's header, `AwaitShell` so the completion ping is consumed, then launch again. + +Re-spawning re-baselines to "from now" — earlier replies are already in the session transcript, so nothing is double-reported. + +**Done when:** the watcher is running and reporting, or the run has stopped for setup. + +## Setup + +One private Slack app in the Blockscout workspace (**api.slack.com/apps → your app**), carrying three tokens. Enable the bot user **Honk** 🪿 (`honk`) under **App Home** first — it is both the channel-reading identity and the disclosure identity. + +- **App-level token** (`xapp-`), scope `connections:write` — created under **Socket Mode → toggle on → generate token**. Opens the WebSocket. +- **User token** (`xoxp-`), **User Token Scopes** `im:history` + `chat:write`. Under **Event Subscriptions → on behalf of users**, subscribe **`message.im` only** — not `message.channels` / `message.groups` (that is a firehose on a user token). Reads DM replies and posts in the developer's own voice. +- **Bot token** (`xoxb-`), **Bot Token Scopes** `channels:history` (add `groups:history` for private channels) + `chat:write`. Under **Event Subscriptions → bot events**, subscribe **`message.channels`** (and `message.groups` for private channels). Bot events fire only for channels the bot is a member of, so **invite Honk to each question channel** (`/invite @Honk`) — that is what scopes the channel feed instead of firehosing. + +Store all three in the Keychain yourself (the script never writes them): + +```bash +security add-generic-password -U -s slack-orchestrator-app-token -a "$USER" -w # prompts for xapp-… +security add-generic-password -U -s slack-orchestrator-user-token -a "$USER" -w # prompts for xoxp-… +security add-generic-password -U -s slack-orchestrator-bot-token -a "$USER" -w # prompts for xoxb-… +``` diff --git a/.agents/skills/slack-watch/scripts/slack-watch b/.agents/skills/slack-watch/scripts/slack-watch new file mode 100755 index 00000000000..50a57b7e1c0 --- /dev/null +++ b/.agents/skills/slack-watch/scripts/slack-watch @@ -0,0 +1,226 @@ +#!/usr/bin/env node +// Slack Socket Mode reply watcher. Holds the WebSocket, acks every event, and +// prints one line per genuinely-new reply in a watched thread. It does no +// reasoning: the live session reads the thread itself (via the Slack MCP) when +// a NEW line arrives. It never prints message content and never logs event +// payloads — the user-token message.im feed is a DM firehose and must not leak. +// +// A single Socket Mode connection carries the app's bot events and its user +// events together, so DM and channel threads are watched over one socket. The +// two identities split by conversation type: DMs are the developer's own (user +// token), channels belong to the Honk bot invited into them (bot token). +// +// Three tokens, all from the macOS Keychain, never in argv, a dotfile, or output: +// app-level (xapp-) opens the Socket Mode socket — slack-orchestrator-app-token +// user (xoxp-) reads DM replies, is the DM identity — slack-orchestrator-user-token +// bot (xoxb-) reads channel replies, is the bot ident — slack-orchestrator-bot-token +// +// Node 22+ only: relies on the built-in global WebSocket and fetch — no npm deps. +// cspell:ignore acks xapp xoxp xoxb +'use strict'; + +const { execFileSync } = require('node:child_process'); + +const APP_TOKEN_SERVICE = 'slack-orchestrator-app-token'; +const USER_TOKEN_SERVICE = 'slack-orchestrator-user-token'; +const BOT_TOKEN_SERVICE = 'slack-orchestrator-bot-token'; +const FATAL_AUTH_ERRORS = new Set(['invalid_auth', 'not_authed', 'account_inactive', 'token_revoked']); + +function die(msg) { + process.stderr.write(`slack-watch: ${msg}\n`); + process.exit(1); +} + +function warn(msg) { + // stderr only — Monitor routes it to the output file, not to notifications. + process.stderr.write(`slack-watch: ${msg}\n`); +} + +function emit(line) { + process.stdout.write(line + '\n'); +} + +function keychain(service) { + try { + return execFileSync('security', ['find-generic-password', '-s', service, '-w'], { + encoding: 'utf8', + }).trim(); + } catch { + die(`no token in Keychain under service '${service}' — see the slack-watch skill (Setup)`); + } +} + +const num = (ts) => parseFloat(ts); + +// A message counts as a real reply unless its subtype marks it as noise +// (edits, joins/leaves, bot_message, channel chrome). Two subtypes are genuine +// human replies and must be kept: `thread_broadcast` (a reply the author also +// sent to the channel) and `file_share` (a reply that carries attachments — +// e.g. screenshots). Plain replies have no subtype at all. +const KEPT_SUBTYPES = new Set([ 'thread_broadcast', 'file_share' ]); +const isReply = (m) => !m.subtype || KEPT_SUBTYPES.has(m.subtype); + +// argv: one "CHANNEL:THREAD_TS" per watched thread. lastTs is the per-thread +// watermark; it starts at thread_ts and only ever advances. +const watched = new Map(); +for (const arg of process.argv.slice(2)) { + const i = arg.indexOf(':'); + if (i < 0) die(`bad thread arg '${arg}', expected CHANNEL:THREAD_TS`); + const channel = arg.slice(0, i); + const thread_ts = arg.slice(i + 1); + watched.set(`${channel}:${thread_ts}`, { channel, thread_ts, lastTs: thread_ts }); +} +if (watched.size === 0) die('no threads to watch — pass CHANNEL:THREAD_TS args'); + +const appToken = keychain(APP_TOKEN_SERVICE); +const userToken = keychain(USER_TOKEN_SERVICE); +const botToken = keychain(BOT_TOKEN_SERVICE); + +const seenEventIds = new Set(); +const ownIds = new Set(); // our own user ids (developer + Honk bot) — never a reply to notify on. +let ws = null; +let established = false; // flips on the first `hello`; later `hello`s mean a reconnect. +let reconnectTimer = null; + +// DM channels (D…) are read with the user token; channels (C…) and private +// groups (G…) are read with the bot token, which has history only where the bot +// was invited. +const tokenFor = (channel) => (channel[0] === 'D' ? userToken : botToken); + +async function call(method, token, params = {}, httpMethod = 'GET') { + const qs = new URLSearchParams(params).toString(); + const url = `https://slack.com/api/${method}` + (httpMethod === 'GET' && qs ? `?${qs}` : ''); + const res = await fetch(url, { + method: httpMethod, + headers: { + Authorization: `Bearer ${token}`, + ...(httpMethod === 'POST' ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}), + }, + body: httpMethod === 'POST' ? qs : undefined, + }); + return res.json(); +} + +// Advance each thread's watermark to Slack's current state. emitMissed=false is +// the first-connect baseline (adopt "from now" silently — earlier replies are +// already in the session transcript); emitMissed=true is the post-downtime +// catch-up that prints what was missed while the socket was down. +async function reconcile(emitMissed) { + for (const w of watched.values()) { + let res; + try { + res = await call('conversations.replies', tokenFor(w.channel), { + channel: w.channel, + ts: w.thread_ts, + oldest: w.lastTs, + inclusive: 'false', + limit: '200', + }); + } catch (e) { + warn(`replies ${w.channel}: ${e.message}`); + continue; + } + if (!res.ok) { + warn(`replies ${w.channel}: ${res.error}`); + continue; + } + for (const m of res.messages || []) { + // Drop edits/joins/bot_message and our own posts; keep genuine replies + // (plain, thread_broadcast, file_share — see isReply). + if (!isReply(m) || ownIds.has(m.user)) continue; + if (num(m.ts) <= num(w.lastTs)) continue; + if (emitMissed) emit(`NEW channel=${w.channel} thread_ts=${w.thread_ts} ts=${m.ts}`); + w.lastTs = m.ts; + } + } +} + +function handleEvent(payload) { + const eventId = payload.event_id; + if (eventId) { + if (seenEventIds.has(eventId)) return; + seenEventIds.add(eventId); + } + const e = payload.event; + // genuine replies only (plain, thread_broadcast, file_share) — drop edits/joins/bot_message. + if (!e || e.type !== 'message' || !isReply(e)) return; + if (ownIds.has(e.user)) return; // our own follow-ups (developer or bot) arrive here too — ignore them + const thread_ts = e.thread_ts; + if (!thread_ts) return; // a top-level message, not a threaded reply + const w = watched.get(`${e.channel}:${thread_ts}`); + if (!w || num(e.ts) <= num(w.lastTs)) return; + emit(`NEW channel=${e.channel} thread_ts=${thread_ts} ts=${e.ts}`); + w.lastTs = e.ts; +} + +function handleFrame(data) { + let msg; + try { + msg = JSON.parse(data); + } catch { + return; + } + if (msg.type === 'hello') { + if (!established) { + established = true; + reconcile(false); + } else { + emit('RECONNECTED'); + reconcile(true); + } + return; + } + if (msg.type === 'disconnect') { + // Slack asks us to reconnect (refresh/too-many-connections). Close and the + // close handler reopens on a fresh URL. + if (ws) ws.close(); + return; + } + if (msg.envelope_id) { + // Ack within Slack's 3s window, before doing anything else with the event. + ws.send(JSON.stringify({ envelope_id: msg.envelope_id })); + } + if (msg.type === 'events_api') handleEvent(msg.payload); +} + +function scheduleReconnect() { + if (reconnectTimer) return; + reconnectTimer = setTimeout(() => { + reconnectTimer = null; + // Retry the whole init, not just connect(): if a startup auth.test threw + // (network/JSON), ownIds is still empty, and opening the socket then would + // report our own posts as NEW. init() re-runs auth.test until ownIds is + // populated; on a plain socket drop it skips straight to connect(). + init().catch(scheduleReconnect); + }, 1000); +} + +async function connect() { + const open = await call('apps.connections.open', appToken, {}, 'POST'); + if (!open.ok) { + if (FATAL_AUTH_ERRORS.has(open.error)) die(`apps.connections.open: ${open.error} (check the app-level token)`); + throw new Error(`apps.connections.open: ${open.error}`); + } + ws = new WebSocket(open.url); + ws.addEventListener('message', (ev) => handleFrame(typeof ev.data === 'string' ? ev.data : '')); + ws.addEventListener('close', scheduleReconnect); + ws.addEventListener('error', () => {}); // a close event always follows; reconnect there +} + +// Establish our own identities, then open the socket. ownIds is populated +// atomically — both auth.test calls succeed before either id is added — so a +// thrown call leaves it empty and a retry re-runs both. Once it is filled (the +// common case on a socket-drop reconnect) init() skips auth.test and reconnects. +async function init() { + if (ownIds.size === 0) { + const user = await call('auth.test', userToken); + if (!user.ok) die(`auth.test: ${user.error} (check the user token)`); + const bot = await call('auth.test', botToken); + if (!bot.ok) die(`auth.test: ${bot.error} (check the bot token)`); + ownIds.add(user.user_id); + ownIds.add(bot.user_id); + } + await connect(); +} + +init().catch(scheduleReconnect); diff --git a/.agents/skills/to-spec/SKILL.md b/.agents/skills/to-spec/SKILL.md index 41d6615fde3..bb0757cfbba 100644 --- a/.agents/skills/to-spec/SKILL.md +++ b/.agents/skills/to-spec/SKILL.md @@ -20,14 +20,22 @@ every task gets a spec — see "Not every task needs a spec" in ## Step 1 — Write the spec and questions Derive the task folder from the issue: `.agents/tasks/<issue-number>-<slug>/` (layout in -[`../../tasks/structure.md`](../../tasks/structure.md)). Write two files: +[`../../tasks/structure.md`](../../tasks/structure.md)). Write files: - **`spec.md`** from [`spec-template.md`](spec-template.md). - **`questions.md`** from [`questions-template.md`](questions-template.md). + Keep the spec an **index of decisions**, not a worklog — what to build and why, pointing at detail (its -Slack thread, the code, the PR) rather than copying it. **Show the user the two files and get their -confirmation of the content — this is the run's one gate.** +Slack thread, the code, the PR) rather than copying it. + +**The header holds only rows with something to say.** Drop a row the grilling left empty (no designer, no +API raise, no feature channel) rather than filling it with `—`; `create-pr` and `finalize-task` read an +absent row as "none". The `Demo` row is always present, written from the grilling's demo answer in the +shape [`../deploy-demo/demo-entries.md`](../deploy-demo/demo-entries.md) gives — the entries are +positional, so its order rule applies. + +**Show the user the files and get their confirmation of the content — this is the run's one gate.** ## Step 2 — Branch and draft PR @@ -37,6 +45,6 @@ again** — it authorizes the branch, commit, push, and draft PR together: 1. **Branch** — `issue-<number>` off `main`. Create/switch if needed and record it in the spec header. 2. **Commit** — commit `spec.md` and `questions.md` as the branch's first commit. 3. **Draft PR** — hand off to the `create-pr` skill (draft-placeholder mode, feature branch → `main`); it - pushes and opens the draft with no further confirmation. Why the draft opens this early is in + pushes and opens the draft. Why the draft opens this early is in [`../../tasks/README.md`](../../tasks/README.md). diff --git a/.agents/skills/to-spec/questions-template.md b/.agents/skills/to-spec/questions-template.md index d8c4b557152..7406a21c82a 100644 --- a/.agents/skills/to-spec/questions-template.md +++ b/.agents/skills/to-spec/questions-template.md @@ -3,11 +3,16 @@ <!-- One entry per question, with a stable id (`Q01`, `Q02`, …). The id is what a ticket names in its `Blocked by` to declare the question gates it, so ids never change once assigned. `to-spec` creates this file and records each Slack permalink when the question is sent; answers are folded in later by a plain -edit — the decision as a phrase plus its date, not the deliberation. --> +edit — the decision as a phrase plus its date, not the deliberation. + +`Resolved when:` names the discrete facts a sufficient reply must contain — write it when authoring the +question. It gives "is this answer enough?" something concrete to check against and gives a follow-up a +target. Phrase it as a checklist of facts." --> ### Q01 — <question> - Owner: <role> (<name>) - Status: `pending` \| `resolved` \| `waived` +- Resolved when: <the discrete facts a sufficient reply must contain> - Slack: <permalink, once sent> - Answer: <the decision as a phrase, + date> diff --git a/.agents/skills/to-spec/spec-template.md b/.agents/skills/to-spec/spec-template.md index ebabc08cb25..85c7744c037 100644 --- a/.agents/skills/to-spec/spec-template.md +++ b/.agents/skills/to-spec/spec-template.md @@ -7,12 +7,16 @@ | PM | <name> | | Designer | <name> | | Backend | <name> | -| Minimum API version | <API version(s) this task requires, e.g. "Core API v11.2.4+"; list several for a multi-service raise; "—" if none> | -| Slack channel | <#feature-channel if the task has one; otherwise "—" (default routing per `grill-the-task`)> | +| Minimum API version | <API version(s) this task requires, e.g. "Core API v11.2.4+"; list several for a multi-service raise> | +| Slack channel | <#feature-channel, when the task has one> | +| Demo | <from grilling; shape in `.agents/skills/deploy-demo/demo-entries.md`> | <!-- Header is static identity — no status row: task status is derived from `progress.md` (see -`.agents/tasks/structure.md`). People default from `.agents/TEAM.md`; override here per task. The spec body -below is immutable once written; only `progress.md` and `questions.md` change as work proceeds. --> +`.agents/tasks/structure.md`). Drop a row that has nothing to say (no designer, no API raise, no feature +channel) instead of filling it with "—"; readers treat an absent row as "none". `Demo` is the one row that +always stays, because its value drives the land step's deploys. People default from `.agents/TEAM.md`; +override here per task. The spec body below is immutable once written; only `progress.md` and +`questions.md` change as work proceeds. --> ## Context & goal @@ -32,8 +36,8 @@ staging-only) and the backend release version that ships the changes (for releas ## UI inventory <!-- Affected pages/tabs/components: routes, navigation entry points, cross-links to existing entity -pages. One Figma node link per screen. State behavioral facts and placement; leave appearance to the -mockups and the [human] style leaves. When you must lean on existing code, point to it by component or +pages. One Figma node link per screen and state. State behavioral facts and placement; leave appearance +to the mockups and the style leaves. When you must lean on existing code, point to it by component or symbol name ("match `LogDecodedInputDataTable`") — never transcribe its values, class names, or line numbers; those rot and the code owns them. Capture only a deliberate deviation and its reason. See "What the spec holds" in `.agents/tasks/concepts.md`. --> diff --git a/.agents/skills/to-tickets/SKILL.md b/.agents/skills/to-tickets/SKILL.md index ce2e91dd651..e425351e2e9 100644 --- a/.agents/skills/to-tickets/SKILL.md +++ b/.agents/skills/to-tickets/SKILL.md @@ -20,7 +20,8 @@ and note it, rather than guessing. ## Step 1 — Load Resolve the task folder from the issue number or the branch (`issue-<number>`), and read its `spec.md`, -`questions.md` and `.agents/delegation.md`. +`questions.md` and `.agents/delegation.md`. An `inbox.md` with a section whose status is `pending` is a +stop: tell the developer to run `process-task-inbox` first, and end. ## Step 2 — Explore the codebase (optional) @@ -31,7 +32,7 @@ Look for opportunities to prefactor the code to make the implementation easier. ## Step 3 — Draft slices Break the work into tracer bullet tickets. -- Each slice cuts a narrow but COMPLETE path through every layer (schema, API, UI, tests) — a vertical slice. +- Each slice cuts a narrow but COMPLETE path through every layer (schema, API, UI, tests) — a vertical slice. Visual tests (`*.pw.tsx`) are not a required layer of that path; read `.agents/rules/tests-visual.md` Purpose before adding a suite. - A completed slice is demoable or verifiable on its own - Each slice is sized to fit in a single fresh context window - Any prefactoring should be done first @@ -62,16 +63,20 @@ For every `[agent]` leaf that runs a project skill (`add-new-page`, `add-api-res **open that skill and run its user-facing interview now**, against the spec — from the skill's current text, not from memory of its questions (e.g. `add-new-page` Step 0). Record the answers in the ticket's **Skill inputs** section, grouped by skill. Where the spec answers a question, take the answer from it and move on; -where it has a genuine gap, ask the developer. This is what lets the later `implement-ticket` run go -uninterrupted. +where it has a genuine gap, ask the developer. What the developer can't settle is not theirs to guess: +record it as a `Q<NN>` to the owning contact in `questions.md` and a `Blocked by Q<NN>` edge on the +ticket. This is what lets the later `implement-ticket` run go uninterrupted. ## Step 6 — Write the files Per approved ticket, write `tickets/NN-<slug>/spec.md` from [`ticket-template.md`](ticket-template.md) — What to build, Acceptance criteria (tagging `(human)` per the ticket model), the Skill inputs from Step 5, the Leaf worklist with each leaf tagged `[agent]` / `[human]` per `.agents/delegation.md`, and the header's -`Blocked by` edges (`T<NN>` / `Q<NN>`). A ticket that can't be scoped gets a `brief.md` instead — its goal, -the known context, and the blocking unknowns with their owners. +`Blocked by` edges (`T<NN>` / `Q<NN>`). UI leaves follow the rule in "Leaves" in `.agents/tasks/concepts.md`: every linked Figma node gets one +`[agent]` style leaf, after the scaffold leaf when there is one; it links its Figma node and, when the task +folder has a `design-readout.md`, that node's block in it, and the ticket carries the criterion +`(human) <component> matches the mockup at every breakpoint`. A ticket that can't be scoped gets a +`brief.md` instead — its goal, the known context, and the blocking unknowns with their owners. Create (or append to) `progress.md` from [`progress-template.md`](progress-template.md) — one checkbox line per ticket. When scoping a deferred ticket, **append** its siblings and retarget the `Blocked by` edges that diff --git a/.agents/skills/to-tickets/ticket-template.md b/.agents/skills/to-tickets/ticket-template.md index 7fec9875b30..3a97b03586b 100644 --- a/.agents/skills/to-tickets/ticket-template.md +++ b/.agents/skills/to-tickets/ticket-template.md @@ -30,6 +30,7 @@ How to verify: `pnpm dev:preset <alias>`, open <route> - [ ] <criterion the review can check from the diff> - [ ] `(human)` <criterion only a person judging the running product can check> +- [ ] `(human)` <component> matches the mockup at every breakpoint <!-- mandatory on a ticket with a style leaf --> ## Details @@ -55,12 +56,18 @@ the developer and records the answer here. --> then styling) while the ticket cuts across them. Tag every leaf `[agent]` or `[human]` — explicitly, never implied; `implement-ticket` reads the tags as its -state machine. A UI component is two linked leaves (scaffold → style). A leaf names the skill it runs; its -answers live in Skill inputs above, not inline here. +state machine. UI work follows the leaf rule in "Leaves" in `.agents/tasks/concepts.md` — so a new page is +`add-new-page` → style, while a change to an existing component is the style leaf alone. Visual tests are not a third leaf by default; extend or pack per +`.agents/rules/tests-visual.md`. A leaf names the skill it runs; its answers live in Skill inputs above, +not inline here. + +The style leaf links the Figma node (and the mobile node, when the spec has one) and, when the task has a +`design-readout.md`, that node's block in it, right beside the node; a task without a readout links the +node alone. The ticket then carries the mandatory `(human)` criterion above. A leaf's checkbox is PROGRESS STATE — how far the ticket has got, since it has no commit yet. It is never a changelog: one line at most, and durable decisions get folded into the sections above instead. --> - [ ] 1 `[agent]` <title> — skill: `add-api-resource` - [ ] 2 `[agent]` <title> — skill: `add-new-page` -- [ ] 3 `[human]` Style <component> to mockup — [Figma](<node URL>) +- [ ] 3 `[agent]` Style <component> to mockup — [Figma](<node URL>) · [readout](../../design-readout.md#<node heading anchor>) diff --git a/.agents/skills/triage-monitoring-event/SKILL.md b/.agents/skills/triage-monitoring-event/SKILL.md new file mode 100644 index 00000000000..5e66842ba79 --- /dev/null +++ b/.agents/skills/triage-monitoring-event/SKILL.md @@ -0,0 +1,130 @@ +--- +name: triage-monitoring-event +description: Triage one error-monitoring event end-to-end — mute it as noise, or open a PR with the fix. +disable-model-invocation: true +argument-hint: <event URL or id, or a Slack message/thread link carrying one> +--- +# Triage a monitoring event + +One event in, one of three outcomes out: the event is **muted** in the monitoring tool, a **PR** with +the fix is open, or the event is reported as **already fixed** on `main`, with the commit named. The mute +and the PR are a click to undo, and the third changes nothing, so the run goes end-to-end without asking. +The user reads the final message. + +The monitoring provider is Rollbar; everything provider-specific — reaching the tool, reading an event, +muting it — is in [`rollbar.md`](rollbar.md). The steps below name the operations; that file says how. + +## Steps + +### 1. Resolve the input + +- An **event URL or id** — that is the event. +- A **Slack message or thread link** — read it per `.agents/slack-thread.md`; the event is the first + event link in the thread. Keep the thread: the outcome is posted back there (step 7). Several + distinct event links, or none, is a stop: ask which one, or for the link. +- Anything else is a stop: ask for the event link. + +**Done when:** exactly one event is named. + +### 2. Check the tool + +Run the provider's **precheck**. A missing tool or a rejected token is a stop: tell the user what to +configure, from the provider doc, and end there. + +**Done when:** the precheck returned data. + +### 3. Read the event + +**Fetch the event** and a handful of its occurrences, so the sample is not one visitor. Collect: the +title and exception class, the occurrence count, first and last timestamps, the release version, and +per occurrence the page URL, the user agent and the telemetry leading up to the error. + +A **group item** (the provider doc says how it answers) has no occurrences of its own: a stop — ask for +the link of one of its constituent items. + +**Done when:** the event and every occurrence the list returned are in hand, however many came back. + +### 4. Locate the code + +Find the throw site by the signals that survive a production build (see the provider doc for what +the frames do and do not give): + +- the **message text**: `grep` it in `src/`, including the templates it may have been built from; +- the **page**: the page URL maps to a route under `src/pages`; the error is on that route's render path; +- the **telemetry**: the console and network lines before the error name the request or action that + triggered it; +- the **release**: the release version is a git tag or, for a build without one, a commit SHA; either is + a rev. If `main` has since changed the suspected code, read it as of that rev (`git show <rev>:<path>`) + and check whether `main` already fixed it — that is the **Already fixed** outcome in step 5, with the + fixing commit named. + +**Done when:** the throw site is named, or it is established that the throw is outside our code (browser, +extension, SDK, infrastructure). + +### 5. Classify + +Pick one outcome, with the test: + +| Outcome | When | +| --- | --- | +| **Mute** | Noise: the throw is environmental or outside our code — scraper and headless user agents, extensions, network and infra failures, a vendored SDK's expected rejection — and nothing we ship would change it. | +| **Fix PR** | Our code throws, or handles a legitimate situation badly, on a path a real user reaches, and `main` still has the bug. | +| **Already fixed** | A bug by the Fix PR test, but a commit on `main` after the release already fixes it. | + +A mute silences one event signature. When the same noise family will come back under new titles (a +variable URL, host or count in the message), a **filter** is the fix — a `checkIgnore` helper or an +`ignoredMessages` entry in `src/services/rollbar/clientConfig.ts`, with the reason comment that file's +entries carry. That is the Fix PR outcome, and the event is muted too (step 6a), since the filter only +lands with the next release — the one case where a fix PR also mutes. + +**Done when:** the outcome and its one-paragraph justification are written down for the final message. + +### 6a. Mute + +**Mute the event** per the provider doc. + +**Done when:** the tool reports the new status. + +### 6b. Fix PR + +Work on a fresh branch off `origin/main`: `monitoring-<id>-<kebab-slug>`. Apply the project rules +(`.agents/rules/code-quality.md`, `.agents/rules/typescript.md`, `.agents/rules/tests-unit.md`): a +regression unit test where the throw is unit-testable, lint and type-check clean on the changed files. + +Then follow the `create-pr` skill, Mode C. The Description names the +event as a link, the occurrence count and the environment signal that made it a bug, and what the fix +changes. The event stays active in the monitoring tool, so it resolves when the release carrying the fix +ships — except when the fix is a filter (step 5), which also runs 6a. + +**Done when:** the PR link is in hand and `git status` is clean. + +### 6c. Already fixed + +Nothing to change: no PR, and the event stays active in the monitoring tool. It resolves when the release carrying the fixing commit ships. (Marking it resolved +against the commit does not work. See explanation in provider doc.) + +**Done when:** the fixing commit on `main` is named for the final message. + +### 7. Report + +Compose the **final message**: the outcome in one line with its link (PR, or the event), the +justification from step 5, for a mute the one-line test a future reader can reuse to recognise the same +noise, and for an already-fixed event the commit on `main` that fixes it and that the event stays active +until the release carrying it ships. + +When the input was a Slack thread, post the same text as a reply in that thread, written per +`.agents/slack-message.md`. Post it without asking — the named exception to `AGENTS.md`'s +approve-before-sending rule. + +**Done when:** the message is shown to the user and, for a Slack-sourced run, posted in the thread. + +## Run by Honk + +When the Honk orchestrator runs this skill headless, follow [`honk.md`](../../honk.md). This skill adds +no statuses of its own; the shared three with their triggers here: + +| Status | When | Resumed? | +| --- | --- | --- | +| `done` | the event is muted, the PR is open, or the fixing commit is named, and the step 7 message is shown — and, for a Slack-sourced run, posted; the message is that text | no | +| `needs_user` | step 1 found no event link or several, the precheck failed, or step 3 hit a group item; the message carries the question (for a group item, which constituent-item link to send) or the setup to do | yes, with the answer | +| `needs_approval` | the mute, the push, the PR creation or the Slack reply needs a tool the worker profile denies; the message carries exactly what would be done | yes, once a human did it or allowed it | diff --git a/.agents/skills/triage-monitoring-event/rollbar.md b/.agents/skills/triage-monitoring-event/rollbar.md new file mode 100644 index 00000000000..ea7f5289a90 --- /dev/null +++ b/.agents/skills/triage-monitoring-event/rollbar.md @@ -0,0 +1,46 @@ +# Rollbar + +The provider part of the `triage-monitoring-event` skill. + +Rollbar is reached through its MCP server (`@rollbar/mcp-server`, tools prefixed `mcp__rollbar__`). +The tool schemas are the manual for names and parameters; this file holds only what they cannot say. + +## Precheck + +Call the cheapest read: list the projects. Three ways it fails, each a stop with its remedy: + +- **No `mcp__rollbar__*` tools in the session** — the server is not configured. Add it to the MCP + config with the token in its environment: + `claude mcp add rollbar -e ROLLBAR_ACCOUNT_ACCESS_TOKEN=<token> -- npx -y @rollbar/mcp-server`. +- **Auth error** — `ROLLBAR_ACCOUNT_ACCESS_TOKEN` is missing or wrong in the server's environment. It + is an account access token (Rollbar → account settings → Account Access Tokens) with **read and + write** scope; read-only cannot mute. +- **Project list without `Frontend`** — the token belongs to another account. Same remedy. + +Other token sources the server accepts (`ROLLBAR_ACCESS_TOKEN`, `.rollbar-mcp.json`) are in its README; +the variable above is the one this skill expects. + +## Reading an event + +- An event is an **item**. The URL ends `/item/Frontend/<counter>`; the counter, plus the project + `Frontend`, is what the read tools take. +- Fetch the item details, then list occurrences with a limit of five or so. A full occurrence nests its + payload under `data`: the page is `data.request.url`, the user agent `data.client.javascript.browser`, + the release `data.code_version` and the console trail `data.body.telemetry`. +- The list is budgeted by `max_tokens`. When the response carries a top-level `_truncation`, some + occurrences came back below `full` (`_tier` says which): the `compact` tier keeps only level, + environment, `code_version` and the exception message, so page, user agent and telemetry are gone. + Raise `max_tokens` or lower the limit until the ones to read are `full`. +- A **group item** answers `group_item_not_supported` instead of a list: its occurrences are on its + constituent items, which the response does not name — the skill stops there and asks for one. +- **Frames are minified and no source maps are uploaded**, so file, line and column in the trace name + nothing. Only the message, the page, the telemetry and the release locate the code. + +## Muting + +Update the item to status `muted`. The update tool takes the item's numeric **`id`** from the details +response (the long one, `1806137227`-shaped) — **not** the counter from the URL. They are different numbers. + +An already-fixed event is **not** resolved here: `resolvedInVersion` reactivates only on a semver `>=` or, +when both sides are SHAs, on commit ancestry, and the deployed `code_version` is a release tag while the +fix is a commit SHA, so the item would never reopen. Leave it active. diff --git a/.agents/slack-message.md b/.agents/slack-message.md new file mode 100644 index 00000000000..02faa0d23de --- /dev/null +++ b/.agents/slack-message.md @@ -0,0 +1,29 @@ +# Compose a Slack message + +How to write a message the Slack connector (`slack_send_message`) posts. Who to send it to is up to the skill that sends it. Slack IDs come from `./TEAM.md`. + +## Language + +Russian — the team's internal language. A reply in an existing thread matches the thread's language. + +## Addressing + +- **Person** — the *Slack member ID* (`U…`). Mention as `<@U…>`; to DM, pass the ID as the channel to the send tool. +- **Team / group** — the *Slack group ID* (`S…`). Mention as `<!subteam^S…>`. +- **Channel** — the *Channel ID* (`C…`). Pass it as the channel target when sending; refer to it in prose by its `#name`. +- **Permalink** — `https://blockscout.slack.com/archives/<channel-id>/p<message-ts>` (the message timestamp with the dot removed). + +## Links + +End a bare URL with a space, an empty line, or the end of the message. Slack's link parser runs through a single line break: with `https://example.com` followed by a newline and `Next line`, the next line's first word becomes part of the link, and Cyrillic gets punycoded into the hostname (`…xn--com-…`). + +``` +Демо: +https://review-foo.k8s-dev.blockscout.com + +Посмотри, пожалуйста. +``` + +## Attribution + +The connector appends a *Sent using* footer naming the agent to every message, so a message sent through it already discloses that an agent wrote it. diff --git a/.agents/tasks/2480-advanced-settings-custom-rpc/spec.md b/.agents/tasks/2480-advanced-settings-custom-rpc/spec.md new file mode 100644 index 00000000000..925a5c41fc3 --- /dev/null +++ b/.agents/tasks/2480-advanced-settings-custom-rpc/spec.md @@ -0,0 +1,200 @@ +# Advanced site settings modal with a user-defined RPC node + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/2480 (custom RPC) + https://github.com/blockscout/frontend/issues/2519 (settings modal) | +| Feature branch | `issue-2480` | +| PM | Ulyana | +| Designer | Tatyana | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +Contract reads and writes on the contract page go through the RPC node the instance operator configured. +When that node is down or rate-limited, the user sees a raw viem error ("HTTP request failed.") and has +no way out. The goal is to let the user point the explorer at their own RPC node and make the failure +actionable: the error names the problem and links straight to the setting. + +The setting needs a home. The current top-bar settings popover is a flat list of toggles; the design +introduces an "Advanced site settings" modal with tabs and trims the popover to colour theme, identicon +and a link to the modal. The two issues ship together: the modal is where the RPC setting lives, and the +RPC setting is what makes the modal worth opening. + +Designer thread with the settled answers: +https://blockscout.slack.com/archives/D03PDKKMLQH/p1792678732622049 + +## Functional requirements + +1. The top-bar settings popover shows only the colour theme picker, the identicon picker and an + "Advanced settings" link that opens the modal. The scam-tokens, poor-reputation, address-format and + local-time controls leave the popover and live in the modal. +2. The "Advanced site settings" modal has two tabs: **General** and **Custom RPC**. On desktop the tab + list is vertical on the left and the active tab's content is on the right. The General tab is always + present; the Custom RPC tab is subject to the gate in FR13. Each control inside a tab keeps its own + visibility gate. +3. General tab, under the heading "General site settings", in this order: colour theme picker, identicon + picker, "Show {prefix} address format" switch (only when the chain has more than one address format), + "Hide scam tokens" and "Hide poor reputation tokens" switches (same behaviour as today: cookie write, + page reload, same gates as in the popover before), "Local time format" switch (persisted in the cookie + the settings context already reads). A hidden control leaves no gap. +4. *(merged into FR3)* +5. *(merged into FR3)* +6. Custom RPC tab: the tab description, a URL field, a Save button, a plug icon button (connect / + disconnect), a status line (status tag + which node the app uses) and, when the custom node has a + problem, an alert under the status line. Plug, status line and alert exist only while a custom URL + is saved; with no saved URL the tab is description, field and Save. The field is pre-filled with + the saved custom URL, or shows the first configured RPC URL as the placeholder when none is saved. +7. Only `https://` URLs are accepted; anything else shows "Invalid format" under the field and keeps + Save disabled. Save is enabled only when the field value differs from the saved value. +8. Saving a URL stores it, marks it as in use and reloads the page; the modal does not reopen after + the reload. Clearing the field and saving removes the stored URL and reloads, returning to the + configured node. The plug button toggles whether the saved URL is in use without forgetting it: + "disconnect" switches the app back to the configured node and reloads, "connect" switches back to + the saved URL and reloads. A saved node that turns out to be broken is never auto-disconnected; the + user decides to disconnect it or to save another URL. +9. The saved custom URL, while in use, is pinged with `eth_chainId`: on every page load (it feeds FR16 + and FR17) and every time the RPC tab is shown. The configured node is never pinged. The ping has + four outcomes: **connected** (answers with the + explorer's chain id), **wrong chain** (answers with another chain id), **unknown chain** (answers, + but not with a chain id), **not responding** (no JSON-RPC answer: HTTP error, timeout, CORS). The + RPC tab shows the outcome as a status tag — "Connected" (green), "Not responding" (red) — followed + by "Using your custom node", and an alert under the status line for wrong chain (warning), unknown + chain (info) and not responding (error). While the saved URL is not in use the status line is the + grey "Disconnected" tag followed by "Using the default node", no ping, no alert. The plug button shows the connected + icon coloured by outcome (green / orange / red) while the custom URL is in use, the grey + disconnected icon while the saved URL is not in use. The field stays editable in every state. +10. While a custom URL is in use, every browser-side RPC request for the explorer's own chain goes to + that URL only: the wagmi transports (contract read / write / simulate, revoke, L2 claims) and the + standalone public client (degraded-mode home, tx, block, address fallbacks). The configured URLs + and the core-API `eth-rpc` fallback are not used while the custom URL is set. +11. The custom URL is permitted by the Content Security Policy for that user only: the CSP middleware + adds the cookie's URL to `connect-src` per request. No blanket relaxation of `connect-src`. +12. On the contract page, when a method call fails at the transport or node level (HTTP error, + timeout, rate limit, internal node error), the result area shows an alert instead of the raw viem + message: "The RPC node is not responding. Try your own RPC node." with the default node, or "Your + RPC node is not responding. Change the RPC node URL." with a custom one. The linked phrase opens the + modal on the Custom RPC tab without a reload. Contract reverts and ABI/argument errors keep their + current rendering. +13. The Custom RPC tab is hidden on multichain instances and when the chain has no configured RPC URL. +14. Saving or clearing the custom URL logs one Mixpanel event. +15. The modal is adaptive: on desktop a centred dialog with the vertical tab list (icon + label); on + mobile a full-height bottom sheet with the same two tabs as a horizontal secondary tab list under + the title (label only), content below. "Open on tab X" selects that tab on both layouts. +16. While a custom URL is in use, the top bar shows a plug icon (next to the CSV export icon, all + breakpoints) coloured by the last ping: green connected, orange wrong / unknown chain, red not + responding. Its tooltip carries the status and the same warning / error text as the RPC tab's + alert; a click opens the modal on the Custom RPC tab. +17. While a custom URL is in use, the contract page's methods alert row gains a "Custom RPC" pill with + the plug icon, in front of the wallet alert: grey when connected, orange on wrong / unknown chain, + red when not responding. A click opens the modal on the Custom RPC tab. Nothing is shown with the + default node. + +## Data & API + +No backend API involved. No new environment variable: the Custom RPC tab is gated on the existing +`NEXT_PUBLIC_NETWORK_RPC_URL` being set and multichain being off. + +Browser-side JSON-RPC used for verification: `eth_chainId` POSTed to the node URL; the hex result is +compared with the configured chain id. A 2xx answer whose `result` is not a hex chain id (or a JSON-RPC +error object) is "unknown chain"; no answer at all is "not responding". + +## UI inventory + +- **Top-bar settings popover** (existing) — trimmed to theme, identicon, "Advanced settings" link. + Figma: https://www.figma.com/design/4In0X8UADoZaTfZ34HaZ3K/BS_2.0-Components?node-id=19733-225343 +- **Advanced site settings modal**, 728×560 on desktop, two tabs. Desktop frame with the General tab + (tab list: `gear` General, `link` Custom RPC): + https://www.figma.com/design/4In0X8UADoZaTfZ34HaZ3K/Blockscout-design-system?node-id=34294-12488 + Mobile (bottom sheet, horizontal secondary tabs under the title, General tab shown): + https://www.figma.com/design/OjqHcLt95E6kq5ElO79EKT/%F0%9F%93%B1-Blockscout-mobile-version?node-id=456-47003 + The mobile frame labels the last switch "Date time format"; the desktop label "Local time format" wins. + - Custom RPC tab content, all states (default connected, default not responding, edit, invalid, save, + custom with chain mismatch, custom with unknown chain, custom not responding): + https://www.figma.com/design/4In0X8UADoZaTfZ34HaZ3K/Blockscout-design-system?node-id=24378-86455 + Deviations from the frame, agreed with the PM: the text after the status tag names the node in use + (FR9) instead of repeating the problem; the "custom not responding" state keeps the *connected* + plug icon in red (the app never disconnects on its own); the two default-node states collapse to + description + field + Save (no plug, no status line, FR6). + - Superseded four-tab frames (Scam tokens / RPC node / Appearance / Time format), kept for the + switch-state references only: `node-id=24385-88460` (switch states `node-id=24377-85724`). +- **Contract page, Read / Write method result** — the "not responding" alert. Reference screenshot in + the issue comment on #2480; no Figma node. +- **Top bar custom-RPC indicator** (FR16), mobile top bar node: + https://www.figma.com/design/4In0X8UADoZaTfZ34HaZ3K/Blockscout-design-system?node-id=34246-7308 + (the icon itself is `I34246:7308;34246:5456`; the red variant is drawn, green / orange follow the + contract pill's colours). +- **Contract page "Custom RPC" pill** (FR17), three colour states: + https://www.figma.com/design/4In0X8UADoZaTfZ34HaZ3K/Blockscout-design-system?node-id=34259-25460 + +Entry points: the popover link; the contract-page alert link, the top-bar indicator and the contract +"Custom RPC" pill (all three open the modal directly on the RPC tab). + +Copy (agreed with the designer, may be shortened but must keep the message): +- RPC tab description: "Requests made directly from your browser, such as contract reads and writes, go + through a public RPC node. Use your own node if the default one is slow, rate-limited, or you want to + keep requests private. Indexed data such as blocks, transactions and balances still comes from the + Blockscout API. HTTPS only. Clear the field and save to go back to the default." (the former + separate "leave empty" helper is folded into it; rewritten after review to explain what the node is + used for, replacing the designer's original "match your selected network" wording) +- RPC status line: tag "Connected" / "Not responding" / "Disconnected", then "Using the default node" / + "Using your custom node" +- RPC alerts: wrong chain — "This RPC belongs to a different network. Make sure you're using the correct + RPC URL to avoid displaying incorrect data."; unknown chain — "We couldn't identify the network for + this RPC. Please verify the RPC URL and make sure it matches your selected network."; not responding + — "This RPC node isn't responding. Check the URL and try again." +- Top-bar tooltip: "Custom RPC: {tag}" plus the alert text when there is one + +## Implementation decisions + +- **Settings modal is a new feature module** owning the modal shell, the tab registry and each tab's + content, with an app-level open/close state (open with a target tab) so both the popover link and the + contract alert can open it. Existing popover controls are moved, not duplicated: each control + component is reused inside its tab, and the popover renders only what FR1 lists. +- **No post-save verification flow**: Save writes the cookie and reloads, nothing else. The page load + that follows pings the custom node (FR9) and the top-bar indicator / contract pill show the result, + so a bad node is visible right after the reload without any extra step. A wrong-chain node does not + trigger the contract-page "not responding" alert (calls return empty data, which viem reports as a + contract error); the orange indicator and pill cover it. +- **Custom RPC state lives in cookies** alongside the other preference cookies, so the server sees it: + one cookie for the saved URL and one flag for whether it is in use (the plug button toggles the flag + only, so disconnecting keeps the URL in the field). The CSP builder reads the URL per request and + appends the origin to `connect-src` only while the flag is on. The server trusts the cookie only + after re-validating it as an `https:` URL; anything else is ignored. +- **Transport resolution is a single helper** that returns the effective RPC URL list for the current + chain: the custom URL alone when it is saved and in use, otherwise the configured list (plus the + core-API `eth-rpc` fallback where it is used today). Both the wagmi transport builder and the standalone public + client call it; the `rpcUrls` on the chain object are left as configured so wallet "add chain" + prompts still advertise the operator's URLs. Because both clients are built at module load, a change + takes effect through the page reload the setting already performs. +- **Node ping** is one react-query keyed by the custom URL that POSTs `eth_chainId` with a short + timeout and returns `connected | wrong-chain | unknown-chain | unreachable` plus the reported chain + id. Three consumers read the same query: the top-bar indicator and the contract pill (mounted only + while a custom URL is in use, which is what makes the ping run at page load), and the RPC tab (which + refetches on show). It runs in the browser only, against the saved custom URL while in use (in the + cookie, therefore allowed by CSP); the configured node is never pinged; there is no server-side + proxy for the check (no SSRF surface, and the check exercises the same path wagmi uses, CORS + included). A URL that is typed but not yet saved is never pinged. One mapping function turns the + outcome into tag / colour / alert copy so the three consumers cannot drift. +- **Mobile modal** reuses the tab registry: the same two entries render as a vertical tab list on + desktop and as a horizontal secondary tab list in a full-height bottom sheet on mobile; "open on tab + X" selects the tab on both. No second registry, no stacked-sections layout. +- **Error classification on the contract page** walks the viem error's cause chain: `HttpRequestError`, + `TimeoutError`, `LimitExceededRpcError` and `InternalRpcError` map to the "not responding" alert; + everything else keeps the current `shortMessage` rendering. The alert's link opens the modal in + place through the modal state, not via reload. +- **Validation** on the client: must parse as a URL with the `https:` scheme; empty means "reset". +- **Analytics**: one new event type for the RPC setting with a `set | reset` action; existing settings + controls keep whatever they log today. +- **Visibility gates** reuse the gates each control already has (scam toggle env, multichain flag, + address-format count, theme count); the tab hides when every control in it is hidden. + +## Out of scope + +- A "match system" colour theme (the 5th swatch in the popover mockup) — separate task. +- Server-side verification of the RPC URL or any proxying of RPC traffic through the Next.js server. +- Custom RPC for chains other than the explorer's own (multichain cluster chains, parent chain, dapp + chains). +- Per-request switching without a reload. +- Changing the URLs advertised to wallets via "add chain". diff --git a/.agents/tasks/2881-token-transfers-table/spec.md b/.agents/tasks/2881-token-transfers-table/spec.md new file mode 100644 index 00000000000..933d2ef7176 --- /dev/null +++ b/.agents/tasks/2881-token-transfers-table/spec.md @@ -0,0 +1,163 @@ +# Unify the token transfers tables into one configurable table + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/2881 | +| Feature branch | `issue-2881` | +| PM | Ulyana | +| Designer | Tatyana | +| Backend | Victor | +| Minimum API version | — | +| Slack channel | — | + +<!-- Header is static identity — no status row: task status is derived from `progress.md` (see +`.agents/tasks/structure.md`). People default from `.agents/TEAM.md`; override here per task. The spec body +below is immutable once written; only `progress.md` and `questions.md` change as work proceeds. --> + +## Context & goal + +Token transfers are listed on four surfaces — the `/token-transfers` page, the address page tab, the +token (and token instance) page tab, and the transaction page tab — and each one has its own table with +its own column set and order. The same transfer reads differently depending on where the user meets it: +the token sits in a "Token" column on one page and inside the "Amount" cell on another, the timestamp +hides inside the hash cell, mint/burn and token-standard badges appear or vanish. Three row +implementations carry three copies of the same rendering logic, so every fix lands three times. + +The goal is one table format for all token-transfer views: a single ordered column vocabulary, a +per-surface default selection that reproduces what each page shows today (adjusted to the mockups), and +a column selector that lets the user add or remove columns the way the advanced filter table already +does. The chosen set survives reloads. + +## Functional requirements + +1. Every token-transfer view (index page, address tab, token tab, token instance tab, transaction tab, + and the user-op and multichain variants that reuse them) renders the same table component with the + same column vocabulary in the same default order: In / Out, Txn hash, Token type, Transfer type, + Method, Timestamp, Block, From / To, Multiplier, Amount, ID / Asset, Value. In multichain context a + chain column precedes them and cannot be hidden or moved. +2. Each surface has a default column selection that matches its mockup, with Value on everywhere: + + | Column | Index | Address tab | Token / instance tab | Tx tab | + | --- | --- | --- | --- | --- | + | In / Out | unavailable | on | unavailable | unavailable | + | Txn hash | on | on | on | unavailable | + | Token type | on | on | off | on | + | Transfer type | off | off | off | off | + | Method | on | on | on | unavailable | + | Timestamp | on | on | on | unavailable | + | Block | off | off | off | unavailable | + | From / To | on | on | on | on | + | Multiplier | on* | on* | on* | on* | + | Amount | on | on | on | on | + | ID / Asset | on | on | on | on | + | Value | on | on | on | on | + + "Off" columns are hidden by default but offered in the selector; "unavailable" columns are neither + rendered nor offered, because their value is constant for every row on that surface. + + \* Multiplier is unavailable when the chain has ERC-8056 off, when the type filter is set without + ERC-8056, and on the token / instance tab when the token is not ERC-8056; a user's stored choice for + it survives while it is unavailable. +3. A column selector button sits next to each surface's existing filter control (tabs right slot or + action bar, wherever that surface keeps its controls today) and toggles the available columns; its + rows can be dragged by a handle to reorder the columns, hidden ones included. A "Reset" link in the + selector, styled like the type filter popover's Reset, restores the surface's default selection and + order; it is disabled while the columns already match the defaults. The mobile selector is the same + control in the mobile action bar. +4. The user's selection and column order are persisted per surface in the browser and restored on the + next visit. Client-side navigation shows them at once; on a hard reload the server-rendered skeleton + carries the default columns and switches to the user's at hydration, before any row data is shown. A + change in one tab applies to the other open tabs. +5. Each surface keeps exactly the controls it has today — the token-type filter, the address + in/out filter, CSV export, the advanced-filter link, pagination, and the socket "new items" notice + are neither added to nor removed from any surface. +6. The cells keep today's behaviour: the address tab highlights the current address and spells the + direction relative to it in the In / Out column (In, Out, Self, or a dash when it is neither side), + the token instance tab does not link the current token id, the Timestamp header keeps the + time-format toggle, fungible amounts are scaled by the token multiplier (raw value in the tooltip, + the factor in the Multiplier column rather than a tag) and show the confidential-value variant, and + NFT rows show the token id (instance image, id, symbol) inside the ID / Asset cell with "1" as the + amount when they carry no value, while fungible rows show icon and symbol only. +7. Toggling a column emits one Mixpanel event carrying the table, the surface, the column id and the new + state; moving a column emits one carrying the table, the surface, the column id and the direction; + a reset emits one carrying the table, the surface, column "All" and the state "Reset". The advanced + filter emits the same events without a surface. +8. The advanced filter page's column selector becomes icon-only (no "Columns" label) and, since the + control is shared, reorders and resets that table's columns; its selection and order are persisted + like a token-transfer surface (FR 4), as one setting for the whole app regardless of chain; no other + change to that page. + +## Data & API + +None. All five list endpoints already exist as `core:token_transfers_all`, `core:address_token_transfers`, +`core:token_transfers`, `core:token_instance_transfers` and `core:tx_token_transfers`, and they return the +same `TokenTransfer` item shape, so no column needs data the surface does not already fetch. The USD +value is derived client-side from the token's exchange rate, as today. The transaction endpoint returns +`method` and `timestamp` as null, which is why those columns are unavailable on the transaction tab. + +No new resource, env var or feature flag. No backend release dependency. + +## UI inventory + +Figma page "Tables: Token transfers", desktop frames under +https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=3882-26170 : + +- `/token-transfers`, "Transfers" tab — https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=3882-31715 +- Address page, "Token transfers" tab (also the multichain address variant) — + https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=3882-32182 +- Token page, "Token transfers" tab, and the token instance page's transfers tab — + https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=3883-4329 +- Transaction page, "Token transfers" tab (also the user-op page's transfers tab) — + https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=3883-4723 +- Advanced filter page (reference only for the icon-only selector button) — + https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=3882-26175 +- Mobile table and column drawer — + https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=3889-33029 and + https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=3893-28801 + +Deliberate deviations from the mockups: + +- Value is on by default on every surface (mockups show it only on the address tab). +- The mobile list/table view switcher is not built: the list views were removed in #3722 and that + decision is final. Mobile shows the horizontally scrolled table only. +- The mobile drawer in the mockup omits Block; the selector offers every available column. +- The control set per surface stays as it is today (see FR 5), not the uniform + Filter · Columns · CSV · Advanced bar the mockups draw on every screen. + +Appearance (column widths, the From/To arrow, drawer vs popover on mobile) stays with the mockups and +the `[human]` style leaves. + +## Implementation decisions + +- **One table component** in the token-transfer slice replaces the three current row/table + implementations (the shared list table, the index-page table, the token-page table). It takes the + surface's column set and the row data; the columns are rendered from an ordered column vocabulary, in + the spirit of the advanced filter's `ItemByColumn` switch, so a column is added once. +- **A column config module** owns the vocabulary, the display names, and the per-surface availability + and defaults (FR 2). Consumers identify themselves by surface, not by passing column lists. +- **The selector UI is the advanced filter's `ColumnsButton`, extracted** to `src/shared/lists/columns/` + and made icon-only, next to a table-agnostic persisted-columns hook. The advanced filter keeps its own + column registry and table and uses the shared hook; the token-transfer slice wraps it per surface. +- **Persistence is localStorage**, one key per table + surface under a common `table_columns_` prefix, + each holding only the overrides from the defaults, so a change to the defaults does not resurrect stale + full lists. A cookie was dropped because it grows with every configurable table, is capped at 4 KB and + rides on every request; the cost is the hydration-time switch described in FR 4. Per-key values keep a + future cross-instance settings sync simple. +- **Type is two columns, From / To is one** (Q01, Q02): "Token type" renders the token-standard tag and + "Transfer type" the mint/burn badge; From and To stay a single combined column backed by the existing + `AddressFromTo` entity and toggled by a single selector entry. +- **Analytics** is one new Mixpanel event shared by both tables, following the existing event-registry + convention; it logs column ids, not display names. +- **Tests**: the unit specs of the deleted tables move to the new table; the Playwright files of each + surface keep their cases; a selector-open state gets one screenshot. +- **One PR, one commit per ticket**, so the deletion of each old table can be reverted on its own. + +## Out of scope + +- The advanced filter table itself: its column set, header filters and the "Fee" → "Tx fee" rename (only + the shared selector and column persistence are touched). +- Cross-chain transfer tables (interchain indexer data) on the index, address and transaction pages. +- The inline token-transfer snippets on the transaction details and Celo epoch pages. +- Adding CSV export, filters or advanced-filter links to surfaces that lack them today, and any backend + work that would enable them. +- Sorting in any token-transfer table. diff --git a/.agents/tasks/3650-shared-multi-bridge-indexer/spec.md b/.agents/tasks/3650-shared-multi-bridge-indexer/spec.md new file mode 100644 index 00000000000..21698c13289 --- /dev/null +++ b/.agents/tasks/3650-shared-multi-bridge-indexer/spec.md @@ -0,0 +1,202 @@ +# Scope every interchain request to the deployment's slice of a shared indexer + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3650 | +| Feature branch | `issue-3650` | +| PM | Ulyana | +| Designer | Tatyana | +| Backend | Evgenii | +| Minimum API version | `interchain-indexer` **v1.8.1** | +| Slack channel | #dev-interchain | + +## Context & goal + +Until now each frontend got its interchain scope from *where it pointed*: one `interchain-indexer` +instance per consumer, indexing exactly that consumer's bridge. Numine pointed at an Avalanche-only +instance, Gnosis at an Omnibridge-only one. The per-frontend instances are being consolidated into one +shared instance per environment (mainnets and testnets), indexing every bridge and every chain, and the +same instance will back Multichain Explorer. + +Repointing a frontend at the shared instance **without** frontend changes makes it show every +cross-chain message the instance knows about — Gnosis↔Ethereum Omnibridge traffic on Numine, Avalanche +subnet traffic on Gnosis. Because unknown query params are silently ignored by the service, a dropped or +misspelled filter is not an error but a cross-frontend data leak that returns `200`. + +Goal: every interchain request declares the deployment's slice, and adding a bridge or a chain on the +backend needs at most an env change — never a frontend release. + +## Functional requirements + +1. Every request to an `interchainIndexer:*` resource carries the deployment's filter profile, including + page 2+, refetches and requests issued from a chain-scoped multichain view. +2. The profile resolves per consumer, with no per-call-site opt-in: + - single-chain explorer, and a **per-chain** multichain view → `home_chain_id` (the focal chain); + - **aggregated** multichain views → `bridge_ids` from env; + - `/stats/chains` and `/interchain/chains` on **every** consumer → `bridge_ids` from env, because + neither endpoint accepts a chain predicate. +3. `include_unindexed_chains` is sent from its own env, defaulting to `false`, on **every** + `interchainIndexer:*` resource except `interchainIndexer:message` — that is, on all list, stats and + directory resources, but never on message details, which deliberately does not accept the param so + that a link to a details page always resolves even for a row the lists hide. No code path hardcodes + the value. +4. A test fails when an `interchainIndexer:*` resource is added without declaring its scope, or declares + a filter name nothing resolves. Asserting that the request returned `200` is explicitly not sufficient. +5. Pointed at the shared instance, the Numine frontend shows only Numine-related traffic and the Gnosis + frontend only Gnosis↔Ethereum traffic. +6. Adding a bridge on the backend surfaces on a deployment after an env change alone; adding a chain to + an existing bridge surfaces with no frontend or env change at all. +7. The message-details request carries `bridge_id`, including after a page reload and from a deep link — + the bridge travels in the URL, not in component state. +8. A malformed message identifier (`400`, `code: 3`) is surfaced as invalid input, not as a service + error. A wrong `bridge_id` (`404`, `code: 5`) surfaces as not-found. An ambiguous unqualified lookup + (`400`, `code: 9`) is not recovered from by retrying — the qualified route makes it unreachable. +9. Rendering never treats `has_unindexed_chain: false` as "all fields are populated", and never caches + the flag as an immutable property of a row: it is derived from live bridge config and flips without a + migration. +10. No regression in cross-chain search (`q`), sorting, pagination or the Protocol column on any + affected surface. + +## Data & API + +**Service** — `interchainIndexer`, host from `NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST`. Shared instances +are already deployed: mainnets `interchain-indexer.k8s-prod-4.blockscout.com`, testnets +`interchain-indexer-testnet.k8s-dev.blockscout.com`. Repointing the instances is DevOps' step at release +time (out of scope here, flagged in the PR description for the release notes). + +**Filter vocabulary** — all params optional, `snake_case`, `AND`-combined, `*_ids` comma-separated. +Blank/comma-only normalizes to "absent"; malformed returns `400 InvalidArgument` naming the param. + +| Param | Applies to | Used by this task | +| --- | --- | --- | +| `home_chain_id` | messages, transfers, their `:byTx` / `:byAddress` variants, `stats/common`, `stats/daily` | yes — focal-chain consumers | +| `bridge_ids` | the above, plus `stats/chains`, `messages-paths/*`, `bridged-tokens`; `/interchain/chains` after Q03 | yes — aggregated multichain, and the two chain-predicate-less resources everywhere | +| `include_unindexed_chains` | the above | yes — from env | +| `counterparty_chain_ids` | as above | already sent by the chain-stats sankey chart; unchanged | +| `src_chain_ids` / `dst_chain_ids` | lists and stats | no — for future "outgoing only" / "incoming only" sub-views | + +**Resources** — all needed resources are already registered under `interchainIndexer:*`. No new resource +is added: the bridge scope comes from env, so `GET /interchain/bridges` is deliberately **not** +registered (see *Out of scope*). + +**Message details** — `GET /interchain/messages/{message_id}` takes an optional `bridge_id` query param. +Verified against the live instance: a correct value resolves; omitting it resolves while no collision +exists; a **wrong** value returns `404 code: 5` (not the `400 code: 9` the issue documents — that is the +cross-bridge-collision case only, which the current bridge set makes unreachable). + +**Pagination** — `page_token` and the raw cursor fields are valid only for the exact filter combination +that produced them. The profile is constant per deployment (and per selected chain inside multichain), so +this holds as long as the profile is applied uniformly; a chain change inside multichain already resets +pagination through the existing chain-select flow. + +**Env vars** — two new, both documented in `docs/ENVS.md` and validated by the envs-validator: + +| Env | Type | Requirement | +| --- | --- | --- | +| `NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS` | array of bridge ids | Required when `NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED=true`. Omitting it would leave `/stats/chains` and `/interchain/chains` unscoped — a silent leak, not an error — so the validator must fail at startup. | +| `NEXT_PUBLIC_CROSS_CHAIN_TXS_INCLUDE_UNINDEXED_CHAINS` | boolean | Optional, default `false`. | + +The neutral (non-multichain) name is deliberate: a single-chain deployment spanning two bridges is +expected, and this way it needs no rename or deprecation cycle. + +**Bridge ids are deployment data, not constants.** Today: mainnet AMB/Omnibridge `1`, mainnet Avalanche +ICTT/ICM `2`, testnet Sepolia↔Chiado AMB `1001`. They must never be hardcoded in `src/`. + +**Types** — bump `@blockscout/interchain-indexer-types` to `1.8.1` (note: `1.7.0` was never +published). Stubs and mocks gain `bridge.id` and `has_unindexed_chain`. Two known type facts, both being +fixed upstream per Q03: `Bridge.indexed_chain_ids` is `number[]` while `Chain.id` is `string`, and +`has_unindexed_chain` is optional despite always being sent. + +## UI inventory + +No visual changes and no mockups — the bridge is already rendered. `Protocol` is an existing column in +both cross-chain tables and both mobile list items, backed by `CrossChainBridgeLink`, so bridge identity +is visible wherever rows from more than one bridge can appear. + +**Route change** — the message-details route becomes `/bridge/[bridgeId]/cross-chain-tx/[id]`. +The old `/cross-chain-tx/[id]` is **deleted with no redirect**. Every link to the page is built from a +row or a message object that already carries `bridge.id`, so no call site needs new data. +Touch points: the page under `src/pages/`, the metadata template registry, the mixpanel page-type map, +`CrossChainMessageEntity`'s default href, and the two `tab: 'transfers'` links. + +**Surfaces the profile must reach** — cross-chain transactions list and its stats block, token-transfers +list, bridged tokens, ICTT users, the message details page and its transfers tab, the latest-cross-chain +block on the home page, the cross-chain messages/transfers blocks on tx details, the cross-chain tab on +address pages, the chain-stats cross-chain sankey chart and its counterparty selector, and the multichain +equivalents of the home, address and chain-stats surfaces. + +## Implementation decisions + +- **The profile is injected centrally, not at call sites.** The API layer applies it to every + `interchainIndexer:*` request. Fifteen call sites spread the same three params by hand would leak the + moment one is missed, and a missed one returns `200`. +- **Which params a resource accepts is declared on the resource entry**, in a *generic* field usable by + any service that needs static filters — not an interchain-specific map. Uniform injection is rejected: + it would send `home_chain_id` to endpoints that silently ignore it, which is the same trap from the + other side. Adding a resource then forces its author to answer the question. +- **Profile derivation** is a single decision point: + - multichain disabled → `home_chain_id = config.chain.id`; + - multichain enabled with a chain in `MultichainContext` → `home_chain_id = <that chain>`; + - multichain enabled, no chain in context → `bridge_ids` from env. + A per-chain multichain view therefore sends `home_chain_id` **only**, byte-identical to a single-chain + explorer — the standing multichain rule that per-chain views mirror a single-chain explorer. The + consequence is accepted: were a cluster chain ever served by a bridge outside the env list, a per-chain + view would show it while the aggregated view hid it. Unreachable today, and reaching such a view would + require a link nobody can construct. +- **`home_chain_id` alone is the correct scope for the list endpoints**, per the backend owner: sending + it means accepting three defaults — unindexed chains excluded, events from **all** bridges covering the + focal chain included, and stats spanning all chains of those bridges. Adding `bridge_ids` there would + only narrow it, so it is not sent. +- **`/stats/chains` and `/interchain/chains` cannot take `home_chain_id`.** "Which chains are reachable + from the focal chain" would mean scanning the full messages/transfers table per request, since a + message can arrive from any chain, and the messages table is already past a million rows. `bridge_ids` + is the agreed scope for these two, confirmed at the 2026-09-02 sync. +- **No client-side intersection of `indexed_chain_ids`.** The env supplies bridge ids directly and the + service does the chain filtering, so `/interchain/bridges` is never fetched and no request is gated on + a directory lookup. +- **The bridge travels in the path, not a query param, and there is no retry on ambiguity.** `bridge_id` + is effectively required in the new paradigm, so the route reflects that; a wrong value 404s, which + makes guessing worse than not guessing. +- **The param-drop test enumerates the resource registry** rather than listing resources by hand, so a + newly added interchain resource is covered on the day it is added. It asserts two invariants — every + resource declares a scope (bar `message`), and every declared name has a resolver — not the specific + filters each resource takes. Pinning those would restate the registry: the expectation would have to be + edited in lockstep with every legitimate change, so it would only ever catch a deliberate edit, which + is code review's job. The leak risk FR4 guards is a *new* resource whose author never answered the + question, and a name that silently resolves to nothing; both are caught without duplication. + +## Out of scope + +- **Indexing-progress UI** from `GET /status/indexing` (the issue's optional item). Live data currently + reads 718k failed blocks on chain `100` and 19% catch-up on `43114`; shipping it would advertise a + backend state without a product decision. Separate ticket if product wants it. +- **A user-facing bridge filter control.** No deployment today sees more than one bridge (Numine → `2`, + Gnosis → `1`, multichain → `1`), and there are no mockups. Revisit when a deployment actually spans two. +- **Deriving bridge or chain selectors from `/interchain/bridges`** — replaced by the env, and rejected + on its own merits at the 2026-09-02 sync: a bridge's `indexed_chain_ids` is not the set of chains the + focal chain has actually talked to, so with ~100 Avalanche chains configured the selector would list + all of them while Numine exchanges messages only with C-Chain. +- **Marking `has_unindexed_chain` rows in the UI** and explaining their empty destination side. Product + decided (2026-09-02) not to show such messages at all — the env exists only as an escape hatch and no + deployment sets it to `true`, so there is nothing to mark. Requirement 9 covers defensive rendering + only, since the flag can still arrive on a row. +- **Repointing the instances** and retiring the old ones — DevOps, at release time. The Numine explorer + is explicitly not being retired: it is the reference instance for the Autoscout rollout. +- **`src_chain_ids` / `dst_chain_ids`** — no "outgoing only" / "incoming only" sub-view exists. +- **Moving the cross-chain summary tiles to the stats service.** Raised at the 2026-09-02 sync: the + `stats/common` endpoints were built for debugging small per-frontend indexers and do direct DB counts, + so they don't hold at shared scale; the same counters exist in the stats service, at ~2 hours' + staleness (accepted). Needs the counter names from the backend owner and its own issue — this task + keeps reading `stats/common`, merely scoped. +- **Rendering a native asset for the new token `type` field** (`native` vs erc20), which the + xDAI/Omnibridge onboarding introduces — a native coin must render without a token link. Same sync, own + issue. +- **Closing the selector/statistics divergence.** Once `bridge_ids` reaches `/interchain/chains` (Q03), + the counterparty selector lists the chains **configured** on the deployment's bridges; the statistics + below it show the chains the deployment has **actually exchanged messages with**. A configured chain + with no traffic therefore appears in the selector and is absent from the chart. Bridge scoping cannot + narrow this further — such a chain is on our own bridge — and the set of "chains we have really talked + to" is not something the service can answer today. Invisible with the current config (all four chains + of the two bridges have traffic), visible as soon as a bridge gains an idle chain. Knowingly accepted + at the 2026-09-02 sync, where the chart itself was taken as the answer to "which chains actually + participate" — not a defect to file. diff --git a/.agents/tasks/3663-code-complexity-ci-gate/spec.md b/.agents/tasks/3663-code-complexity-ci-gate/spec.md new file mode 100644 index 00000000000..521cf83d96c --- /dev/null +++ b/.agents/tasks/3663-code-complexity-ci-gate/spec.md @@ -0,0 +1,162 @@ +# Add a cognitive-complexity and CRAP-score CI gate + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3663 | +| Feature branch | `issue-3663` | +| PM | — (frontend tooling task) | +| Designer | — | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +Complex, under-tested code lands unnoticed today: nothing measures per-function +complexity, and the coverage tooling reports only statement/branch/function/line +coverage, never complexity or CRAP. The goal is a CI gate that flags code which is either hard to +read *or* both complex and under-tested — CRAP = `c²·(1 − cov)³ + c` — before it merges, scoped to +what a PR actually changes so it never blocks on pre-existing debt. + +## Functional requirements + +1. A `tools/code-complexity/` CLI computes per-function scores by walking the TS/TSX syntax tree via + the `typescript` compiler API (`ts.createSourceFile`), with no type-checker. +2. Each function gets two scores, both counted on that one walk: **cognitive complexity**, following + the SonarSource model (flat control flow is cheap, nesting is penalised progressively, boolean + runs collapse), and **cyclomatic complexity**, following ESLint's `complexity` rule. + Nested/arrow/method functions count as their own units under both. The exact increment rules and + the deliberate divergences from those two references are documented in the tool. +3. The tool computes CRAP `c²·(1 − cov)³ + c` per function by joining **cyclomatic** complexity with + per-function line coverage read from a v8/istanbul `coverage-final.json`. Cognitive complexity + never feeds CRAP. +4. Every function is classified from the AST — not its file extension — by whether JSX appears + directly in its own body (`JsxElement` / `JsxSelfClosingElement` / `JsxFragment`), outside any + nested function: **`jsx`** for a render body, **`behavior`** for everything else (handlers, + `useCallback`/`useMemo` bodies, hooks, utils) wherever it lives, including nested inside a + component. Only `behavior` functions are CRAP-scored. A `jsx` function is covered, if at all, by + Playwright visual tests that emit no vitest coverage, so scoring it would flood the report with + 0%s; its cognitive cap is the backstop instead. +5. A *file* needs coverage generated for it when it is JSX-less or has a co-located vitest spec + (`X.spec.tsx` beside `X.tsx`) — this decides only whether the tool's vitest run pulls the file + in, not which functions are scored. `*.primed.spec.tsx` drift tests never count as that spec and + are excluded from the coverage runs the tool triggers (they mount pages without exercising + behavior). +6. The gate scopes to **functions touched by the diff** against a base ref (default + `origin/main`) — a function is in scope when a changed line falls within its body. No + baseline artifact is kept. +7. Three independent thresholds gate, all configurable: a **cognitive-complexity cap per function + class** — a high backstop for `jsx`, a tighter one for `behavior` — and a **CRAP threshold** on + `behavior` functions. The cognitive caps are enforced even when no coverage data is present. +8. File scope is an allowlist of two roots — the app (`src/`) and the repo's own tooling (`tools/`, + so the gate also scores its own implementation) — with the extension set `.ts` `.tsx` `.mjs` `.js` + `.cjs`. Excluded within them: specs (`*.spec.*`, `*.pw.tsx`, `*.pwstory.tsx`), generated files + (`*.d.ts`, `envs.js`), configuration (`*.config.*`), and build output + (`src/toolkit/package/**`, `tools/**/dist/`). `deploy/**` stays out — it is outside ESLint and the + root TypeScript project, so this gate should not be its first automated check (issue #3675) — and + so do `playwright/**`, `vitest/**` and the repo-root runtime files. +9. On any violation the CLI exits non-zero. It always prints a table of **all** checked functions, + sorted by CRAP descending, offenders flagged with which threshold they broke. Under + `$GITHUB_ACTIONS` it additionally emits `::error file=,line=::` annotations for offenders and + writes the table to `$GITHUB_STEP_SUMMARY`. +10. The gate runs inside the existing `vitest_tests` CI job: coverage is enabled on the + affected-tests run, and the tool runs as a post-step selecting diff scope with `--changed` and + consuming that `coverage-final.json` via `--coverage-file` (so CI never regenerates coverage). +11. The interface has two independent axes, mirroring vitest. **Selection** — which functions to + score — is *full repo* by default (every in-scope function, FR8), *focused* when explicit + file paths are given, or *diff-scoped* under `--changed[=<ref>]` / `--base <ref>` (functions a + changed line falls within, vs the base ref, default `origin/main`). **Coverage source** — + generated by running vitest scoped to the selection (default, no pre-step), consumed from a + prebuilt report via `--coverage-file <path>` (skips vitest — the CI path), or skipped via + `--no-coverage` (cognitive gate only). A `pnpm test:code-complexity` script exposes the tool. +12. **Full-repo mode** (the default selection) scores every in-scope function and is what the + threshold calibration uses to produce the repo-wide distributions. **Focused mode** + (explicit paths) scores every function in those files and generates their coverage via `vitest + related` (the specs transitively importing them, minus the excluded `*.primed.spec.tsx`), so a + single command verifies a newly written or edited function sits within threshold before pushing. + Because all three selections collect coverage through the module graph, they agree on a given + file's number. +13. Thresholds live in the tool as configurable defaults (constants/config under + `tools/code-complexity/`), overridable by CLI flags; CI carries no threshold numbers, so a + local run and a CI run gate identically. + +## Data & API + +None. No endpoints, resources, env vars, or feature flags. + +## UI inventory + +None. This is CI/tooling only; no routes, pages, or components. + +## Implementation decisions + +- **Bespoke tool, no external service.** Built on the `typescript` compiler API, already a + dependency (the `@typescript/typescript6` alias exposes `ts.createSourceFile` and + `ts.SyntaxKind`), keeping the pipeline self-contained with no external service or CI + secrets. This rationale stays in the spec only — the shipped tool names no third-party + quality-gate service, and cites SonarSource and ESLint solely as the published counting models it + is measured against. +- **Coverage rides the per-PR affected-tests run.** CI's `vitest_tests` job already runs + `vitest run --changed=origin/main`; add `--coverage` (`@vitest/coverage-v8`, already + resolvable in the pnpm store). Because `vitest --changed` runs every spec that + *transitively imports* a changed module, the coverage collected for a changed file equals + its whole-suite coverage — so affected-scoped coverage is correct, not an undercount. This + corrects the issue's "free rider on the coverage run CI already produces" premise: CI + produced **no** coverage before, and on PRs runs only changed specs. +- **The tool generates coverage itself for local runs; CI feeds it the artifact.** Coverage + has three sources behind one interface: generated by default (focused: `vitest related + <paths>`; diff: `vitest run --changed <merge-base>`, both into a throwaway temp dir), + consumed from a prebuilt report via `--coverage-file`, or skipped via `--no-coverage`. This + keeps the local UX a single command (no "generate coverage first, then pass it" pre-step) + while CI stays efficient by passing `--coverage-file` pointed at the coverage the + `vitest_tests` step already produced — the gate regenerates nothing in CI. The generation + scope reuses the same transitive-importer logic as the CI run, so a local number matches + CI's for the same files. +- **Missing coverage = 0%.** A changed in-scope file absent from `coverage-final.json` is + treated as 0% coverage (derived from the git-changed file list), rather than enabling a + global `coverage.all`. For a JSX-less logic file this correctly flags untested code. The one + exception is a hand-passed `--coverage-file` in focused mode, where absence may simply mean the + report predates the file, so it reports "no data" instead of 0%. +- **Granularity: touched functions only.** Map git diff hunks to function line ranges; gate + only functions the diff added or modified. No committed baseline, no keying scheme to + maintain. +- **JSX detection is AST-based, not extension-based.** ~78 non-test `.tsx` files currently + contain no JSX (mostly `useX.tsx` hooks), so the extension is an unreliable + component-vs-logic signal. Classification is free — the tool already parses every file. + (Aligning extensions with content is tracked separately in issue #3668, out of scope here.) +- **Cognitive complexity is the readability gate; cyclomatic only feeds CRAP.** Cyclomatic counts + independent paths ≈ tests needed, which makes it the right CRAP input and a poor decomposition + signal — it scores a flat `switch` the same as an equivalent nested `if` chain and is blind to + nesting. So the gate that says "a human should split this up" is cognitive complexity, and it + charges nesting **quadratically** (`1 + nesting²`) rather than SonarSource's linear `1 + nesting`: + the two agree at depths 0 and 1 and diverge from the third level in, which is what lets a single + cap forgive wide-but-shallow logic while still catching the nested tail. Recorded as an ADR in the + tool, alongside the exclusions from the count. +- **CRAP applies per function class, not per file.** Every `behavior` function is CRAP-scored and no + `jsx` function ever is, decided from the AST per function rather than per file — so a component's + render body loses its noise 0% while the handlers inside it gain a real score. The co-located + `X.spec.tsx` rule survives only as *generation scope*: it decides whether a file causes a vitest + run at all, not which of its functions are scored. `*.primed.spec.tsx` drift tests are excluded + from those runs entirely — they mount whole page trees (importing much of the app) without + exercising behavior, so `vitest related` would otherwise pull them in for almost any file, adding + tens of seconds and no meaningful coverage. +- **Thresholds calibrated from real data as the final step.** The tool was run repo-wide against + whole-suite coverage to produce the CRAP and cognitive-complexity distributions; each cap was set + from the far tail so the gate flags genuine offenders rather than ordinary code. The three caps are + coupled — to each other and to the counting model — so none can be re-tuned in isolation. The live + values and their rationale live in the tool's `config.ts`; the calibration figures are in the + landing PR. +- **CI-only gate, no husky hook** — coverage-dependent and too slow for a commit hook. +- **Residual risk:** a changed file exercised only through a dynamic import or other + non-static path the module graph misses would be undercounted and could fail falsely; rare + in this codebase, and the changed-scope + touched-function limits contain the blast radius. + +## Out of scope + +- Adopting SonarCloud / any external quality-gate service. +- A baseline of pre-existing violations (superseded by the touched-functions scope). +- Remapping Playwright component-test (`*.pw.tsx`) coverage into the gate. (`jsx` render bodies are + never CRAP-scored; their cognitive cap is the backstop instead.) +- Enforcing the `.tsx`→`.ts` rename and the `react/jsx-filename-extension` rule (issue #3668). +- Gating the whole repo or historical code in **CI**; the CI gate is strictly diff-scoped. (A + full-repo mode exists for local use and calibration; CI never invokes it.) diff --git a/.agents/tasks/3665-mutation-testing/progress.md b/.agents/tasks/3665-mutation-testing/progress.md new file mode 100644 index 00000000000..f8f68bdf925 --- /dev/null +++ b/.agents/tasks/3665-mutation-testing/progress.md @@ -0,0 +1,9 @@ +# Progress — Add diff-scoped mutation testing + +- [x] 01 → `tickets/01-stryker-boots/` +- [x] 02 → `tickets/02-cli-selection-modes/` +- [x] 03 → `tickets/03-mutation-ranges/` +- [x] 04 → `tickets/04-bounded-run/` +- [x] 05 → `tickets/05-findings-report/` +- [x] 06 → `tickets/06-ci-gate/` (its `(human)` criterion deferred to task land — see the ticket's `notes.md`) +- [x] 07 → `tickets/07-docs/` diff --git a/.agents/tasks/3665-mutation-testing/spec.md b/.agents/tasks/3665-mutation-testing/spec.md new file mode 100644 index 00000000000..f7dea978315 --- /dev/null +++ b/.agents/tasks/3665-mutation-testing/spec.md @@ -0,0 +1,123 @@ +# Add diff-scoped mutation testing + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3665 | +| Feature branch | `issue-3665` | +| PM | — (frontend tooling task) | +| Designer | — | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +Coverage answers "was this line executed?". It cannot answer "would a bug here be caught?" — a test can +execute a branch and assert nothing about it. Mutation testing answers the second question directly: change +the code, and see whether any test notices. + +The goal is to measure **assertion strength of the vitest specs the repo already has**, and to stop new, +weakly-asserted logic from landing. + +## Functional requirements + +1. A CLI runs StrykerJS with the vitest test runner over a selected set of source files and reports which + mutants survived — that is, which code changes no test detected. +2. **Only logic mutators are generated**: conditional expressions, equality operators, logical operators, + arithmetic operators, and boolean literals. Every other mutator class is excluded at generation time, not + filtered afterwards. +3. A file is **eligible** only when a co-located vitest spec exists beside it (`X.spec.ts` / `X.spec.tsx` + next to `X.ts` / `X.tsx`). Ineligible files are + never mutated, so a file with no unit test produces no findings rather than a run of unkillable mutants. +4. Mutants located inside a **`jsx` function body** are excluded, using the same AST function + classification the complexity gate applies. `behavior` functions are mutated wherever they live. +5. The CLI has three **selection** modes, mirroring the complexity gate's flags: + the **full eligible set** when invoked bare, **focused** on whole files when given explicit paths, + and **diff-scoped** under `--changed[=<ref>]` (default `origin/main`, resolved through the merge-base so + it captures the branch's own commits plus uncommitted edits, and never base-branch churn). +6. In diff-scoped mode, only the **changed lines** are mutated, expressed as Stryker mutation ranges. This + restricts mutant *creation*, not merely reporting . Focused mode mutates whole files. +7. When the selection resolves to nothing, the CLI exits 0 **without invoking Stryker at all**, printing one line + explaining why it found nothing to do. +8. Output is produced by consuming Stryker's JSON report rather than its clear-text reporter, which is + unusable at this scale. It comprises a per-file table (score, mutants, killed, survived, no-coverage) and + a listing of findings **grouped by source line**. Survivors and no-coverage mutants are separated, keyed off the + `status` field Stryker records per mutant; no-coverage is summarised compactly, being a coverage finding + the CRAP gate already owns. +9. An HTML report is written to a gitignored path and its location printed. +10. Results are **deterministic**: repeated runs over an unchanged tree produce identical counts. This + requires static mutants to be ignored by default, a raised mutation timeout, and the exclusion in FR11. +11. The `*.primed.spec.tsx` drift tests are excluded from the vitest runs this tool triggers. They mount + whole pages without exercising behaviour, so their kills are incidental to the question being asked, and + they dominated runtime. This matches the complexity gate, which already excludes them from its coverage runs. +12. A **wall-clock budget** bounds any single run. Results are written to disk as each mutant is tested, so + when the budget expires the run is stopped and everything completed so far is reported. The output always + states that the run was truncated and how much of the selection it covered; truncation is never silent. +13. Stryker's own configuration lives in a **committed config file**, so every setting is reviewable in a + diff and schema-validated in an editor. The CLI contributes only what genuinely varies per run. +14. A **CI job** runs the tool diff-scoped on pull requests. It is its own job — it cannot reuse the unit-test + job's artifacts, because Stryker must drive vitest itself — and it chains on the unit-test job, since a + red suite makes Stryker abort during its dry run with an error that reads like a tooling failure. +15. **The CI job fails when any mutant on a changed line survives.** Findings are additionally emitted as + inline annotations on the PR diff, naming the surviving mutator and the line, so they are visible during + review rather than buried in a job log. +16. Suppressing a mutant requires Stryker's disable comment carrying **both the mutator name and a reason**; + blanket file-level disables are not permitted. This makes each suppression a reviewable claim rather + than a mute button. + +## Data & API + +None. This task adds no runtime code, no API resource, and no environment variable. + +## UI inventory + +None. This task ships no user-facing surface. + +## Implementation decisions + +- **Two pnpm integration blockers must be handled; both were reproduced and solved during grilling.** + - Stryker fails to boot because the repo pins `brace-expansion` to a 1.x security override globally, while + the `minimatch` version Stryker depends on needs a 5.x ESM build. The fix is a **scoped** override for + that dependency path only, following the precedent already in the workspace file for `vite-plugin-dts`. + The global security pin is not widened. + - Stryker discovers plugins by globbing its own scope in `node_modules`, which pnpm's isolated layout + defeats: the run fails with "no TestRunner plugins were loaded". The vitest runner must be named + explicitly in the config's plugin list. +- Stryker copies the project into a sandbox per run, so its ignore patterns need tuning; left untuned it + also fails outright on symlinks under agent worktree directories. +- **Diff resolution and file-scope logic are reused from the complexity gate**, not reimplemented — the + merge-base resolution, the `--unified=0` hunk-range parsing, the scope allowlist, and the AST function + classifier FR4 needs. Direct import across tool directories is the right coupling for now; extracting a + shared location is warranted only if a third consumer appears. +- **StrykerJS has no `--since` flag.** The issue proposed one, but that option belongs to Stryker.NET; the + JS CLI has no equivalent. Diff-scoping is therefore something this tool computes and expresses through + mutation ranges, which is why FR5 and FR6 are stated the way they are. +- **No incremental mode and no committed report artifact.** The issue proposed committing + `reports/stryker-incremental.json`; it is rejected. +- **Runtime is governed by import-graph centrality, not mutant count.** Five leaf utilities with 140 mutants + ran in 10 seconds; one 28-mutant file imported across the app took 70 seconds, because Stryker's dry run + executes everything related to it. This is why FR12 bounds by wall-clock time rather than mutant count: + diff size does not predict cost, and a mutant-count bound would have to track Stryker's own generator to + stay honest. +- The gating mutator set in FR2 was chosen from evidence, not taste. Sampling 22 survivors across all + mutators found roughly a third unkillable by any vitest test — React dependency arrays, theme-variable + objects, colour-token string literals, all of them visual or idiomatic rather than behavioural. Sampling + 18 survivors restricted to the logic mutators found **zero** such cases; all 18 were real gaps. +- Promoting or demoting a mutator class is a one-line config change, which is the intended ratchet if the + excluded classes later prove to hide a real bug. + +## Out of scope + +- **The `review-changes` skill's "mutation-thinking" prompt.** The issue proposed adding an LLM reasoning + step to that skill's correctness axis; it is dropped from this task entirely. +- **Playwright tests.** Stryker's vitest runner cannot execute them, and browser mode is explicitly + unsupported. Nothing in the 228-file screenshot suite is measured. +- **Non-logic mutators** — string literals, array and object declarations, block statements, optional + chaining, method and call expressions, arrow functions, regexes. Not generated, not reported. +- **A scheduled or whole-repo CI run.** The full eligible set took 17 min 29 s locally before FR2's mutator + restriction; it is reproducible on demand via the CLI's bare invocation, but no workflow runs it. +- **A mutation-score percentage threshold.** The gate is "no survivor on a changed line" (FR15). A + percentage is unstable at the small mutant counts a diff produces, where one survivor can swing the number + by double digits. +- **Files without a co-located vitest spec**, including newly added untested files. Catching those is the + CRAP gate's role. diff --git a/.agents/tasks/3665-mutation-testing/tickets/01-stryker-boots/spec.md b/.agents/tasks/3665-mutation-testing/tickets/01-stryker-boots/spec.md new file mode 100644 index 00000000000..e90cb3fb109 --- /dev/null +++ b/.agents/tasks/3665-mutation-testing/tickets/01-stryker-boots/spec.md @@ -0,0 +1,65 @@ +# 01 — Stryker boots on this repo + +| | | +| --- | --- | +| Parent spec | [`../../spec.md`](../../spec.md) → ticket 01 of #3665 | +| Blocked by | none | + +## What to build + +StrykerJS installed and configured so that a bare `stryker run` over one hand-named source file completes +and reports killed/survived counts. Two pnpm integration blockers stand in the way and are both solved by +configuration, not by code (see the parent spec's Implementation decisions). Everything the run needs that +does not vary per invocation lives in a committed `stryker.config.json`: the mutator restriction, the +determinism settings, the reporters and their output paths. + +No CLI yet — this ticket's deliverable is that Stryker itself works here, which is the thing every later +ticket assumes. + +## Acceptance criteria + +How to verify: `./node_modules/.bin/stryker run --mutate <some src file with a co-located spec>` + +- [ ] The run completes: no "no TestRunner plugins were loaded", no `minimatch`/`brace-expansion` boot error, + no failure on symlinks under `.claude/worktrees/`. +- [ ] Only conditional-expression, equality-operator, logical-operator, arithmetic-operator and + boolean-literal mutants appear in the report. No string-literal, array/object-declaration, + block-statement, optional-chaining, method/call-expression, arrow-function or regex mutants. +- [ ] Two consecutive runs over an unchanged tree report identical killed / survived / no-coverage counts. +- [ ] The vitest runs Stryker drives do not execute `*.primed.spec.tsx`. +- [ ] `stryker.config.json` carries a `$schema` pointer and every non-varying setting; nothing needed for a + plain run is passed on the command line. +- [ ] The JSON and HTML reports land under `tools/mutation-testing/reports/`, the sandbox under + `tools/mutation-testing/.stryker-tmp`, and both are gitignored. +- [ ] The global `brace-expansion` security override in `pnpm-workspace.yaml` is unchanged. +- [ ] `(human)` The lockfile delta is reviewed: Stryker's dependency tree brings nothing unexpected, and the + scoped override does not widen the global 1.x pin. + +## Details + +**The two blockers.** The scoped `brace-expansion` override follows the `vite-plugin-dts>brace-expansion` +precedent already in `pnpm-workspace.yaml`'s `overrides` block — add a sibling entry for the dependency path +that reaches Stryker's `minimatch`, and leave the global `brace-expansion: "1.1.12"` pin alone. The vitest +test runner must be named explicitly in the config's `plugins` array, because Stryker discovers plugins by +globbing `node_modules/@stryker-mutator/*` and pnpm's isolated layout defeats that. + +**Determinism (FR10).** Static mutants ignored by default, and a raised mutation timeout — a mutant that +times out under load would otherwise flip between `timeout` and `survived` between runs. + +**Sandbox.** Stryker copies the project per run, so its ignore patterns need tuning; left untuned it fails +outright on the symlinks under agent worktree directories. + +**Reporters.** `json` and `html` both on; the clear-text reporter is unusable at this scale (FR8) and later +tickets read the JSON. `tempDirName` points the sandbox inside the tool folder rather than the repo root. + +**Gitignore.** The existing `/tools/code-complexity/dist/` line is the placement precedent. + +## Leaf worklist + +- [x] 1 `[agent]` Add the Stryker dependencies and the scoped `brace-expansion` override; verify a bare run + boots +- [x] 2 `[agent]` Write `tools/mutation-testing/stryker.config.json` — explicit plugin list, logic-only + mutators, `ignoreStatic`, raised timeout, primed-spec exclusion, sandbox ignores, json + html reporters + into `tools/mutation-testing/reports/` +- [x] 3 `[agent]` Gitignore the reports directory and the sandbox +- [x] 4 `[agent]` Verify determinism: two runs, identical counts diff --git a/.agents/tasks/3665-mutation-testing/tickets/02-cli-selection-modes/spec.md b/.agents/tasks/3665-mutation-testing/tickets/02-cli-selection-modes/spec.md new file mode 100644 index 00000000000..a90882ab703 --- /dev/null +++ b/.agents/tasks/3665-mutation-testing/tickets/02-cli-selection-modes/spec.md @@ -0,0 +1,63 @@ +# 02 — The CLI and its three selection modes + +| | | +| --- | --- | +| Parent spec | [`../../spec.md`](../../spec.md) → ticket 02 of #3665 | +| Blocked by | T01 | + +## What to build + +`pnpm test:mutation-testing`, a CLI that decides which files to mutate, invokes Stryker over them, and +prints a per-file score table read from Stryker's JSON report. + +Three selection modes mirror the complexity gate's flags: bare invocation takes the full eligible set, +explicit paths focus on those files, and `--changed[=<ref>]` scopes to the diff against a base ref +(default `origin/main`, through the merge-base). A file is eligible only when a vitest spec sits beside it; +a file with no unit test produces no findings rather than a run of unkillable mutants. When the selection +resolves to nothing, the CLI says why in one line and exits 0 without invoking Stryker at all. + +Whole files are mutated in this ticket. Narrowing to changed lines and excluding `jsx` bodies is T03. + +## Acceptance criteria + +How to verify: `pnpm test:mutation-testing tools/code-complexity/measure/crap.ts` + +- [x] Bare invocation selects every eligible file under the scope allowlist; explicit paths select exactly + those files; `--changed` selects the files the diff touches, and `--changed=<ref>` honours the ref. +- [x] A file with no co-located `*.spec.ts` / `*.spec.tsx` is never mutated in any mode, including when + named explicitly. +- [x] `--changed` on a branch with no in-scope changes prints one explanatory line, exits 0, and never + spawns Stryker (verifiable by the absence of a fresh sandbox and the run's wall time). +- [x] `--changed` resolves through the merge-base: commits landing on `origin/main` after the fork point + never appear in the selection. +- [x] Output is a per-file table with score, mutants, killed, survived and no-coverage columns, built from + the JSON report — Stryker's clear-text reporter is not used. +- [x] `--help` documents the three modes. +- [x] The tool's own files pass the complexity gate (`pnpm test:code-complexity --changed`). +- [x] Unit specs cover eligibility, mode resolution and the empty-selection exit. + +## Details + +**Reuse, do not reimplement (parent spec).** `tools/code-complexity/select/diff.ts` supplies +`resolveBaseCommit`, `getChangedFiles`, `getAllSourceFiles` and `getChangedLineRanges`; +`tools/code-complexity/select/scope.ts` supplies `isInScope`. Import them directly across tool directories — +extracting a shared location is warranted only if a third consumer appears. + +**Eligibility (FR3)** is the same naming-convention check `tools/code-complexity/index.ts` already makes in +`hasCoLocatedSpec`; Playwright `*.pw.tsx` files do not count. + +**Shape.** Follow the code-complexity layout: a `run.sh` that compiles through a local `tsconfig.json` into a +gitignored `dist/` and then runs `dist/index.js`, an `index.ts` that parses flags and orchestrates, specs +beside what they test. Its flag-parsing table (`FLAGS`, `applyArg`) is the pattern to follow for +`--changed[=<ref>]`, which must not swallow the following token. + +**Package script.** `"test:mutation-testing": "./tools/mutation-testing/run.sh"`, beside +`test:code-complexity`. + +## Leaf worklist + +- [x] 1 `[agent]` Scaffold `tools/mutation-testing/` — `run.sh`, `tsconfig.json`, gitignored `dist/`, package + script +- [x] 2 `[agent]` Selection: eligibility check, the three modes, the empty-selection early exit; specs +- [x] 3 `[agent]` Invoke Stryker over the selection and parse its JSON report +- [x] 4 `[agent]` Render the per-file table; specs diff --git a/.agents/tasks/3665-mutation-testing/tickets/03-mutation-ranges/spec.md b/.agents/tasks/3665-mutation-testing/tickets/03-mutation-ranges/spec.md new file mode 100644 index 00000000000..c3bfb9154a2 --- /dev/null +++ b/.agents/tasks/3665-mutation-testing/tickets/03-mutation-ranges/spec.md @@ -0,0 +1,53 @@ +# 03 — Mutate only behavior code, only on changed lines + +| | | +| --- | --- | +| Parent spec | [`../../spec.md`](../../spec.md) → ticket 03 of #3665 | +| Blocked by | T02 | + +## What to build + +Narrow what Stryker mutates from whole files down to the lines worth mutating, expressed as Stryker mutation +ranges so this restricts mutant *creation* rather than filtering findings afterwards. + +Two independent restrictions compose. Everywhere, mutants inside a `jsx` function body are excluded — sampling +during grilling found those survivors to be visual or idiomatic rather than behavioural, so they are noise by +construction. Additionally, under `--changed` only the lines the diff touched are mutated, so a one-line fix +in a large file does not pay for the whole file. Focused and bare modes still mutate whole files, minus the +`jsx` bodies. + +## Acceptance criteria + +- [x] A `.tsx` file whose only logic lives in a render body yields zero mutants; a `behavior` function in the + same file is still mutated. +- [x] A `behavior` function declared inside a component (an `onClick` handler, a `useCallback` body) is + mutated — the exclusion keys off the function's own classification, not its enclosing file. +- [x] Under `--changed`, mutants appear only on lines the diff added or modified. An untouched conditional + elsewhere in a changed file produces no mutant. +- [x] Focused mode (`pnpm test:mutation-testing <path>`) mutates the whole file, minus `jsx` bodies. +- [x] When the ranges for a file come out empty, that file is dropped from the selection rather than passed + to Stryker with an empty range. +- [x] Range computation is unit-tested, including a `jsx` body overlapping a changed hunk. + +## Details + +**Function classification (FR4)** reuses `computeFunctionComplexities` from +`tools/code-complexity/measure/complexity.ts`, whose `FunctionComplexity` carries `startLine`, `endLine` and +`containsJsx` — the same AST classification the complexity gate applies. `containsJsx` means JSX appears +directly in that function's own body, outside any nested function, which is exactly the `jsx` / `behavior` +split FR4 names. + +**Ranges are an include-list.** Stryker's `mutate` accepts `file.ts:startLine[:col]-endLine[:col]`; there is +no exclude form. So a `jsx` body is excluded by emitting the complement — the spans of the file *not* covered +by any `jsx` function — and under `--changed` by intersecting that complement with the changed line ranges +from `getChangedLineRanges`. + +**Changed lines** come from the complexity gate's `--unified=0` hunk parsing (`parseHunkNewRanges`), already +resolved against the merge-base in T02. + +## Leaf worklist + +- [x] 1 `[agent]` Compute per-file `jsx`-body spans from the complexity gate's classifier and derive their + complement; specs +- [x] 2 `[agent]` Intersect with changed line ranges under `--changed`; specs +- [x] 3 `[agent]` Emit the ranges as Stryker `mutate` entries and drop files whose ranges are empty diff --git a/.agents/tasks/3665-mutation-testing/tickets/04-bounded-run/spec.md b/.agents/tasks/3665-mutation-testing/tickets/04-bounded-run/spec.md new file mode 100644 index 00000000000..682a54b03ed --- /dev/null +++ b/.agents/tasks/3665-mutation-testing/tickets/04-bounded-run/spec.md @@ -0,0 +1,52 @@ +# 04 — Bound a run by wall-clock time, report what completed + +| | | +| --- | --- | +| Parent spec | [`../../spec.md`](../../spec.md) → ticket 04 of #3665 | +| Blocked by | T02 | + +## What to build + +A wall-clock budget on any single run, so a selection that reaches deep into the import graph cannot grind +for hours. When the budget expires the Stryker process is stopped and the results collected up to that point +are reported, with the output stating plainly that the run was truncated and how much of the selection it +covered. + +Stryker writes its JSON report only when the whole run finishes, so a killed process would otherwise leave +nothing behind. A small custom reporter plugin closes that gap: it appends each mutant's result as it is +tested, and the CLI falls back to that stream when the run did not finish. The normal, complete path still +reads Stryker's own JSON report untouched. + +## Acceptance criteria + +- [x] A run that exceeds the budget is stopped and still prints a report covering the mutants tested before + the cutoff. +- [x] The output states the run was truncated and how much of the selection was covered. A truncated run is + never presented as a complete one. +- [x] A run that finishes inside the budget is byte-identical to what T02 produced — the streaming path + changes nothing on the normal path. +- [x] The reporter plugin is named explicitly in `stryker.config.json`'s plugin list, alongside the vitest + runner (pnpm's layout defeats Stryker's plugin globbing). +- [x] Stopping the run leaves no orphaned vitest or Stryker child processes and no stale sandbox directory. +- [x] The budget is a named constant in the tool's config module, overridable per invocation. +- [x] Unit specs cover parsing the streamed results and the truncated-vs-complete decision. + +## Details + +**Why time and not mutant count (FR12).** Runtime is governed by import-graph centrality, not mutant count — +five leaf utilities with 140 mutants ran in 10 seconds while one 28-mutant file imported across the app took +70, because Stryker's dry run executes everything related to it. A mutant-count bound would additionally have +to track Stryker's own generator to stay honest, and any drift would make the bound lie. + +**The plugin** hooks Stryker's per-mutant reporter event and appends one record per line to a file under +`tools/mutation-testing/reports/`, so a partial file is always parseable. It is declared through Stryker's +plugin declaration API and loaded by explicit path. + +**Config precedent** for the budget constant: `tools/code-complexity/config.ts` keeps its caps in one module +so a local run and a CI run gate identically. + +## Leaf worklist + +- [x] 1 `[agent]` Write the streaming reporter plugin and register it in `stryker.config.json` +- [x] 2 `[agent]` Enforce the budget: stop the run at expiry, clean up children and the sandbox +- [x] 3 `[agent]` Read the streamed results on a truncated run and mark the report truncated; specs diff --git a/.agents/tasks/3665-mutation-testing/tickets/05-findings-report/spec.md b/.agents/tasks/3665-mutation-testing/tickets/05-findings-report/spec.md new file mode 100644 index 00000000000..1581ec667f6 --- /dev/null +++ b/.agents/tasks/3665-mutation-testing/tickets/05-findings-report/spec.md @@ -0,0 +1,47 @@ +# 05 — Findings grouped by source line + +| | | +| --- | --- | +| Parent spec | [`../../spec.md`](../../spec.md) → ticket 05 of #3665 | +| Blocked by | T04 | + +## What to build + +The listing half of the output: after the per-file table, the mutants that nothing killed, named by mutator +and grouped by the source line they sit on. Grouping by line is what makes the report actionable — several +mutators surviving on one line is one weak assertion, not several findings. + +No-coverage mutants are a different problem from survivors: they mean no test executed the line at all, +which the CRAP gate already owns. They are separated off the `status` field Stryker records per mutant and +summarised compactly rather than listed one by one. The HTML report's location is printed at the end for +anyone who wants to browse the whole thing. + +## Acceptance criteria + +How to verify: `pnpm test:mutation-testing <a file with known weak assertions>` + +- [x] Survivors are listed grouped by source line, each naming its mutator, under the file they belong to. +- [x] No-coverage mutants never appear in the survivor listing; they are summarised compactly and separately. +- [x] The split reads Stryker's per-mutant `status` field rather than inferring it. +- [x] A run with no survivors and no no-coverage mutants says so in one line instead of printing empty + sections. +- [x] The HTML report path is printed, and the path resolves to a file that opens. +- [x] A truncated run (T04) renders its partial findings the same way, still marked truncated. +- [x] Formatting is unit-tested, including the multiple-mutators-on-one-line grouping. +- [x] `(human)` The report is legible on a real diff: the table, the grouped findings and the no-coverage + summary read as one thing a reviewer can act on, not three dumps. + +## Details + +**Precedent** for the rendering split is `tools/code-complexity/render/` — pure formatters, with the side +effects kept in `index.ts`. Follow it: a module that turns parsed report rows into text, tested directly. + +**Why not Stryker's own reporter (FR8).** The clear-text reporter prints every mutant with its full diff and +is unusable at this scale; consuming the JSON is what makes the compact form possible. + +## Leaf worklist + +- [x] 1 `[agent]` Split survivors from no-coverage mutants off the `status` field; specs +- [x] 2 `[agent]` Render the grouped-by-line survivor listing and the compact no-coverage summary; specs +- [x] 3 `[agent]` Print the HTML report location +- [x] 4 `[human]` Read the output on a real diff and confirm it is actionable diff --git a/.agents/tasks/3665-mutation-testing/tickets/06-ci-gate/notes.md b/.agents/tasks/3665-mutation-testing/tickets/06-ci-gate/notes.md new file mode 100644 index 00000000000..19691095e4d --- /dev/null +++ b/.agents/tasks/3665-mutation-testing/tickets/06-ci-gate/notes.md @@ -0,0 +1,58 @@ +# Notes — 06 + +## `process.chdir()` in a spec aborts the whole run (found while verifying T03) + +Stryker's vitest runner passes `pool: 'threads'` to `createVitest` as a command-line override +(`vitest-test-runner.js`, `#getVitestPoolConfig`), so a config-file `pool` setting cannot win. In a worker +thread `process.chdir()` throws, and any spec calling it fails the **dry run** — which aborts the entire run +with `ConfigError: There were failed tests in the initial test run.`, exit code 1, and no report. + +`tools/mutation-testing/select/files.spec.ts` switches into a throwaway git repository that way for its +git-backed modes, so a diff-scoped run that selects `select/files.ts` aborts: + +``` +ERROR DryRunExecutor One or more tests failed in the initial test run: + git-backed modes selects only the eligible files the branch itself touched + process.chdir() is not supported in workers +``` + +This matters for the gate: a PR touching that file (this branch's own PR included) fails the job for a +tooling reason, not a finding. The fix is to make the selection's git calls take a working directory rather +than move the process into one — which means threading a `cwd` through the complexity gate's +`select/diff.ts` helpers, wider than T03 was scoped for. Decide in this ticket whether the gate works around +it (skipping those specs under `STRYKER_MUTATOR_WORKER`, which downgrades their mutants to no-coverage) or +the specs get fixed properly. + +**Decided: the specs were fixed properly, inside T03.** `selectFiles` takes the repository to resolve +against as an argument, and `select/files.spec.ts` addresses its throwaway repo by path +(`execFileSync(..., { cwd: repo })`) instead of moving the process into it. The gate needs no +workaround, and a PR touching `select/files.ts` — this branch's own included — runs clean. + +## What stood in for the deferred PR run + +The `(human)` criterion needs a non-draft PR, which is after T07. Verified locally instead, with +`GITHUB_ACTIONS=1` set so the annotation path ran: + +- **Fails on a survivor.** Deleting one assertion from `render/truncation.spec.ts` produced + `::error file=tools/mutation-testing/render/truncation.ts,line=21::…` and exit 1. Restoring it: + exit 0, no annotations. +- **A well-formed disable suppresses.** `// Stryker disable next-line ConditionalExpression: <reason>` + above that line dropped the file from 12 scored mutants to 10 and the survivor with it. Swapping it + for `// Stryker disable all` made the ESLint rule error on the real file. +- **Wall time.** A diff-scoped run over this branch's whole diff — 12 files, 761 generated / 288 scored + mutants — took **34 s**. The job's prelude (checkout at `fetch-depth: 0`, pnpm, node, frozen install) + measured **86 s** on run `33516039521`'s identical `vitest_tests` steps, which is what `timeout-minutes: + 20` is sized against: 15-min budget + prelude + teardown ≈ 17 min worst case. + +What could not be checked without GitHub rendering it: that the annotations land on the right diff +lines. The file/line pairs in the directives are correct and repo-relative. + +## Outstanding: the gate fails this branch + +That same rehearsal reported **18 survivors, score 77%** — in the tool's own code, not tooling noise: +`index.ts` L120/L128, `render/table.ts` L9/L13, `select/files.ts` L65/L68/L85, `select/ranges.ts` +L31/L32, `stryker/report.ts` L111/L112/L130, `stryker/stream.ts` L44. Plus 49 no-coverage mutants +(31 of them in `stryker/invoke.ts`), which do not gate. + +So the task's own PR is red until those assertions are strengthened. Not T06's scope — T06's job was to +make the gate fail correctly, which it does — but it has to be dealt with before this lands. diff --git a/.agents/tasks/3665-mutation-testing/tickets/06-ci-gate/spec.md b/.agents/tasks/3665-mutation-testing/tickets/06-ci-gate/spec.md new file mode 100644 index 00000000000..a0b411b6130 --- /dev/null +++ b/.agents/tasks/3665-mutation-testing/tickets/06-ci-gate/spec.md @@ -0,0 +1,59 @@ +# 06 — The PR gate + +| | | +| --- | --- | +| Parent spec | [`../../spec.md`](../../spec.md) → ticket 06 of #3665 | +| Blocked by | T03, T05 | + +## What to build + +A CI job that runs the tool diff-scoped on every pull request and fails when any mutant on a changed line +survives. Findings are additionally emitted as inline annotations on the PR diff, naming the surviving +mutator and the line, so a weak assertion is visible during review rather than buried in a job log. + +Suppressing a mutant stays possible but must be a reviewable claim: Stryker's disable comment carrying both +the mutator name and a reason. Blanket file-level disables are not permitted, and an ESLint rule enforces +that rather than leaving it to review discipline. + +## Acceptance criteria + +- [x] The job runs only on pull requests, diff-scoped against `origin/main`, and carries an explicit timeout. +- [x] It is its own job, chained on the unit-test job. It does not attempt to reuse that job's coverage + artifacts. +- [x] A surviving mutant on a changed line fails the job; no survivors passes it. +- [x] Each survivor produces a `::error file=…,line=…::` annotation naming the mutator, and the annotation + appears inline on the diff. +- [x] A no-coverage mutant alone does not fail the job — that is the CRAP gate's finding, not this one. +- [x] `// Stryker disable all` and any file-scoped disable are an ESLint error. +- [x] A disable comment missing either the mutator name or the `: reason` is an ESLint error; one carrying + both passes and does suppress the mutant. +- [x] The ESLint rule has unit coverage, or is verified against fixture files in both directions. +- [ ] `(human)` The first real PR run behaves: the job is ordered correctly, its wall time is acceptable, and + the annotations land on the right lines. **Deferred to task land** — the job cannot run until the PR + leaves draft, which is after T07. See `notes.md` for what was verified locally in its place. + +## Details + +**Job placement.** `.github/workflows/checks.yml`; `vitest_tests` is the job to chain on and the shape to +copy (checkout with `fetch-depth: 0` so the merge-base resolves, pnpm + node setup, frozen-lockfile install). + +**Why its own job (FR14).** Stryker must drive vitest itself, so the unit-test job's coverage artifacts are +useless here. It chains on that job because a red suite makes Stryker abort during its dry run with an error +that reads like a tooling failure. + +**Annotations** follow `tools/code-complexity/render/github.ts` — pure formatters returning the directive +strings, with the `process.env.GITHUB_ACTIONS` guard and the stdout writes in `index.ts`. Annotation messages +are single-line; newlines truncate the directive. + +**The ESLint rule** reads comments via `context.sourceCode.getAllComments()`. It was built inline in +`eslint.config.mjs` on the `spdxLicenseRule` precedent, then extracted to +`tools/mutation-testing/eslint/well-formed-disable.mjs` and imported from the config — it belongs to the +tool it enforces, and out there a co-located spec both tests it and makes it mutation-eligible itself. + +## Leaf worklist + +- [x] 1 `[agent]` Emit `::error` annotations for survivors and set a failing exit code; specs +- [x] 2 `[agent]` Add the CI job to `checks.yml`, chained on `vitest_tests`, with a timeout +- [x] 3 `[agent]` Add the inline ESLint rule for well-formed Stryker disable comments; specs +- [ ] 4 `[human]` Confirm the first real PR run — ordering, wall time, annotation placement + (deferred to task land, see the acceptance criteria) diff --git a/.agents/tasks/3665-mutation-testing/tickets/07-docs/spec.md b/.agents/tasks/3665-mutation-testing/tickets/07-docs/spec.md new file mode 100644 index 00000000000..b5670b5b01a --- /dev/null +++ b/.agents/tasks/3665-mutation-testing/tickets/07-docs/spec.md @@ -0,0 +1,46 @@ +# 07 — Document the tool + +| | | +| --- | --- | +| Parent spec | [`../../spec.md`](../../spec.md) → ticket 07 of #3665 | +| Blocked by | T06 | + +## What to build + +The documentation a developer needs when this gate fails on their PR and they have never seen it before: +what a surviving mutant means, why it is not the same complaint as a coverage miss, what to do about it, and +when suppressing one is legitimate. + +The complexity gate's docs are the model to follow — a `CONTEXT.md` that opens with "the gate failed, what +now" and a file map, plus a `docs/` for the detail. It is also the place to state what this tool deliberately +does not measure, so nobody rediscovers those boundaries by trying. + +## Acceptance criteria + +- [ ] `tools/mutation-testing/CONTEXT.md` exists, opens with how to reproduce a CI failure locally, explains + what a surviving mutant means as distinct from a coverage miss, and carries a file map. +- [ ] The exclusions are stated with their reasons: Playwright tests, non-logic mutators, files without a + co-located spec, `jsx` function bodies, and the absence of a whole-repo CI run. +- [ ] The suppression policy is documented — the disable-comment form that passes the ESLint rule, and what + makes a suppression a legitimate claim. +- [ ] `.claude/CLAUDE.md`'s per-directory context list has an entry for `tools/mutation-testing/`. +- [ ] `.agents/rules/code-quality.md` mentions the gate beside the complexity and CRAP sections, with the + commands to run it. +- [ ] Cross-references to `tools/code-complexity/` are accurate: the reuse of its selection and classification + code is described where it matters, without restating what those files already document. +- [ ] `pnpm lint:cspell` passes on the new files. + +## Details + +Follow the model of `tools/code-complexity/CONTEXT.md`: a "where to look" table, the failure-triage section +first, the file map last, with per-file detail left in each file's own header comment rather than duplicated. + +Reasoning that belongs in the docs rather than the spec: why the gating mutator set is the five logic classes +(sampling found roughly a third of all-mutator survivors unkillable by any vitest test, versus zero of the +logic-only ones), and that promoting or demoting a mutator class is a one-line config change. + +## Leaf worklist + +- [x] 1 `[agent]` Write `tools/mutation-testing/CONTEXT.md` +- [x] 2 `[agent]` Write the `docs/` detail pages +- [x] 3 `[agent]` Add the entries to `.claude/CLAUDE.md` and `.agents/rules/code-quality.md` diff --git a/.agents/tasks/3671-token-multiplier/spec.md b/.agents/tasks/3671-token-multiplier/spec.md new file mode 100644 index 00000000000..3616a1fb52e --- /dev/null +++ b/.agents/tasks/3671-token-multiplier/spec.md @@ -0,0 +1,135 @@ +# ERC-8056 token multiplier support + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3671 | +| Feature branch | `issue-3671` | +| PM | Nikita S. | +| Designer | Tatyana | +| Backend | Alexey | +| Minimum API version | Core API v12.0.0+ | +| Slack channel | — | + +## Context & goal + +ERC-8056 is a token standard whose contract exposes a *UI multiplier*: the amount a holder should see is the +raw ERC-20 amount scaled by that factor (`uiAmount = rawAmount × uiMultiplier`). The multiplier changes over +time, each change announced by a `UIMultiplierUpdated` event carrying an activation timestamp, so a change +can be scheduled ahead of when it takes effect. + +The explorer currently renders these tokens as plain ERC-20s, showing raw amounts. A holder comparing the +explorer against their wallet sees different numbers for the same balance, with nothing explaining the +discrepancy. + +This task makes the explorer speak the token's own units: every displayed amount of an ERC-8056 token is +scaled, the raw value stays reachable in a tooltip, and a tag marks that scaling is in effect at all. + +## Functional requirements + +1. `ERC-8056` is a selectable token type wherever token types are filtered, and appears as the type tag on + token entities. +2. Every amount of an ERC-8056 token rendered anywhere in the app is the scaled amount, never the raw one — + the single exception is the amount tooltip, which discloses the raw value. +3. An amount of an ERC-8056 token carries a multiplier tag showing the factor in effect, shown even when the + factor is exactly 1. +4. The amount tooltip states the scaled value, the raw value, and the multiplier applied. +5. The token details page shows a Multiplier row with the currently effective factor and an explanatory + tooltip. +6. The token details page shows the most recent multiplier changes inline, capped at five, linking to the + full history when more exist. +7. A Multiplier history tab lists every recorded multiplier change with its transaction, block, old and new + factor, activation date, and whether it is the active one; the tab carries a count. +8. A token whose multiplier data is absent, or one on an instance where the type is not enabled, renders + exactly as an ERC-20 does today — no scaling, no tag, no tooltip, no Multiplier row. +9. Fiat values of ERC-8056 amounts are computed from the scaled amount. + +## Data & API + +Shipped in **Core API v12.0.0** (testing builds sit on top of 11.3.0). All fields are nullable; the +multiplier is a fixed-point integer with **18 decimals of precision**, independent of the token's own +`decimals`. + +**Token model** (`token`, wherever it is embedded): + +- `ui_multiplier` — the factor in effect at request time. The API already resolves a scheduled change, so + this is the effective value, not the raw stored one. +- `new_ui_multiplier` — the factor scheduled to replace it. +- `ui_multiplier_effective_at` — when that replacement takes effect. A change is *pending* exactly when this + is in the future. + +**Token transfers** — `total.ui_multiplier` carries the factor in force when the transfer happened. + +**State changes** — `ui_multiplier` sits alongside `balance_before` / `balance_after` / `change`. + +**Type filtering** — `?type=ERC-20` no longer returns ERC-8056 tokens; `?type=ERC-8056` selects them. + +**Supplies** — `total_supply` is raw and must be scaled by `token.ui_multiplier`. `circulating_supply` is +already in UI units and must not be scaled. `circulating_market_cap` is fiat, not a token quantity, and must +not be scaled either. + +**Exchange rate** — quoted per *UI* token, so fiat is `uiAmount × rate`. The existing USD path is correct +once it receives the scaled amount. + +**New resource** — the multiplier history endpoint `/tokens/{hash}/ui-multiplier-changes` needs a +`service:name` resource; its response shape is Q02. Its count arrives as `ui_multiplier_changes_count` in +`/tokens/{hash}/counters`. + +**Readiness** — the token fields, transfer `total.ui_multiplier`, state-change `ui_multiplier` and type +filtering are deployed and observable on a live instance. The history endpoint and the counter are not. + +**Live example** — https://eth-sepolia.blockscout.com/address/0x6D50E6CBca0e390BbCF82bEA80B31F4c2694395e + +**Env** — instances opt in through the existing `NEXT_PUBLIC_NETWORK_ADDITIONAL_TOKEN_TYPES` by listing +`ERC-8056`. No new env var. + +## UI inventory + +Parent frame: +[Token multiplier support #3671](https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=6004-41185). + +| Surface | Change | Node | +| --- | --- | --- | +| Token transfers table | type filter option, multiplier tag, amount tooltip | [5995:28720](https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=5995-28720) | +| Address → token transfers tab | same treatment | [5995:28716](https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=5995-28716) | +| Token details → Details tab | Multiplier row, info tooltip, inline history (max 5) with link to the tab, scaled supply | [5995:20900](https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=5995-20900) | +| Token details → Multiplier history tab | new tab, table + mobile list, tab counter | [5995:28735](https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=5995-28735) | +| Advanced filter | Multiplier column, amount tooltip | [6004:40199](https://www.figma.com/design/CEgxqWOzVulwfTUHhs0gUC/?node-id=6004-40199) | + +Route for the new tab: `/token/{hash}?tab=multiplier_history`. + +Surfaces absent from the mockups but in scope, because they render an amount of the token and would +otherwise disagree with the ones that are: token holders (Quantity column), address token balances and net +worth, the address token-select dropdown, and transaction state changes. They reuse the amount treatment +above — no new elements. + +Search results need a fix of a different kind: they branch on `ERC-20` to choose between showing a price and +showing an NFT-style item count, so an ERC-8056 token currently renders as if it were an NFT collection. +Search carries no multiplier fields and displays no amount, so it needs the branch corrected, not scaling. + +## Implementation decisions + +- **The frontend scales; the API never does.** API v2 hands over raw values plus the multiplier. (Backend + scaling does exist, but only on the old-UI and notification-email paths.) +- **One predicate owns the decision to scale.** A single helper resolves a token to its multiplier or to + nothing, and every amount site multiplies by what it returns. It yields nothing unless the instance + enables `ERC-8056` *and* the response carries multiplier data. When it yields nothing the whole treatment + is suppressed together — scaling, tag, tooltip and Multiplier row — so a half-configured instance degrades + to today's ERC-20 rendering rather than to a mix of scaled and raw figures. +- **Multiplier formatting is one shared rule**, reused everywhere the factor appears: six decimals, no + trailing zeros, and the app's existing "below the smallest representable value" treatment underneath that. + This departs from the mockups, which render `1.00x`; the PM confirmed the trailing zeros carry no meaning. +- **Amount precision is unchanged.** Scaled amounts use the app's existing accuracy in the cell and full + precision in the tooltip; computation stays full-precision throughout, rounding only at render. +- **A transfer shows the multiplier that applied to it**, from `total.ui_multiplier`, not the token's current + factor — pending Q01 for what to do when that value is absent. +- **The Details Multiplier row and the history block are separable.** The row comes from the token model and + works with no history at all; the inline block and the tab come from the history endpoint. When history is + unavailable or empty, the row renders alone. + +## Out of scope + +- **B-20.** It carries a comparable multiplier interface but brings a much larger surface of its own; + supporting it is a separate task. +- **CSV exports.** Generated backend-side; scaling them is a backend change. +- **Reconstructing historical fiat.** Fiat follows from the scaled amount and the current rate. +- **Analytics events.** No custom Mixpanel events; tab views are covered by existing page-view tracking. diff --git a/.agents/tasks/3674-tools-scripts-rewrite/spec.md b/.agents/tasks/3674-tools-scripts-rewrite/spec.md new file mode 100644 index 00000000000..8e4f5101420 --- /dev/null +++ b/.agents/tasks/3674-tools-scripts-rewrite/spec.md @@ -0,0 +1,115 @@ +# Rewrite the .mjs scripts under tools/ in TypeScript + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3674 | +| Feature branch | `issue-3674` | +| PM | — | +| Designer | — | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +Three `.mjs` scripts under `tools/` are the only executable logic there that no gate can see. The +`.mjs` extension keeps them out of the root `tsconfig.json` `include`, so `pnpm lint:tsc` never +type-checks them; a `*.spec.mjs` would not be discovered by `vitest.config.ts` without widening +suite-wide test discovery, so they have no tests; and with no tests they report 0% coverage, which +makes the CRAP half of the complexity gate uninformative for exactly the highest-complexity tooling +code in the repo. + +Rewriting them in TypeScript brings all three under the type-check and the unit suite, and lets the +complexity gate report something meaningful. While `check-doc-links` is open it also takes a scope +extension: its check surface currently reaches only files named exactly `CONTEXT.md`, so a directory +documenting itself across several markdown files gets one of them checked and the relative +references *inside* the others can break silently. + +Blocker issue #3663 (the complexity gate, its caps, and its coverage of `tools/**`) is closed; the +gate is live and already measures `.mjs`. + +## Functional requirements + +1. `pnpm lint:doc-links`, `pnpm profile:analyze`, `pnpm presets:lint` and `pnpm presets:sync` behave + identically from a caller's point of view — same arguments, same output, same exit codes. +2. All three tools' sources are TypeScript and are type-checked by `pnpm lint:tsc`. +3. `pnpm test:code-complexity` passes on all three tools: every function is within the cognitive cap + for its class and within the CRAP cap. +4. Co-located `*.spec.ts` files exercise all three tools, so their reported coverage is real rather + than 0%. `vitest.config.ts` `include` is unchanged. +5. `pnpm lint:doc-links` checks every markdown file in and below any directory that contains a + `CONTEXT.md`, nested subdirectories of records included, and resolves their relative references. + `src/toolkit/package/` is exempt: it is the published npm package wrapper and its readme addresses + package consumers rather than agents. +6. Every reference in the extended surface resolves — including the two that do not today, in + `tools/code-complexity/docs/RUNNING.md` and `tools/mutation-testing/docs/RUNNING.md`. +7. Compiled JavaScript is git-ignored; no build artifact is committed. +8. `pnpm dev:preset`, `pnpm dev:local`, `pnpm prod:preset`, the Docker image build and the container + entrypoint are unaffected. + +## Data & API + +None. No endpoint, no `service:name` resource, no env var, no feature flag, no analytics event. + +## UI inventory + +None. No user-visible surface; developer tooling only. + +## Implementation decisions + +### Layout + +- **`tools/doc-links/`** — a new folder replacing `tools/scripts/check-doc-links.mjs`, flat files + split by concern: surface collection, line stripping, reference resolution, per-line checking, + reporting, entry. That checker's per-file check function is the task's one real decomposition + target, and the scope extension lands in its collection step. +- **`tools/dev-server/sync-presets/`** — a subfolder for the preset-list sync tool alone, named for + the job: `presets/` would read as though the registry lived in it. `registry.json` and + `envs-rules.json` stay at the `tools/dev-server/` root — the registry's other reader, the env + fetcher, is not moving, and its path is a contract in the Dockerfile, the container entrypoint, + several skills and the contributing guide. +- **`tools/profiling/`** keeps its shape; the aggregator stays one module. It breaks no cognitive + cap, so its lever is coverage, not decomposition. + +### Constraints + +Not free choices — the rest of how these tools are shaped internally is the implementing agent's +call, judged against the functional requirements and whatever the gate reports at the time: + +- **The preset sync tool needs its own `tsconfig.json`**, not the existing `tools/dev-server/` one: + giving that config an `outDir` relocates the env fetcher's emitted entry and breaks the + Dockerfile's `COPY` of it. +- **Each tool's CLI invocation lives in its own entry file**, not behind an entry-point guard inside + the module. +- **No committed real-world DevTools profile export.** Hand-built minimal fixtures instead: an + export pins the fixture to one DevTools version, and the wire format is what's under test. + +### Doc-link scope extension + +- Two references in the newly-covered surface don't resolve, both writing `./run.sh` from a `docs/` + subdirectory where the file sits one level up. Fix them as docs — not by resolving relative paths + against the `CONTEXT.md` directory, since `./` means "beside this file" everywhere else in the + instruction surface and special-casing it would weaken the check the extension exists to add. +- The `src/toolkit/package/` exemption (FR5) goes in the script's existing exclusion list as a path, + not as a `README.md` filename rule: `.agents/rules/docs.md` governs a module `README.md` as a doc + kind, so a filename rule would pre-emptively unprotect the files that rule expects to be checked. + +### Docs + +`tools/doc-links/` gets a `CONTEXT.md` — a file map, registered in the per-directory list in +`.agents/AGENTS.md`. Convention rationale stays in per-file header comments rather than moving into +it. Note the loop this closes: the tool then checks its own docs. + +`tools/code-complexity/select/scope.spec.ts` asserts scope membership using two of the `.mjs` paths +this task deletes. `.mjs` stays a legitimate in-scope extension so the assertions keep passing, but +swap the strings for names that exist. + +## Out of scope + +- **Moving the env fetcher** out of `tools/dev-server/` — tempting while restructuring its + neighbours, but its path is a contract in the Docker build and `COPY`, the container entrypoint, + four `deploy/tools/*` dev scripts, three `tools/scripts/*.sh` wrappers and a documented skill + command line. A separate issue if wanted at all. +- **Bringing `deploy/` under the complexity gate** — tracked as issue #3675. +- **Moving the caps** in the complexity gate's config. It is the cheap way to satisfy FR3 and it is + not available. diff --git a/.agents/tasks/3680-pw-mocks-env-desync/spec.md b/.agents/tasks/3680-pw-mocks-env-desync/spec.md new file mode 100644 index 00000000000..5ae6b20fdd8 --- /dev/null +++ b/.agents/tasks/3680-pw-mocks-env-desync/spec.md @@ -0,0 +1,94 @@ +# Prevent env-derived query params from desyncing Playwright mocks from the app + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3680 | +| Feature branch | `issue-3680` | +| PM | tom | +| Designer | — | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +The Playwright `mockApiResponse` fixture builds its route matcher by calling the production URL builder +**in Node**, where `src/config` is a frozen singleton evaluated from `playwright/.env.pw`. The component +under test builds the same URL **in the browser**, where `getEnvValue` honours the `localStorage` overrides +written by the `mockEnvs` fixture. Any env that takes part in URL building — API hosts, ports and base +paths, the network id, the multichain flag, and now the interchain scope filters — therefore resolves +differently on the two sides whenever a test overrides it. The matcher misses, the request falls through +to a dead `localhost` port, and the component renders an empty or error state that only surfaces as a +screenshot diff. + +The latest instance (PR #3679) was patched per call site by restating the derived query params by hand and +aligning a mock's chain id with `.env.pw`, which duplicates production derivation logic in test setup. + +Goal: a test that overrides an env used in URL building keeps matching its mocks with no per-call-site +restatement, and any request a test fails to mock fails that test with a diagnostic that names the +mismatch. + +The planned migration to Playwright's stateful-stories model does not remove the trap on its own: test +code and `page.route` still run in Node while the story runs in the browser. The fix below moves URL +computation to the browser page, which the stories gallery can own just as well, so it carries over. + +## Functional requirements + +1. A `mockApiResponse` or `mockConfigResponse` registered after `mockEnvs` overrides matches the request + the component actually sends, for every env that participates in URL building, including the + `interchainIndexer` scope filters. The caller passes only the path and query params the component + itself passes; env-derived params are never restated at the call site. +2. Both fixtures keep returning the matcher URL as a string. +3. Calling `mockEnvs` after a mock has been registered in the same test fails that test immediately with a + message naming both calls and the required order. +4. A request to `localhost` on any port other than the component-test server and the test socket server + that no registered mock handled fails the test. The failure lists each such URL, then the registered + matchers sharing its pathname, then a count of the remaining matchers. Requests to non-`localhost` + hosts stay silently aborted as today. +5. There is no per-test opt-out of requirement 4. A test that needs an API call to fail mocks it with an + error status. +6. The cross-chain-txs visual tests no longer restate `home_chain_id`, `include_unindexed_chains` or + `bridge_ids` by hand, and no longer carry a mock whose chain id must match `.env.pw`. +7. The full suite passes in Docker with requirement 4 enforced: every previously unmocked request is + either mocked or deliberately answered with an error status. +8. The visual-test rules and the Playwright runner context describe the browser-side URL resolution, the + fixture ordering rule, and the unmocked-request failure. + +## Data & API + +No API changes. Env vars involved are only those `buildUrl`, `getResourceParams`, `isNeedProxy`, +`resolveScopeFilters` and `buildExternalAssetFilePath` already read. `playwright/.env.pw` is not changed +to switch any feature on. + +## UI inventory + +None. Test infrastructure only; no product UI changes. + +## Implementation decisions + +- **One env source: the browser.** The harness entry loaded by the component-test page exposes a + window-level builder that dynamically imports the production URL builder and the external-asset path + helper on first use. `mockApiResponse` and `mockConfigResponse` call it through `page.evaluate` instead + of importing the production modules in Node. Evaluating `src/config` in the page at that moment is + correct because the component shares the same module graph and would evaluate it with the same + `localStorage` state at mount. Arguments cross the boundary as plain data; the `chainConfig` option is + already serialisable mock data. +- **Ordering guard.** A per-test fixture state records whether any mock has been registered; `mockEnvs` + throws when that flag is set. This is what makes the browser-side singleton safe. +- **Unmocked-request detection** lives in the existing catch-all route in the shared test setup: it is + consulted last, so anything reaching it with a `localhost` host and a port outside the CT server and + socket server is unmocked by definition. Those URLs are recorded per test; the mock fixtures record every + matcher they register; an `afterEach` assertion compares the two and formats the diagnostic. +- **Fail, not warn.** Warnings go unread; the target state of the task is a failing test. The audit of + currently unmocked requests is unknown in size, which is why it is its own ticket. +- **Proof of the fix** is reverting the PR #3679 workaround in the cross-chain-txs tests: drop the + hand-written scope-filter query params and the `homeChain` mock aligned with `.env.pw`, and re-override + the network id via `mockEnvs` where the test needs it. +- Rejected: re-evaluating Node-side config under overrides (fragile in Playwright's module loader), and a + lenient matcher that ignores extra query params (hides real bugs). + +## Out of scope + +- Migrating to Playwright's stateful-stories model and off the removed experimental CT packages. +- Changing how production code reads envs or builds URLs. +- Flagging aborted non-`localhost` requests (ads, third-party scripts, remote images). diff --git a/.agents/tasks/3697-paginated-query-hook-refactor/spec.md b/.agents/tasks/3697-paginated-query-hook-refactor/spec.md new file mode 100644 index 00000000000..9b91bc28b4f --- /dev/null +++ b/.agents/tasks/3697-paginated-query-hook-refactor/spec.md @@ -0,0 +1,140 @@ +# Stop redundant requests and skeleton cycles in paginated list navigation + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3697 | +| Feature branch | `issue-3697` | +| PM | Ulyana | +| Designer | Tatyana | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +Every paginated list in the app (address transactions, token transfers, logs, blocks, and ~100 more +call sites) is driven by one shared hook, `useQueryWithPages`. An audit of that hook on the address +transactions tab found that it is not a render-cost hotspot itself, but its design produces +user-visible waste on every navigation: extra API requests, requests for page/filter combinations +the user never asked for, and skeleton passes over data that is already cached. + +The root cause is that page, cursor, filter and sort state live in three places at once — the URL, +the hook's own React state, and the calling component's state — and the hook writes the URL first +and then re-syncs its state from the URL through effects. Measured on the address transactions tab: + +| Interaction | API requests today | Should be | +| --- | --- | --- | +| "First" from page 3 | 3 (page 3 refetched, page 1 twice; page-3 skeleton flashes first) | 1 | +| Filter change while on page 3 | 2 (first one = old cursor + new filter) | 1 | +| "Prev" from page 2 to page 1 | 1, with skeleton, although page 1 is cached | 0 blocking (background refresh at most) | +| Unrelated `router.query` change | 0, but a full re-render of the list subtree | no re-render | + +The goal is to make the URL the single source of truth for list state, so that one user action is +exactly one URL push, one query key, one request and one render; to stop discarding cached pages; +to make the hook's return value stable so the memoization already present in list components and +tab containers actually holds. Replacing the skeleton pass on page changes with keeping the current +rows visible (dimmed) is deferred to #3704 pending design; this task ships its plumbing inert. + +## Functional requirements + +1. Each pagination action — next page, previous page, first page, filter change, sorting change — + issues exactly one API request, for the query the user asked for, and never a request for a + transient combination (for example the previous page's cursor combined with a new filter). +2. Navigating back to a page whose data is cached shows that data immediately, with no skeleton. + Page 1 may refresh in the background while its cached rows are displayed; it is never dropped + from the cache before being displayed. +3. Cache operations performed by the hook affect only the queries of the list it drives (that + resource with those path params), never other addresses, chains, or lists sharing the resource + name. +4. Page, cursor, filters, sorting and (on multichain instances) selected chain are read from the + URL on every render. The hook keeps no React state that mirrors a URL value, and no effect + re-syncs state from the URL. Reloading, sharing or navigating back to a URL restores the same + list state as today (page number, `next_page_params`, filter and sort params keep their current + names and encoding). +5. Callers no longer keep their own copy of filter or sort state; they read typed values from the + hook and call its change handlers. Tab switches, which strip list params from the URL, therefore + reset filters and sorting without caller-side bookkeeping. +6. The hook's return value, its `pagination` object and every callback it exposes are referentially + stable between renders when their inputs have not changed, so a memoized consumer does not + re-render on an unrelated route change or on a socket-driven cache update. +7. When the user moves to another page of the same list (same filters and sorting, different + cursor), skeleton rows are shown until the new page's data arrives, as today. The hook and the + shared list wrapper carry an `isTransitioning` flag / prop wired to every migrated list but never + set; the dimmed, non-interactive page-transition state is deferred to #3704 pending design. +8. Skeleton rows are still shown on first load of a list and after a filter or sorting change. The + lazy-render window of long lists resets on every dataset change as it does today. +9. All existing pagination behaviour that is not named above is preserved: the "next page" button + hides when the API returns no cursor, the "first" and "previous" buttons stay disabled on page 1, + scroll-to-top (or to the configured element) happens on every navigation, the socket-driven + "new items" notices keep prepending into page 1, and CSV export and count/label props keep + reading the same values. +10. The composed hook is renamed to `useApiPaginatedQuery` to sit next to `useApiQuery` and + `useApiInfiniteQuery`; the rename is applied to every call site. +11. The multichain-only capabilities (selected chain value and its change handler) are provided by + a separate opt-in hook; single-chain callers neither receive nor pay for them. +12. The existing unit test coverage for the hook is kept or extended, with a realistic router + stand-in that re-renders on push so that the number of requests and renders per action is + asserted, not only the final state. + +## Data & API + +None. No endpoints, resources, env vars or feature flags change. Pagination params (`page`, +`next_page_params`), filter and sorting query parameter names and encodings stay exactly as they are +so that existing links keep working. + +## UI inventory + +- Every paginated list page and tab in the app (the ~106 call sites of the current hook), with the + address details page transactions tab (single chain) as the reference integration: `RoutedTabs` + → tab content → sorting wrapper → list content → table/list rows → `Pagination`. +- No new screens and no new visual state. The **page-transition** state for the list body (current + rows dimmed and non-interactive) is deferred to #3704 (see `questions.md`, Q01); `DataList` + carries the `isTransitioning` prop for it, never set. +- Skeleton state stays as is for first load, page changes and filter/sort changes. + +## Implementation decisions + +- **URL is the single source of truth.** All list state is derived from `router.query` on each + render; the previous-page cursors needed for "previous" are kept in a ref keyed by page number, + populated on "next", and are the only in-memory list state. Handlers perform one shallow + `router.push` each and nothing else; there are no `.then` callbacks, no `isMounted` timers, no + router-sync effects. +- **Split into single-responsibility hooks, composed by a thin public hook.** `usePaginationParams` + reads page, cursor, filters and sorting from the URL (pure derivation, no state, no effects). + `usePaginationActions` returns stable next/prev/first/filter/sorting callbacks that read the + latest router through a ref. The composed `useApiPaginatedQuery` builds the query key, calls + `useApiQuery`, and returns a memoized object; it is what the vast majority of callers use with + the same call shape as today. `useChainValue` is the opt-in multichain piece. A caller that + needs only part (resource chosen from the filter, chain selection) composes the pieces itself. +- **No prefix-scoped cache removal.** The `removeQueries([resourceName])` calls go away. Page 1 keeps + `staleTime: 0` so it refreshes in the background on return; deeper pages keep `staleTime: + Infinity`. If a forced refresh is ever needed it targets the exact query key. +- **Placeholder strategy decided inside the hook.** `placeholderData` stays the caller's stub for + every query-key change (first load, page change, filter/sort change). The hook exposes two flags: + `isInitialLoading` (placeholder is the stub → rows render skeletons) and `isTransitioning`, always + `false` until #3704 flips the placeholder to the previous data on page changes. + `pagination.isLoading` stays true whenever a placeholder is shown, for button disabling. +- **Dimming is one global wrapper, not per-row.** The shared list wrapper (`DataList`) gains an + `isTransitioning` prop and applies opacity, `pointer-events: none` and `aria-busy` to the body + it already wraps, leaving the action bar outside. Row and cell components keep their `isLoading` + prop with its current meaning (skeleton). List content components wire two props: + `isLoading={ isInitialLoading }` to rows and `isTransitioning` to the wrapper. The prop is never + true in this task; #3704 styles and activates it. +- **Row keys no longer depend on loading state** for real data: the index suffix on keys applies + only while rendering the stub, so during a page transition the previous rows keep their keys and + the new rows replace them in a single commit. +- **Rename last, mechanically.** `useQueryWithPages` → `useApiPaginatedQuery` is a separate + codemod commit after the behavioural change, so the behavioural diff stays reviewable. +- **Migration is per call-site family.** The reference integration (address transactions tab) is + migrated first and reviewed; the remaining call sites follow in groups by shared list component + (transactions lists, token transfers, logs, blocks, and the long tail), each group removing its + duplicated filter/sort state. + +## Out of scope + +- Row-level render cost (cell components, `TxsTableItem` and siblings) and the lazy-render window + mechanics; those were addressed in the previous list-view optimization and are unchanged here. +- Changing pagination URL parameter names or encoding. +- The infinite-scroll hook (`useLazyLoadedList`) and its callers. +- Backend or API changes. +- Any redesign of the pagination controls themselves. diff --git a/.agents/tasks/3706-playwright-affected-tests-ci/spec.md b/.agents/tasks/3706-playwright-affected-tests-ci/spec.md new file mode 100644 index 00000000000..13c9bbf6111 --- /dev/null +++ b/.agents/tasks/3706-playwright-affected-tests-ci/spec.md @@ -0,0 +1,123 @@ +# Rework how Playwright component tests are selected and run in CI + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3706 | +| Feature branch | `issue-3706` | +| PM | — (frontend tooling task) | +| Designer | — | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +Playwright component tests (`*.pw.tsx`) run on every PR, scoped by a custom affected-tests tool that walks +the import graph with `dependency-tree`. The walker has known gaps (type-only imports count as dependencies, +the diff is taken against the base-branch tip rather than the merge-base, no forced full run when the test +harness or the lockfile changes), and the CI wiring wastes runner time: the three matrix jobs boot even when +the resolve job found nothing to run, the `default` project alone takes ~16 min while the other two take +4–5 min, and every matrix job spends ~3 min in redundant post-job cache saves plus a git-lfs install nothing +uses. The tooling is also split between `deploy/tools/affected-tests` (a path CI's `paths-ignore` excludes, +so changes to the tool never trigger checks) and `tools/scripts/pw*.sh`. + +The goal is one `pnpm test:pw` entrypoint shaped like the sibling gates (`test:code-complexity`, +`test:mutation-testing`), affected-test selection delegated to Playwright's own `--only-changed`, and a CI +layout that skips empty runs and balances the buckets — so an average feature-branch run finishes in a +fraction of today's wall time and a human or agent has one command to reach for. + +## Functional requirements + +1. A `tools/playwright/` tool, exposed as `pnpm test:pw`, is the single entrypoint for running Playwright + component tests locally, in Docker, and in CI. It follows the sibling tools' conventions: TypeScript + compiled on run via a `run.sh` wrapper, a `--help` usage text, co-located specs, and a `CONTEXT.md`. +2. Its own flags are `--changed[=<ref>]`, `--base <ref>`, `--docker`, `--docker-deps`, and `--help`. Every + other argument (`--project`, `--shard`, `-g`, `--update-snapshots`, `--clear-cache`, file paths, …) is + passed through to `playwright test` untouched. +3. `--changed` selects affected tests against the **merge-base** of the base ref (default `origin/main`) + and `HEAD`, including uncommitted working-tree edits — the same semantics as the sibling gates' + `--changed`. Playwright's bare "uncommitted vs HEAD" mode is not exposed. +4. Under `--changed`, if any changed file falls under a **force-full list** — `src/sprite/icons/**`, + `playwright/**`, `playwright-ct.config.ts`, `pnpm-lock.yaml` — the tool runs the whole suite. Otherwise + it runs Playwright with `--only-changed=<merge-base sha>`, so the bundler's real module graph decides + which test files are affected; type-only imports never count because the bundler erases them. +5. Before every run the tool regenerates `playwright/envs.js` from `playwright/.env.pw` and builds the SVG + sprite for the `pw` app env, as the current script does. The unconditional deletion of Playwright's build + cache stays in the tool but commented out, with the reason recorded next to it, so it can be flipped back + on if a stale build is ever observed. +6. `--docker` runs the same command inside the pinned Playwright image with the Linux `node_modules` + mounted; `--docker-deps` installs those Linux dependencies. The existing `test:pw:docker` and + `test:pw:docker:deps` package scripts remain as aliases of the flags. +7. Every run writes a JSON report alongside the existing reporter output (`blob` in CI, `html` locally) so + an agent can read outcomes and screenshot-diff paths without parsing the console reporter. +8. `deploy/tools/affected-tests` and `tools/scripts/pw*.sh` are removed; `package.json` scripts point at + the new tool. +9. In `checks.yml`, the affected-tests resolve job becomes a **no-install gate**: it computes the + merge-base and lists changed files under the watched paths (`src/`, `playwright/`, + `playwright-ct.config.ts`, `pnpm-lock.yaml`); the matrix jobs are skipped when the list is empty. The + gate's path list and the tool's force-full list are documented as a pair that must stay in sync. +10. The matrix is five jobs via `include`: `default` split into three shards, `mobile`, and + `dark-color-mode`. Each runs `pnpm test:pw --changed --project=<name> [--shard=<n>/3] + --pass-with-no-tests`, checks out with full history (the merge-base needs it), and uploads its blob + report as today; the report-merge job is unchanged. +11. The matrix jobs no longer install git-lfs or check out with LFS, and the duplicate dependency cache + (`cache: true` on the pnpm setup action, alongside `setup-node`'s pnpm cache) is dropped. +12. `.agents/rules/tests-visual.md` and the tool's `CONTEXT.md` document the new commands; a + module-scoped ADR under `tools/playwright/adr/` records why selection is delegated to Playwright rather + than a custom dependency walk. +13. ~~An upstream Playwright issue is filed for `--only-changed --list` reporting zero tests in + component-testing mode (list mode never sets up the CT plugin, so no component dependencies are + populated), and linked from the tool's `CONTEXT.md`.~~ **Dropped at ticket 05**: Playwright 1.63 + froze the experimental CT packages and the maintainers rule out source-to-test mapping in the + replacement stories model (microsoft/playwright#40691). Reproduction and draft kept in + `tickets/05-upstream-playwright-issue/notes.md`; the migration question is deferred, deliberately. + +## Data & API + +None. No endpoints, resources, env vars, or feature flags. + +## UI inventory + +None. This is CI/tooling only. + +## Implementation decisions + +- **Playwright's `--only-changed` replaces the custom walker.** Verified in this repo: with + `@playwright/experimental-ct-react` the CT plugin builds the Vite bundle, records each registered + component's module graph, and maps changed files to test files through it. Touching a type-only file + selected 0 tests; touching a leaf component selected only its 31 dependents; touching a theme recipe, a + toolkit component, or `TestApp` selected the full project, because `TestApp` is registered as a + component through the render fixture. The custom walker with `dependency-tree` could be patched + (`detective: { ts, tsx: { skipTypeImports: true } }` cuts ~20% of edges) but stays a parallel model of + what the bundler already knows. +- **Icons are the one blind spot, hence the force-full list.** SVG icons reach the browser as a sprite + built at run time, not through the module graph. `playwright/**` covers template files (`index.ts`, + `index.html`, `.env.pw`, fonts) that are not component dependencies; the config and the lockfile cover + build-shape and dependency changes. `package.json` needs no special handling: under `--frozen-lockfile` + any dependency change also changes `pnpm-lock.yaml`, while script/metadata edits do not. +- **Merge-base, not base-tip.** A two-dot diff against `origin/main` reports files that only changed on + main since the branch forked, over-selecting on stale branches. The tool resolves `git merge-base + <base> HEAD` and passes that sha to Playwright, matching `tools/code-complexity`'s diff scoping. +- **The empty-run gate is plain shell in the workflow, not the tool.** The gate is one `git diff + --name-only <merge-base> -- <paths>`; running the TypeScript tool there would cost a dependency install + (~1.5 min serial) on every PR. The four paths are duplicated between the workflow step and the tool's + config and documented as such; if drift ever bites, the gate moves into the tool. +- **Sharding, not workers.** `default` runs every test not tagged `-@default` (~720 tests) versus ~150–180 + in the other two projects. Three shards bring it to the others' size deterministically; raising + `workers` above 1 is left for a later, measured change because the flake rate is already non-trivial. +- **Agent surface is the JSON report, not a dry-run.** Playwright's `--list` is the natural "which tests + would run" answer but is broken with `--only-changed` in CT mode. A bespoke dry-run would have to + drive Playwright internals and would break on upgrade; the JSON report is the chosen shape for now + (the upstream bug report was dropped, see requirement 13). +- **Full runs stay on pre-release and manual dispatch.** Two years of this cadence have surfaced few broken + tests on `main`; adding a push-to-main full run is deferred. + +## Out of scope + +- The vitest gate's `--changed=origin/main` selection: vitest already diffs `<ref>...HEAD` (merge-base + semantics), so it has no equivalent bug and needs no change. +- Raising Playwright `workers` in CI or tuning `retries`. +- A scheduled or push-to-main full Playwright run. +- Sharding `mobile` or `dark-color-mode`. +- A dry-run / "list affected tests" command. +- Any change to the tests themselves, screenshots, or the `playwright/` harness (fixtures, mocks, `TestApp`). diff --git a/.agents/tasks/3720-jev-review-screen/spec.md b/.agents/tasks/3720-jev-review-screen/spec.md new file mode 100644 index 00000000000..b54c6011d34 --- /dev/null +++ b/.agents/tasks/3720-jev-review-screen/spec.md @@ -0,0 +1,127 @@ +# Pilot Jev typed judgments as a fourth subagent in the agent code-review workflow + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3720 | +| Feature branch | `issue-3720` | +| PM | — (frontend tooling task; owner: tom) | +| Designer | — | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +The agent code review (`review-changes`) runs three LLM axes — spec, standards, correctness — each reading +the whole change blind. A fast typed-judgment model (TypeSafe's Jev) can score every rubric rule against +every touched file in well under a second per call, but it returns probabilities, not claims. The pilot +measures whether such a screen, verified by a subagent, finds things the axes miss — precision, unique +contribution, recall gaps, added latency — over about ten reviews, so the developer can decide keep or kill +from evidence rather than a demo. + +## Functional requirements + +1. A CLI tool under `tools/` screens a change and emits suspects as JSON. It resolves the base ref, the + touched files (untracked included) and the task spec from `--scope branch|uncommitted`, or takes them + explicitly via `--base <ref>` and `--spec <path>`; explicit inputs are never re-derived. It runs standalone + (`pnpm review:screen`) for rubric calibration, and the pilot dataset can be replayed from it. +2. **Standards grid.** For each rubric rule and each touched file matching the rule's glob, the tool scores + the probability of a breach with a yes/no (`noul`) judgment. The scored state is the file's changed hunks + plus surrounding context, each line prefixed with a line id. A cell over its threshold gets a second, + `choice` call over the changed line ids to locate the offending line. Hunks exceeding the model's state + limit are split into windows and the file takes the maximum score. +3. **Spec grid.** When a task spec exists, each Functional Requirement is scored per touched file for the + probability that the diff addresses it; the requirement's score is its maximum across files. A + requirement whose score falls below the spec threshold is a suspect. With no spec the grid is skipped and + the output says so. +4. **The rubric** is a hand-written file of 8–10 conventions that linters cannot catch. Each rule has an id, + the rule file it cites, a file glob, a question, and counterexamples expressed as the model's structured + criteria (`not_for` / `examples`). The rules are drafted from `.agents/rules/*.md`, `smells.md` and the + `CONTEXT.md` files and approved by the developer before implementation. +5. **Thresholds** live in the tool's config: one default for the standards grid with optional per-rule + overrides, a separate threshold for the spec grid, and a cap on the number of suspects passed on. Values + are calibrated during implementation against a few past diffs with known findings. +6. Each suspect carries a rule or requirement id, the file, the line (or `—` for a spec suspect) and the + score. The tool sets no severity and writes no claim or fix text. +7. **The key is the tool's concern only.** It reads `TYPESAFE_API_KEY` from the shell environment. With no + key, or on any API failure, it exits 0 with `status: skipped|failed` and a reason; no agent instruction + names the variable. +8. **Sidecar.** Every run of the screen writes one JSON file to `.ai/jev/` in the repository's **main + checkout** (resolved through the git common dir, so worktrees share one dataset), named by date, branch, + scope and ticket. It records every cell score (not only over-threshold ones), the suspects, the model + version, per-call timings and token usage. A later `--origins` invocation, given the review's final + findings table, records each suspect's fate (confirmed / dropped with reason / merged with an axis finding) + and each finding's origin (`axis`, `jev`, `both`) into the same file. +9. **Workflow integration.** In a `first` round, `review-changes` dispatches a fourth `general-purpose` + subagent — the `jev` axis — alongside the three blind axes, with the same inputs they get. Its brief in + `axes.md` is the only place the tool is mentioned. It runs the screen, then for each suspect opens the + location, reads the cited rule or requirement, and either writes a finding in the standard shape or drops + the suspect with a one-line reason. It returns every suspect exactly once — confirmed or dropped — plus the + sidecar path. It never looks beyond its suspects. +10. A confirmed Jev finding is labelled by the grid that produced it — `standards` or `spec`. Findings carry + no provenance marker; `resolve-review` and the `follow-up` round are unchanged. +11. Normalization (step 4) de-duplicates across all four sources as today; the orchestrator additionally + notes which sources raised each surviving finding. After publishing, it spawns a fresh subagent with the + `jev` brief, the sidecar path and the final table (id, axis, location, sources) to run `--origins`. +12. When the `jev` axis returns `skipped` or `failed`, or with zero suspects, the review proceeds on three + axes and the terminal report states the reason. A tool failure never fails a review. +13. The terminal report gains one line for the `jev` axis: suspects sent, confirmed, dropped, and the + origin split of the published findings. +14. `pnpm review:screen --report` reads every sidecar in `.ai/jev/` and prints one table: confirmed vs + dropped per rule, the `jev`-only / `axis`-only / `both` counts, and added seconds per review. Nothing is + computed during a review. +15. The integration works for `pr` and `md` outputs and for both `branch` and `uncommitted` scopes. +16. **Keep-or-kill** is the developer's judgment, informed by the `--report` table and their own reading of + the `jev`-only findings at Gate 1 / on the PR. No numeric gate is fixed. + +## Data & API + +- TypeSafe Jev: `POST https://api.typesafe.ai/v1/systemone`, bearer auth with `TYPESAFE_API_KEY`, via the + typed `@typesafe-ai/sdk` npm package (dev dependency, Node 20+, MIT). Primitives used: `noul` (breach + probability), `choice` (line location). Model pinned to `jev-1.13.0`; the response's `model` is recorded in + the sidecar. Limits that shape FR2: 64k tokens per request, 32k for state plus the longest question. +- No `NEXT_PUBLIC_*` env var, no runtime code, no API resource. + +## UI inventory + +None. This task ships no user-facing surface. + +## Implementation decisions + +- **Tool name `review-screen`**, script `pnpm review:screen`. The name describes the job, not the vendor; + `jev` remains the provenance value, the axis name and the sidecar folder. +- Follows the `tools/<name>/` layout of the complexity and mutation gates (`index.ts`, `config.ts`, `run.sh`, + `CONTEXT.md`), with flag parsing from `tools/cli`. +- **The SDK over raw `fetch`**: it ships its own typings and retries 429/529 with backoff. +- **Hunks, not whole files** (FR2): a review covers the diff, and whole-file scoring would flag breaches that + predate the change. +- **Spec grid is per file, ranked by max**, never one call over the whole diff — the state limit. +- **The tool lives inside the fourth subagent**, not the orchestrator: the orchestrator learns only "spawn + a `jev` axis" and "hand the final table to a `jev` subagent". Removing the pilot is deleting the tool, the + `jev` brief, and those two lines. +- **A fresh subagent for `--origins`** rather than resuming the finished `jev` one. It needs only the + sidecar path and the table, so nothing is lost, and it behaves identically on every agent host (Cursor's + parent-initiated resume is unverified; Claude Code's would need a `SendMessage` grant on `code-reviewer`). +- **Sidecar in the main checkout's gitignored `.ai/`** (already ignored) because task folders are pruned at + land, non-task branch reviews have no task folder, and a worktree's own files vanish with the worktree. +- **All cell scores are logged**, not just suspects, so thresholds can be re-tuned offline and recall gaps + measured without re-running. +- **`--origins` in the tool, not in the agent**: the tool matches finding locations to its confirmed suspects + mechanically; the subagent only forwards the table. +- **Cost is not a decision input**: at $0.042 per million input tokens a 10-rule × 20-file grid costs cents. +- **Prerequisite**: #3724 (per-finding word cap replacing the per-axis 400-word cap) lands before the first + pilot review, since it changes the axis baseline the pilot compares against. The `jev` axis has no total + word cap either — a suspect silently cut for length would skew the counts. + +## Out of scope + +- **Test-gap and general correctness screening.** The complexity and mutation gates cover test gaps; the + model gives no explanation to act on for correctness. +- **Running the screen on `follow-up` rounds** (regressions from fixes). Revisit after the pilot. +- **Accepted-on-resolve tracking** — writing findings' final verdicts back to the sidecar. The developer + judges `jev`-only findings directly. +- **Numeric keep-or-kill thresholds.** Ten reviews are too few for them to mean much. +- **A CI integration** posting comments on PRs. Deferred until precision is known: fork PRs have no + repository secrets, and unverified output on public PRs is noise. +- **Any change to `resolve-review`**, or to the existing axes' briefs beyond #3724. +- **Any provenance marker on findings** — in the PR, in `review.md`, or in their ids. diff --git a/.agents/tasks/3722-mobile-lists-to-tables/spec.md b/.agents/tasks/3722-mobile-lists-to-tables/spec.md new file mode 100644 index 00000000000..b3f10e21df8 --- /dev/null +++ b/.agents/tasks/3722-mobile-lists-to-tables/spec.md @@ -0,0 +1,125 @@ +# Replace the remaining mobile list views with table views and remove the list components + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3722 | +| Feature branch | `issue-3722` | +| PM | Ulyana | +| Designer | Tatyana | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +Almost every paginated view in the app ships two layouts: a table for `lg` and up, and a +purpose-built list of stacked label/value rows below it. The address page moved to table-on-mobile in +#3502 behind an A/B experiment (`txns_view_exp`, with a user-facing view toggle and a preference +cookie), and the list implementation was deliberately left in place as a rollback path. The +experiment has since gone stale — the toggle was never wired to a call site, `showTableView` is +hardcoded on the migrated views, and no user complaints followed. The decision to keep table view on +mobile is final. + +That leaves the codebase carrying two renderings of the same data on ~68 surfaces. Both branches are +mounted in the DOM on every page (the split is CSS `hideFrom` / `hideBelow`, not a conditional +render), so each one costs render work and markup on both viewports, and every new column has to be +added twice — which is how defects like #3702 (a tooltip present in the table view and missing from +the list view) appear. + +The goal is one rendering per view: mobile shows the same table as desktop, scrolled horizontally, +and every list container, list item and mobile-list primitive is deleted. + +## Functional requirements + +1. On mobile viewports, every migrated view renders the same table as desktop — same columns, same + order, no column dropped or hidden — inside a horizontally scrollable container. +2. Sorting on mobile is performed through the action-bar sort dropdown, not the table header. The + dropdown is present on every sortable view, including the transaction views where the experiment + suppressed it and the sortable views that never had one (bridged tokens, name domain history, + transaction internals). +3. Action bars, pagination, filters, CSV export links and socket "new items" notices keep their + current mobile behaviour and placement; only the rows below them change. +4. No list layout remains: no `*List` container, no `*ListItem` component, and neither of the shared + `ListItemMobile` / `ListItemMobileGrid` primitives, nor the mobile variant of the socket + new-items notice. +5. No experiment code remains: the view-toggle hook and button, the `showTableView` prop threading, + the `table_view_on_mobile` cookie and its `NAMES` entry, the `txns_view_exp` GrowthBook flag + declaration and its test mock, the `Txn view switch` Mixpanel event, and the `list_view` sprite + icon. +6. Existing Playwright coverage keeps its meaning: tests and cases that exercised a list-only + component are removed, and so is the mobile coverage of every migrated view — a `+@mobile` tag or + a mobile-only case whose job was the list layout is dropped together with its screenshots. A table + on a mobile viewport gets no screenshot of its own; the desktop one already covers it. + +## Data & API + +None. No endpoint, `service:name` resource, response type, env var or feature flag is added or +changed. The `txns_view_exp` GrowthBook flag declaration is removed from the client; PMs confirmed +the experiment and its analytics event are stale and safe to drop, so no data needs preserving and +no dashboard coordination is required. + +## UI inventory + +Affected surfaces, all of which already have a desktop table counterpart — the migration is the same +transform on each, no new table is designed: + +- **Core slices** — transactions index and its tabs, blocks index, tokens index, token transfers + (index, token page, transaction page), internal transactions (index, transaction and block tabs), + verified contracts, addresses index, search results, token holders, transaction state. +- **Rollup features** — Optimism (batches, deposits, withdrawals, output roots, dispute games), + Arbitrum (batches, messages, transaction withdrawals), Scroll (batches, deposits, withdrawals), + ZkSync batches, Shibarium deposits and withdrawals. +- **Chain variants** — beacon chain deposits and withdrawals (index and block tabs), Celo epochs, + TAC operations, ZetaChain CCTXs, the Zilliqa / Stability / Blackfort validator pages. +- **Multichain and cross-chain** — multichain accounts, contracts, internal transactions, token + transfers, user ops, ecosystems, address portfolio; cross-chain bridged tokens, ICTT users, and the + transaction-level cross-chain transfer tabs. +- **Remaining features** — name services (domains index, domain history, clusters leaderboard and + directory), hot contracts, DEX pools, flashblocks, user ops, blobs, FHE operations, transaction + authorizations, asset flows, tag search, interop messages, dapp approvals. +- **Account pages** — watchlist, API keys, private address and transaction tags, custom ABI, + verified addresses. +- **Home page** — the latest cross-chain transactions widget, the one surface whose desktop side is a + narrow headerless table inside a card. Converted in its own commit and reviewed by the designer on + a preview deployment; see `questions.md` Q01. + +No new screens, no new states, no mockups: the treatment is the one #3502 established. + +## Implementation decisions + +- **The per-view transform is fixed**: delete the mobile list branch, unwrap the desktop-only + wrapper box, wrap the table in `TableContainerScrollable`, and give the table root a `minW` chosen + from its content so the columns do not compress. Deviating from it needs a reason recorded on the + ticket. +- **Deletion happens with the migration, not after it.** Each ticket deletes the list containers and + list items it orphans, so no ticket leaves dead code behind for a later sweep. +- **The shared primitives die last.** `ListItemMobile`, `ListItemMobileGrid` and the socket notice's + mobile variant are removed in a final teardown ticket, once no consumer remains. +- **The experiment teardown goes first.** It is pure deletion, it blocks nothing, and it restores the + mobile sort dropdown that the experiment suppressed — so the sorting requirement is satisfied from + the first ticket rather than at the end. +- **Sorting stays a dropdown on mobile.** A sortable table header sits off-screen behind horizontal + scroll, so the header is not a usable mobile affordance. The shared `Sort` control is already + viewport-adaptive (icon button on mobile, labelled select on desktop) and is reused as is. +- **The home widget is isolated and reversible.** It is one commit of its own so that a "no" from the + designer is a single revert. Whichever way that decision goes, the list item it uses has its + container inlined so that the shared primitives are deleted regardless. +- **Verification is per ticket.** Each ticket carries a human acceptance criterion: open its routes at + 375px against the matching dev-server preset (`eth` for the core slices, `optimism` / `arbitrum` / + `scroll_sepolia` for rollups, `celo` / `zetachain` / `tac` for chain variants, `multichain` for the + multichain pages) and confirm the table scrolls, the action bar and pagination survive, and nothing + clips. +- **Screenshots travel with their code.** Each ticket deletes the mobile screenshots it orphans and + runs its remaining Playwright files through the Docker runner so they match CI; a desktop baseline + that does change is regenerated there and committed alongside the change. The branch is never + intentionally red between commits. +- **One PR, one commit per ticket**, so any single area can be reverted on its own. + +## Out of scope + +- Designing new tables or changing any existing table's columns, order or content. +- Card-based surfaces that have no table counterpart — the home page's latest blocks and + transactions widgets, and the marketplace dapp cards. +- Making table headers usable for sorting on mobile (sticky or pinned columns). +- Any change to desktop rendering. +- Backend or API changes. diff --git a/.agents/tasks/3747-release-workflow/spec.md b/.agents/tasks/3747-release-workflow/spec.md new file mode 100644 index 00000000000..c8d4841eedc --- /dev/null +++ b/.agents/tasks/3747-release-workflow/spec.md @@ -0,0 +1,156 @@ +# Redesign the release workflow around labeled PRs and traceable backports + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3747 | +| Feature branch | `issue-3747` | +| PM | — | +| Designer | — | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +The CI workflows and release tooling in this repo are owned by the frontend team (tom); DevOps owns only the +demo-deploy and cleanup workflows and is not a contact for this task. + +## Context & goal + +Patch releases are built from hand-made cherry-picks on a `release/vX.Y.Z` branch, so the previous tag is +never an ancestor of `main`. Release notes are generated from a SHA range, so every backported PR reappears +in the next minor's notes and is removed by hand (8 PRs in the last minor). Nothing links a backport to its +source PR, PRs are never labeled with the version that shipped them, the PR template is not enforced, and +category labels are optional — so notes generation and backporting rely on reading and tribal knowledge. + +The target is a workflow where "what shipped where" is a label query, every release-branch commit names its +source commit and PR, and each phase (prepare, alpha, publish) is one command with a reviewable +artifact, for a minor and a hotfix alike. The first release cut on the new scheme is v2.13.0; the v2.12 +line already on staging finishes on the current process. + +Verified during grilling against the v2.11 patch line: of the four PRs that were hand-backported there, +three cherry-pick from their `main` squash commit with zero conflicts and the fourth (#3708) yields two +modify/delete conflicts because a refactoring on `main` touched files the release branch lacks — resolved by +dropping those files. Conflicts are resolved once: the release branch is never merged back to `main`. + +## Functional requirements + +1. `main` is trunk. Every release `vX.Y.Z` has its own branch `release/vX.Y.Z`, cut by the prepare command: + from `main` for a minor (`Z = 0`), from the line's previous final tag `vX.Y.(Z-1)` for a patch. Every tag + of the release, alpha and final, is on that branch. Nothing is committed only to a release branch except + the docs commits from prepare and alpha, which return to `main` by `git cherry-pick -x` at publish. +2. Every non-docs commit on a release branch is a `git cherry-pick -x` of a `main` squash commit: its + message carries `(cherry picked from commit …)` and the original `(#N)`. +3. The final-release workflow labels every PR shipped by the tag with the `vX.Y.Z` label, in addition to the + linked issues it labels today. The pre-release workflow applies `pre-release` to PRs the same way and the + final-release workflow removes it from PRs as it does from issues today. +4. Commit → PR resolution: the `cherry picked from commit <sha>` trailer first, then `(#N)` in the subject, + then GitHub's commit → PR association. A PR that already carries any `v*` label is never relabeled and + never listed again. +5. Release notes for `vX.Y.0` = PRs merged to `main` since the fork point of the previous minor + (`merge-base(main, previous minor tag)`) that carry no version label. Notes for `vX.Y.Z` = the PRs picked + onto the branch since the previous tag. Both use the same section generator; empty sections are omitted. + The generated list for a minor needs no manual removal of previously released PRs. +6. `backport` on a merged PR means "ship in the release being prepared". Prepare and alpha pick every such + PR not yet on the release branch, in `main` order, before generating the notes. A PR is on the branch + when its `main` commit is an ancestor of the branch head or a branch commit's trailer names it. Picking + stops on a conflict and is idempotent, so re-running the command resumes it; the commands print the PRs + they skipped. `backport` is replaced by the version label when the PR is released; a PR that was not + picked keeps `backport`. +7. A `pull_request` check fails when the body lacks a heading of `docs/PULL_REQUEST_TEMPLATE.md`, still + contains the template's placeholder text, carries no category label, carries labels of more than one + category (release-notes section), or combines `dependencies` with any other category. Several labels of + one category pass. PRs labeled `release` are exempt. +8. `chore` is the catch-all category ("Other changes"). The section ↔ label mapping has one source of truth + in the release tool; `docs/RELEASING.md` reproduces it and a unit test fails when the two drift. +9. One GitHub pre-release per release, minor or patch: created as a draft by prepare (its only creator), + re-pointed to each new alpha tag with its notes regenerated by the alpha command, turned into the final + release by publish. Alpha fails when the release has no pre-release; a line never has two open + pre-releases. +10. Prepare and alpha replace every `upcoming` on the release branch, including what a picked PR brings, + with `vX.Y.Z+` in a docs commit. A tag whose ENV docs still contain `upcoming`, or whose notes list a + PR already carrying a version label, fails both in the CLI before pushing and in CI (`pre-release.yml` + and `release.yml`) before the image is built. +11. `docs/RELEASING.md` holds the decision table ("I need to… → run …") and one state diagram; the skills + reference it rather than restating it. `create-pr` reads `docs/PULL_REQUEST_TEMPLATE.md` instead of + carrying a copy. +12. The staging roll-up Slack request keeps today's content: breaking ENV changes derived from the PR + bodies' "Environment variables" sections. +13. Project-card updates ("Released" status) keep working from the labeled issues as today. + +## Data & API + +None. No endpoint, env var, feature flag, or analytics event. GitHub API via `GITHUB_TOKEN` in CI and the +operator's `gh` auth locally. + +## UI inventory + +None. Developer tooling, CI workflows, docs, and agent skills only. + +## Implementation decisions + +### One module backs CI and the skills + +- `tools/release/` is a TypeScript module in the repo's `tools/<name>/` shape (co-located `*.spec.ts`, + `run.sh`, under `pnpm lint:tsc`, the complexity gate and Vitest). It exposes one CLI with subcommands: + `prepare`, `alpha`, `publish`, `label`, `notes`, `check-pr`, `check-tag`. Picking is a step inside + `prepare` and `alpha`, not a subcommand. +- Pure logic is separated from GitHub/git I/O and unit-tested: trailer and `(#N)` parsing, label-set + computation, exclusion of already-versioned PRs, notes query construction, section mapping, PR-body + validation, the `dependencies`-stands-alone rule, drift check between the mapping and `RELEASING.md`. +- Workflow steps shrink to checkout + install + one CLI call. The inline `actions/github-script` logic in + `label-issues-in-release.yml`, `release.yml` and `pre-release.yml` moves into the module; the + `fetch-release-prs.js` script in the `prepare-release` skill is removed. +- Labeling stays workflow-driven (release events), not CLI-driven, so the guarantee is independent of who + ran the command; the CLI waits for the run and reports. + +### Phases + +A minor and a hotfix run the same three phases; they differ only in where prepare cuts the branch. + +- `prepare vX.Y.Z`: cut `release/vX.Y.Z` (from `main` for `Z = 0`; for a patch, from `vX.Y.(Z-1)`, which + must be the line's latest final tag); pick; release `upcoming` in `docs/ENVS.md` and + `docs/DEPRECATED_ENVS.md` as `vX.Y.Z+` in a docs commit; generate notes from the labeled set; create the + draft pre-release. No changelog file is committed — the draft release is the reviewed artifact. +- `alpha vX.Y.Z-alpha.N`: on the branch inferred from the version, pick and release `upcoming` again, then + re-point the pre-release to the tag with regenerated notes, tag, push (fires `pre-release.yml`, one image + per tag), then the existing staging-request flow. +- `publish vX.Y.Z`: tag the approved alpha commit again as `vX.Y.Z`, publish as the final release marked + latest (fires `release.yml`), cherry-pick the release's docs commits to `main` with `-x`. +- Picking (inside prepare and alpha): query merged PRs with `backport` and no version label, cherry-pick + `-x` in `main` order the ones not on the branch, stop on conflict, run checks before pushing. +- Fixes found while a release is on staging take the hotfix path into it: PR to `main`, `backport` label, + the next `alpha` picks it. + +### Operator model + +- The skills run in a session with the developer present. Prepare and alpha work on the operator's + checkout of the release branch. On a pick conflict the agent may resolve it but never runs `--continue` + or pushes until the developer has approved the resolved diff; after `--continue` the same command is + re-run. + +### Labels + +- Reuse `chore` as the catch-all; create `backport` and `release`. Allowed category set = every label in the + mapping table (`feature`, `enhancement`, `client feature`, `bug`, `performance`, `dependencies`, `design`, + `refactoring`, `tech`, `devops`, `chore`). `dependencies` is only for PRs whose sole purpose is bumping a + package version. +- The `pre-release` and version label jobs must not derive the PR set from a bare SHA range: with the + release branch, the previous release can sit on another branch, so the range would include already + shipped PRs. The exclusion in requirement 4 is what keeps them correct. + +### Docs and skills + +- `docs/RELEASING.md` is linked from `docs/CONTRIBUTING.md`; `RELEASE_NOTES.md` moves into `tools/release/` + as the generator's template. +- `prepare-release` is replaced by one `release` skill around the CLI that covers a minor and a hotfix. + +### Delivery + +- One PR for the whole task, in the usual medium/big-task shape. + +## Out of scope + +- Computing staging ENV deltas against the live instance config. +- A per-PR backport GitHub Action. +- Renaming or rewriting history of existing release branches; the v2.12 line. +- Preparing two releases at once: a `backport` PR goes to whichever release picks it first. +- Changing the project-management, deploy, cleanup, or e2e workflows beyond the label calls above. diff --git a/.agents/tasks/3754-posthog-analytics/spec.md b/.agents/tasks/3754-posthog-analytics/spec.md new file mode 100644 index 00000000000..65916f076f4 --- /dev/null +++ b/.agents/tasks/3754-posthog-analytics/spec.md @@ -0,0 +1,105 @@ +# Integrate PostHog for product analytics + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3754 | +| Feature branch | `issue-3754` | +| PM | Ulyana | +| Designer | — | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +Product analytics today goes to Mixpanel only, and the Mixpanel module *is* the app's analytics API: +every call site imports it directly, and page views, identity, person profiles, and logout reset are all +Mixpanel-specific. An instance operator who wants PostHog instead of (or alongside) Mixpanel has no +option. The goal is PostHog as a second, optional, env-configured provider that receives exactly the +same data Mixpanel receives — page views, custom events, button clicks, identity and person +properties — so dashboards in either tool answer the same questions. + +## Functional requirements + +1. PostHog is enabled by a `NEXT_PUBLIC_POSTHOG_API_KEY` env var; a companion + `NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES` (JSON subset of the SDK config) can only be set when the key + is. Both are documented, validated, mocked and listed in `.env.example` like their Mixpanel + counterparts. +2. PostHog is subject to the same gating as Mixpanel: off in private mode, and off when Usercentrics + is configured and the user has not consented to the "PostHog" service. +3. Every event the app sends to Mixpanel — same event name, same property keys and values — is also + sent to PostHog when it is enabled, including the GrowthBook "Experiment started" event. Enabling + either provider alone, both, or neither works. +4. Page views reach PostHog as the SDK's native `$pageview` event, carrying the same properties the + Mixpanel "Page view" event carries (page type, tab, page, source, color mode, color theme), fired on + every route change by the app, not by the SDK's own pageview autocapture. +5. Identity and profile parity: the same uuid cookie is the distinct id; the same super-properties are + registered on every event; the same person properties are set / set-once; logout resets the + PostHog identity as it resets Mixpanel's. +6. SDK defaults when enabled: EU ingestion host, autocapture off, SDK pageview and pageleave capture + off, session recording off, feature flags disabled, `localStorage` persistence. All overridable via + the config-overrides env. +7. Events fired before the SDK chunk has loaded are buffered and replayed to every enabled provider + with their original timestamp; a provider whose SDK fails to load is silently disabled for the page + load without affecting the other. +8. The Content Security Policy allows PostHog hosts (script, connect, img) only when PostHog is + enabled and not in private mode. +9. The analytics debug switch is `_analytics_debug` (query param and cookie) and turns on SDK debug + logging for every enabled provider. The former `_mixpanel_debug` is removed, not aliased. +10. No analytics call site imports a vendor module; all go through a provider-neutral analytics + facade. Event names, payload types and the page-type dictionary keep their current shape. + +## Data & API + +No backend API involved. Environment variables (next release, `v2.12.0+`): + +- `NEXT_PUBLIC_POSTHOG_API_KEY` — PostHog project API key; presence enables the provider. +- `NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES` — JSON subset of the `posthog-js` config merged over the + app defaults (FR6); requires the key. + +Third-party references: `posthog-js` config and API docs +(https://posthog.com/docs/libraries/js/config, https://posthog.com/docs/libraries/js/features), CSP +guidance (https://posthog.com/docs/advanced/content-security-policy). + +## UI inventory + +No user-facing UI. Affected surfaces are invisible: the app-level analytics init in the page wrapper, +CSP headers, and the Usercentrics consent service list. + +## Implementation decisions + +- **Provider-neutral facade under `src/shared/analytics/`** owns the public API every call site uses: + `logEvent`, `EventTypes` + payload types, `userProfile` (`set`, `setOnce`), `reset`, `useInit`, + `useLogPageView`, `getPageType`. It is cross-cutting with no vendor owner, hence `shared`. + `userProfile.increment` is dropped: no caller uses it and PostHog has no equivalent. +- **Providers are thin vendor wrappers under `src/services/`** — the existing Mixpanel module reduced + to one, a new PostHog module as the other — each implementing one common provider interface: + `init(options)` plus synchronous `track`, `identify`/`register`, `peopleSet`, `peopleSetOnce`, + `reset`. Each has its own `config.ts` (consent + private-mode gated, exposed via + `config.services.<provider>`), CSP policy, and Usercentrics service entry. +- **One buffer queue in the facade**, moved out of the Mixpanel module: one idle-deferred init loads + every enabled provider's SDK chunk, runs its setup (super-props, identify, profile writes), then + replays the buffer into each. Replay backdates events: Mixpanel via the `time` property, PostHog via + the capture `timestamp` option. A provider whose init throws is disabled individually (FR7). +- **Page views** — the facade's `useLogPageView` emits one logical event; the PostHog provider maps the + "Page view" name to `$pageview` and passes the properties through unchanged. All other events keep + their name verbatim. +- **Call-site migration** is mechanical: every `import * as mixpanel from 'src/services/mixpanel'` + becomes the facade import, usages renamed accordingly; done with `ast-grep` in one pass. Tests + mocking the Mixpanel module move to mocking the facade or the provider as appropriate. +- **Debug flag** — the Mixpanel-specific query param and cookie are renamed to `_analytics_debug` in + place (dev-only switch, no backward compatibility). +- **GrowthBook** keeps calling the facade, so experiment events fan out to both providers for free. +- **CSP** — a `posthog` policy adding `*.posthog.com` to `script-src`, `connect-src` and `img-src` + (PostHog's own guidance: wildcard, since lazy-loaded bundles come from a separate assets subdomain). +- **Consent** — new `posthog` entry named "PostHog" in the Usercentrics services list; the CMP-side + ruleset must list the same service name (Q01). + +## Out of scope + +- PostHog session recording, surveys, feature flags, toolbar, or using PostHog as a GrowthBook + replacement — all explicitly disabled by default. +- Removing or deprecating Mixpanel. +- A single "analytics provider" switch env; providers are enabled independently by their own keys. +- Rolling the key out to deployed instances (operator / DevOps task after release). +- Google Analytics is untouched: it is a script tag with no event API and stays outside the facade. diff --git a/.agents/tasks/3756-design-readout/spec.md b/.agents/tasks/3756-design-readout/spec.md new file mode 100644 index 00000000000..630dd638753 --- /dev/null +++ b/.agents/tasks/3756-design-readout/spec.md @@ -0,0 +1,181 @@ +# Design readout: map a Figma node to repo components, props and tokens (phase 1) + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3756 | +| Feature branch | `issue-3756` | +| PM | — (frontend tooling task; owner: tom) | +| Designer | — | +| Backend | — | +| Minimum API version | — | +| Slack channel | — | + +## Context & goal + +"Final markup and styling to match the designer's Figma mockups" is on the humans-only list in +`.agents/delegation.md`. The blocker is not the agent's eye but the input: the Figma files are dirty by +policy — detached components, unnamed layers, style names that disagree with the actual colors — and the +designer's workflow will not change. So the *semantic* channel from Figma (component, variant and style +names) is unreliable, while the *value* channel (text content, fills, fonts, icon instance names, geometry) +is intact. A hand calibration over five nodes confirmed this: every value-based recognition hit, and three +of five style names were misleading. + +The task does recognition on our side. A `design-readout` tool and skill turn a Figma node into a readout +that names the repo component, its props and the design tokens per node, and lists every ambiguous, +unrecognized and layout item explicitly for a developer to resolve *before* any markup work starts. Phase 1 +built the readout as the developer's input for a hand-made markup leaf. Q02 then loosened the boundary: +the readout is a *supporting* input, the agent does the markup leaf from it — or from the mockup alone +when no readout was made — and the developer verifies in the running app and has every correction +recorded. Phase 2 — automated verification of the rendered page against the readout — is a later issue; +the gap log is read by hand. + +## Functional requirements + +1. **Tool** — a CLI under `tools/design-readout/` (`pnpm design:readout`) that, given a Figma node URL, + reads the node tree through the Figma REST API nodes endpoint. It takes its personal access token from + the environment; the variable is the tool's concern only and no agent instruction names it. A missing or + rejected token fails the run with a clear message; the tool never falls back to another source. +2. **Scoping outline.** The tool's first output for a node is an outline for the developer to confirm: + the content root and the chrome it dropped on the way down. One link is one screen in one state: a + state or a mobile variant of the screen is a separate node the developer links separately, so the + tool never looks for siblings or variants, and hidden layers (visibility off) are not part of the + screen and are ignored. Chrome is recognized structurally (library instances with no exposed children + spanning the *screen's* width or height — the linked node's, not the parent's, so an empty-state + instance filling its column is content), by a name list the tool ships (menu, navigation, top bar, + search header, footer; matched across case and separators), or by holding nothing but chrome (a + sidebar frame wrapping the menu and its collapse bar). The content root is reached by descending + through single-visible-child wrappers, dropping chrome at each level, until a node with two or more + non-chrome children; inside the content root, chrome is still dropped wherever the name list matches + (a search header beside the page title), while the structural rule stops at the root. +3. **Readout.** For each confirmed region the tool extracts, per leaf node, the *values*: text content, + fill hex plus opacity per role (text, background, border, icon), font family / weight / size / line + height, icon instance name, trailing glyphs, bounding box. The Figma style and component names are + carried as *hints* only, flagged where they disagree with the values. +4. **Deterministic recognition** lives in the tool, unit-tested, in this priority order: text-shape rules + (address, transaction and method hashes, block / batch / epoch numbers, timestamps, tickers, NFT ids) + with lookalike-character normalization (Cyrillic `х` in `0х05…` was seen in a mockup); a truncated hash + with no icon is always ambiguous. Then icon recognition by normalized instance name against the + generated sprite name list. Then hex plus role to semantic token via a reverse map. Then composite rules + over recognized siblings (entity + arrow + entity, amount + ticker). +5. **Reverse color map** is built in-process from the theme's default colors and semantic tokens, keyed + by color mode; nothing is generated into the repo. Runtime theme overrides from app config are ignored. A hex that serves several tokens returns all of them and + the role filters; the color mode is detected from the values themselves, with the frame background as + tiebreaker, and recorded per run. +6. **Skill** — `.agents/skills/design-readout/` is the thin driver: it runs the tool, applies the + judgment parts the tool cannot (context override from the ticket and API resource type toward + interchain / L1 / external entity variants; badge and tag fingerprints; layout questions such as a + value shown in its own column vs under another cell), and produces the readout. It runs in a + subagent and returns only the Ambiguous, Unrecognized, Layout and By convention lists (the last + one the layout questions `layout-conventions.md` already answers, applied) with a count of + Recognized nodes. +7. **Readout rules.** Never invent a component — an unmatched node is Unrecognized with its resolved + values, not a guess. Trust the hex over the Figma style name and record the disagreement. When the + shipped code and the mockup conflict (a batch icon in Figma vs `noIcon` in the shipped row), report the + conflict; do not pick. +8. **Sidecar.** Every run writes one JSON to `.ai/design-readout/` in the main checkout (resolved through + the git common dir): file key, node id, file `lastModified` and `version`, the detected color mode, and + per node its values, decision (component, props, tokens, the signal that fired), status (recognized / + ambiguous / unrecognized), the human correction and the style override once given, and bounding box. Figma hints are not + stored. +9. **Re-run.** Running the tool again for a node it has a sidecar for diffs against it and reports only + changed leaves; settled corrections carry over. No workflow step re-runs on its own; the developer + re-runs when the mockup moved. +10. **Calibration.** `tools/design-readout/calibration/` holds committed value snapshots (the tool's own + extraction, not raw Figma payloads) for a labeled set, each paired with the expected component and + props per cell. `pnpm design:readout --calibrate` runs recognition over the snapshots offline and + prints hits and misses per signal; `--refresh` re-fetches a snapshot from Figma, and a vanished node + marks its entry stale rather than failing the run. The set is seeded with ten shipped components, + six of them table rows, each with its Figma node (Q01). +11. **Gap log.** `.ai/design-readout/gaps.md`, one line per miss with a stage (readout / markup) and a + category from shape / icon / color / composite / context / layout / convention / markup. The skill + appends a line whenever the developer corrects an Ambiguous or Unrecognized item in session (category + proposed, developer confirms). Misses found at the markup leaf are the developer's own edits: on + request the agent reads the developer's diff against the hand-off tree and records each one — + node-mapped through `--correct` / `--override`, the rest through `--note <text> --gap markup`. The + phase 2 decision is a hand count over this file. +12. **Workflow integration.** + - `grill-the-task` enumerates the Figma links, one node per screen and state; it runs no readout. + A new route's nav icon is `add-new-page`'s own Step 0 input, not an interview item. + - The readout is an optional step the developer runs between `to-spec` and `to-tickets`, per link or + with no URL for every spec link without a block yet: scoping outline confirmed in the main session, + readout in a subagent, Ambiguous items resolved by the developer first; the skill writes + `design-readout.md` into the task folder (Recognized table, Ambiguous, Unrecognized, Layout + questions, By convention) and a `questions.md` entry per design-intent question the developer sends on. + `structure.md` carries the file's row; it is pruned at land like the ticket files. + - `to-tickets` cuts the style leaf `[agent]` with a mandatory `(human)` "matches the mockup" + criterion and links the readout block beside the Figma node when one exists. A style leaf covers + every breakpoint. + - `implement-ticket` runs the markup leaf in session from the readout, or from the mockup through + the Figma MCP when there is none — it never runs the tool, which is the developer's step; at hand-off it stages the work and prints its tree hash; on the developer's + request it records their corrections from the diff. No `TODO (design):` markers: an item still + with the designer is a `Blocked by Q<NN>` edge and nothing else. + - `delegation.md`: design readouts, markup and styling to the mockup, and sprite icons the readout + recognized are agent work; visual polish, Playwright baselines and design sign-off stay human. + - A small task that gets no spec gets no readout; the agent styles from the mockup. + +## Data & API + +- Figma REST API `GET /v1/files/:key/nodes?ids=…`, header `X-Figma-Token`, scopes `file_content:read` + + `current_user:read`. Personal access tokens expire after at most 90 days; the tool's `--help` says so. + Verified in session on a dark-mode node: the payload carries per-node `fills` with color and opacity, + text style, `visible: false` on hidden nodes (the MCP design context omits those), bounding boxes, + resolved style names, and file `lastModified` / `version`. +- No `NEXT_PUBLIC_*` env var, no runtime code, no API resource. + +## UI inventory + +None. This task ships no user-facing surface. + +## Implementation decisions + +- **REST, not the Figma MCP, for the tool.** The MCP is session-only and its metadata for one page frame + exceeds 400k characters, so it cannot be read in context anyway; REST returns the value channel as JSON, + works for calibration refresh in any session, and is testable against saved responses. The MCP stays + available to the skill for a screenshot only. +- **Tool + skill split by determinism**: what is a pure function of the node tree (scoping, text shapes, + color map, icon names, composites, calibration diff) is TypeScript with specs; what needs the ticket, + the API type or taste is skill text. +- **Follows the `tools/<name>/` layout** of `tools/review-screen/` (`index.ts`, `config.ts`, `run.sh`, + `CONTEXT.md`, flag parsing from `tools/cli`), and its sidecar convention: main checkout, git-ignored + `.ai/`, one JSON per run. +- **Icon matching by name, not by SVG bytes.** Figma's exporter re-serializes paths and the sprite + pipeline runs SVGO and rewrites fills to `currentColor`, so byte or path equality is hopeless. Instance + names stayed linked in every calibrated node even when the parent was detached. Geometry matching, if + ever, is phase 2. +- **Hex first, hints as labels.** The dark-mode probe returned `rgba(255,255,255,0.8)` with a style hint + naming `text.primary` at `#FFFFFF`; the value resolves to `whiteAlpha.800` → `text.primary` (dark), the + hint's hex would have mis-tokenized to `white`. The same file mixes light and dark hints. +- **Readout after the spec, before tickets** (Q02; at first it ran inside grilling). The spec carries the + context the readout's judgment needs — entity family, API resource type — and ambiguities still become + `questions.md` entries before tickets are cut, which is the whole point of the question gate in + `implement-ticket`. Running it in its own session keeps the grill short. +- **Supporting, not required** (Q02). The agent styles with or without a readout and the developer always + verifies; the readout's worth is the question gate and the logged corrections, not a precondition. +- **Corrections come from the developer's diff, not from dictation** (Q02): fixing by hand is faster than + describing the fix; the agent's job is to read the diff and log it. The boundary is the tree hash the + agent prints at hand-off, so staging on either side cannot blur it, and nothing unverified is committed. +- **The readout is a pruned task artifact, not spec content.** A per-node component table in the spec's UI + inventory would be the value-copying that `concepts.md` forbids. +- **Sidecar shape is the minimum the phase 2 decision and calibration need**: status, correction and gap + category answer "are the gaps small?"; values and the fired signal give per-signal precision and re-run + diffs; bounding boxes are free from REST. Figma hints are dropped — the calibration already proved them + misleading. +- **Source of the shape**: the five-step template of the pstack `create-verification-skill` + (interview the repo → generate → seed a feature map → prove by running once → maintain) — adopted as a + shape, not verbatim; the calibration set is the feature map, `--calibrate` is the proof. +- **Vocabulary**: "readout" and "design readout" go into `.agents/GLOSSARY.md`. + +## Out of scope + +- **Phase 2**: automated verification of a rendered component against the readout (pixel or structure + diff) and a `verify-design` review axis. A side-by-side of a Playwright shot and the Figma screenshot + in the hand-off is the first candidate. +- **Agent-run Playwright baselines**: the developer runs the one command after verifying. +- **Dropping `TODO (api-data):` markers**: they are `add-new-page`'s own phase marker, not a hand-over. +- **Icon geometry matching** against sprite sources. +- **Any change to the designer's Figma workflow or file hygiene.** +- **Automated routing of Ambiguous items to the designer** — they go through the normal grill-time + question flow. +- **A token setup flow in the skill**: the skill says the tool needs a token and stops; obtaining one is + the developer's two-minute job. +- **Numeric phase 2 gates.** The gap log is read by hand. diff --git a/.agents/tasks/3778-cross-chain-filters/spec.md b/.agents/tasks/3778-cross-chain-filters/spec.md new file mode 100644 index 00000000000..519a7ddb489 --- /dev/null +++ b/.agents/tasks/3778-cross-chain-filters/spec.md @@ -0,0 +1,139 @@ +# Cross-chain views: column filters by chain and protocol + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3778 | +| Feature branch | `issue-3778` | +| PM | Nikita S. | +| Designer | Tatyana | +| Backend | Evgenii | +| Minimum API version | `interchain-indexer` v1.11.0 (already deployed on the shared mainnet instance) | +| Slack channel | #dev-interchain | + +## Context & goal + +The cross-chain transactions and cross-chain token-transfers tables show every message the deployment's +bridges carry, with no way to narrow them. The indexer already accepts directional chain filters and a +bridge filter on every list endpoint; the frontend sends none of them from user input. Goal: let a user +narrow both tables by source chain, destination chain and protocol (bridge) from the column headers, the +same way the advanced-filters table does, and tidy the token-transfers table layout the designer asked for +at the same time. + +## Functional requirements + +1. The cross-chain transactions table and the cross-chain token-transfers table each expose three column + filters: **Source tx** (source chain), **Dest tx** (destination chain), **Protocol** (bridge). No + other column has a filter. +2. Chain filters are a checkbox group (one checkbox per chain, logo + name) with no "All" entry — an + empty selection means no filter. A search field (by chain name or chain ID) appears only when there + are 10 or more chains. The selection maps to the comma-separated `src_chain_ids` / `dst_chain_ids` + params. Chain options come from the indexer's chain directory, so + the filters work on a single-chain explorer with no multichain configuration. +3. The protocol filter is a checkbox group ("All" + one checkbox per bridge) over the bridges the + deployment is configured for; it is always rendered, even with a single bridge. The selection maps to + `bridge_ids`. +4. A user protocol selection replaces the env-derived `bridge_ids` scope filter for that request; with no + selection the env scope applies as before. A user can never widen the deployment's scope: the option + list is the intersection of the indexer's enabled bridges and the env list. +5. Filter state lives in the URL under the API param names, is restored on reload / deep link, and resets + pagination to page 1 on change. +6. The filters appear on every surface that renders these tables against a list endpoint accepting the + params: transactions and token-transfers index pages (single-chain and multichain), the cross-chain tabs + on address pages (single-chain and multichain), and the cross-chain tabs on transaction details. The + home-page latest list stays filter-less. +7. With an active filter and no rows, the list shows the active-filters empty state instead of the plain + empty text. +8. Whenever any filter is active, a non-sticky row above the table lists the active filters as closable + tags (one tag per filter, multiple values joined; closing a tag clears that filter) followed by a + "Reset all" control that clears every filter. The row is the reset affordance when the table header + is out of view (empty state, or scrolled past). +9. The advanced-filter page's existing tags row is restyled to the same mockup: the "Filtered by:" title + is dropped, the reset control sits right after the tags and reads "Reset all", and the tag close icon is + 14px inside the unchanged 20px click area. Its non-closable "Chain" tag and the default "Type / Age" + placeholder tags stay. +10. Token-transfers table: the Message and Timestamp columns are merged into one column (message id on the + first line, time below); the Source token and Target token cells get more width. The transactions table + gets the same Message + Timestamp merge. +11. The filters, the tags row and the empty state look and behave the same at every breakpoint; there is + no separate mobile mockup. On mobile the tags row sits above the pagination action bar. +12. No regression in search (`q`), scope filters, pagination or the Protocol column on any affected + surface, and none on the advanced-filter page beyond the restyled row. + +## Data & API + +**Endpoints** — `/interchain/messages`, `/interchain/transfers` and their `:byAddress` / `:byTx` variants +all accept `src_chain_ids`, `dst_chain_ids`, `bridge_ids` (comma-separated, AND-combined; a destination +filter excludes rows with an unknown destination). Verified on the shared mainnet instance. Swagger: +`interchain-indexer/interchain-indexer-proto/swagger/v1/interchain-indexer.swagger.yaml` in +`blockscout-rs`. + +**Resources** — existing: `interchainIndexer:messages`, `transfers`, `address_messages`, +`address_transfers`, `tx_messages`, `tx_transfers` gain the three params as `filterFields`; +`interchainIndexer:chains` supplies chain options. **New**: `interchainIndexer:bridges` → +`GET /api/v1/interchain/bridges` (`id`, `name`, `type`, `enabled`, `indexed_chain_ids`), no params, +typed by `GetBridgesResponse` from `@blockscout/interchain-indexer-types` (present in the installed +`1.11.0`). This reverses the "not registered" decision of task 3650: a deployment now spans two bridges +(mainnet `1` and `3`) and the filter needs bridge names. + +**Scope-filter precedence** — `bridge_ids` is both an env scope filter and now a user filter. The user +value wins when present; the resolver falls back to the env list otherwise. + +**No new env vars.** No analytics events. + +**What the API does not offer** (and this task does not build): status, date range, amount, address +direction, token or message-id filters. Only `q` multisearch exists beyond the params above. + +## UI inventory + +Mockup (token-transfers table + filter popovers): +https://www.figma.com/design/GHtMTzWKQGAcVyGdrKuQjD/Blockscout-Multichain-explorer?node-id=9120-121109 + +- Table: node `9120-115382`. +- Source tx chain popover: node `9120-120563`; Destination tx popover: node `9120-120521`; Protocol + popover: node `9120-120033`. +- The Source tx popover (`9120-120563`) is the reference for both chain popovers: a checkbox list + with chain logos and a search field. The Destination tx node still shows the earlier select-based + layout and is superseded. Deviations agreed with the designer, not yet in Figma: the Protocol + popover is a checkbox group, not an input. +- The remaining popovers in the section (Status/Address, Source token, Message/time) are out of scope. +- The transactions table has no mockup; it mirrors the token-transfers filters on the same column names. +- Empty state with active filters + the active-filter tags row: + https://www.figma.com/design/GHtMTzWKQGAcVyGdrKuQjD/Blockscout-Multichain-explorer?node-id=9136-48611 + (tags row node `9138-91679`). The empty-state illustration and copy are the existing generic + active-filters empty state. The tags in the mockup are illustrative; the real ones are Source chain, + Destination chain, Protocol. +- The same tags-row mockup is the target for the advanced-filter page's row (currently "Filtered by:" + title + right-aligned "Reset filters"). + +Placement and behaviour: filter trigger icon in the column header, popover with title + Reset link + +Filter button — match `FilterByColumn` / `TableColumnFilterWrapper` / `TableColumnFilter` from the +advanced-filters feature. Chain popover body is a `CheckboxGroup` with an optional `FilterInput` +above it, matching `MethodFilter`; protocol popover body matches `TypeFilter`. + +## Implementation decisions + +- **Filters are column filters, not a filter bar.** Same wrapper and popover components as advanced + filters; no new shared primitives. +- **URL-backed state through `filterFields`**, so the paginated-query hook reads them and the cursor is + invalidated with the filter combination; the per-surface pages don't manage filter state themselves. +- **Chain options** are fetched with the existing chains resource inside the popover component, relying + on React Query caching with `refetchOnMount: false` — no hoisting to the table. +- **Bridge options** are fetched with the new bridges resource the same way and intersected client-side + with the feature config's bridge ids and `enabled`. +- **The filter components live in the cross-chain-txs feature** and are shared by both tables; the table + header takes an "is filterable" switch so the home-page latest list renders no triggers. +- **The active-filter tags row is one shared filters component** (tags + "Reset all"), consumed by the + advanced-filter page and by both cross-chain tables; the advanced-filter page's inline row is replaced by + it. It renders only when at least one filter is active and is not sticky. +- **Close-icon sizing is scoped to the tag's `filter` variant**: the close trigger keeps its 20px box + and gains 4px padding so the icon renders at 14px; other tag variants are untouched. +- **Column changes**: merged Message/Timestamp cell follows the Source tx / chain-label two-line pattern; + token cells get a larger `maxW` (set to 200px, to be verified visually by the developer). + +## Out of scope + +- Any other change to the advanced-filter page beyond its tags row. +- Filters on token columns, a tx-hash input, status / date / amount / address / message filters — none + exist in the API. +- A mockup for the transactions table; mirrored from the token-transfers one. +- Any change to the home-page latest cross-chain list. diff --git a/.agents/tasks/3822-review-loop/spec.md b/.agents/tasks/3822-review-loop/spec.md new file mode 100644 index 00000000000..731aa86f335 --- /dev/null +++ b/.agents/tasks/3822-review-loop/spec.md @@ -0,0 +1,147 @@ +# Automate the post-finalize review loop, CI fixes and demo deploys for task PRs + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3822 | +| Feature branch | `issue-3822` | +| PM | tom (frontend tooling task) | +| Demo | none | + +<!-- Header is static identity — no status row: task status is derived from `progress.md` (see +`.agents/tasks/structure.md`). Rows with nothing to say are dropped (a decision this task makes, see +Implementation decisions); `Demo` is always present because it drives an action. --> + +## Context & goal + +Landing a product task ends today at "PR ready for review". Everything after that is driven by hand: the +developer opens a Cursor session in a second terminal and runs `review-changes` so a different model +provider reviews the agent's work, then runs `resolve-review` with its two confirmation gates, pushes, +reruns the review, watches CI, fixes what CI flags, and finally runs `deploy-demo` once or twice. The pieces +exist; the loop between them is the developer. + +This task closes the loop. After `finalize-task` flips the PR to ready, the session runs a review loop: +a headless Cursor agent reviews the PR, an autonomous resolver fixes or rejects the findings, CI failures +from the previous run are fixed in the same push, and the cycle repeats until the review is cleared and +CI is green. The one thing the loop never does is guess at a decision the code and the spec cannot settle: +a `needs-human` finding pauses the loop, the developer answers in the terminal, and the answers fold into +the same round. Once cleared and green, demos deploy from presets the spec recorded at grilling time. + +The developer then opens the PR to a reviewed, green, deployed change, with the review history and the +unresolved human questions on the PR threads. + +## Functional requirements + +1. **Loop entry.** `finalize-task` runs, in order: prune → `create-pr` Mode B (flip to ready, which starts + CI) → the review loop → the demo deploys → a final report. The review loop is its own skill, + `review-loop`, runnable by hand on any PR; `create-pr` Mode C never offers it. +2. **Reviewer.** Each round runs the repo's `review-changes` skill in `pr` mode under the tag `cursor` + through the Cursor CLI headlessly, with `first` on round 1 and `follow-up` afterwards. The review itself + is unchanged: inline PR comments, the summary with the `Blocked`/`Cleared` status, the arbitration + round that closes threads. +3. **Outcome.** The loop reads the round's outcome from the PR (the latest summary carrying the reviewer's + footer), never from the CLI's text. +4. **Resolver.** Each round dispatches `resolve-review pr --auto` in a fresh subagent. Auto mode keeps the + adjudication procedure and changes the gating: no confirmation before fixing, no diff approval before + pushing; the only stop is a `needs-human` finding. +5. **Nits in auto mode** are fixed when the fix is at most 5 lines in one file with no new test and no new + file, and always when the nit concerns comments, docs or tests; otherwise `deferred`. A deferred nit + stays an open thread for the developer. +6. **Rejections in auto mode** follow the existing rule (no repeat rejection on the same grounds), tightened: + a second dispute from the reviewer turns the finding `needs-human`; there is never a third rejection. +7. **Pause on `needs-human`.** Any `needs-human` finding, whether raised by the reviewer or by the + resolver, stops the round before any edit: the resolver returns its full verdict table and the questions, + the orchestrator presents them in the terminal, fires a push notification (PR link, number of questions) + and waits. The developer's answers go back to the same resolver, which folds them into its fix set and + proceeds. The loop never ends with an unanswered `needs-human` finding. +8. **CI per round.** After the resolver has fixed, the loop waits for the CI run that is in progress on the + branch. A red run is fixed by the same resolver in a separate commit. Review fixes and CI fixes go out in + one push per round. Playwright failures are fixable: the resolver reproduces in Docker, views the diff + image, and updates the baseline only when the diff is explained by a spec requirement it cites in the + commit; any other visual diff is `needs-human`. Other gate failures (mutation, complexity, React Doctor) + are fixable with the same escape: a fix that changes behaviour or restructures beyond the finding is + `needs-human`. +9. **Terminal condition.** The loop ends when the review outcome is `cleared` and the CI run for the + current HEAD is green. `cleared` with CI pending waits; `cleared` with CI red fixes and pushes without + another review round. Bounds: 3 review rounds, 2 post-clear CI-fix cycles. Hitting a bound, a reviewer + failure after one retry, or a timeout stops the loop with the PR in a consistent pushed state and a + report saying why. +10. **Reviewer invocation.** `agent -p --trust --approve-mcps --output-format json "<skill invocation>"` + run in the background with a 30-minute limit, Cursor's default model unless the loop is given a model + override. Transport failures (non-zero exit, no output) get one retry; a review that ran gets none. +11. **Provider seam.** Everything Cursor-specific (binary, flags, timeout, failure detection, the tag) lives + in one reviewer file under the skill; the skill body speaks only of "the reviewer" and takes + `--reviewer <name>` defaulting to `cursor`. The reviewer's tag is its name. +12. **Demo presets at grilling.** `grill-the-task` asks which preset(s) the demo runs on, offering the + workflow's `envs_preset` list with a recommendation inferred from the task (chain-type features → + that chain's preset; multichain → `multichain`; generic UI → `staging`). Up to two entries; a third is + refused with the reason (two deployment slots). `to-spec` writes the answer as the header row + `| Demo | <preset> [(review-2)] · <preset> [(review-2)] |` or `| Demo | none |`. Small tasks hold the + answer in session and `create-pr` Mode C offers the deploy. +13. **Demo deploys.** After the loop ends `cleared` with green CI, and only then, `finalize-task` deploys + the header's entries sequentially: the first with an image build, the second reusing it + (`build_image=false`). The first entry takes the `review` slot, the second `review-2`; an explicit + `(review-2)` mark on a single entry selects that slot. `none` deploys nothing. A loop that stopped + short deploys nothing. +14. **`deploy-demo` inputs.** The skill accepts explicit preset, variant and build-flag inputs for + non-interactive use, alongside its current prose inference. +15. **Final report.** `finalize-task` ends with a push notification and a terminal report: PR link, review + outcome and rounds, CI status, demo URLs, and anything left open. No demo comment on the PR; GitHub's + deployment entry already links it. +16. **Spec header rule.** Header rows with nothing to say are dropped rather than filled with `—`; `Demo` + is always present. `create-pr` keeps treating an absent `Minimum API version` row as "None". +17. **Delegation.** `delegation.md` gains, under what agents may do: resolve agent-review findings and push + the fixes within the loop's rules; update a Playwright baseline when the diff is explained by a cited + spec requirement. The rest of the baseline rule stays humans-only. +18. **Docs.** `tasks/README.md` step 6 describes the extended land step. Every edited skill keeps its + frontmatter and doc links valid (`pnpm lint:doc-links`). + +## Data & API + +No application code, endpoints or env vars. External surfaces the skills drive: + +- Cursor CLI (`agent`, headless print mode with JSON output). Skills under `.agents/skills/` are loaded + natively; `-p "/<skill> <args>"` attaches a skill; trust and MCP approval are per absolute path, which is + why `--trust --approve-mcps` are mandatory in a fresh worktree. +- GitHub: PR reviews and threads (`gh api`), the Checks workflow runs (`gh run list/watch`), the + deploy-review workflow (`gh workflow run`). The Checks workflow has no cancel-in-progress, so each push + starts a run while earlier ones continue. +- Playwright reports: the CI HTML report, and local Docker runs for reproduction and baseline regeneration. + +## UI inventory + +None. This task edits agent instructions only. + +## Implementation decisions + +- **A standalone `review-loop` skill**, handed off to by `finalize-task`, not an inline step: it is + reusable on non-task PRs and keeps `finalize-task` a sequence of handoffs. +- **The session orchestrates; the resolver is a fresh subagent per round**, so it adjudicates against the + code rather than defending what it wrote. Within a round it is resumed (answers to `needs-human`, then + the CI fix) rather than replaced, so one agent holds both fix sets. The skill names resumption + harness-neutrally and points at the Claude Code mechanism. +- **`--auto` is a flag on `resolve-review`**, not a sibling skill: one adjudication procedure with two + gating policies, so the two cannot drift. +- **The reviewer runs in the background** from the orchestrator, polled to completion; it exceeds the + foreground command cap. The orchestrator makes no edits while the reviewer runs in the same tree. +- **Outcome re-derived from the PR**, not parsed from the CLI result: the PR is the record and the CLI text + can be truncated. +- **One push per round, separate commits** for review fixes and CI fixes, so the history shows which change + came from which source. No rewriting of ticket commits. +- **Wait for CI before pushing** rather than pipelining pushes against running CI: fewer concurrent runs, + one push carries everything, and small tasks' CI is often faster than the review anyway. +- **No re-review after `cleared`** for CI fixes: a follow-up round over a trivial CI fix would be arbitration + with nothing to arbitrate. +- **Demos wait for cleared and green**, because a demo of unreviewed code is the thing the loop exists to + avoid. +- **Sequential demo deploys with one image build**: the image is preset- and variant-agnostic. +- **Header rows dropped when empty, `Demo` always explicit**, because `none` is a decision and absence would + be indistinguishable from "never asked". + +## Out of scope + +- A second reviewer in parallel (Claude's `code-reviewer` alongside Cursor); the seam allows it later. +- Changes to the review axes, the finding shape, or the arbitration rules of `review-changes`. +- Offering the review loop from `create-pr` Mode C; non-task PRs run it by hand in a new session. +- Pinning a reviewer model in the repo. +- Any change to the Checks or deploy-review workflows. +- Cursor hooks or Cursor-side automation; the loop is driven from Claude Code. diff --git a/.agents/tasks/3830-router-facade/spec.md b/.agents/tasks/3830-router-facade/spec.md new file mode 100644 index 00000000000..c077132bb09 --- /dev/null +++ b/.agents/tasks/3830-router-facade/spec.md @@ -0,0 +1,132 @@ +# Introduce a framework-neutral router facade and make the toolkit router-agnostic + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/3830 | +| Feature branch | `issue-3830` | +| PM | tom (frontend tech task) | +| Demo | staging | + +<!-- Header is static identity — no status row: task status is derived from `progress.md` (see +`.agents/tasks/structure.md`). Rows with nothing to say are dropped; `Demo` is always present because it +drives an action. --> + +## Context & goal + +Application code reaches for Next.js routing primitives directly in hundreds of files: `useRouter` from +`next/router`, `route()` / `Route` from `nextjs-routes`, `usePathname` / `useRouter` from `next/navigation`, +and `next/link` inside the published `@blockscout/ui-toolkit` package. Any future change of router or +framework therefore touches ~400 files, and the toolkit cannot be installed without Next.js. + +The task puts a framework-neutral facade between the app and the router so the framework dependency lives in +a handful of modules. It is worthwhile on its own: it shrinks a future router change to ~50 files, frees the +toolkit from a hard `next` dependency, and makes the test infrastructure independent of the framework's +router. Rationale and the wider analysis: `docs/research/tanstack-start-migration.md` (Phase 1). + +No user-visible behaviour changes. + +## Functional requirements + +1. No file outside the facade modules, their framework adapter, and the test infrastructure imports + `next/router`, `next/navigation`, `next/link` or `nextjs-routes`; ESLint enforces it. +2. The app has one router hook (`useRouter` in `src/shared/router/`) exposing exactly the members the app + uses — `query`, `pathname`, `asPath`, `push`, `replace` — and one `usePathname` hook with the semantics + of today's `next/navigation` pathname (changes on every real path change, including same-route + navigations). All existing router helpers (`useQueryParams`, `updateQueryParam`, `removeQueryParam`, + `useEtherscanRedirects`, …) consume them. +3. `push` / `replace` take `(url, options?)` where options cover `shallow` and `scroll`; Next's `as` + argument is gone from the app. +4. `route()` and the `Route`, `Query`, `DynamicRoute` types have one import surface, the existing wrapper + module in `src/shared/router/`. The generated route map stays the source of truth for typed paths. +5. `@blockscout/ui-toolkit` builds and type-checks with no `next` import and no `next` peer dependency. + `Link`, `LinkOverlay`, `RoutedTabs` and `useActiveTabFromQuery` obtain navigation from a toolkit-owned + router context; without a provider, `Link` renders a plain anchor and the router is a no-op. +6. The toolkit `Link` keeps its `scroll`, `shallow`, `prefetch` props; they are forwarded to the injected + link component through a documented adapter interface. +7. The app supplies the Next.js adapter (link component + router) to the toolkit context at the shell + level; the facade hooks read the same context, so `next/router` / `next/link` / `next/navigation` are + imported in exactly one adapter module. +8. Tests inject the router through the toolkit provider, not module mocks: the Vitest and Playwright test + apps wrap in the provider; Playwright's `hooksConfig.router` API is unchanged for the 63 tests that use it + (retyped to the facade's router type); the global Vitest `next/router` mock, the Vitest router utils and + the 13 specs that mock `next/router` directly move to the provider. +9. Facade specs cover query parsing, `push` / `replace` delegation (including the options mapping) and the + link adapter. +10. The marketplace auto-connect flag no longer listens to router events: the page that sets it resets it + on unmount. +11. The unused `eslint-config-next` dev dependency is removed; `@next/eslint-plugin-next` stays. +12. Agent instruction set and rule docs reference the facade instead of `next/router` / `nextjs-routes`: + `architecture.md`, `code-quality.md` (Links), `tests-visual.md` (router mocking), the `add-new-page` + skill and its templates. +13. Navigation, query-param filters, shallow routing, pagination and tab switching behave exactly as + before; Playwright visual baselines are unchanged. +14. Type-check, lint, unit tests, component tests, toolkit typecheck + build and the code-complexity gate + pass. + +## Data & API + +None. No endpoints, env vars or feature flags are touched. + +## UI inventory + +No new or changed UI. Every page that navigates or reads the URL is affected mechanically; the demo deploy on +`staging` exists for a manual regression click-through by the developer. + +## Implementation decisions + +- **Toolkit owns the router contract.** A new toolkit module (`src/toolkit/router/`) holds the context, the + provider, the router / link adapter types, and the defaults (plain `<a>`, no-op router). Exported from the + package index. Toolkit components (`Link`, `LinkOverlay`, `RoutedTabs`, `useActiveTabFromQuery`) read it. +- **Single injection point.** The app facade `useRouter` in `src/shared/router/` reads the toolkit context + rather than `next/router`. One adapter module in `src/shared/router/` builds the Next.js implementation + (link component over `next/link`; router over `next/router` + `next/navigation` for the pathname) and is + mounted in the app shell. This is the one place to swap when the framework changes. +- **Hook naming.** `useRouter`, not `useAppRouter`: in the Pages Router world "app router" reads as the + other Next.js routing model. The lint ban on `next/router` removes the ambiguity. +- **Router interface.** `{ query, pathname, asPath, push, replace }`; `query` typed as today's string / + string-array / undefined record; the unused `useRouter<P>()` route generic is dropped. `events` is not on + the interface (see marketplace below). `push(url, options?)` / `replace(url, options?)` with + `{ shallow?, scroll? }`; the codemod removes the `undefined` `as` argument at the 13 call sites that pass + it. +- **`usePathname`** is a facade hook implemented over `next/navigation` today; `useLogPageView` and + `useNotifyOnNavigation` consume it. +- **AdbutlerBanner** drops its `next/navigation` router effect dependency: the object is stable, so the + dependency is a no-op today, and wiring pathname in would re-place the ad on every navigation. +- **Marketplace auto-connect flag.** `MarketplaceContextProvider` stops subscribing to `routeChangeStart`; + `MarketplaceApp`, which already sets the flag from data, resets it in its unmount cleanup. Chosen over a + pathname effect in the provider because child effects run before parent effects and a cached dapp → dapp + navigation would otherwise set-then-reset in one commit. +- **`route()` entry.** The existing wrapper in `src/shared/router/routes.ts` (chain / external / absolute + params) becomes the only `route()`; the 100 raw `nextjs-routes` importers are codemodded to it. The + `Route`, `Query`, `DynamicRoute` types are re-exported from the same module. +- **Link adapter props.** `scroll`, `shallow`, `prefetch` are kept on the adapter interface (only `scroll` + is used in-app, 3 places). Zero behaviour change and no break for downstream projects. +- **Lint.** `no-restricted-imports` bans `next/router`, `next/navigation`, `next/link` and `nextjs-routes` + repo-wide, replacing the existing `next/link`-only ban. Exempt: the Next adapter module in + `src/shared/router/`, `src/toolkit/router/**`, `vitest/**`, `playwright/**`. `src/pages/_app.tsx` + imports the `Route` type today and moves to the facade like everyone else. +- **Tests.** Provider-based injection everywhere. Playwright: the `next/router` Vite alias and the module + mock go away; `hooksConfig.router` feeds the provider value in `TestApp`. Vitest: `vitest/setup.ts` stops + mocking `next/router`; `mockRouter` / `routerStandIn` become provider values; a small `wrapper` helper for + `renderHook` specs. The 13 specs mocking `next/router` migrate so they survive a framework change. +- **Codemod.** The bulk rewrite (~150 `useRouter` importers, ~130 `nextjs-routes` importers, 13 + `push`/`replace` signatures) is done with `ast-grep --rewrite`; `tsc` is the regression net. +- **Toolkit versioning.** The toolkit version follows the app version and is published at app release, so + no version bump and no CHANGELOG in this task. The breaking change (provider required for client-side + navigation, `next` peer dependency dropped) is recorded in the PR description; the only consumers are + the team's own projects. +- **Import style.** Direct module paths (`src/shared/router/useRouter`, `src/shared/router/routes`), no + barrel. +- **Docs.** `architecture.md` gains the facade as the routing entry point; the `nextjs-routes` mention in + `code-quality.md` and the router-mocking lines in `tests-visual.md` are rewritten; the `add-new-page` + templates import the facade. + +## Out of scope + +- Any framework or router migration (TanStack Start or otherwise); the facade is implemented over Next.js. +- Changing `src/pages/**`, `getServerSideProps`, redirects, or anything server-side. +- Removing `@next/eslint-plugin-next` or its rules. +- Toolkit version bump, CHANGELOG, or npm publish; notifying external consumers. +- Adding `isReady`, `prefetch`, `back` or other router members the app does not use. +- Re-placing the Adbutler banner on navigation, or any other behaviour change. +- The issue-text correction for the ESLint claim is an edit on the GitHub issue, not repo work. diff --git a/.agents/tasks/README.md b/.agents/tasks/README.md index 86b9e0cb629..8a0bc44bce1 100644 --- a/.agents/tasks/README.md +++ b/.agents/tasks/README.md @@ -28,14 +28,24 @@ Each step names the skill that runs it; the session model — what runs where, a 1. **Grill** — run `grill-the-task` with the issue URL. 2. **Spec** — `to-spec` writes `spec.md` and `questions.md`, then opens the draft PR. + - *Optional* — **Design readout** — the developer runs `design-readout` for the spec's Figma links; it + writes `design-readout.md` and the designer questions into `questions.md`. 3. **Break into tickets** — `to-tickets` runs with the spec and open questions as its input. It writes the ticket files and `progress.md`. 4. **Answers** — when colleagues reply, read the threads and fold each decision into `questions.md`. When an answer changes the work, realise it through `to-tickets` — a new sibling ticket, or an edit to the affected ticket if it isn't implemented yet, retargeting `Blocked by` edges. + - **Outer-loop context** — a decision made where no session was listening (the weekly, a thread, a + document) lands in the task's `inbox.md` as a pending section; `debrief-meeting` writes the weekly's. + `process-task-inbox` folds each pending section into questions, spec and tickets. The three + implementing skills below refuse to start while a section is pending. 5. **Implement** — run `implement-ticket <NN>` repeatedly, **one ticket per run**. -6. **Land** — `finalize-task` prunes `tickets/`, `progress.md`, and `questions.md` (only `spec.md` survives), - then hands off to `create-pr` to push, write the real description, and flip the draft to ready for review. +6. **Land** — [`finalize-task`](../skills/finalize-task/SKILL.md) runs five handoffs in order: + - it prunes the task folder down to `spec.md`; + - [`create-pr`](../skills/create-pr/SKILL.md) pushes, writes the real description and flips the draft to ready; + - [`review-loop`](../skills/review-loop/SKILL.md) reviews, resolves and fixes CI round by round until the review + is cleared and CI is green, pausing only on a `needs-human` finding; + - [`deploy-demo`](../skills/deploy-demo/SKILL.md) deploys the spec header's `Demo` entries. ## Supporting files diff --git a/.agents/tasks/concepts.md b/.agents/tasks/concepts.md index 852777d4c69..0554e1097cc 100644 --- a/.agents/tasks/concepts.md +++ b/.agents/tasks/concepts.md @@ -18,6 +18,10 @@ this file carries the meaning they act on. Layout and file ownership live in - **Questions** — every open question the task raised, each with a stable id (`Q01`), its owner, Slack permalink, status, and answer once it lands; `questions.md`. A ticket that a question gates names that id in its `Blocked by`. +- **Inbox** — decisions about the task made in the **outer loop**: the part of the work no session sees, + where the team meets, chats and writes docs. Each source is one section of `inbox.md`, `pending` until + `process-task-inbox` folds it into the questions, the spec and the tickets. A pending section blocks + `to-tickets`, `implement-ticket` and `finalize-task`: the task does not move on context it has not read. - **Brief** — the marker of a **deferred** ticket: a ticket folder with a `brief.md` and no `spec.md`, because the ticket can't be scoped until something happens first (a prototype, a spike, an answer nobody has yet). @@ -42,9 +46,11 @@ rather than a linear plan. Each leaf carries `[agent]` or `[human]` per the capability boundary in [`../delegation.md`](../delegation.md) — exactly one, written explicitly, because `implement-ticket` reads -the tag as its state machine. UI work is **two linked leaves** by default: an `[agent]` scaffold, then a -`[human]` style leaf that takes it to the mockup — layout, spacing, styling, icons — with the exact Figma -node linked on that leaf and the scaffold's `TODO (design):` markers as its worklist. +the tag as its state machine. + +UI work follows the rule: +- an optional leaf per project scaffold skill the ticket runs (`add-new-page`), before the style leaf +- a style leaf per linked Figma node that takes it to the mockup and links the exact node and, when the task has a `design-readout.md`, that node's block beside it. A leaf's checkbox is **progress state**: a ticket has no commit until it finishes, so the boxes are the only durable record of how far it has got inside the ticket. They mark which leaves are done, never what @@ -58,11 +64,10 @@ criterion marked `(human)` is one only a person looking at the running product c whole-task review contract is the spec's Functional Requirements (below), so acceptance criteria are not needed once the ticket lands. -The test for a `(human)` criterion: *does this change what a user sees or does?* +The test for a `(human)` criterion: *does this change what a user sees or does in a way that the agent cannot fully verify itself?* -- **Earns one** — component scaffolds (placeholder ones included), data wiring that renders, page - behaviour, perf-sensitive changes, anything touching CSP or security, and new dependencies. -- **Does not** — env vars, API resources and response types, route plumbing, metadata, sitemap, analytics, +- **Earns one** — final component styling to match the provided mockups, page behaviour, perf-sensitive changes, anything touching CSP or security, and new dependencies. +- **Does not** — component scaffolds, data wiring that renders, env vars, API resources and response types, route plumbing, metadata, sitemap, analytics, unit tests, glossary and docs, behaviour-preserving refactors. Getting it wrong costs in both directions: a needless `(human)` criterion stalls an unattended chain, and a @@ -94,7 +99,7 @@ Three rules keep the artifacts a *final statement of intent*, never a log of how `to-spec` runs **once** per task; there is no update or merge mode. The spec body — Functional Requirements, Data & API, UI inventory — is **immutable**. The mutable artifacts are `progress.md` checkboxes, -`questions.md`, and — each until it freezes — the ticket specs, their leaf checkboxes included. A rare +`questions.md`, `inbox.md`, and — each until it freezes — the ticket specs, their leaf checkboxes included. A rare genuine requirement change is a plain in-place edit: no superseding history, no changelog. The spec is always the *final* statement, never a record of iterations. @@ -117,11 +122,12 @@ as a whole. ### Disposability and pruning -At land, `finalize-task` prunes `tickets/`, `progress.md`, and `questions.md` — **only `spec.md` survives** -in the tree. The decomposition is preserved in git history (one commit per ticket), so nothing is lost: -precedent to browse is the accumulated specs; decomposition precedent is git history. Pruning runs -**before** the whole-task `review-changes` pass, which reads the spec and the diff via inline PR comments -and so needs no ticket files. +At land, `finalize-task` prunes `tickets/`, `progress.md`, `questions.md`, `inbox.md` and any review file — **only +`spec.md` survives** in the tree. The decomposition is preserved in git history (one commit per ticket), so +nothing is lost: precedent to browse is the accumulated specs; decomposition precedent is git history. +Pruning runs **before** the whole-task `review-changes` pass, which reads the spec and the diff and posts to +the PR, so it needs no ticket files. A mid-ticket review in `md` mode is disposable for the same reason: +its findings were resolved before the ticket was committed, and the diff is the record. ## What the spec holds, and what it doesn't diff --git a/.agents/tasks/structure.md b/.agents/tasks/structure.md index 70a2ef384cd..2b2780d228a 100644 --- a/.agents/tasks/structure.md +++ b/.agents/tasks/structure.md @@ -13,12 +13,16 @@ One folder per specced task, under `.agents/tasks/`: spec.md task spec — the durable statement of intent progress.md one checkbox per ticket questions.md open questions, each with a stable id (Q01) + inbox.md optional — decisions from outside any session, one section per source + design-readout.md optional — the design readout + review.md optional — an md-mode review of the whole branch tickets/ NN-<slug>/ spec.md the ticket (once scoped) brief.md OR this, for a deferred ticket (no spec.md) research.md optional — research / prototype notes notes.md optional — implementation findings, PR evidence + review.md optional — an md-mode review of this ticket's uncommitted work ``` **Naming is mechanical.** The task folder is `<issue>-<slug>/` — the bare GitHub issue number, then a @@ -30,12 +34,15 @@ lets a skill infer the task from the branch with no arguments. | File | Mutability | Holds | Written / mutated by | | --- | --- | --- | --- | -| `spec.md` | **immutable** once created | Context & goal, Functional Requirements (the whole-task review contract), Data & API, UI inventory, Out of scope. Header is static identity. | `to-spec` creates it. Edited in place only for a rare genuine requirement change. | -| `progress.md` | mutable | One checkbox per ticket: `- [ ] NN → tickets/NN-<slug>/`. No titles, edges, or content. | `to-tickets` creates it and appends a line per ticket; `implement-ticket` checks the box. | -| `questions.md` | mutable | Every open question, each with a stable id (`Q01`): owner, Slack permalink, status, answer. | `to-spec` creates it; answers folded in later by a plain edit. | -| `tickets/NN-<slug>/spec.md` | mutable until fully implemented, then **frozen** | What to build, Acceptance criteria (with `(human)` tags), Skill inputs (grouped by skill), Leaf worklist. Header: `Blocked by` (`T<NN>` ticket + `Q<NN>` question blockers). | `to-tickets` creates it; `implement-ticket` checks its leaf boxes as it works them. | -| `tickets/NN-<slug>/brief.md` | informal | Deferred-ticket marker. Goal, known context, the blocking unknowns and who owns each. | `to-tickets` when it can't scope the ticket; or dropped in by the developer. | +| `spec.md` | **immutable** once created | Context & goal, Functional Requirements (the whole-task review contract), Data & API, UI inventory, Out of scope. Header is static identity. | `to-spec` creates it. Edited in place only for a rare genuine requirement change, by hand or by `process-task-inbox`. | +| `progress.md` | mutable | One checkbox per ticket: `- [ ] NN → tickets/NN-<slug>/`. No titles, edges, or content. | `to-tickets` creates it and appends a line per ticket; `process-task-inbox` appends a line per brief; `implement-ticket` checks the box. | +| `questions.md` | mutable | Every open question, each with a stable id (`Q01`): owner, Slack permalink, status, answer. | `to-spec` creates it; answers folded in later by a plain edit, or by `process-task-inbox` from an inbox section, which also adds a question an inbox decision raises. | +| `inbox.md` | mutable | One section per outer-loop source (a meeting, a thread, a document): its link, a `pending` / `folded` status, and the decisions with deep links into the source. Shape: `.agents/skills/debrief-meeting/inbox-section-template.md`. | `debrief-meeting` appends a section, uncommitted; any future source skill does the same. `process-task-inbox` folds a section into the other files and flips it to `folded`. | +| `design-readout.md` | regenerated, never hand-edited | One block per Figma node the task carries: Recognized table, Ambiguous, Unrecognized, Layout questions, By convention — a view of the node's sidecar in the shape `.agents/skills/design-readout/readout-template.md` defines. | The `design-readout` skill writes it, and rewrites a node's block when the developer re-runs it. | +| `tickets/NN-<slug>/spec.md` | mutable until fully implemented, then **frozen** | What to build, Acceptance criteria (with `(human)` tags), Skill inputs (grouped by skill), Leaf worklist. Header: `Blocked by` (`T<NN>` ticket + `Q<NN>` question blockers). | `to-tickets` creates it; `process-task-inbox` edits it while unfrozen; `implement-ticket` checks its leaf boxes as it works them. | +| `tickets/NN-<slug>/brief.md` | informal | Deferred-ticket marker. Goal, known context, the blocking unknowns and who owns each. | `to-tickets` when it can't scope the ticket; `process-task-inbox` for new work an inbox decision brings; or dropped in by the developer. | | `tickets/NN-<slug>/{research,notes}.md` | optional | Research / prototype notes; implementation findings kept as PR evidence. | session / developer. | +| `review.md` (task or ticket level) | mutable | An `md`-mode review: one thread per finding — claim, fix, status, replies. `review-<tag>.md` where several reviewers ran at once. | `review-changes` in `md` mode writes it; `resolve-review` appends the replies. Pruned at land like the rest. | ## Status is derived, never stored diff --git a/.claude/agents/code-reviewer.md b/.claude/agents/code-reviewer.md index 8dc515be15e..b2403172b2b 100644 --- a/.claude/agents/code-reviewer.md +++ b/.claude/agents/code-reviewer.md @@ -1,6 +1,6 @@ --- name: code-reviewer -description: Reviews a change on three axes (spec, standards, correctness) by running the repo's review-changes skill, and returns the outcome. Invoked manually (e.g. to review a task at land, or ad hoc); not a general-purpose reviewer. +description: Reviews a change axis by axis by running the repo's review-changes skill, and returns the outcome. Invoked manually (e.g. to review a task at land, or ad hoc); not a general-purpose reviewer. model: inherit effort: high color: cyan @@ -10,11 +10,12 @@ tools: Read, Glob, Grep, Bash, Write, Edit, Agent Read `.agents/skills/review-changes/SKILL.md` and follow it. That file is the procedure; this definition only launches it. -You are the orchestrator described there: you spawn the axis agents, normalize what they return, and post -the findings as inline PR comments (or report them in chat when there is no PR). You never edit source code, -and you write no review record — the findings live on the PR. +You are the orchestrator described there: you spawn the axis agents, normalize what they return, and +publish the findings. Pass on the inputs you were dispatched with — the output (`pr` or `md`), and any +`--round`, `--scope`, `--as` or `--ticket`. A dispatch that names no output stops at the skill's input +check; ask for one rather than picking. You never edit source code. -Your final text is a **return value**, not a message to a person. Return exactly: the PR review URL (or, in -chat mode, that the findings were reported there), counts per severity, counts per axis, and the `Outcome`. -Whoever dispatched you gates on that `Outcome`: `clear` when no `blocker` or `major` finding is open, -otherwise the open counts. +Your final text is a **return value**, not a message to a person. Return exactly: where the review was +published (the PR review URL, or the review file's path), counts per severity, counts per axis, the `jev` +line, and the `Outcome`. Whoever dispatched you gates on that `Outcome`: `cleared` when no `blocker` or `major` finding +is open, otherwise the open counts. diff --git a/.claude/hooks/worktree-deps.sh b/.claude/hooks/worktree-deps.sh index cc9689b1b1d..b423fedced9 100755 --- a/.claude/hooks/worktree-deps.sh +++ b/.claude/hooks/worktree-deps.sh @@ -44,7 +44,7 @@ if [ "$mode" = "session-start" ]; then jq -n '{ hookSpecificOutput: { hookEventName: "SessionStart", - additionalContext: "This worktree has no node_modules. A PreToolUse hook runs `pnpm install --frozen-lockfile` automatically before the first Bash command that needs the local toolchain (pnpm/npx/eslint/tsc/vitest/playwright/next), so do not install by hand. Expect that one command to take an extra minute." + additionalContext: "This worktree has no node_modules. A PreToolUse hook runs `pnpm install --frozen-lockfile` automatically before the first Bash command that needs the local toolchain (pnpm/npx/eslint/tsc/vitest/playwright/next, or a `git commit`/`git push` that runs husky hooks), so do not install by hand. Expect that one command to take an extra minute." } }' exit 0 @@ -55,7 +55,10 @@ fi cmd="$(field '.tool_input.command // empty')" [ -n "$cmd" ] || exit 0 -needs='(^|[;&|(]|&&|\|\|)[[:space:]]*(pnpm|npx|next|eslint|tsc|vitest|playwright)[[:space:]]|node_modules/\.bin/' +# `git commit`/`git push` are here because the husky pre-commit and pre-push hooks shell +# into node_modules (lint-staged, eslint, tsc); without deps they fail and tempt a +# --no-verify bypass. `[^;&|]*` lets global flags like `git -C dir commit` still match. +needs='(^|[;&|(]|&&|\|\|)[[:space:]]*(pnpm|npx|next|eslint|tsc|vitest|playwright)[[:space:]]|node_modules/\.bin/|(^|[;&|(]|&&|\|\|)[[:space:]]*git[[:space:]][^;&|]*(commit|push)([[:space:]]|$)' # Dependency-management subcommands run fine without node_modules, and skipping them # keeps the hook from recursing into the install it is about to perform. selfmanaged='pnpm[[:space:]]+(install|i|add|remove|rm|up|update|dlx|store|why|licenses|approve-builds|rebuild)([[:space:]]|$)' diff --git a/.claude/settings.json b/.claude/settings.json index ce1c24730f0..2414e699161 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,11 +1,13 @@ { - "enabledPlugins": { - "figma@claude-plugins-official": false - }, "hooks": { "SessionStart": [ { "hooks": [ + { + "type": "command", + "command": "git -C \"$CLAUDE_PROJECT_DIR\" fetch --quiet origin 2>/dev/null || true", + "timeout": 30 + }, { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/worktree-deps.sh session-start", @@ -32,5 +34,6 @@ ] } ] - } + }, + "enabledPlugins": {} } diff --git a/.cursor/BUGBOT.md b/.cursor/BUGBOT.md deleted file mode 100644 index 2c684ec0fe8..00000000000 --- a/.cursor/BUGBOT.md +++ /dev/null @@ -1,39 +0,0 @@ -# Bugbot PR Review Rules - -In addition to the regular bug-finding process, check the following aspects in the code changes introduced by the Pull Request. - -## 1. Design System & Theming - -See `.agents/rules/design-system.md`. - -## 2. TypeScript - -See `.agents/rules/typescript.md`. - -## 3. Code Quality - -See `.agents/rules/code-quality.md`. - -## 4. Environment Variables - -See `.agents/rules/env-vars.md`. - -## 5. Testing - -- Unit tests: See `.agents/rules/tests-unit.md`. -- Visual component tests: See `.agents/rules/tests-visual.md`. - -## 6. Code smells - -See `.agents/skills/review-changes/smells.md` — thirteen smells, each a judgement call, each overridden by -anything the rules files above document. - -When the change touches the agent instruction surface instead of code — `.agents/`, `AGENTS.md`, any -`CONTEXT.md`, `.cursor/` — use `.agents/skills/review-changes/prose-smells.md` in its place. Those files are -code that runs on an agent, and none of the thirteen above apply to them. - -## 7. Not findings - -See the **Out of bounds** section of `.agents/skills/review-changes/SKILL.md`. Most importantly: styling and -visual judgements belong to a human, a `TODO (design):` marker is a scaffold working as designed, and a style -preference with no rule or precedent behind it is not a finding. diff --git a/.cursor/mcp.json b/.cursor/mcp.json index e5f807b0ce1..9667a1ac9f9 100644 --- a/.cursor/mcp.json +++ b/.cursor/mcp.json @@ -13,6 +13,15 @@ "-y", "next-devtools-mcp@latest" ] + }, + "playwright": { + "command": "npx", + "args": [ + "-y", + "@playwright/mcp@latest", + "--headless", + "--isolated" + ] } } -} \ No newline at end of file +} diff --git a/.cursor/rules/adr.mdc b/.cursor/rules/adr.mdc new file mode 120000 index 00000000000..2ea80472b00 --- /dev/null +++ b/.cursor/rules/adr.mdc @@ -0,0 +1 @@ +../../.agents/rules/adr.md \ No newline at end of file diff --git a/.cursor/rules/docs.mdc b/.cursor/rules/docs.mdc new file mode 120000 index 00000000000..dbddf32213f --- /dev/null +++ b/.cursor/rules/docs.mdc @@ -0,0 +1 @@ +../../.agents/rules/docs.md \ No newline at end of file diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index cc48cec34ce..3482f005eeb 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,6 +1,6 @@ { "name": "blockscout dev", - "image": "mcr.microsoft.com/devcontainers/typescript-node:20", + "image": "mcr.microsoft.com/devcontainers/typescript-node:24", "forwardPorts": [ 3000 ], "customizations": { "vscode": { diff --git a/.dockerignore b/.dockerignore index fd4ab7d0bc5..42549158fba 100644 --- a/.dockerignore +++ b/.dockerignore @@ -9,6 +9,6 @@ README.md .git *.tsbuildinfo .eslintcache -/test-results/ +/playwright-results/ /playwright-report/ /blob-report/ \ No newline at end of file diff --git a/.env.example b/.env.example index 427c9f69b48..de2797ca1f8 100644 --- a/.env.example +++ b/.env.example @@ -3,5 +3,6 @@ NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID=xxx NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY=xxx NEXT_PUBLIC_GOOGLE_ANALYTICS_PROPERTY_ID=UA-XXXXXX-X NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN=xxx +NEXT_PUBLIC_POSTHOG_API_KEY=xxx NEXT_PUBLIC_GROWTH_BOOK_CLIENT_KEY=xxx NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID=xxx \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 439bca677db..db97790d394 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -7,5 +7,5 @@ contact_links: url: https://github.com/orgs/blockscout/discussions about: Ask questions and discuss topics with other community members - name: Join our Discord Server - url: https://discord.gg/blockscout + url: https://discord.gg/3yAWj8TXV2 about: The official Blockscout Discord community \ No newline at end of file diff --git a/.github/workflows/check-tag.yml b/.github/workflows/check-tag.yml new file mode 100644 index 00000000000..dc3c60ff415 --- /dev/null +++ b/.github/workflows/check-tag.yml @@ -0,0 +1,39 @@ +name: Check release tag + +on: + workflow_call: + inputs: + tag: + description: 'Release tag' + required: true + type: string + +jobs: + run: + name: Run + runs-on: ubuntu-latest + steps: + # The ENV docs are read from the checkout, which on a tag push or a release event is the tag. + - name: Checkout repo + uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v6 + with: + version: 12.4.1 + cache: true + + - name: Setup node + uses: actions/setup-node@v4 + with: + node-version: 24.21.0 + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Check the ENV docs and the release notes + run: pnpm release check-tag "$TAG" + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ inputs.tag }} diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 3f5c22acd12..f901e3d27c3 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -10,10 +10,10 @@ on: - '.vscode/**' - '.agents/**' - '.cursor/**' - - 'deploy/**' + - 'deploy/values/**' + - 'deploy/scripts/**' - 'docs/**' - 'public/**' - - 'tools/**' # concurrency: # group: ${{ github.workflow }}__${{ github.job }}__${{ github.ref }} @@ -42,13 +42,13 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v6 with: - version: 11.5.1 + version: 12.4.1 cache: true - name: Setup node uses: actions/setup-node@v7 with: - node-version: 22.14.0 + node-version: 24.21.0 cache: 'pnpm' - name: Install dependencies @@ -73,6 +73,9 @@ jobs: - name: Check preset lists are in sync with registry run: pnpm presets:lint + - name: Build the envs-validator bundle + run: pnpm --filter envs-validator build + toolkit_build_check: name: Toolkit build check needs: [ code_quality ] @@ -84,13 +87,13 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v6 with: - version: 11.5.1 + version: 12.4.1 cache: true - name: Setup node uses: actions/setup-node@v7 with: - node-version: 22.14.0 + node-version: 24.21.0 cache: 'pnpm' - name: Install project dependencies @@ -121,6 +124,7 @@ jobs: exit 1 fi +<<<<<<< HEAD envs_validation: name: ENV variables validation runs-on: ubuntu-latest @@ -147,9 +151,11 @@ jobs: - name: Run validation tests run: pnpm --filter envs-validator test +======= +>>>>>>> v2.13.0 vitest_tests: name: Unit tests - needs: [ code_quality, envs_validation ] + needs: [ code_quality ] runs-on: ubuntu-latest steps: - name: Checkout repo @@ -160,98 +166,154 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v6 with: - version: 11.5.1 + version: 12.4.1 cache: true - name: Setup node uses: actions/setup-node@v7 with: - node-version: 22.14.0 + node-version: 24.21.0 cache: 'pnpm' - name: Install dependencies run: pnpm install --frozen-lockfile - name: Run Vitest - run: pnpm test:vitest ${{ github.event_name == 'pull_request' && '--changed=origin/main' || '' }} --passWithNoTests + run: pnpm test:vitest ${{ github.event_name == 'pull_request' && '--changed=origin/main --coverage --coverage.provider=v8 --coverage.reporter=json' || '' }} --passWithNoTests + + - name: Cognitive complexity & CRAP gate + if: ${{ github.event_name == 'pull_request' }} + run: pnpm test:code-complexity --changed=origin/main --coverage-file coverage/coverage-final.json - pw_affected_tests: - name: Resolve affected Playwright tests + - name: React Doctor gate + if: ${{ github.event_name == 'pull_request' }} + run: pnpm lint:react-doctor --scope changed --base origin/main --no-color + + mutation_tests: + name: Mutation testing gate + needs: [ vitest_tests ] runs-on: ubuntu-latest - needs: [ code_quality, envs_validation ] if: github.event_name == 'pull_request' + # Outside the run's own 15-min wall-clock budget (tools/mutation-testing/config.ts), leaving room + # for checkout and install so that expiring the budget still reaches the truncation report rather + # than being killed mid-write. A normal PR gets nowhere near either bound. + timeout-minutes: 20 steps: - name: Checkout repo uses: actions/checkout@v7 with: + # The diff is resolved through the merge-base with origin/main, which a shallow clone lacks. fetch-depth: 0 - name: Install pnpm uses: pnpm/action-setup@v6 with: - version: 11.5.1 + version: 12.4.1 cache: true - name: Setup node uses: actions/setup-node@v7 with: - node-version: 22.14.0 + node-version: 24.21.0 cache: 'pnpm' - name: Install dependencies run: pnpm install --frozen-lockfile - - name: Run script - run: pnpm test:pw:detect-affected + - name: Mutation testing gate + run: pnpm test:mutation-testing --changed=origin/main +<<<<<<< HEAD - name: Upload result file uses: actions/upload-artifact@v7 +======= + pw_changes: + name: Check for Playwright-relevant changes + runs-on: ubuntu-latest + needs: [ code_quality ] + if: github.event_name == 'pull_request' + outputs: + has_changes: ${{ steps.diff.outputs.has_changes }} + steps: + - name: Checkout repo + uses: actions/checkout@v4 +>>>>>>> v2.13.0 with: - name: playwright-affected-tests - path: ./playwright/affected-tests.txt - retention-days: 3 + # The diff is resolved through the merge-base with origin/main, which a shallow clone lacks. + fetch-depth: 0 + + - name: Diff watched paths against the merge-base + id: diff + # No dependency install here on purpose: the gate is one git command, so a PR that touches + # nothing Playwright cares about skips the whole matrix in seconds. + # The path list is paired with FORCE_FULL_PATHS in tools/playwright/config.ts (the tool's + # "run the whole suite" triggers); it is a superset of that list plus src/, where the tests + # and everything they import live. Keep the two in sync. + run: | + base=$(git merge-base origin/main HEAD) + changed=$(git diff --name-only "$base" -- src playwright playwright-ct.config.ts pnpm-lock.yaml) + if [ -n "$changed" ]; then + echo "Changed files under the watched paths:" + echo "$changed" + echo "has_changes=true" >> "$GITHUB_OUTPUT" + else + echo "No changes under the watched paths; the Playwright matrix will be skipped." + echo "has_changes=false" >> "$GITHUB_OUTPUT" + fi pw_tests: - name: 'Playwright tests / Project: ${{ matrix.project }}' - needs: [ code_quality, envs_validation, pw_affected_tests ] + name: 'Playwright tests / ${{ matrix.name }}' + needs: [ code_quality, pw_changes ] + # The gate only runs on pull requests; a skipped gate (workflow_call from pre-release, manual + # dispatch) means a full run. if: | always() && needs.code_quality.result == 'success' && - needs.envs_validation.result == 'success' && - (needs.pw_affected_tests.result == 'success' || needs.pw_affected_tests.result == 'skipped') + (needs.pw_changes.result == 'skipped' || (needs.pw_changes.result == 'success' && needs.pw_changes.outputs.has_changes == 'true')) runs-on: ubuntu-latest container: - image: mcr.microsoft.com/playwright:v1.57.0-noble + image: mcr.microsoft.com/playwright:v1.62.1-noble strategy: fail-fast: false matrix: - project: [ default, mobile, dark-color-mode ] + include: + - name: default-1 + project: default + shard: 1/3 + - name: default-2 + project: default + shard: 2/3 + - name: default-3 + project: default + shard: 3/3 + - name: mobile + project: mobile + - name: dark-color-mode + project: dark-color-mode steps: - - name: Install git-lfs - run: apt-get update && apt-get install git-lfs - - name: Checkout repo uses: actions/checkout@v7 with: - lfs: 'true' + # --changed resolves the merge-base with origin/main, which a shallow clone lacks. + fetch-depth: 0 - name: Install pnpm uses: pnpm/action-setup@v6 with: - version: 11.5.1 - cache: true + version: 12.4.1 - name: Setup node uses: actions/setup-node@v7 with: - node-version: 22.14.0 + node-version: 24.21.0 cache: 'pnpm' - name: Install dependencies run: pnpm install --frozen-lockfile +<<<<<<< HEAD - name: Download affected tests list if: ${{ needs.pw_affected_tests.result == 'success' }} uses: actions/download-artifact@v8 @@ -259,18 +321,26 @@ jobs: with: name: playwright-affected-tests path: ./playwright +======= + - name: Trust the checkout inside the container + # actions/checkout registers the workspace as a safe.directory in the global git config of the + # HOME it ran under (/github/home); the run step below sets HOME=/root, where git finds no such + # entry and refuses the repo ("dubious ownership") when --changed resolves the merge-base. + run: git config --global --add safe.directory "$GITHUB_WORKSPACE" + env: + HOME: /root +>>>>>>> v2.13.0 - name: Run PlayWright - run: pnpm test:pw:ci --affected=${{ github.event_name == 'pull_request' }} --pass-with-no-tests + run: pnpm test:pw ${{ github.event_name == 'pull_request' && '--changed' || '' }} --project=${{ matrix.project }} ${{ matrix.shard && format('--shard={0}', matrix.shard) || '' }} --pass-with-no-tests env: HOME: /root - PW_PROJECT: ${{ matrix.project }} - name: Upload blob report to GitHub Actions Artifacts if: ${{ !cancelled() }} uses: actions/upload-artifact@v7 with: - name: blob-report-${{ matrix.project }} + name: blob-report-${{ matrix.name }} path: blob-report retention-days: 1 @@ -307,14 +377,14 @@ jobs: if: steps.check-reports.outputs.has_reports == 'true' uses: pnpm/action-setup@v6 with: - version: 11.5.1 + version: 12.4.1 cache: true - name: Setup node if: steps.check-reports.outputs.has_reports == 'true' uses: actions/setup-node@v7 with: - node-version: 22.14.0 + node-version: 24.21.0 cache: 'pnpm' - name: Install dependencies @@ -337,4 +407,13 @@ jobs: if: steps.check-reports.outputs.has_reports == 'true' run: | echo "### Playwright report" >> $GITHUB_STEP_SUMMARY +<<<<<<< HEAD echo "Download the **playwright-html-report** artifact below to view the report (open \`index.html\` in a browser)." >> $GITHUB_STEP_SUMMARY +======= + if [ -n "${{ env.PLAYWRIGHT_URL }}" ]; then + echo "[View report (S3)](${{ env.PLAYWRIGHT_URL }})" >> $GITHUB_STEP_SUMMARY + else + echo "Download the **playwright-html-report** artifact below to view the report (open \`index.html\` in a browser)." >> $GITHUB_STEP_SUMMARY + fi + echo "[Read about ducks](https://animalkingdom.org/animals/ducks/)" >> $GITHUB_STEP_SUMMARY +>>>>>>> v2.13.0 diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml index c161233a8e0..6f7c8dc678f 100644 --- a/.github/workflows/copilot-setup-steps.yml +++ b/.github/workflows/copilot-setup-steps.yml @@ -23,12 +23,12 @@ jobs: - name: Install pnpm uses: pnpm/action-setup@v6 with: - version: 11.5.1 + version: 12.4.1 - name: Setup node uses: actions/setup-node@v7 with: - node-version: 22.14.0 + node-version: 24.21.0 cache: 'pnpm' - name: Install dependencies diff --git a/.github/workflows/deploy-review.yml b/.github/workflows/deploy-review.yml index 5e000fc80c0..17e26b73236 100644 --- a/.github/workflows/deploy-review.yml +++ b/.github/workflows/deploy-review.yml @@ -35,7 +35,7 @@ on: - eth - eth_sepolia - filecoin - - garnet + - fuse - gnosis - gnosis_chiado - hpp @@ -50,7 +50,6 @@ on: - rootstock - rootstock_testnet - robinhood - - scroll_sepolia - shibarium - stability_testnet - staging @@ -61,7 +60,6 @@ on: - zetachain_testnet - zilliqa - zksync - - zora # presets:end permissions: diff --git a/.github/workflows/label-issues-in-release.yml b/.github/workflows/label-issues-in-release.yml index 652ad30972b..c0c8dce4c25 100644 --- a/.github/workflows/label-issues-in-release.yml +++ b/.github/workflows/label-issues-in-release.yml @@ -21,6 +21,11 @@ on: default: 'FFFFFF' required: false type: string + dry_run: + description: 'List the PRs and issues without labeling them' + default: false + required: false + type: boolean workflow_call: inputs: tag: @@ -41,30 +46,64 @@ on: default: 'FFFFFF' required: false type: string + dry_run: + description: 'List the PRs and issues without labeling them' + default: false + required: false + type: boolean outputs: issues: - description: "JSON encoded list of issues linked to commits in the release" + description: "JSON encoded list of issues linked to the PRs in the release" value: ${{ jobs.run.outputs.issues }} -# concurrency: -# group: ${{ github.workflow }}__${{ github.job }}__${{ github.ref }} -# cancel-in-progress: true permissions: contents: read issues: write + pull-requests: write jobs: run: name: Run runs-on: ubuntu-latest outputs: - issues: ${{ steps.linked_issues.outputs.result }} + issues: ${{ steps.label.outputs.issues }} steps: +<<<<<<< HEAD - name: Getting tags of the two latest releases id: tags uses: actions/github-script@v9 +======= + # Full history and tags: the tool computes the previous tag and the commit range from the checkout. + - name: Checkout repo + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Install pnpm + uses: pnpm/action-setup@v6 + with: + version: 12.4.1 + cache: true + + - name: Setup node + uses: actions/setup-node@v4 + with: + node-version: 24.21.0 + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Label PRs and issues + id: label + run: | + issues=$(pnpm --silent release label "$TAG" --label="$LABEL_NAME" --description="$LABEL_DESCRIPTION" --color="$LABEL_COLOR" $DRY_RUN_FLAG) + echo "issues=$issues" >> "$GITHUB_OUTPUT" +>>>>>>> v2.13.0 env: + GH_TOKEN: ${{ github.token }} TAG: ${{ inputs.tag }} +<<<<<<< HEAD with: script: | const { repository: { releases: { nodes: releases } } } = await github.graphql(` @@ -236,9 +275,11 @@ jobs: id: label_creating uses: actions/github-script@v9 env: +======= +>>>>>>> v2.13.0 LABEL_NAME: ${{ inputs.label_name }} - LABEL_COLOR: ${{ inputs.label_color }} LABEL_DESCRIPTION: ${{ inputs.label_description }} +<<<<<<< HEAD with: script: | try { @@ -289,3 +330,7 @@ jobs: labels: [ label ], }); } +======= + LABEL_COLOR: ${{ inputs.label_color }} + DRY_RUN_FLAG: ${{ inputs.dry_run && '--dry-run' || '' }} +>>>>>>> v2.13.0 diff --git a/.github/workflows/pre-release.yml b/.github/workflows/pre-release.yml index ab28f94d972..5b373c209d4 100644 --- a/.github/workflows/pre-release.yml +++ b/.github/workflows/pre-release.yml @@ -7,6 +7,7 @@ on: - 'v[0-9]+.[0-9]+.[0-9]+-[a-z]+*' # e.g v1.2.3-alpha.2 jobs: +<<<<<<< HEAD version: name: Pre-release version info runs-on: ubuntu-latest @@ -28,12 +29,48 @@ jobs: const isInitial = match && !match[1] ? true : false; core.info('is_initial flag value: ', isInitial); return isInitial; +======= + checks: + name: Run code checks + uses: "./.github/workflows/checks.yml" + secrets: inherit + permissions: + contents: read + pull-requests: write + + check_tag: + name: Check release tag + uses: './.github/workflows/check-tag.yml' + with: + tag: ${{ github.ref_name }} + permissions: + contents: read + issues: read + pull-requests: read + + publish_image: + name: Publish Docker image + needs: check_tag + uses: './.github/workflows/publish-image.yml' + secrets: inherit + permissions: + contents: read + packages: write + with: + platforms: linux/amd64 + + # e2e_tests: + # decided to disable e2e temporarily + # name: Run e2e tests + # needs: checks + # uses: "./.github/workflows/e2e-tests.yml" + # secrets: inherit + # permissions: write-all +>>>>>>> v2.13.0 label_issues: - name: Add pre-release label to issues + name: Add pre-release label to PRs and issues uses: './.github/workflows/label-issues-in-release.yml' - needs: [ version ] - if: ${{ needs.version.outputs.is_initial == 'true' }} with: tag: ${{ github.ref_name }} label_name: 'pre-release' @@ -42,3 +79,4 @@ jobs: permissions: contents: read issues: write + pull-requests: write diff --git a/.github/workflows/project-management.yml b/.github/workflows/project-management.yml new file mode 100644 index 00000000000..726ef037c6a --- /dev/null +++ b/.github/workflows/project-management.yml @@ -0,0 +1,98 @@ +name: Project management +on: + issues: + types: [ closed ] + pull_request: + types: [ review_requested ] + +jobs: + not_planned_issue: + name: Update task for not planned issue + if: ${{ github.event.issue && github.event.action == 'closed' && github.event.issue.state_reason == 'not_planned' }} + uses: './.github/workflows/update-project-cards.yml' + with: + project_name: ${{ vars.PROJECT_NAME }} + field_name: Status + field_value: Done + issues: "[${{ github.event.issue.number }}]" + secrets: inherit + permissions: + issues: read + + completed_issue: + name: Update task for completed issue + if: ${{ github.event.issue && github.event.action == 'closed' && github.event.issue.state_reason == 'completed' }} + uses: './.github/workflows/update-project-cards.yml' + with: + project_name: ${{ vars.PROJECT_NAME }} + field_name: Status + field_value: Ready For Release + issues: "[${{ github.event.issue.number }}]" + secrets: inherit + permissions: + issues: read + + pr_linked_issues: + name: Get issues linked to PR + runs-on: ubuntu-latest + if: ${{ github.event.pull_request && github.event.action == 'review_requested' }} + outputs: + issues: ${{ steps.linked_issues.outputs.result }} + steps: + - name: Fetching issues linked to pull request + id: linked_issues + uses: actions/github-script@v7 + env: + PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }} + with: + script: | + const response = await github.graphql(` + query ($owner: String!, $repo: String!, $pr: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $pr) { + number + title + closingIssuesReferences(first: 100) { + nodes { + number + title + closed + } + } + } + } + } + `, { + owner: context.repo.owner, + repo: context.repo.repo, + pr: Number(process.env.PULL_REQUEST_NUMBER), + }); + + const { repository: { pullRequest: { closingIssuesReferences } } } = response; + const issues = closingIssuesReferences.nodes.map(({ number }) => number); + + if (!issues.length) { + core.notice(`No linked issues found for pull request #${ process.env.PULL_REQUEST_NUMBER }`); + return; + } + + core.info(`Found ${ issues.length } issue(s): ${ issues.join(', ') || '-' }`); + + return issues; + permissions: + issues: read + pull-requests: read + + issues_in_review: + name: Update status for issues in review + needs: [ pr_linked_issues ] + if: ${{ needs.pr_linked_issues.outputs.issues }} + uses: './.github/workflows/update-project-cards.yml' + secrets: inherit + with: + project_name: ${{ vars.PROJECT_NAME }} + field_name: Status + field_value: Review + issues: ${{ needs.pr_linked_issues.outputs.issues }} + permissions: + issues: read diff --git a/.github/workflows/pull-request-check.yml b/.github/workflows/pull-request-check.yml new file mode 100644 index 00000000000..3cf397a7bea --- /dev/null +++ b/.github/workflows/pull-request-check.yml @@ -0,0 +1,44 @@ +name: PR check +on: + pull_request: + types: [ opened, edited, synchronize, labeled, unlabeled, ready_for_review ] + +# Label and body edits fire in bursts; only the latest state of the PR matters. +concurrency: + group: ${{ github.workflow }}__${{ github.event.pull_request.number }} + cancel-in-progress: true + +permissions: + contents: read + pull-requests: read + +jobs: + check_pr: + name: PR template and category label + runs-on: ubuntu-latest + # Draft PRs are skipped: the spec-first workflow opens them before the description is written. + if: ${{ github.event.pull_request.draft != true }} + steps: + - name: Checkout repo + uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v6 + with: + version: 12.4.1 + cache: true + + - name: Setup node + uses: actions/setup-node@v4 + with: + node-version: 24.21.0 + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # The body is fetched by number, not read from the event payload, so an `edited` run sees the saved body. + - name: Check the PR body and labels + run: pnpm release check-pr ${{ github.event.pull_request.number }} + env: + GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 63db3bd4600..ba576846de7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,8 +7,9 @@ on: jobs: remove_prerelease_label: - name: Remove pre-release label from issues + name: Remove pre-release label from PRs and issues runs-on: ubuntu-latest +<<<<<<< HEAD steps: - name: Remove label id: tags @@ -52,8 +53,36 @@ jobs: core.info('Done.\n'); } +======= +>>>>>>> v2.13.0 permissions: + contents: read issues: write + pull-requests: write + steps: + - name: Checkout repo + uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v6 + with: + version: 12.4.1 + cache: true + + - name: Setup node + uses: actions/setup-node@v4 + with: + node-version: 24.21.0 + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Remove label + run: pnpm release label "$TAG" --remove=pre-release + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.ref_name }} label_released_issues: name: Label released issues @@ -66,3 +95,54 @@ jobs: permissions: contents: read issues: write +<<<<<<< HEAD +======= + pull-requests: write + + update_project_cards: + name: Update project tasks statuses + needs: label_released_issues + uses: './.github/workflows/update-project-cards.yml' + with: + project_name: ${{ vars.PROJECT_NAME }} + field_name: Status + field_value: Released + issues: ${{ needs.label_released_issues.outputs.issues }} + secrets: inherit + permissions: + issues: read + + check_tag: + name: Check release tag + uses: './.github/workflows/check-tag.yml' + with: + tag: ${{ github.ref_name }} + permissions: + contents: read + issues: read + pull-requests: read + + publish_image: + name: Publish Docker image + needs: check_tag + uses: './.github/workflows/publish-image.yml' + secrets: inherit + with: + platforms: linux/amd64,linux/arm64/v8 + # NOTE: by default the image will be built with type=ref,event=tag; so we need to specify it here + tags: | + type=raw,value=latest + permissions: + contents: read + packages: write + + publish_toolkit: + name: Publish toolkit package to NPM + uses: './.github/workflows/toolkit-npm-publisher.yml' + secrets: inherit + with: + version: ${{ github.ref_name }} + permissions: + contents: read + id-token: write +>>>>>>> v2.13.0 diff --git a/.github/workflows/toolkit-npm-publisher.yml b/.github/workflows/toolkit-npm-publisher.yml new file mode 100644 index 00000000000..502845a99be --- /dev/null +++ b/.github/workflows/toolkit-npm-publisher.yml @@ -0,0 +1,64 @@ +name: Publish toolkit package to NPM + +on: + workflow_dispatch: + inputs: + version: + description: Package version + type: string + required: true + workflow_call: + inputs: + version: + description: Package version + type: string + required: true + +jobs: + publish: + runs-on: ubuntu-latest + name: Publish package to NPM registry + permissions: + id-token: write + contents: read + + steps: + - name: Checkout repo + uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v6 + with: + version: 12.4.1 + + # Also it will setup .npmrc file to publish to npm + - name: Setup node + uses: actions/setup-node@v4 + with: + node-version: '24.21.0' + registry-url: 'https://registry.npmjs.org' + cache: 'pnpm' + + - name: Update package version + run: | + cd ./src/toolkit/package + npm version ${{ inputs.version }} + + - name: Install dependencies and build the package + run: | + pnpm install --frozen-lockfile + pnpm --filter @blockscout/ui-toolkit build + + - name: Publish to NPM registry + run: | + cd ./src/toolkit/package + # Determine npm tag based on version + if [[ "${{ inputs.version }}" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + # Stable release (e.g., 1.7.2 or v1.7.2) + npm publish --access public --tag latest + else + # Pre-release (e.g., 1.7.2-alpha.1 or v1.7.2-alpha.1) + npm publish --access public --tag beta + fi + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.gitignore b/.gitignore index 21bf70ead54..ab8575a3d87 100644 --- a/.gitignore +++ b/.gitignore @@ -55,26 +55,62 @@ npm-debug.log* # compiled dev-server fetch script /tools/dev-server/fetch.js +# compiled preset-list sync tool +/tools/dev-server/sync-presets/dist/ + +# compiled code-complexity gate +/tools/code-complexity/dist/ + +# compiled doc-link checker +/tools/doc-links/dist/ + +# react-doctor standalone install (not part of the root workspace) +/tools/react-doctor/node_modules/ + +# compiled React profile aggregator +/tools/profiling/dist/ + +# mutation-testing per-run compile output, reports, Stryker's sandbox and the run lock +/tools/mutation-testing/.build.*/ +/tools/mutation-testing/reports/ +/tools/mutation-testing/.stryker-tmp/ +/tools/mutation-testing/.lock + +# compiled Playwright runner +/tools/playwright/dist/ + +# compiled review-screen CLI +/tools/review-screen/dist/ + +# compiled design-readout CLI +/tools/design-readout/dist/ + +# compiled release tool +/tools/release/dist/ + # typescript *.tsbuildinfo .eslintcache **.decrypted~** -/test-results/ +/playwright-results/ /playwright-report/ /blob-report/ /playwright/.cache/ /playwright/.browser/ /playwright/envs.js -/playwright/affected-tests.txt +/.playwright-mcp/ **.dec** # build outputs /toolkit/package/dist license.json -release-prs-data.json .ai +<<<<<<< HEAD .codex/worktrees/ +======= +/ds-bundle +>>>>>>> v2.13.0 diff --git a/.license-reportrc b/.license-reportrc index e90e8c13951..accad98b8c5 100644 --- a/.license-reportrc +++ b/.license-reportrc @@ -1,6 +1,10 @@ { "exclude": [ - // It currently has two licenses (MIT and Apache-2.0), which are not correctly recognized by license-report-check. - "@helia/verified-fetch" + // These have two licenses (MIT and Apache-2.0), which are not correctly recognized by license-report-check. + "@helia/http", + "@helia/verified-fetch", + "helia", + "multiformats", + "posthog-js" ] } \ No newline at end of file diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 00000000000..1bd22b5d166 --- /dev/null +++ b/.mcp.json @@ -0,0 +1,13 @@ +{ + "mcpServers": { + "playwright": { + "command": "npx", + "args": [ + "-y", + "@playwright/mcp@latest", + "--headless", + "--isolated" + ] + } + } +} diff --git a/.nvmrc b/.nvmrc index 200763baef7..0a6e235142e 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ ->=22.14.0 \ No newline at end of file +>=24.21.0 \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index bdd9e81ba44..59579abe84e 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -49,11 +49,11 @@ "group": "build", }, { - "type": "npm", - "script": "lint:eslint:fix", + "type": "shell", + "command": "pnpm lint:eslint --fix", "problemMatcher": [], "label": "eslint", - "detail": "run eslint", + "detail": "run eslint --fix", "presentation": { "reveal": "always", "panel": "shared", @@ -73,7 +73,7 @@ // PW TESTS { "type": "shell", - "command": "${input:pwDebugFlag} pnpm test:pw:local ${relativeFileDirname}/${fileBasename} ${input:pwArgs}", + "command": "${input:pwDebugFlag} pnpm test:pw ${relativeFileDirname}/${fileBasename} ${input:pwArgs}", "problemMatcher": [], "label": "pw: local", "detail": "run visual components tests for current file", @@ -94,7 +94,7 @@ }, { "type": "shell", - "command": "pnpm test:pw:docker ${relativeFileDirname}/${fileBasename} ${input:pwArgs}", + "command": "pnpm test:pw --docker ${relativeFileDirname}/${fileBasename} ${input:pwArgs}", "problemMatcher": [], "label": "pw: docker", "detail": "run visual components tests for current file", @@ -115,7 +115,7 @@ }, { "type": "shell", - "command": "pnpm test:pw:docker ${input:pwArgs}", + "command": "pnpm test:pw --docker ${input:pwArgs}", "problemMatcher": [], "label": "pw: docker all", "detail": "run visual components tests", @@ -136,10 +136,10 @@ }, { "type": "shell", - "command": "npx playwright show-report", + "command": "pnpm test:pw --docker --changed ${input:pwArgs}", "problemMatcher": [], - "label": "pw: report", - "detail": "serve test report", + "label": "pw: changed", + "detail": "run visual components tests affected by the changed files in the current branch", "presentation": { "reveal": "always", "panel": "shared", @@ -149,7 +149,7 @@ }, "icon": { "color": "terminal.ansiBlue", - "id": "output" + "id": "beaker" }, "runOptions": { "instanceLimit": 1 @@ -157,10 +157,10 @@ }, { "type": "shell", - "command": "pnpm test:pw:detect-affected", + "command": "npx playwright show-report", "problemMatcher": [], - "label": "pw: detect affected", - "detail": "detect PW tests affected by changes in current branch", + "label": "pw: report", + "detail": "serve test report", "presentation": { "reveal": "always", "panel": "shared", @@ -170,11 +170,11 @@ }, "icon": { "color": "terminal.ansiBlue", - "id": "diff" + "id": "output" }, "runOptions": { "instanceLimit": 1 - }, + } }, // VITEST TESTS @@ -221,6 +221,50 @@ }, }, + // CODE COMPLEXITY + { + "type": "shell", + "command": "pnpm test:code-complexity ${relativeFileDirname}/${fileBasename}", + "problemMatcher": [], + "label": "code complexity: file", + "detail": "run code complexity for current file", + "presentation": { + "reveal": "always", + "panel": "shared", + "focus": true, + "close": false, + "revealProblems": "onProblem", + }, + "icon": { + "color": "terminal.ansiBlue", + "id": "file-binary" + }, + "runOptions": { + "instanceLimit": 1 + }, + }, + { + "type": "shell", + "command": "pnpm test:code-complexity --changed", + "problemMatcher": [], + "label": "code complexity: changed", + "detail": "run code complexity for changed files in the current branch", + "presentation": { + "reveal": "always", + "panel": "shared", + "focus": true, + "close": false, + "revealProblems": "onProblem", + }, + "icon": { + "color": "terminal.ansiBlue", + "id": "file-binary" + }, + "runOptions": { + "instanceLimit": 1 + }, + }, + { "type": "npm", "script": "build:docker", @@ -305,7 +349,6 @@ "options": [ "", "--update-snapshots", - "--update-snapshots --affected", "--ui", ], "default": "" @@ -333,7 +376,7 @@ "eth", "eth_sepolia", "filecoin", - "garnet", + "fuse", "gnosis", "gnosis_chiado", "hpp", @@ -348,7 +391,6 @@ "rootstock", "rootstock_testnet", "robinhood", - "scroll_sepolia", "shibarium", "stability_testnet", "staging", @@ -359,7 +401,6 @@ "zetachain_testnet", "zilliqa", "zksync", - "zora", // presets:end ], "default": "staging" diff --git a/.worktreeinclude b/.worktreeinclude new file mode 100644 index 00000000000..5ed92037411 --- /dev/null +++ b/.worktreeinclude @@ -0,0 +1,2 @@ +.zed/ +.env.local diff --git a/Dockerfile b/Dockerfile index 1bd5d0ee8c7..10bb1a4e2ac 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,14 +1,14 @@ # ***************************** # *** STAGE 0: Shared base **** # ***************************** -FROM node:22.14.0-alpine AS base +FROM node:24.21.0-alpine AS base # corepack prepare makes a single network request to the npm registry and has no # built-in retry. Transient registry failures (HTTP 429, timeout, DNS) are not # uncommon, so retry with a linear backoff. RUN set -eu; \ corepack enable; \ n=0; \ - until corepack prepare pnpm@11.5.1 --activate; do \ + until corepack prepare pnpm@12.4.1 --activate; do \ n=$((n + 1)); \ if [ "$n" -ge 5 ]; then echo "corepack prepare failed after $n attempts" >&2; exit 1; fi; \ echo "corepack prepare attempt $n failed, retrying in $((n * 10))s..." >&2; \ @@ -72,6 +72,9 @@ RUN pnpm run build RUN cd ./deploy/tools/feature-reporter && pnpm run build +### ASSETS DOWNLOADER +RUN cd ./deploy/tools/assets-downloader && pnpm run build + ### ENV VARIABLES CHECKER RUN cd ./deploy/tools/envs-validator && pnpm run build @@ -101,7 +104,7 @@ RUN pnpm exec tsc -p ./tools/dev-server/tsconfig.json # ******* STAGE 3: Run ******** # ***************************** # Production image, copy all the files and run next -FROM node:22.14.0-alpine AS runner +FROM node:24.21.0-alpine AS runner RUN apk add --no-cache --upgrade bash curl jq unzip ### APP @@ -122,6 +125,7 @@ COPY --from=builder /app/public ./public COPY --from=builder /app/package.json ./package.json # Copy tools +COPY --from=builder /app/deploy/tools/assets-downloader/dist/index.js ./assets-downloader/index.js COPY --from=builder /app/deploy/tools/envs-validator/dist/index.js ./envs-validator/index.js COPY --from=builder /app/deploy/tools/feature-reporter/dist/index.js ./feature-reporter.js COPY --from=builder /app/deploy/tools/multichain-config-generator/dist ./deploy/tools/multichain-config-generator/dist @@ -137,7 +141,7 @@ COPY --chmod=755 ./deploy/scripts/make_envs_script.sh . ## Assets downloader COPY --chmod=755 ./deploy/scripts/download_assets.sh . ## OG image generator -COPY ./deploy/scripts/og_image_generator.js . +COPY ./deploy/tools/og-image-generator/index.js ./deploy/tools/og-image-generator/index.js ## Pro API support flag COPY --chmod=755 ./deploy/scripts/export_pro_api_flag.sh . ## Favicon generator diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md deleted file mode 100644 index 72bc8378b4f..00000000000 --- a/RELEASE_NOTES.md +++ /dev/null @@ -1,50 +0,0 @@ -## 🚀 New Features -- Description of the new feature 1. -- Description of the new feature 2. - -## 🐛 Bug Fixes -- Description of the bug fix 1. -- Description of the bug fix 2. - -## ⚡ Performance Improvements -- Description of the performance improvement 1. -- Description of the performance improvement 2. - -## 📦 Dependencies Updates -- Updated dependency: PackageName 1 to version x.x.x. -- Updated dependency: PackageName 2 to version x.x.x. - -## 🛠️ DX & Tooling -- New tool #1 -- Improvement #2 - -## 🎨 Design Updates -- New style 1. -- New style 2. - -## ✨ Other Changes -- Another minor change 1. -- Another minor change 2. - -## 🚨 Changes in ENV variables -- Added new environment variable: ENV_VARIABLE_NAME with value. -- Updated existing environment variable: ENV_VARIABLE_NAME to new value. - -**Full list of the ENV variables**: [v1.2.3](https://github.com/blockscout/frontend/blob/v1.2.3/docs/ENVS.md) - -## 💑 Compatibility -This release raises the minimum required version of the following API services: - -| Service | Version | -| --- | --- | -| Blockscout API | ... | -| Stats microservice API | ... | -| ... | ... | - -## 🦄 New Contributors -- @contributor1 made their first contribution in https://github.com/blockscout/frontend/pull/1 -- @contributor2 made their first contribution in https://github.com/blockscout/frontend/pull/2 - ---- - -**Full Changelog**: https://github.com/blockscout/frontend/compare/v1.2.2...v1.2.3 diff --git a/cspell.jsonc b/cspell.jsonc index 9d6eaf1e4a5..fb7205cb65a 100644 --- a/cspell.jsonc +++ b/cspell.jsonc @@ -23,7 +23,11 @@ "public/static/capybara/index.js", "src/toolkit/pages/design-system/utils.ts", "src/features/external-txs/components/TxExternalTxs.pw.tsx", - ".agents/TEAM.md" + ".agents/TEAM.md", + // raw Figma payloads: the designer's layer names are data, not prose + "tools/design-readout/fixtures", + // calibration snapshots: the mockups' own layer names and text, plus the Figma file key + "tools/design-readout/calibration" ], "enableGlobDot": true, "ignoreRandomStrings": true, @@ -31,6 +35,8 @@ "ignoreRegExpList": [ // Ignore filecoin f410f-like native addresses "f410f[a-z2-7]{39}", + // IPFS CIDv1 in base32 + "b[a-z2-7]{58}", // Specify publisher key "spk_\\w+", // Posthog project key @@ -55,6 +61,7 @@ "Ahrefs", "airtable", "Alexa", + "Alexey", "alfajores", "andb", "anyblock", @@ -64,6 +71,7 @@ "appkit", "Applebot", "Arianee", + "arweave", "ARTIS", "astar", "asymp", @@ -72,6 +80,7 @@ "Baiduspider", "barooumba", "basehead", + "bbox", "bech", "bedag", "bingbot", @@ -95,6 +104,7 @@ "chainid", "chainscout", "chakra", + "chdir", "clstr", "commitish", "Computor", @@ -107,6 +117,7 @@ "dbaeumer", "deepdao", "defi", + "desyncing", "devnet", "didn", "doesn", @@ -114,6 +125,7 @@ "DRPC", "DTEND", "duckduckgo", + "dweb", "dynamicwaas", "eamodio", "Eigenda", @@ -129,6 +141,8 @@ "flashblock", "flashblocks", "foos", + "ftyp", + "miaf", "fxios", "geas", "giga", @@ -153,6 +167,7 @@ "inpage", "internaltx", "ipfs", + "ipns", "iszero", "jazzicon", "jfif", @@ -166,12 +181,14 @@ "LCIA", "libc", "libp", + "lifi", "linkedinbot", "Liquality", "llms", "lokijs", "LUKSO", "mainnets", + "mcps", "megaeth", "merkle", "metasuites", @@ -193,12 +210,14 @@ "negb", "nextjs", "noopener", + "noul", "noreferrer", "noves", "numine", "nums", "octav", "okex", + "oxfmtrc", "okhttp", "opblock", "opengraph", @@ -208,9 +227,11 @@ "peekers", "pino", "pjpeg", + "Pocock", "posthog", "protobufjs", "PRRT", + "pstack", "PWDEBUG", "pwstory", "pyftsubset", @@ -235,6 +256,7 @@ "rollbar", "ROLLUP", "rollups", + "rsbuild", "rubic", "Sastana", "schnorr", @@ -242,6 +264,7 @@ "scure", "sdiv", "SEMRESATTRS", + "srvx", "Semrush", "servedbyadbutler", "sevio", @@ -262,6 +285,7 @@ "smol", "sokol", "solidityscan", + "sonarjs", "Sourcify", "Succ", "superchain", @@ -284,6 +308,7 @@ "uidotdev", "Ulyana", "unfinalized", + "unindexed", "unminified", "UNKN", "unparse", diff --git a/deploy/scripts/CONTEXT.md b/deploy/scripts/CONTEXT.md index 1f8a59d7601..eff5c19e60d 100644 --- a/deploy/scripts/CONTEXT.md +++ b/deploy/scripts/CONTEXT.md @@ -28,7 +28,10 @@ runtime image. ### Build the runtime tools Each of runtime tools is built into a small standalone JS bundle so the runtime -image doesn't need to ship the full source tree or `node_modules`. +image doesn't need to ship the full source tree or `node_modules`. Only that +build is per-package: the root ESLint, type-check and complexity gate cover +`deploy/tools/*` the same way they cover `src/`, so a package needs no +`tsconfig.json` of its own. ## Runtime @@ -43,19 +46,21 @@ time. write it to a temp file, and export it into the environment. `--omit-local-envs` drops the local APP_* keys so the deployment's own values survive; the committed `.env.extra` is then layered on top. -2. **`download_assets.sh`** — fetches the external assets referenced by env - vars (network logo, marketplace config JSON, featured-networks list, - etc.) into `public/assets/configs/<downloaded>/` so the app serves them same-origin - and not depend on 3rd-party insfrastructure. +2. **`download_assets.sh`** → `assets-downloader` — fetches the external assets referenced by + env vars (network logo, marketplace config JSON, featured-networks list, etc.) into + `public/assets/configs/<downloaded>/` so the app serves them same-origin and does not depend on 3rd-party + infrastructure. A file is written only after its content passed the check for what the + variable is documented to hold; a rejected or unreachable asset stops the container. This + step is not covered by `SKIP_ENVS_VALIDATION`. 3. **`validate_envs.sh`** → `envs-validator` — fail-fast check that the container's env vars conform to the schema. Skippable via `SKIP_ENVS_VALIDATION=true`. 4. **`favicon_generator.sh`** → `favicon-generator` — regenerates favicons - from the (possibly just-downloaded) network icon. -5. **`og_image_generator.js`** — renders the Open Graph preview image used + from the network icon saved by step 2 (or from `FAVICON_MASTER_URL`, fetched directly). +5. **`og-image-generator`** — renders the Open Graph preview image used for link unfurls. 6. **`export_pro_api_flag.sh`** — auto-detects whether the configured chain - is supported by the Blockscout Pro API and exports + is supported by the Blockscout API and exports `NEXT_PUBLIC_PRO_API_SUPPORTED` accordingly (unless the operator already set it). 7. **`make_envs_script.sh`** — writes every `NEXT_PUBLIC_*` value into diff --git a/deploy/scripts/download_assets.sh b/deploy/scripts/download_assets.sh index c62f70b5f65..bfb92233d42 100755 --- a/deploy/scripts/download_assets.sh +++ b/deploy/scripts/download_assets.sh @@ -1,140 +1,15 @@ #!/bin/bash -echo -echo "⬇️ Downloading external assets..." +# Runs the assets downloader (deploy/tools/assets-downloader): the bundle copied next to this script +# in the container image, or a fresh build when invoked from the source tree. -# Check if the number of arguments provided is correct -if [ "$#" -ne 1 ]; then - echo "🛑 Error: incorrect amount of arguments. Usage: $0 <ASSETS_DIR>." - exit 1 -fi - -# Define the directory to save the downloaded assets -ASSETS_DIR="$1" - -# Define a list of environment variables containing URLs of external assets -ASSETS_ENVS=( - "NEXT_PUBLIC_MARKETPLACE_CONFIG_URL" - "NEXT_PUBLIC_MARKETPLACE_CATEGORIES_URL" - "NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL" - "NEXT_PUBLIC_MARKETPLACE_GRAPH_LINKS_URL" - "NEXT_PUBLIC_FEATURED_NETWORKS" - "NEXT_PUBLIC_FOOTER_LINKS" - "NEXT_PUBLIC_NETWORK_LOGO" - "NEXT_PUBLIC_NETWORK_LOGO_DARK" - "NEXT_PUBLIC_NETWORK_ICON" - "NEXT_PUBLIC_NETWORK_ICON_DARK" - "NEXT_PUBLIC_OG_IMAGE_URL" - "NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL" - "NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL" - "NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG" -) - -# Create the assets directory if it doesn't exist -mkdir -p "$ASSETS_DIR" - -# Track failed downloads -FAILED_DOWNLOADS=0 - -# Function to determine the target file name based on the environment variable -get_target_filename() { - local env_var="$1" - local url="${!env_var}" - - # Extract the middle part of the variable name (between "NEXT_PUBLIC_" and "_URL") in lowercase - local name_prefix="${env_var#NEXT_PUBLIC_}" - local name_suffix="${name_prefix%_URL}" - local name_lc="$(echo "$name_suffix" | tr '[:upper:]' '[:lower:]')" - - # Check if the URL starts with "file://" - if [[ "$url" == file://* ]]; then - # Extract the local file path - local file_path="${url#file://}" - # Get the filename from the local file path - local filename=$(basename "$file_path") - # Extract the extension from the filename - local extension="${filename##*.}" - else - if [[ "$url" == http* ]]; then - # Remove query parameters from the URL and get the filename - local filename=$(basename "${url%%\?*}") - # Extract the extension from the filename - local extension="${filename##*.}" - else - local extension="json" - fi - fi - - # Convert the extension to lowercase - extension=$(echo "$extension" | tr '[:upper:]' '[:lower:]') - - # Construct the custom file name - echo "$name_lc.$extension" -} - -# Function to download and save an asset -download_and_save_asset() { - local env_var="$1" - local url="$2" - local filename="$3" - local destination="$ASSETS_DIR/$filename" - - # Check if the environment variable is set - if [ -z "${!env_var}" ]; then - echo " [.] $env_var: Variable is not set. Skipping download." - return 1 - fi - - # Check if the URL starts with "file://" - if [[ "$url" == file://* ]]; then - # Copy the local file to the destination - cp "${url#file://}" "$destination" - else - # Check if the value is a URL - if [[ "$url" == http* ]]; then - # Download the asset using curl with built-in retries - if ! curl -f -s --connect-timeout 10 --max-time 60 --retry 3 --retry-delay 3 --retry-max-time 180 -o "$destination" "$url"; then - echo " [-] $env_var: Failed to download from $url after 3 retry attempts (timeout or connection error)" - FAILED_DOWNLOADS=$((FAILED_DOWNLOADS + 1)) - return 1 - fi - else - # Convert single-quoted JSON-like content to valid JSON - json_content=$(echo "${!env_var}" | sed "s/'/\"/g") - - # Save the JSON content to a file - echo "$json_content" > "$destination" - fi - fi - - if [[ "$url" == file://* ]] || [[ "$url" == http* ]]; then - local source_name=$url - else - local source_name="raw input" - fi - - # Check if the download was successful - if [ $? -eq 0 ]; then - echo " [+] $env_var: Successfully saved file from $source_name to $destination." - return 0 - else - echo " [-] $env_var: Failed to save file from $source_name." - return 1 - fi -} - -# Iterate through the list and download assets -for env_var in "${ASSETS_ENVS[@]}"; do - url="${!env_var}" - filename=$(get_target_filename "$env_var") - download_and_save_asset "$env_var" "$url" "$filename" -done +script_dir="$(dirname "$0")" +bundle="$script_dir/assets-downloader/index.js" -# Check if any downloads failed and exit with error code -if [ $FAILED_DOWNLOADS -gt 0 ]; then - echo "🛑 Error: $FAILED_DOWNLOADS asset download(s) failed. The application cannot start." - exit 1 +if [ ! -f "$bundle" ]; then + tool_dir="$script_dir/../tools/assets-downloader" + (cd "$tool_dir" && pnpm run build) || exit 1 + bundle="$tool_dir/dist/index.js" fi -echo "✅ Done." -echo +node --no-warnings "$bundle" "$@" diff --git a/deploy/scripts/entrypoint.sh b/deploy/scripts/entrypoint.sh index 5bb8947601e..2042726ca27 100755 --- a/deploy/scripts/entrypoint.sh +++ b/deploy/scripts/entrypoint.sh @@ -63,7 +63,7 @@ fi echo # Generate OG image -node --no-warnings ./og_image_generator.js +node --no-warnings ./deploy/tools/og-image-generator/index.js # Expose Pro API support flag for the current chain (if NEXT_PUBLIC_NETWORK_ID is set) source ./export_pro_api_flag.sh diff --git a/deploy/scripts/export_pro_api_flag.sh b/deploy/scripts/export_pro_api_flag.sh index 91f15efaf83..b2c07c8969a 100755 --- a/deploy/scripts/export_pro_api_flag.sh +++ b/deploy/scripts/export_pro_api_flag.sh @@ -7,34 +7,34 @@ check_pro_api_supported() { local network_id="${NEXT_PUBLIC_NETWORK_ID// /}" if [ -z "$network_id" ]; then - echo "⚠️ NEXT_PUBLIC_NETWORK_ID is not set. Skipping Pro API support check." >&2 + echo "⚠️ NEXT_PUBLIC_NETWORK_ID is not set. Skipping Blockscout API support check." >&2 return 1 fi if ! command -v jq >/dev/null 2>&1; then - echo "⚠️ jq not found. Skipping Pro API support check." >&2 + echo "⚠️ jq not found. Skipping Blockscout API support check." >&2 return 1 fi if ! command -v curl >/dev/null 2>&1; then - echo "⚠️ curl not found. Skipping Pro API support check." >&2 + echo "⚠️ curl not found. Skipping Blockscout API support check." >&2 return 1 fi - echo "⏳ Checking Pro API support for chain ${network_id}..." >&2 + echo "⏳ Checking Blockscout API support for chain ${network_id}..." >&2 local response if ! response=$(curl -f -sS --connect-timeout 10 --max-time 30 "$SUPPORTED_CHAINS_URL"); then - echo "⚠️ Failed to fetch Pro API config." >&2 + echo "⚠️ Failed to fetch Blockscout API config." >&2 return 1 fi if echo "$response" | jq -e --arg id "$network_id" '.chains[$id]' >/dev/null; then - echo "✅ Chain ${network_id} is supported by Blockscout PRO API." >&2 + echo "✅ Chain ${network_id} is supported by Blockscout API." >&2 return 0 fi - echo "ℹ️ Chain ${network_id} is not supported by Blockscout PRO API." >&2 + echo "ℹ️ Chain ${network_id} is not supported by Blockscout API." >&2 return 1 } diff --git a/deploy/scripts/favicon_generator.sh b/deploy/scripts/favicon_generator.sh index 9be9d9b5b0f..650eae3beb0 100755 --- a/deploy/scripts/favicon_generator.sh +++ b/deploy/scripts/favicon_generator.sh @@ -1,7 +1,11 @@ #!/bin/bash -master_url="${FAVICON_MASTER_URL:-$NEXT_PUBLIC_NETWORK_ICON}" -export MASTER_URL="$master_url" +if [ -n "$FAVICON_MASTER_URL" ]; then + export MASTER_URL="$FAVICON_MASTER_URL" +else + # The downloader has already fetched and checked NEXT_PUBLIC_NETWORK_ICON; reuse that copy instead of fetching the URL again. + export MASTER_FILE="$(ls "$(pwd)"/public/assets/configs/network_icon "$(pwd)"/public/assets/configs/network_icon.* 2>/dev/null | head -n 1)" +fi cd ./deploy/tools/favicon-generator node "$(pwd)/index.js" @@ -18,4 +22,4 @@ else fi mkdir -p "$favicon_folder" cp -r ./deploy/tools/favicon-generator/output/* "$favicon_folder" -fi \ No newline at end of file +fi diff --git a/deploy/scripts/make_envs_script.sh b/deploy/scripts/make_envs_script.sh index cda13bdc0e4..cb5c3d7f0cc 100755 --- a/deploy/scripts/make_envs_script.sh +++ b/deploy/scripts/make_envs_script.sh @@ -27,8 +27,9 @@ for var in $(env | grep '^NEXT_PUBLIC_' | cut -d= -f1); do # Get the value of the variable value="${!var}" - # Replace double quotes with single quotes - value="${value//\"/\'}" + # Escape backslashes and double quotes so the browser reads the value exactly as the server does + value="${value//\\/\\\\}" + value="${value//\"/\\\"}" # Write the variable name and value to the output file echo "${var}: \"${value}\"," >> "$output_file" diff --git a/deploy/scripts/og_image_generator.js b/deploy/scripts/og_image_generator.js deleted file mode 100755 index d4ca42b4073..00000000000 --- a/deploy/scripts/og_image_generator.js +++ /dev/null @@ -1,70 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -/* eslint-disable no-console */ -import fs from 'fs'; -import path from 'path'; - -console.log('🎨 Generating OG image...'); - -const targetFile = path.resolve(process.cwd(), 'public/static/og_image.png'); - -function copyPlaceholderImage() { - const sourceFile = path.resolve(process.cwd(), 'public/static/og_placeholder.png'); - fs.copyFileSync(sourceFile, targetFile); -} - -if (process.env.NEXT_PUBLIC_OG_IMAGE_URL) { - console.log('⏩ NEXT_PUBLIC_OG_IMAGE_URL is set. Skipping OG image generation...'); -} else if (!process.env.NEXT_PUBLIC_NETWORK_NAME) { - console.log('⏩ NEXT_PUBLIC_NETWORK_NAME is not set. Copying placeholder image...'); - copyPlaceholderImage(); -} else if (!process.env.NEXT_PUBLIC_NETWORK_LOGO && !process.env.NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG) { - console.log('⏩ Neither NEXT_PUBLIC_NETWORK_LOGO nor NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG is set. Copying placeholder image...'); - copyPlaceholderImage(); -} else { - try { - const bannerConfig = JSON.parse(process.env.NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG?.replaceAll('\'', '"') || '{}'); - const data = { - title: bannerConfig.text || `${ process.env.NEXT_PUBLIC_NETWORK_NAME } explorer`, - logo_url: process.env.NEXT_PUBLIC_NETWORK_LOGO_DARK ?? process.env.NEXT_PUBLIC_NETWORK_LOGO, - background: bannerConfig.background?.[0], - title_color: bannerConfig.text_color?.[0], - invert_logo: !process.env.NEXT_PUBLIC_NETWORK_LOGO_DARK, - app_url: process.env.NEXT_PUBLIC_APP_HOST, - }; - - console.log('⏳ Making request to OG image generator service...'); - - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), 30_000); - - const response = await fetch('https://bigs.services.blockscout.com/generate/og', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(data), - signal: controller.signal, - }); - - clearTimeout(timeoutId); - - if (response.ok) { - console.log('⬇️ Downloading the image...'); - const buffer = await response.arrayBuffer(); - const imageBuffer = Buffer.from(buffer); - fs.writeFileSync(targetFile, imageBuffer); - } else { - const payload = response.headers.get('Content-type')?.includes('application/json') ? await response.json() : await response.text(); - console.error('🛑 Failed to generate OG image. Response:', payload); - console.log('Copying placeholder image...'); - copyPlaceholderImage(); - } - } catch (error) { - console.error('🛑 Failed to generate OG image. Error:', error?.message); - console.log('Copying placeholder image...'); - copyPlaceholderImage(); - } -} - -console.log('✅ Done.'); diff --git a/deploy/tools/affected-tests/.gitignore b/deploy/tools/affected-tests/.gitignore deleted file mode 100644 index 30bc1627986..00000000000 --- a/deploy/tools/affected-tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules \ No newline at end of file diff --git a/deploy/tools/affected-tests/index.js b/deploy/tools/affected-tests/index.js deleted file mode 100644 index 6cb58f03090..00000000000 --- a/deploy/tools/affected-tests/index.js +++ /dev/null @@ -1,208 +0,0 @@ -/* eslint-disable no-console */ -const { execSync } = require('child_process'); -const dependencyTree = require('dependency-tree'); -const fs = require('fs'); -const path = require('path'); - -const ROOT_DIR = path.resolve(__dirname, '../../../'); - -const TARGET_FILE = path.resolve(ROOT_DIR, './playwright/affected-tests.txt'); - -const NON_EXISTENT_DEPS = []; - -const DIRECTORIES_WITH_TESTS = [ - path.resolve(ROOT_DIR, './src'), -]; -const VISITED = {}; - -function getAllPwFilesInDirectory(directory) { - const files = fs.readdirSync(directory, { recursive: true }); - return files - .filter((file) => file.endsWith('.pw.tsx')) - .map((file) => path.join(directory, file)); -} - -function getFileDeps(filename, changedNpmModules) { - return dependencyTree.toList({ - filename, - directory: ROOT_DIR, - filter: (path) => { - if (path.indexOf('node_modules') === -1) { - return true; - } - - if (changedNpmModules.some((module) => path.startsWith(module))) { - return true; - } - - return false; - }, - tsConfig: path.resolve(ROOT_DIR, './tsconfig.json'), - nonExistent: NON_EXISTENT_DEPS, - visited: VISITED, - }); -} - -async function getChangedFiles() { - const command = process.env.CI ? - `git diff --name-only origin/${ process.env.GITHUB_BASE_REF } ${ process.env.GITHUB_SHA } -- ${ ROOT_DIR }` : - `git diff --name-only main $(git branch --show-current) -- ${ ROOT_DIR }`; - - console.log('Executing command: ', command); - const files = execSync(command) - .toString() - .trim() - .split('\n') - .filter(Boolean); - - return files.map((file) => path.join(ROOT_DIR, file)); -} - -function checkChangesInChakraTheme(changedFiles) { - const themeDir = path.resolve(ROOT_DIR, './src/toolkit/theme'); - return changedFiles.some((file) => file.startsWith(themeDir)); -} - -function checkChangesInSvgSprite(changedFiles) { - const iconDir = path.resolve(ROOT_DIR, './src/icons'); - const areIconsChanged = changedFiles.some((file) => file.startsWith(iconDir)); - - if (!areIconsChanged) { - return false; - } - - const svgNamesFile = path.resolve(ROOT_DIR, './public/icons/name.d.ts'); - const areSvgNamesChanged = changedFiles.some((file) => file === svgNamesFile); - - if (!areSvgNamesChanged) { - // If only the icons have changed and not the names in the SVG file, we will need to run all tests. - // This is because we cannot correctly identify the test files that depend on these changes. - return true; - } - - // If the icon names have changed, then there should be changes in the components that use them. - // Otherwise, typescript would complain about that. - return false; -} - -function createTargetFile(content) { - fs.writeFileSync(TARGET_FILE, content); -} - -function getPackageJsonUpdatedProps(packageJsonFile) { - const command = process.env.CI ? - `git diff --unified=0 origin/${ process.env.GITHUB_BASE_REF } ${ process.env.GITHUB_SHA } -- ${ packageJsonFile }` : - `git diff --unified=0 main $(git branch --show-current) -- ${ packageJsonFile }`; - - console.log('Executing command: ', command); - const changedLines = execSync(command) - .toString() - .trim() - .split('\n') - .filter(Boolean) - .filter((line) => line.startsWith('+ ') || line.startsWith('- ')); - - const changedProps = [ ...new Set( - changedLines - .map((line) => line.replaceAll(' ', '').replaceAll('+', '').replaceAll('-', '')) - .map((line) => line.split(':')[0].replaceAll('"', '')), - ) ]; - - return changedProps; -} - -function getUpdatedNpmModules(changedFiles) { - const packageJsonFile = path.resolve(ROOT_DIR, './package.json'); - - if (!changedFiles.includes(packageJsonFile)) { - return []; - } - - try { - const packageJsonContent = JSON.parse(fs.readFileSync(packageJsonFile, 'utf-8')); - const usedNpmModules = [ - ...Object.keys(packageJsonContent.dependencies || {}), - ...Object.keys(packageJsonContent.devDependencies || {}), - ]; - const updatedProps = getPackageJsonUpdatedProps(packageJsonFile); - - return updatedProps.filter((prop) => usedNpmModules.includes(prop)); - } catch (error) {} -} - -async function run() { - // NOTES: - // - The absence of TARGET_FILE implies that all tests should be run. - // - The empty TARGET_FILE implies that no tests should be run. - - const start = Date.now(); - - fs.unlink(TARGET_FILE, () => {}); - - const changedFiles = await getChangedFiles(); - - if (!changedFiles.length) { - createTargetFile(''); - console.log('No changed files found. Exiting...'); - return; - } - - console.log('Changed files in the branch: ', changedFiles); - - if (checkChangesInChakraTheme(changedFiles)) { - console.log('Changes in Chakra theme detected. It is advisable to run all test suites. Exiting...'); - return; - } - - if (checkChangesInSvgSprite(changedFiles)) { - console.log('There are some changes in the SVG sprite that cannot be linked to a specific component. It is advisable to run all test suites. Exiting...'); - return; - } - - let changedNpmModules = getUpdatedNpmModules(changedFiles); - - if (!changedNpmModules) { - console.log('Some error occurred while detecting changed NPM modules. It is advisable to run all test suites. Exiting...'); - return; - } - - console.log('Changed NPM modules in the branch: ', changedNpmModules); - - changedNpmModules = [ - ...changedNpmModules, - ...changedNpmModules.map((module) => `@types/${ module }`), // there are some deps that are resolved to .d.ts files - ].map((module) => path.resolve(ROOT_DIR, `./node_modules/${ module }`)); - - const allTestFiles = DIRECTORIES_WITH_TESTS.reduce((acc, dir) => { - return acc.concat(getAllPwFilesInDirectory(dir)); - }, []); - - const isDepChanged = (dep) => changedFiles.includes(dep) || changedNpmModules.some((module) => dep.startsWith(module)); - - const testFilesToRun = allTestFiles - .map((file) => ({ file, deps: getFileDeps(file, changedNpmModules) })) - .filter(({ deps }) => deps.some(isDepChanged)); - const testFileNamesToRun = testFilesToRun.map(({ file }) => path.relative(ROOT_DIR, file)); - - if (!testFileNamesToRun.length) { - createTargetFile(''); - console.log('No tests to run. Exiting...'); - return; - } - - createTargetFile(testFileNamesToRun.join('\n')); - - const end = Date.now(); - - const testFilesToRunWithFilteredDeps = testFilesToRun.map(({ file, deps }) => ({ - file, - deps: deps.filter(isDepChanged), - })); - - console.log('Total time: ', ((end - start) / 1_000).toLocaleString()); - console.log('Total test to run: ', testFileNamesToRun.length); - console.log('Tests to run with changed deps: ', testFilesToRunWithFilteredDeps); - console.log('Non existent deps: ', NON_EXISTENT_DEPS); -} - -run(); diff --git a/deploy/tools/affected-tests/package.json b/deploy/tools/affected-tests/package.json deleted file mode 100644 index a34f145916c..00000000000 --- a/deploy/tools/affected-tests/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "affected-tests", - "version": "1.0.0", - "main": "index.js", - "dependencies": { - "dependency-tree": "10.0.9" - } -} diff --git a/deploy/tools/assets-downloader/.gitignore b/deploy/tools/assets-downloader/.gitignore new file mode 100644 index 00000000000..8225baa4a77 --- /dev/null +++ b/deploy/tools/assets-downloader/.gitignore @@ -0,0 +1,2 @@ +/node_modules +/dist diff --git a/deploy/tools/assets-downloader/assets.ts b/deploy/tools/assets-downloader/assets.ts new file mode 100644 index 00000000000..438bf051580 --- /dev/null +++ b/deploy/tools/assets-downloader/assets.ts @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +export type AssetKind = 'json-array' | 'json-object' | 'image' | 'html'; + +export interface AssetEnv { + readonly envName: string; + readonly kind: AssetKind; +} + +export const ASSET_ENVS: ReadonlyArray<AssetEnv> = [ + { envName: 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', kind: 'json-array' }, + { envName: 'NEXT_PUBLIC_MARKETPLACE_CATEGORIES_URL', kind: 'json-array' }, + { envName: 'NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL', kind: 'html' }, + { envName: 'NEXT_PUBLIC_MARKETPLACE_GRAPH_LINKS_URL', kind: 'json-object' }, + { envName: 'NEXT_PUBLIC_FEATURED_NETWORKS', kind: 'json-array' }, + { envName: 'NEXT_PUBLIC_FOOTER_LINKS', kind: 'json-array' }, + { envName: 'NEXT_PUBLIC_NETWORK_LOGO', kind: 'image' }, + { envName: 'NEXT_PUBLIC_NETWORK_LOGO_DARK', kind: 'image' }, + { envName: 'NEXT_PUBLIC_NETWORK_ICON', kind: 'image' }, + { envName: 'NEXT_PUBLIC_NETWORK_ICON_DARK', kind: 'image' }, + { envName: 'NEXT_PUBLIC_OG_IMAGE_URL', kind: 'image' }, + { envName: 'NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL', kind: 'json-object' }, + { envName: 'NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', kind: 'json-array' }, + { envName: 'NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG', kind: 'json-array' }, +]; diff --git a/deploy/tools/assets-downloader/content.spec.ts b/deploy/tools/assets-downloader/content.spec.ts new file mode 100644 index 00000000000..adf5fd89641 --- /dev/null +++ b/deploy/tools/assets-downloader/content.spec.ts @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { checkAssetContent, detectImageType } from './content'; + +const PNG = Buffer.from([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d ]); +const JPEG = Buffer.from([ 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10 ]); +const GIF = Buffer.from('GIF89a\x01\x00\x01\x00', 'latin1'); +const WEBP = Buffer.concat([ Buffer.from('RIFF'), Buffer.from([ 0x24, 0, 0, 0 ]), Buffer.from('WEBP'), Buffer.from('VP8 ') ]); +const ftyp = (majorBrand: string, ...compatibleBrands: Array<string>) => Buffer.concat([ + Buffer.from([ 0, 0, 0, 16 + compatibleBrands.length * 4 ]), + Buffer.from(`ftyp${ majorBrand }`), + Buffer.alloc(4), + ...compatibleBrands.map((brand) => Buffer.from(brand)), +]); +const AVIF = ftyp('avif', 'mif1'); +const AVIF_MIF1_MAJOR = ftyp('mif1', 'miaf', 'avif'); +const AVIF_SEQUENCE = ftyp('msf1', 'avis', 'miaf'); +const AVIF_UNSIZED_FTYP_BOX = Buffer.concat([ Buffer.alloc(4), Buffer.from('ftyp'), Buffer.from('mif1'), Buffer.alloc(4), Buffer.from('avif') ]); +const HEIC_FOLLOWED_BY_AVIF_BYTES = Buffer.concat([ ftyp('heic', 'mif1'), Buffer.from('avif') ]); +const ICO = Buffer.from([ 0x00, 0x00, 0x01, 0x00, 0x01, 0x00 ]); +const SVG = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"></svg>'); +const SVG_WITH_PROLOGUE = Buffer.from('<?xml version="1.0" encoding="UTF-8"?>\n<!-- logo -->\n<svg xmlns="http://www.w3.org/2000/svg"/>'); +const SVG_WITH_LEADING_COMMENT = Buffer.from('<!-- logo -->\n<svg xmlns="http://www.w3.org/2000/svg"/>'); +const SVG_WITH_DOCTYPE = Buffer.from('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n<svg/>'); +const SVG_UPPERCASE = Buffer.from('<SVG xmlns="http://www.w3.org/2000/svg"></SVG>'); + +describe('detectImageType', () => { + it.each([ + [ 'png', PNG ], + [ 'jpeg', JPEG ], + [ 'gif', GIF ], + [ 'gif', Buffer.from('GIF87a\x01\x00\x01\x00', 'latin1') ], + [ 'webp', WEBP ], + [ 'avif', AVIF ], + [ 'avif', AVIF_MIF1_MAJOR ], + [ 'avif', AVIF_SEQUENCE ], + [ 'avif', AVIF_UNSIZED_FTYP_BOX ], + [ 'ico', ICO ], + [ 'svg', SVG ], + [ 'svg', SVG_WITH_PROLOGUE ], + [ 'svg', SVG_WITH_LEADING_COMMENT ], + [ 'svg', SVG_WITH_DOCTYPE ], + [ 'svg', SVG_UPPERCASE ], + ])('detects %s', (type, buffer) => { + expect(detectImageType(buffer)).toBe(type); + }); + + it.each([ + [ 'JSON', Buffer.from('{"type":"shamir","sealed":false}') ], + [ 'HTML', Buffer.from('<!DOCTYPE html><html><body>Moved</body></html>') ], + [ 'XML without svg', Buffer.from('<?xml version="1.0"?><root/>') ], + [ 'XML whose svg element is not the root', Buffer.from('<root><svg/></root>') ], + [ 'element whose name merely starts with svg', Buffer.from('<svgfoo/>') ], + [ 'HEIC (ftyp without an AVIF brand)', ftyp('heic', 'mif1', 'heic') ], + [ 'HEIC whose next box happens to start with avif', HEIC_FOLLOWED_BY_AVIF_BYTES ], + [ 'plain text', Buffer.from('root:x:0:0:root:/root:/bin/sh') ], + [ 'RIFF container that is not WEBP', Buffer.concat([ Buffer.from('RIFF'), Buffer.from([ 0x24, 0, 0, 0 ]), Buffer.from('WAVE') ]) ], + [ 'empty', Buffer.alloc(0) ], + ])('rejects %s', (name, buffer) => { + expect(detectImageType(buffer)).toBeUndefined(); + }); +}); + +describe('checkAssetContent', () => { + describe('json-array', () => { + it('accepts a JSON array', () => { + expect(checkAssetContent('json-array', Buffer.from('[{"title":"Foo"}]'), 'json')).toEqual({ ok: true }); + }); + + it('rejects a JSON object', () => { + expect(checkAssetContent('json-array', Buffer.from('{"type":"shamir","sealed":false}'), 'json')) + .toEqual({ ok: false, reason: 'content is not a JSON array' }); + }); + + it('rejects invalid JSON', () => { + expect(checkAssetContent('json-array', Buffer.from('<html>Moved Permanently</html>'), 'json')) + .toEqual({ ok: false, reason: 'content is not valid JSON' }); + }); + }); + + describe('json-object', () => { + it('accepts a JSON object', () => { + expect(checkAssetContent('json-object', Buffer.from('{"0x1":[{"title":"a","url":"b"}]}'), 'json')).toEqual({ ok: true }); + }); + + it.each([ + [ 'array', '[]' ], + [ 'null', 'null' ], + [ 'string', '"text"' ], + ])('rejects a JSON %s', (name, content) => { + expect(checkAssetContent('json-object', Buffer.from(content), 'json')) + .toEqual({ ok: false, reason: 'content is not a JSON object' }); + }); + }); + + describe('image', () => { + it('accepts an image whose type matches the file extension', () => { + expect(checkAssetContent('image', PNG, 'png')).toEqual({ ok: true }); + expect(checkAssetContent('image', JPEG, 'jpg')).toEqual({ ok: true }); + expect(checkAssetContent('image', JPEG, 'jpeg')).toEqual({ ok: true }); + expect(checkAssetContent('image', SVG, 'svg')).toEqual({ ok: true }); + }); + + it('accepts any supported image when the file has no extension', () => { + expect(checkAssetContent('image', WEBP, undefined)).toEqual({ ok: true }); + }); + + it('rejects a non-image', () => { + expect(checkAssetContent('image', Buffer.from('{"type":"shamir","sealed":false}'), 'svg')) + .toEqual({ ok: false, reason: 'content is not a supported image (svg, png, jpg, jpeg, gif, webp, ico, avif)' }); + }); + + it('rejects an image whose type does not match the file extension', () => { + expect(checkAssetContent('image', PNG, 'svg')) + .toEqual({ ok: false, reason: 'content is a png image but the URL points to a ".svg" file' }); + }); + + it('rejects an unsupported image extension', () => { + expect(checkAssetContent('image', PNG, 'bmp')) + .toEqual({ ok: false, reason: '".bmp" is not a supported image extension (svg, png, jpg, jpeg, gif, webp, ico, avif)' }); + }); + }); + + it('accepts anything for html', () => { + expect(checkAssetContent('html', Buffer.from('<div>banner</div>'), undefined)).toEqual({ ok: true }); + expect(checkAssetContent('html', Buffer.alloc(0), 'html')).toEqual({ ok: true }); + }); +}); diff --git a/deploy/tools/assets-downloader/content.ts b/deploy/tools/assets-downloader/content.ts new file mode 100644 index 00000000000..27eab510c3f --- /dev/null +++ b/deploy/tools/assets-downloader/content.ts @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { AssetKind } from './assets'; + +export type ImageType = 'svg' | 'png' | 'jpeg' | 'gif' | 'webp' | 'ico' | 'avif'; + +export type ContentCheck = { readonly ok: true } | { readonly ok: false; readonly reason: string }; + +const IMAGE_TYPE_BY_EXTENSION: Readonly<Record<string, ImageType>> = { + svg: 'svg', + png: 'png', + jpg: 'jpeg', + jpeg: 'jpeg', + gif: 'gif', + webp: 'webp', + ico: 'ico', + avif: 'avif', +}; + +const SUPPORTED_IMAGES = 'svg, png, jpg, jpeg, gif, webp, ico, avif'; + +const PNG_SIGNATURE = '\x89PNG\r\n\x1a\n'; +const JPEG_SIGNATURE = '\xff\xd8\xff'; +const ICO_SIGNATURE = '\x00\x00\x01\x00'; +const SVG_SNIFF_LENGTH = 1024; + +const startsWith = (buffer: Buffer, signature: string, offset = 0): boolean => { + const expected = Buffer.from(signature, 'latin1'); + return buffer.subarray(offset, offset + expected.length).equals(expected); +}; + +const SVG_PREAMBLE = /^(?:\s|<\?xml[\s\S]*?\?>|<!--[\s\S]*?-->|<!DOCTYPE[\s\S]*?>)*/i; +const SVG_ROOT_TAG = /^<svg[\s>/]/i; + +const isSvg = (buffer: Buffer): boolean => { + const head = buffer.subarray(0, SVG_SNIFF_LENGTH).toString('utf8').replace(SVG_PREAMBLE, ''); + return SVG_ROOT_TAG.test(head); +}; + +const AVIF_BRANDS: ReadonlySet<string> = new Set([ 'avif', 'avis' ]); +const FTYP_BOX_TYPE_OFFSET = 4; +const FTYP_MAJOR_BRAND_OFFSET = 8; +const FTYP_COMPATIBLE_BRANDS_OFFSET = 16; +const BRAND_LENGTH = 4; + +const ftypBrands = (buffer: Buffer): Array<string> => { + if (!startsWith(buffer, 'ftyp', FTYP_BOX_TYPE_OFFSET)) { + return []; + } + const boxEnd = Math.min(buffer.length, buffer.readUInt32BE(0) || buffer.length); + const brand = (offset: number) => buffer.subarray(offset, offset + BRAND_LENGTH).toString('latin1'); + const brands = [ brand(FTYP_MAJOR_BRAND_OFFSET) ]; + for (let offset = FTYP_COMPATIBLE_BRANDS_OFFSET; offset + BRAND_LENGTH <= boxEnd; offset += BRAND_LENGTH) { + brands.push(brand(offset)); + } + return brands; +}; + +const isAvif = (buffer: Buffer): boolean => ftypBrands(buffer).some((brand) => AVIF_BRANDS.has(brand)); + +export function detectImageType(buffer: Buffer): ImageType | undefined { + if (startsWith(buffer, PNG_SIGNATURE)) { + return 'png'; + } + if (startsWith(buffer, JPEG_SIGNATURE)) { + return 'jpeg'; + } + if (startsWith(buffer, 'GIF87a') || startsWith(buffer, 'GIF89a')) { + return 'gif'; + } + if (startsWith(buffer, 'RIFF') && startsWith(buffer, 'WEBP', 8)) { + return 'webp'; + } + if (isAvif(buffer)) { + return 'avif'; + } + if (startsWith(buffer, ICO_SIGNATURE)) { + return 'ico'; + } + if (isSvg(buffer)) { + return 'svg'; + } + return undefined; +} + +type ParsedJson = { readonly ok: true; readonly value: unknown } | { readonly ok: false }; + +const parseJson = (buffer: Buffer): ParsedJson => { + try { + return { ok: true, value: JSON.parse(buffer.toString('utf8')) }; + } catch { + return { ok: false }; + } +}; + +const fail = (reason: string): ContentCheck => ({ ok: false, reason }); +const PASS: ContentCheck = { ok: true }; + +function checkJson(buffer: Buffer, expected: 'array' | 'object'): ContentCheck { + const parsed = parseJson(buffer); + if (!parsed.ok) { + return fail('content is not valid JSON'); + } + const isArray = Array.isArray(parsed.value); + const isObject = typeof parsed.value === 'object' && parsed.value !== null && !isArray; + if (expected === 'array' && !isArray) { + return fail('content is not a JSON array'); + } + if (expected === 'object' && !isObject) { + return fail('content is not a JSON object'); + } + return PASS; +} + +function checkImage(buffer: Buffer, fileExtension: string | undefined): ContentCheck { + const detected = detectImageType(buffer); + if (!detected) { + return fail(`content is not a supported image (${ SUPPORTED_IMAGES })`); + } + if (fileExtension === undefined) { + return PASS; + } + const expected = IMAGE_TYPE_BY_EXTENSION[fileExtension]; + if (expected === undefined) { + return fail(`".${ fileExtension }" is not a supported image extension (${ SUPPORTED_IMAGES })`); + } + if (expected !== detected) { + return fail(`content is a ${ detected } image but the URL points to a ".${ fileExtension }" file`); + } + return PASS; +} + +export function checkAssetContent(kind: AssetKind, buffer: Buffer, fileExtension: string | undefined): ContentCheck { + switch (kind) { + case 'json-array': + return checkJson(buffer, 'array'); + case 'json-object': + return checkJson(buffer, 'object'); + case 'image': + return checkImage(buffer, fileExtension); + case 'html': + return PASS; + } +} diff --git a/deploy/tools/assets-downloader/download.spec.ts b/deploy/tools/assets-downloader/download.spec.ts new file mode 100644 index 00000000000..6d3de3d624e --- /dev/null +++ b/deploy/tools/assets-downloader/download.spec.ts @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import type { DownloadOptions } from './download'; +import { downloadAssets } from './download'; + +const PNG = Buffer.from([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d ]); +const SVG = '<svg xmlns="http://www.w3.org/2000/svg"></svg>'; +const VAULT_SEAL_STATUS = '{"type":"shamir","sealed":false,"initialized":true}'; + +type Responder = (url: string, attempt: number) => Response; + +let assetsDir: string; +let sourceDir: string; + +const fetchWith = (responder: Responder): typeof globalThis.fetch => { + const attempts = new Map<string, number>(); + const fetchDouble: typeof globalThis.fetch = async(input, init) => { + const url = input instanceof URL ? input.href : String(input); + const attempt = (attempts.get(url) ?? 0) + 1; + attempts.set(url, attempt); + const response = responder(url, attempt); + const location = response.headers.get('location'); + return location !== null && init?.redirect !== 'manual' ? fetchDouble(location, init) : response; + }; + return fetchDouble; +}; + +const routes = (table: ReadonlyArray<[ string, () => Response ]> = []): typeof globalThis.fetch => fetchWith((url) => { + const respond = table.find(([ route ]) => route === url)?.[1]; + return respond ? respond() : new Response('not found', { status: 404 }); +}); + +const run = async(envs: DownloadOptions['envs'], fetch: typeof globalThis.fetch = routes()) => { + const lines: Array<string> = []; + const report = await downloadAssets({ envs, assetsDir, fetch, retryDelay: 0, log: (line) => lines.push(line) }); + const failureLine = lines.find((line) => line.includes('[-]')); + return { ...report, lines, failureLine, files: (await readdir(assetsDir)).sort() }; +}; + +beforeEach(async() => { + assetsDir = await mkdtemp(join(tmpdir(), 'assets-downloader-out-')); + sourceDir = await mkdtemp(join(tmpdir(), 'assets-downloader-src-')); +}); + +afterEach(async() => { + await rm(assetsDir, { recursive: true, force: true }); + await rm(sourceDir, { recursive: true, force: true }); +}); + +describe('downloadAssets', () => { + it('skips unset variables and reports nothing saved', async() => { + const result = await run({ NEXT_PUBLIC_NETWORK_LOGO: '' }); + + expect(result).toMatchObject({ saved: [], failed: [], files: [] }); + expect(result.lines).toContain(' [.] NEXT_PUBLIC_NETWORK_LOGO: Variable is not set. Skipping download.'); + }); + + it('saves a fetched asset under the file name the app will request', async() => { + const fetch = routes([ + [ 'https://example.com/images/Logo.PNG?v=2', () => new Response(PNG) ], + [ 'https://example.com/config.json', () => new Response('[{"id":"app"}]') ], + ]); + + const result = await run({ + NEXT_PUBLIC_NETWORK_LOGO: 'https://example.com/images/Logo.PNG?v=2', + NEXT_PUBLIC_MARKETPLACE_CONFIG_URL: 'https://example.com/config.json', + }, fetch); + + expect(result.failed).toEqual([]); + expect(result.saved).toEqual([ 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', 'NEXT_PUBLIC_NETWORK_LOGO' ]); + expect(result.files).toEqual([ 'marketplace_config.json', 'network_logo.png' ]); + expect(await readFile(join(assetsDir, 'network_logo.png'))).toEqual(PNG); + expect(result.lines).toContain( + ` [+] NEXT_PUBLIC_NETWORK_LOGO: Successfully saved file from https://example.com/images/Logo.PNG?v=2 to ${ join(assetsDir, 'network_logo.png') }.`, + ); + }); + + it('saves an image without a file extension under the bare name', async() => { + const fetch = routes([ [ 'https://imagedelivery.net/abc/390b3c31/public', () => new Response(SVG) ] ]); + + const result = await run({ NEXT_PUBLIC_NETWORK_ICON: 'https://imagedelivery.net/abc/390b3c31/public' }, fetch); + + expect(result.files).toEqual([ 'network_icon' ]); + }); + + it('copies a file:// asset', async() => { + const filePath = join(sourceDir, 'links.json'); + await writeFile(filePath, '[{"title":"Docs"}]'); + + const result = await run({ NEXT_PUBLIC_FOOTER_LINKS: pathToFileURL(filePath).href }); + + expect(result.saved).toEqual([ 'NEXT_PUBLIC_FOOTER_LINKS' ]); + expect(await readFile(join(assetsDir, 'footer_links.json'), 'utf8')).toBe('[{"title":"Docs"}]'); + }); + + it('writes a raw JSON value as a json file with double quotes', async() => { + const result = await run({ NEXT_PUBLIC_FEATURED_NETWORKS: `[{'title':'Astar','url':'https://astar.blockscout.com/'}]` }); + + expect(result.files).toEqual([ 'featured_networks.json' ]); + expect(await readFile(join(assetsDir, 'featured_networks.json'), 'utf8')).toBe('[{"title":"Astar","url":"https://astar.blockscout.com/"}]'); + }); + + it('does not save a JSON config whose content is not the expected shape', async() => { + const fetch = routes([ [ 'http://10.42.4.28:8200/v1/sys/seal-status', () => new Response(VAULT_SEAL_STATUS) ] ]); + + const result = await run({ NEXT_PUBLIC_FEATURED_NETWORKS: 'http://10.42.4.28:8200/v1/sys/seal-status' }, fetch); + + expect(result.failed).toEqual([ 'NEXT_PUBLIC_FEATURED_NETWORKS' ]); + expect(result.files).toEqual([]); + expect(result.lines).toContain( + ' [-] NEXT_PUBLIC_FEATURED_NETWORKS: rejected content from http://10.42.4.28:8200/v1/sys/seal-status: content is not a JSON array', + ); + }); + + it('does not save a file:// asset whose content is not an image', async() => { + const filePath = join(sourceDir, 'passwd'); + await writeFile(filePath, 'root:x:0:0:root:/root:/bin/sh\n'); + + const result = await run({ NEXT_PUBLIC_NETWORK_LOGO: pathToFileURL(filePath).href }); + + expect(result.failed).toEqual([ 'NEXT_PUBLIC_NETWORK_LOGO' ]); + expect(result.files).toEqual([]); + expect(result.failureLine).toMatch(/^ {3}\[-\] NEXT_PUBLIC_NETWORK_LOGO: rejected content from file:\/\/.*: content is not a supported image/); + }); + + it('fails a missing file:// asset', async() => { + const result = await run({ NEXT_PUBLIC_FOOTER_LINKS: pathToFileURL(join(sourceDir, 'missing.json')).href }); + + expect(result.failed).toEqual([ 'NEXT_PUBLIC_FOOTER_LINKS' ]); + expect(result.failureLine).toMatch(/^ {3}\[-\] NEXT_PUBLIC_FOOTER_LINKS: unable to read from file:\/\/.*missing\.json: ENOENT/); + }); + + it('fails a raw value that is neither a URL nor JSON', async() => { + const result = await run({ NEXT_PUBLIC_FEATURED_NETWORKS: 'not a url' }); + + expect(result.failed).toEqual([ 'NEXT_PUBLIC_FEATURED_NETWORKS' ]); + expect(result.lines).toContain(' [-] NEXT_PUBLIC_FEATURED_NETWORKS: value is neither a URL nor a JSON document'); + }); + + it.each([ 300, 302, 399 ])('does not follow a redirect (HTTP %i)', async(status) => { + const fetch = routes([ + [ 'https://example.com/logo.svg', () => new Response(null, { status, headers: { location: 'http://10.43.0.1/' } }) ], + [ 'http://10.43.0.1/', () => new Response(SVG) ], + ]); + + const result = await run({ NEXT_PUBLIC_NETWORK_LOGO: 'https://example.com/logo.svg' }, fetch); + + expect(result.failed).toEqual([ 'NEXT_PUBLIC_NETWORK_LOGO' ]); + expect(result.lines).toContain( + ` [-] NEXT_PUBLIC_NETWORK_LOGO: unable to read from https://example.com/logo.svg: redirect (HTTP ${ status }) to "http://10.43.0.1/" is not followed`, + ); + }); + + it('retries a transient server error and saves the eventual response', async() => { + const fetch = fetchWith((url, attempt) => attempt < 3 ? new Response('busy', { status: 503 }) : new Response(SVG)); + + const result = await run({ NEXT_PUBLIC_NETWORK_LOGO: 'https://example.com/logo.svg' }, fetch); + + expect(result.saved).toEqual([ 'NEXT_PUBLIC_NETWORK_LOGO' ]); + expect(result.files).toEqual([ 'network_logo.svg' ]); + }); + + it('succeeds on the last retry attempt', async() => { + const fetch = fetchWith((url, attempt) => attempt < 4 ? new Response('busy', { status: 503 }) : new Response(SVG)); + + const result = await run({ NEXT_PUBLIC_NETWORK_LOGO: 'https://example.com/logo.svg' }, fetch); + + expect(result.saved).toEqual([ 'NEXT_PUBLIC_NETWORK_LOGO' ]); + }); + + it('gives up after the retry budget on a persistent error', async() => { + let calls = 0; + const fetch = fetchWith(() => { + calls++; + return new Response('busy', { status: 503 }); + }); + + const result = await run({ NEXT_PUBLIC_NETWORK_LOGO: 'https://example.com/logo.svg' }, fetch); + + expect(calls).toBe(4); + expect(result.failed).toEqual([ 'NEXT_PUBLIC_NETWORK_LOGO' ]); + expect(result.lines).toContain( + ' [-] NEXT_PUBLIC_NETWORK_LOGO: unable to read from https://example.com/logo.svg: failed after 3 retry attempts (HTTP 503)', + ); + }); + + it.each([ 400, 404 ])('does not retry a client error (HTTP %i)', async(status) => { + let calls = 0; + const fetch = fetchWith(() => { + calls++; + return new Response('gone', { status }); + }); + + const result = await run({ NEXT_PUBLIC_NETWORK_LOGO: 'https://example.com/logo.svg' }, fetch); + + expect(result.failed).toEqual([ 'NEXT_PUBLIC_NETWORK_LOGO' ]); + expect(calls).toBe(1); + expect(result.lines).toContain(` [-] NEXT_PUBLIC_NETWORK_LOGO: unable to read from https://example.com/logo.svg: HTTP ${ status }`); + }); + + it('retries a network error', async() => { + const fetch = fetchWith((url, attempt) => { + if (attempt === 1) { + throw new TypeError('fetch failed'); + } + return new Response(SVG); + }); + + const result = await run({ NEXT_PUBLIC_NETWORK_LOGO: 'https://example.com/logo.svg' }, fetch); + + expect(result.saved).toEqual([ 'NEXT_PUBLIC_NETWORK_LOGO' ]); + }); + + it('keeps saving the other assets when one fails', async() => { + const fetch = routes([ + [ 'https://example.com/logo.svg', () => new Response(VAULT_SEAL_STATUS) ], + [ 'https://example.com/icon.png', () => new Response(PNG) ], + ]); + + const result = await run({ + NEXT_PUBLIC_NETWORK_LOGO: 'https://example.com/logo.svg', + NEXT_PUBLIC_NETWORK_ICON: 'https://example.com/icon.png', + }, fetch); + + expect(result.failed).toEqual([ 'NEXT_PUBLIC_NETWORK_LOGO' ]); + expect(result.saved).toEqual([ 'NEXT_PUBLIC_NETWORK_ICON' ]); + expect(result.files).toEqual([ 'network_icon.png' ]); + }); +}); diff --git a/deploy/tools/assets-downloader/download.ts b/deploy/tools/assets-downloader/download.ts new file mode 100644 index 00000000000..505c7fb7c75 --- /dev/null +++ b/deploy/tools/assets-downloader/download.ts @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { basename, extname, join } from 'node:path'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { fileURLToPath } from 'node:url'; + +import { buildExternalAssetFilePath } from 'src/config/utils/envs'; + +import { SECOND } from 'src/toolkit/utils/consts'; + +import type { AssetEnv } from './assets'; +import { ASSET_ENVS } from './assets'; +import { checkAssetContent } from './content'; + +const RETRY_ATTEMPTS = 3; +const REQUEST_TIMEOUT = 60 * SECOND; +const RETRYABLE_STATUSES: ReadonlySet<number> = new Set([ 408, 429, 500, 502, 503, 504 ]); + +export const DEFAULT_RETRY_DELAY = 3 * SECOND; + +export interface DownloadOptions { + readonly envs: Readonly<Record<string, string | undefined>>; + readonly assetsDir: string; + readonly fetch: typeof globalThis.fetch; + readonly retryDelay: number; + readonly log: (line: string) => void; +} + +export interface DownloadReport { + readonly saved: ReadonlyArray<string>; + readonly failed: ReadonlyArray<string>; +} + +interface RemoteSource { readonly type: 'url'; readonly url: URL } +interface LocalFileSource { readonly type: 'local-file'; readonly url: URL } +interface RawJsonSource { readonly type: 'raw-json' } +type AssetSource = RemoteSource | LocalFileSource | RawJsonSource; + +type ReadResult = { readonly ok: true; readonly content: Buffer } | { readonly ok: false; readonly reason: string }; + +class NonRetryableError extends Error {} + +const parseUrl = (value: string): URL | undefined => { + try { + return new URL(value); + } catch { + return undefined; + } +}; + +const resolveSource = (value: string): AssetSource => { + const url = parseUrl(value); + if (!url) { + return { type: 'raw-json' }; + } + return url.protocol === 'file:' ? { type: 'local-file', url } : { type: 'url', url }; +}; + +const describeSource = (source: AssetSource): string => source.type === 'raw-json' ? 'raw input' : source.url.href; + +const isRedirect = (status: number): boolean => status >= 300 && status < 400; + +const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error); + +async function fetchOnce(url: URL, fetch: typeof globalThis.fetch): Promise<Buffer> { + const response = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(REQUEST_TIMEOUT) }); + if (isRedirect(response.status)) { + throw new NonRetryableError(`redirect (HTTP ${ response.status }) to "${ response.headers.get('location') ?? '' }" is not followed`); + } + if (!response.ok) { + const message = `HTTP ${ response.status }`; + throw RETRYABLE_STATUSES.has(response.status) ? new Error(message) : new NonRetryableError(message); + } + return Buffer.from(await response.arrayBuffer()); +} + +async function fetchWithRetries(url: URL, options: DownloadOptions): Promise<ReadResult> { + let lastError: unknown; + for (let attempt = 0; attempt <= RETRY_ATTEMPTS; attempt++) { + // Stryker disable next-line ConditionalExpression,EqualityOperator: only skips the delay before attempt 0; with retryDelay 0 an extra sleep is unobservable + if (attempt > 0) { + await sleep(options.retryDelay); + } + try { + return { ok: true, content: await fetchOnce(url, options.fetch) }; + } catch (error) { + if (error instanceof NonRetryableError) { + return { ok: false, reason: error.message }; + } + lastError = error; + } + } + return { ok: false, reason: `failed after ${ RETRY_ATTEMPTS } retry attempts (${ errorMessage(lastError) })` }; +} + +async function readLocalFile(url: URL): Promise<ReadResult> { + try { + return { ok: true, content: await readFile(fileURLToPath(url)) }; + } catch (error) { + return { ok: false, reason: errorMessage(error) }; + } +} + +function readContent(source: AssetSource, value: string, options: DownloadOptions): Promise<ReadResult> { + switch (source.type) { + case 'url': + return fetchWithRetries(source.url, options); + case 'local-file': + return readLocalFile(source.url); + case 'raw-json': + return Promise.resolve({ ok: true, content: Buffer.from(value, 'utf8') }); + } +} + +const fileExtensionOf = (fileName: string): string | undefined => extname(fileName).slice(1) || undefined; + +async function processAsset(asset: AssetEnv, value: string, options: DownloadOptions): Promise<ReadResult> { + const normalizedValue = value.replaceAll('\'', '"'); + const source = resolveSource(normalizedValue); + const assetPath = buildExternalAssetFilePath(asset.envName, normalizedValue); + if (assetPath === undefined) { + return { ok: false, reason: 'value is neither a URL nor a JSON document' }; + } + const fileName = basename(assetPath); + + const result = await readContent(source, normalizedValue, options); + if (!result.ok) { + return { ok: false, reason: `unable to read from ${ describeSource(source) }: ${ result.reason }` }; + } + + const check = checkAssetContent(asset.kind, result.content, fileExtensionOf(fileName)); + if (!check.ok) { + return { ok: false, reason: `rejected content from ${ describeSource(source) }: ${ check.reason }` }; + } + + const destination = join(options.assetsDir, fileName); + await writeFile(destination, result.content); + options.log(` [+] ${ asset.envName }: Successfully saved file from ${ describeSource(source) } to ${ destination }.`); + return result; +} + +export async function downloadAssets(options: DownloadOptions): Promise<DownloadReport> { + await mkdir(options.assetsDir, { recursive: true }); + const saved: Array<string> = []; + const failed: Array<string> = []; + + for (const asset of ASSET_ENVS) { + const value = options.envs[asset.envName]; + if (!value) { + options.log(` [.] ${ asset.envName }: Variable is not set. Skipping download.`); + continue; + } + const result = await processAsset(asset, value, options); + if (result.ok) { + saved.push(asset.envName); + } else { + failed.push(asset.envName); + options.log(` [-] ${ asset.envName }: ${ result.reason }`); + } + } + + return { saved, failed }; +} diff --git a/deploy/tools/assets-downloader/index.ts b/deploy/tools/assets-downloader/index.ts new file mode 100644 index 00000000000..acc0c1174de --- /dev/null +++ b/deploy/tools/assets-downloader/index.ts @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { DEFAULT_RETRY_DELAY, downloadAssets } from './download'; + +main(); + +async function main(): Promise<void> { + const assetsDir = process.argv[2]; + if (!assetsDir || process.argv.length !== 3) { + console.log('🛑 Error: incorrect amount of arguments. Usage: node index.js <ASSETS_DIR>.'); + process.exit(1); + } + + console.log(''); + console.log('⬇️ Downloading external assets...'); + + try { + const report = await downloadAssets({ + envs: process.env, + assetsDir, + fetch: globalThis.fetch, + retryDelay: DEFAULT_RETRY_DELAY, + log: console.log, + }); + if (report.failed.length > 0) { + console.log(`🛑 Error: ${ report.failed.length } asset download(s) failed. The application cannot start.`); + process.exit(1); + } + console.log('✅ Done.'); + console.log(''); + } catch (error) { + console.log('🚨 Unexpected error occurred while downloading assets.'); + console.error(error); + process.exit(1); + } +} diff --git a/deploy/tools/assets-downloader/package.json b/deploy/tools/assets-downloader/package.json new file mode 100644 index 00000000000..90a95f92317 --- /dev/null +++ b/deploy/tools/assets-downloader/package.json @@ -0,0 +1,15 @@ +{ + "name": "assets-downloader", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "dist/index.js", + "scripts": { + "build": "vite build --logLevel error", + "download": "node ./dist/index.js" + }, + "devDependencies": { + "@types/node": "24.13.4", + "vite": "8.3.5" + } +} diff --git a/deploy/tools/assets-downloader/vite.config.ts b/deploy/tools/assets-downloader/vite.config.ts new file mode 100644 index 00000000000..f2b82577bb7 --- /dev/null +++ b/deploy/tools/assets-downloader/vite.config.ts @@ -0,0 +1,28 @@ +import { resolve } from 'path'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + build: { + lib: { + entry: { + index: resolve(__dirname, 'index.ts'), + }, + formats: [ 'es' ], + fileName: (format, entryName) => `${ entryName }.js`, + }, + rolldownOptions: { + external: [ 'node:url', 'node:path', 'node:fs/promises', 'node:timers/promises' ], + output: { + dir: 'dist', + entryFileNames: '[name].js', + chunkFileNames: '[name].js', + assetFileNames: '[name].[ext]', + }, + }, + }, + resolve: { + alias: { + src: resolve(__dirname, '../../../src'), + }, + }, +}); diff --git a/deploy/tools/envs-validator/CONTEXT.md b/deploy/tools/envs-validator/CONTEXT.md index e23233f0b81..b0cf8401a29 100644 --- a/deploy/tools/envs-validator/CONTEXT.md +++ b/deploy/tools/envs-validator/CONTEXT.md @@ -1,150 +1,122 @@ # envs-validator — context -Validates the container's `NEXT_PUBLIC_*` environment against a [yup](https://github.com/jquense/yup) schema at +Validates the container's `NEXT_PUBLIC_*` environment against a [valibot](https://valibot.dev) schema at startup. -## Schemas +## Layout -- **`schema.ts`** — the default top-level schema; selected when - `NEXT_PUBLIC_MULTICHAIN_ENABLED` is unset or `false`. -- **`schema_multichain.ts`** — the multichain variant; selected when - `NEXT_PUBLIC_MULTICHAIN_ENABLED=true`. +- **`index.ts`** — the CLI the container runs: reads the environment, the placeholder registry and the + downloaded JSON configs, prints the report, sets the exit code. No rule lives here. +- **`checks.ts`** — the pure core (`runChecks`). Everything the CLI decides is decided here on pre-read + inputs, which is what the specs exercise. +- **`deprecations.ts`** — variables that only produce a startup warning. +- **`schema.ts`** — the default top-level schema; selected when `NEXT_PUBLIC_MULTICHAIN_ENABLED` is unset or + `false`. +- **`schema_multichain.ts`** — the multichain variant; selected when `NEXT_PUBLIC_MULTICHAIN_ENABLED=true`. +- **`schemas/`** — the sub-schemas the top-level ones are composed from; `schemas/app.ts` holds the entries + both top-level schemas share, `schemas/features/<name>.ts` one multi-variable feature each. +- **`utils.ts`** — the env-string parsers, the companion-variable rules and `composeSchemas`. +- **`mocks/`** — typed fixtures shared by the specs. `test-utils.ts` holds `toEnvValue`. + +The package is type-checked, linted and tested from the repo root like `src/`. Only the `vite` build is its +own: the Dockerfile ships `dist/index.js`. ## Adding a new variable -1. **Pick the rule's home** — see "Where to put the rule" below. If the - variable applies in both modes, mirror the rule in `schema.ts` and - `schema_multichain.ts`; otherwise update only the relevant one. +1. **Pick the rule's home** — see "Where to put the rule" below. If the variable applies in both modes, + put it in a sub-schema both top-level files compose (or in `schemas/app.ts`); otherwise update only + the relevant one. 2. **Write the rule** following the conventions in this file. -3. **Add it to a test preset under `test/`:** - - Default: append to `test/.env.base`. Most variables belong here. - - If the variable has alternative configurations that depend on other - variables (e.g. provider-specific add-ons for - `NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER`), use `test/.env.alt` to cover - the second shape. - - For larger, self-contained scenarios (ads, rollups, chain variants, - marketplace, …) it can make sense to add to or create a dedicated - `test/.env.<scenario>` preset. This is a judgement call, not a rule. - - **Multichain-only variable** → `test/.env.multichain` (validated - standalone, without `.env.common`). - - **JSON config URL variable** → also drop an example payload at - `test/assets/configs/<name>.json` (filename = the env name with - `NEXT_PUBLIC_` and `_URL` stripped, lowercased) and register the - variable in the `envsWithJsonConfig` array in `index.ts`. +3. **Test it in the sibling spec** (`schemas/features/<name>.spec.ts`, `schema.spec.ts`, …): one case + with an accepted value and one per rejection path asserting the exact message. A JSON-shaped value is a + typed object passed through `toEnvValue`, which produces the single-quoted form operators use. A + variable applying in both modes needs a line in both top-level specs. + - **JSON config URL variable** → register it in `ENVS_WITH_JSON_CONFIG` in `checks.ts`; at validation + time the variable carries the downloaded file content, not the URL, so the spec feeds it + `JSON.stringify(content)`. 4. **Run the suite:** ```bash - # from the tool directory - pnpm test - - # or from the repo root - pnpm --filter envs-validator test + pnpm test:vitest deploy/tools/envs-validator ``` - Each preset should end with `👍 All good!`. A failure prints the - aggregated yup errors for that preset — fix top-down, since later - errors can be downstream of earlier ones. - -5. **Verify the negative path.** The presets only exercise the happy - path, so the rule itself isn't proven until you see it reject bad - input. Temporarily edit the preset to violate the rule (wrong type, - missing companion variable, malformed JSON), re-run the suite, - confirm the expected error fires, then revert. + `docs.spec.ts` fails until the variable has a row in `docs/ENVS.md`. ## Conventions -Follow these when writing or modifying a rule — they're enforced by example -across the existing schemas, not by lint, so they're easy to miss. +Follow these when writing or modifying a rule — they're enforced by example across the existing schemas, +not by lint, so they're easy to miss. -### Use `urlTest`, not `yup.string().url()` +### Parse env strings with the helpers in `utils.ts` -Yup's built-in URL validator is intentionally disabled in this project -(`url(): never;` declared at the top of `schema.ts`). For any URL-shaped -value, attach the custom `urlTest` from `utils.ts`: +Every variable arrives as a string and valibot does not coerce, so a bare `v.boolean()` or `v.number()` +rejects every real value. Use the env parsers (`envBoolean`, `envNumber`, `envPositiveInteger`, `envUrl`, +`envRequiredString`, `envJson`) for top-level variables. *Inside* a JSON value the fields are real JS +types and take plain `v.string()` / `v.number()` / `v.boolean()`, with two exceptions: a field documented +as a decimal *string* (AdButler `width`/`height`) stays on `envNumber`, and a URL field is +`v.pipe(v.string(), v.url())`, which rejects `''` — `envUrl` is for top-level variables only. -```ts -NEXT_PUBLIC_SOMETHING_URL: yup.string().test(urlTest), -``` +The parsers are stricter than the app's tolerance on purpose: a boolean is only `true`/`false` (the app +reads `=== 'true'`, so `1` or `TRUE` would pass validation and silently mean *false*), and a number is a +plain decimal. -### JSON-shaped values: `.transform(replaceQuotes).json()` +`envUrl` accepts the empty string — operators unset a variable with `FOO=`, and the container turns a +missing value into `''` as well. `envBoolean`, `envNumber` and `envJson` reject it, as they always did, and +a companion rule treats `''` as "not provided". -A variable that carries a JSON object or array (read in app code via -`parseEnvJson`) must apply two transforms before any shape rules: +### JSON-shaped values: `envJson(schema)` -```ts -yup.object<MyType>().transform(replaceQuotes).json().shape({ … }) -``` +A variable carrying JSON (read in app code via `parseEnvJson`) wraps its value schema in `envJson`, which +does the single-quote → double-quote conversion and the parse. Nested problems are reported with a dot +path (`NEXT_PUBLIC_X.0.name: Invalid key …`), so there's no hand-written "invalid schema" message to +maintain. -`replaceQuotes` converts single quotes to double quotes so operators can -paste `'{"a":1}'` into a shell or `.env` file without escaping. `.json()` -then parses the resulting string. Omitting either step makes the -operator-facing single-quote syntax fail validation. - -### Companion variables: `.when(...)` with a guard - -When variable B is only meaningful if variable A is set, gate B on A and -forbid B in the otherwise-branch. The exact "forbid" test depends on the -value type: - -```ts -// Scalar B — assert it is undefined when A is unset. -NEXT_PUBLIC_B: yup.string().when('NEXT_PUBLIC_A', { - is: (value: string) => Boolean(value), - then: (schema) => schema.test(urlTest), - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_B can only be used with NEXT_PUBLIC_A', - value => value === undefined, - ), -}), - -// Array or string-length B — use max(-1) so even an empty value fails. -NEXT_PUBLIC_B: yup.array().when('NEXT_PUBLIC_A', { - is: true, - then: (schema) => schema, - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_B cannot be used without NEXT_PUBLIC_A'), -}), -``` +### Companion variables: `requires` / `requiredIf` on the object -`max(-1)` is used because an empty array still satisfies `=== undefined` -checks. See `tacSchema`, `beaconChainSchema`, and `marketplaceSchema` for -working examples. - -### Deeply-nested JSON: `yup.mixed().test('shape', …)` - -For JSON values with non-trivial nested shapes, don't inline `.shape({…})` -at the top level — yup's nested-object error messages are unhelpful. -Instead wrap the rule in `yup.mixed().test('shape', …)` and build the -real schema inside the test function: - -```ts -NEXT_PUBLIC_FOO: yup.mixed().test( - 'shape', - 'Invalid schema for NEXT_PUBLIC_FOO, it should have …', - (data) => { - const isUndefined = data === undefined; - const valueSchema = yup.object<Foo>().transform(replaceQuotes).json().shape({ - name: yup.string().required(), - url_template: yup.string().required(), - }); - return isUndefined || valueSchema.isValidSync(data); - }, -), -``` +"B only when A" is an object-level rule, not a per-field one — `schemas/features/tac.ts` is the smallest +example; `requires`, `requiredIf` and the general `companionRule` are in `utils.ts`. Two things about them +are not visible from a call site: `when` receives the *parsed* value of A (a flag is `true`/`false`, a +JSON list is an array), and the rule only runs once both variables are individually valid, so a malformed +A yields one error, not two. -This gives one clear, schema-author-controlled error message instead of -the auto-derived one. Existing examples: `NEXT_PUBLIC_GAS_REFUEL_PROVIDER_CONFIG`, -`NEXT_PUBLIC_ADDRESS_USERNAME_TAG`, the marketplace essential-dapps config. +A rule may name a variable declared in another schema file. Two things make that work, and both are easy +to miss: the sub-schema must be a `v.looseObject` (a plain `v.object` strips the foreign key before the +rule runs, and the rule then silently passes), and the rule sees that variable's raw string, not a parsed +value. The sub-schema spec passes the sibling key alongside; `schema.spec.ts` covers the composed case. + +### Composition: `composeSchemas` + +The two top-level schemas are `composeSchemas([...])` of the sub-schemas. Each sub-schema validates the +whole env map independently (that's what makes cross-file rules work); a variable unknown to all of them is +reported once, listing every unknown name. Entries that both top-level schemas need live in `schemas/app.ts` +— don't redeclare them in `schema.ts` or `schema_multichain.ts`. ### Where to put the rule -- **One-variable feature** (single flag or single URL) — declare it inline - in `schema.ts` under the run-time block. -- **Multi-variable feature** (two or more related variables, conditional - relationships, nested config) — create or extend a dedicated sub-schema - under `schemas/features/<name>.ts` and re-export it through +- **One-variable feature** (single flag or single URL) — declare it inline in `schema.ts`, in + `singleVariableFeaturesSchema`. +- **Multi-variable feature** (two or more related variables, conditional relationships, nested config) — + create or extend a dedicated sub-schema under `schemas/features/<name>.ts` and re-export it through `schemas/features/index.ts`. -There's an explicit comment in `schema.ts` codifying this split; don't -let the top-level schema grow a cluster of related vars. +Don't let the top-level schema grow a cluster of related vars. + +## Validating a real instance config by hand + +The CLI needs the bundle, the placeholder registry and the downloaded JSON configs the container has at +startup: + +```bash +cd deploy/tools/envs-validator +pnpm run build +../../scripts/collect_envs.sh ../../../docs/ENVS.md +pnpm exec dotenv -e /path/to/instance.env -- ../../scripts/download_assets.sh ./public/assets/configs +pnpm exec dotenv -e /path/to/instance.env -- pnpm run validate +``` + +`collect_envs.sh` writes `.env.registry` and `.env` next to the bundle; both are git-ignored. +Without the `download_assets.sh` step the CLI stops with `Unable to read file` (e.g. `featured_networks.json`) on a +fresh checkout; re-run it when the instance env changes. The script builds `deploy/tools/assets-downloader` on first +use. A failed or rejected download (e.g. a dead logo URL) makes it exit 1 after saving the rest; validate only needs +the JSON configs, so it still runs unless one of those failed. diff --git a/deploy/tools/envs-validator/checks.spec.ts b/deploy/tools/envs-validator/checks.spec.ts new file mode 100644 index 00000000000..151bf282bc4 --- /dev/null +++ b/deploy/tools/envs-validator/checks.spec.ts @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { + findDeprecationWarnings, + findEnvsWithoutPlaceholder, + pickAppEnvs, + runChecks, + substituteJsonConfigs, + validateEnvs, +} from './checks'; +import { DEPRECATED_ENVS } from './deprecations'; + +const MINIMAL_ENVS = { + NEXT_PUBLIC_APP_HOST: 'localhost', + NEXT_PUBLIC_API_HOST: 'blockscout.com', + NEXT_PUBLIC_NETWORK_NAME: 'Testnet', + NEXT_PUBLIC_NETWORK_ID: '1', +}; + +const MINIMAL_MULTICHAIN_ENVS = { + NEXT_PUBLIC_MULTICHAIN_ENABLED: 'true', + NEXT_PUBLIC_APP_HOST: 'localhost', + NEXT_PUBLIC_NETWORK_NAME: 'Testnet', +}; + +const registryOf = (envs: Record<string, string>) => Object.keys(envs); + +describe('pickAppEnvs', () => { + it('keeps only NEXT_PUBLIC_ variables and turns an unset value into an empty string', () => { + expect(pickAppEnvs({ NEXT_PUBLIC_A: 'a', NEXT_PUBLIC_B: undefined, PATH: '/bin', HOME: undefined })).toEqual({ + NEXT_PUBLIC_A: 'a', + NEXT_PUBLIC_B: '', + }); + }); +}); + +describe('findDeprecationWarnings', () => { + const deprecated = DEPRECATED_ENVS[0]; + + it('warns about a deprecated variable that is set, even to an empty string', () => { + expect(findDeprecationWarnings({ [deprecated.name]: '' })).toEqual([ deprecated.message ]); + }); + + it('returns nothing when no deprecated variable is set', () => { + expect(findDeprecationWarnings({ NEXT_PUBLIC_APP_HOST: 'localhost' })).toEqual([]); + }); +}); + +describe('findEnvsWithoutPlaceholder', () => { + it('lists the variables that are neither in the registry nor build-time', () => { + const envs = { NEXT_PUBLIC_A: '1', NEXT_PUBLIC_B: '2', NEXT_PUBLIC_C: '3', NEXT_PUBLIC_D: '4' }; + expect(findEnvsWithoutPlaceholder(envs, [ 'NEXT_PUBLIC_A' ], [ 'NEXT_PUBLIC_B' ])).toEqual([ 'NEXT_PUBLIC_C', 'NEXT_PUBLIC_D' ]); + }); + + it('returns nothing when every variable has a placeholder', () => { + expect(findEnvsWithoutPlaceholder({ NEXT_PUBLIC_A: '1' }, [ 'NEXT_PUBLIC_A' ], [])).toEqual([]); + }); +}); + +describe('substituteJsonConfigs', () => { + it('replaces the URL of a set JSON-config variable with the file content', () => { + const envs = { NEXT_PUBLIC_FOOTER_LINKS: 'https://example.com/links.json', NEXT_PUBLIC_APP_HOST: 'localhost' }; + expect(substituteJsonConfigs(envs, { NEXT_PUBLIC_FOOTER_LINKS: '[{"title":"Foo","links":[]}]' })).toEqual({ + NEXT_PUBLIC_FOOTER_LINKS: '[{"title":"Foo","links":[]}]', + NEXT_PUBLIC_APP_HOST: 'localhost', + }); + }); + + it('falls back to an empty array when the file content is missing or empty', () => { + const envs = { NEXT_PUBLIC_FOOTER_LINKS: 'https://example.com/links.json' }; + expect(substituteJsonConfigs(envs, {})).toEqual({ NEXT_PUBLIC_FOOTER_LINKS: '[]' }); + expect(substituteJsonConfigs(envs, { NEXT_PUBLIC_FOOTER_LINKS: '' })).toEqual({ NEXT_PUBLIC_FOOTER_LINKS: '[]' }); + }); + + it('leaves an unset JSON-config variable alone', () => { + expect(substituteJsonConfigs({ NEXT_PUBLIC_APP_HOST: 'localhost' }, { NEXT_PUBLIC_FOOTER_LINKS: '[]' })).toEqual({ + NEXT_PUBLIC_APP_HOST: 'localhost', + }); + }); +}); + +describe('validateEnvs', () => { + it('accepts a minimal single-chain configuration', () => { + expect(validateEnvs(MINIMAL_ENVS, {})).toEqual([]); + }); + + it('collects every error instead of stopping at the first one', () => { + const errors = validateEnvs({ ...MINIMAL_ENVS, NEXT_PUBLIC_APP_PORT: 'abc', NEXT_PUBLIC_NETWORK_ID: 'xyz' }, {}); + expect(errors.toSorted()).toEqual([ + 'NEXT_PUBLIC_APP_PORT: Expected a decimal number but received "abc"', + 'NEXT_PUBLIC_NETWORK_ID: Expected a decimal number but received "xyz"', + ]); + }); + + it('validates against the multichain schema when NEXT_PUBLIC_MULTICHAIN_ENABLED is true', () => { + expect(validateEnvs(MINIMAL_MULTICHAIN_ENVS, {})).toEqual([]); + expect(validateEnvs({ ...MINIMAL_MULTICHAIN_ENVS, NEXT_PUBLIC_GAS_TRACKER_ENABLED: 'true' }, {})).toEqual([ + 'NEXT_PUBLIC_GAS_TRACKER_ENABLED: Invalid type: Expected false but received true', + ]); + }); + + it('validates the JSON-config file content in place of the URL', () => { + const envs = { ...MINIMAL_ENVS, NEXT_PUBLIC_FOOTER_LINKS: 'https://example.com/links.json' }; + expect(validateEnvs(envs, { NEXT_PUBLIC_FOOTER_LINKS: '[{"title":"Foo","links":[]}]' })).toEqual([]); + expect(validateEnvs(envs, { NEXT_PUBLIC_FOOTER_LINKS: '[{"links":[]}]' })).toEqual([ + 'NEXT_PUBLIC_FOOTER_LINKS.0.title: Invalid key: Expected "title" but received undefined', + ]); + }); +}); + +describe('runChecks', () => { + it('passes a valid configuration with placeholders for every variable', () => { + expect(runChecks({ envs: MINIMAL_ENVS, registryNames: registryOf(MINIMAL_ENVS), buildTimeNames: [], jsonConfigs: {} })).toEqual({ + ok: true, + deprecationWarnings: [], + placeholderErrors: [], + validationErrors: [], + }); + }); + + it('stops before validation when a variable has no placeholder', () => { + const envs = { ...MINIMAL_ENVS, NEXT_PUBLIC_UNKNOWN: 'x', NEXT_PUBLIC_APP_PORT: 'abc' }; + expect(runChecks({ envs, registryNames: registryOf(MINIMAL_ENVS), buildTimeNames: [], jsonConfigs: {} })).toEqual({ + ok: false, + deprecationWarnings: [], + placeholderErrors: [ 'NEXT_PUBLIC_UNKNOWN', 'NEXT_PUBLIC_APP_PORT' ], + validationErrors: [], + }); + }); + + it('does not require a placeholder for a build-time variable', () => { + const envs = { ...MINIMAL_ENVS, NEXT_PUBLIC_GIT_TAG: 'v1.0.0' }; + const report = runChecks({ envs, registryNames: registryOf(MINIMAL_ENVS), buildTimeNames: [ 'NEXT_PUBLIC_GIT_TAG' ], jsonConfigs: {} }); + expect(report.ok).toBe(true); + }); + + it('fails on validation errors and reports them', () => { + const envs = { ...MINIMAL_ENVS, NEXT_PUBLIC_APP_PROTOCOL: 'ftp' }; + expect(runChecks({ envs, registryNames: registryOf(envs), buildTimeNames: [], jsonConfigs: {} })).toEqual({ + ok: false, + deprecationWarnings: [], + placeholderErrors: [], + validationErrors: [ 'NEXT_PUBLIC_APP_PROTOCOL: Invalid type: Expected ("http" | "https") but received "ftp"' ], + }); + }); + + it('reports a deprecation warning without failing', () => { + const deprecated = DEPRECATED_ENVS[0]; + const envs = { ...MINIMAL_ENVS, [deprecated.name]: 'hello' }; + expect(runChecks({ envs, registryNames: registryOf(envs), buildTimeNames: [], jsonConfigs: {} })).toEqual({ + ok: true, + deprecationWarnings: [ deprecated.message ], + placeholderErrors: [], + validationErrors: [], + }); + }); +}); diff --git a/deploy/tools/envs-validator/checks.ts b/deploy/tools/envs-validator/checks.ts new file mode 100644 index 00000000000..869a1721ed3 --- /dev/null +++ b/deploy/tools/envs-validator/checks.ts @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { DEPRECATED_ENVS } from './deprecations'; +import schema from './schema'; +import schemaMultichain from './schema_multichain'; +import { getValidationErrors } from './utils'; + +export const ENVS_WITH_JSON_CONFIG: ReadonlyArray<string> = [ + 'NEXT_PUBLIC_FEATURED_NETWORKS', + 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', + 'NEXT_PUBLIC_MARKETPLACE_CATEGORIES_URL', + 'NEXT_PUBLIC_MARKETPLACE_GRAPH_LINKS_URL', + 'NEXT_PUBLIC_FOOTER_LINKS', + 'NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL', + 'NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', + 'NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG', +]; + +export type EnvMap = Readonly<Record<string, string>>; + +export interface CheckInput { + readonly envs: EnvMap; + readonly registryNames: ReadonlyArray<string>; + readonly buildTimeNames: ReadonlyArray<string>; + readonly jsonConfigs: EnvMap; +} + +export interface CheckReport { + readonly ok: boolean; + readonly deprecationWarnings: ReadonlyArray<string>; + readonly placeholderErrors: ReadonlyArray<string>; + readonly validationErrors: ReadonlyArray<string>; +} + +export function pickAppEnvs(env: Readonly<Record<string, string | undefined>>): Record<string, string> { + return Object.entries(env) + .filter(([ key ]) => key.startsWith('NEXT_PUBLIC_')) + .reduce((result, [ key, value ]) => { + result[key] = value || ''; + return result; + }, {} as Record<string, string>); +} + +export function findDeprecationWarnings(envs: EnvMap): Array<string> { + return DEPRECATED_ENVS + .filter(({ name }) => envs[name] !== undefined) + .map(({ message }) => message); +} + +export function findEnvsWithoutPlaceholder( + envs: EnvMap, + registryNames: ReadonlyArray<string>, + buildTimeNames: ReadonlyArray<string>, +): Array<string> { + return Object.keys(envs) + .filter((name) => !buildTimeNames.includes(name)) + .filter((name) => !registryNames.includes(name)); +} + +export function substituteJsonConfigs(envs: EnvMap, jsonConfigs: EnvMap): Record<string, string> { + const result = { ...envs }; + for (const name of ENVS_WITH_JSON_CONFIG) { + if (result[name]) { + result[name] = jsonConfigs[name] || '[]'; + } + } + return result; +} + +export function validateEnvs(envs: EnvMap, jsonConfigs: EnvMap): Array<string> { + const value = substituteJsonConfigs(envs, jsonConfigs); + const activeSchema = value.NEXT_PUBLIC_MULTICHAIN_ENABLED === 'true' ? schemaMultichain : schema; + return getValidationErrors(activeSchema, value); +} + +export function runChecks(input: CheckInput): CheckReport { + const deprecationWarnings = findDeprecationWarnings(input.envs); + const placeholderErrors = findEnvsWithoutPlaceholder(input.envs, input.registryNames, input.buildTimeNames); + + if (placeholderErrors.length > 0) { + return { ok: false, deprecationWarnings, placeholderErrors, validationErrors: [] }; + } + + const validationErrors = validateEnvs(input.envs, input.jsonConfigs); + + return { ok: validationErrors.length === 0, deprecationWarnings, placeholderErrors, validationErrors }; +} diff --git a/deploy/tools/envs-validator/deprecations.ts b/deploy/tools/envs-validator/deprecations.ts new file mode 100644 index 00000000000..765dacce6b5 --- /dev/null +++ b/deploy/tools/envs-validator/deprecations.ts @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +export interface DeprecatedEnv { + readonly name: string; + readonly message: string; +} + +export const DEPRECATED_ENVS: ReadonlyArray<DeprecatedEnv> = [ + { + name: 'NEXT_PUBLIC_API_DOCS_ALERT_MESSAGE', + message: 'The NEXT_PUBLIC_API_DOCS_ALERT_MESSAGE variable no longer has any effect and will be removed in the next release. ' + + 'The alert is not displayed on the API documentation page anymore.', + }, +]; diff --git a/deploy/tools/envs-validator/docs.spec.ts b/deploy/tools/envs-validator/docs.spec.ts new file mode 100644 index 00000000000..da7d5c6d30b --- /dev/null +++ b/deploy/tools/envs-validator/docs.spec.ts @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { readFileSync } from 'node:fs'; + +import { describe, expect, it } from 'vitest'; + +import { DEPRECATED_ENVS } from './deprecations'; +import { extractDocumentedEnvNames } from './registry'; +import schema from './schema'; +import schemaMultichain from './schema_multichain'; + +const readDoc = (name: string): string => readFileSync(new URL(`../../../docs/${ name }`, import.meta.url), 'utf8'); + +const documentedRunTimeNames = extractDocumentedEnvNames(readDoc('ENVS.md')); +const documentedNames = new Set([ + ...documentedRunTimeNames, + ...extractDocumentedEnvNames(readDoc('BUILD-TIME_ENVS.md')), +]); +const deprecatedNames = new Set(extractDocumentedEnvNames(readDoc('DEPRECATED_ENVS.md'))); +const schemaNames = new Set([ ...schema.envNames, ...schemaMultichain.envNames ]); + +describe('docs/ENVS.md', () => { + it('has a row for every variable the schemas accept', () => { + const undocumented = Array.from(schemaNames).filter((name) => !documentedNames.has(name)); + expect(undocumented).toEqual([]); + }); + + it('has no row for a variable the schemas do not accept', () => { + const unknown = documentedRunTimeNames.filter((name) => !schemaNames.has(name)); + expect(unknown).toEqual([]); + }); +}); + +describe('docs/DEPRECATED_ENVS.md', () => { + it('lists every variable the validator warns about, unless the variable is still documented as active', () => { + const missing = DEPRECATED_ENVS + .map(({ name }) => name) + .filter((name) => !deprecatedNames.has(name) && !documentedNames.has(name)); + expect(missing).toEqual([]); + }); +}); diff --git a/deploy/tools/envs-validator/index.ts b/deploy/tools/envs-validator/index.ts index 6a9a485344d..bdff7a07fd2 100644 --- a/deploy/tools/envs-validator/index.ts +++ b/deploy/tools/envs-validator/index.ts @@ -1,165 +1,86 @@ -/* eslint-disable no-console */ -import fs from 'node:fs'; +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { readFile } from 'node:fs/promises'; import { dirname, resolve as resolvePath } from 'node:path'; -import type { ValidationError } from 'yup'; +import { fileURLToPath } from 'node:url'; import { buildExternalAssetFilePath } from 'src/config/utils/envs'; -import schema from './schema'; -import schemaMultichain from './schema_multichain'; -import { fileURLToPath } from 'node:url'; -const currentFilePath = fileURLToPath(import.meta.url); -const distDir = dirname(currentFilePath); +import type { CheckReport, EnvMap } from './checks'; +import { ENVS_WITH_JSON_CONFIG, findEnvsWithoutPlaceholder, pickAppEnvs, runChecks } from './checks'; +import { parseEnvNames } from './registry'; +const distDir = dirname(fileURLToPath(import.meta.url)); const silent = process.argv.includes('--silent'); -run(); - -async function run() { - !silent && console.log(); - try { - const appEnvs = Object.entries(process.env) - .filter(([ key ]) => key.startsWith('NEXT_PUBLIC_')) - .reduce((result, [ key, value ]) => { - result[key] = value || ''; - return result; - }, {} as Record<string, string>); +const log = (message: string): void => { + if (!silent) { + console.log(message); + } +}; - printDeprecationWarning(appEnvs); - await checkPlaceholdersCongruity(appEnvs); - checkDeprecatedEnvs(appEnvs); - await validateEnvs(appEnvs); +main(); +async function main(): Promise<void> { + log(''); + try { + const envs = pickAppEnvs(process.env); + const registryNames = parseEnvNames(await readRootFile('.env.registry')); + const buildTimeNames = parseEnvNames(await readRootFile('.env')); + // A missing JSON-config file must not pre-empt the placeholder report, so the files are only + // read once every variable is known to have a placeholder. + const hasPlaceholderErrors = findEnvsWithoutPlaceholder(envs, registryNames, buildTimeNames).length > 0; + const jsonConfigs = hasPlaceholderErrors ? {} : await readJsonConfigs(envs); + + const report = runChecks({ envs, registryNames, buildTimeNames, jsonConfigs }); + printReport(report); + process.exit(report.ok ? 0 : 1); } catch (error) { + console.log('🚨 Unexpected error occurred during validation.'); + console.error(error); process.exit(1); } } -async function validateEnvs(appEnvs: Record<string, string>) { - !silent && console.log(`🌀 Validating ENV variables values...`); +function printReport(report: CheckReport): void { + report.deprecationWarnings.forEach((warning) => console.warn(`❗ ${ warning }`)); - try { - // replace ENVs with external JSON files content - const envsWithJsonConfig = [ - 'NEXT_PUBLIC_FEATURED_NETWORKS', - 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', - 'NEXT_PUBLIC_MARKETPLACE_CATEGORIES_URL', - 'NEXT_PUBLIC_MARKETPLACE_GRAPH_LINKS_URL', - 'NEXT_PUBLIC_FOOTER_LINKS', - 'NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL', - 'NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', - 'NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG', - ]; - - for await (const envName of envsWithJsonConfig) { - if (appEnvs[envName]) { - appEnvs[envName] = await getExternalJsonContent(envName) || '[]'; - } - } - - if (appEnvs.NEXT_PUBLIC_MULTICHAIN_ENABLED === 'true') { - await schemaMultichain.validate(appEnvs, { stripUnknown: false, abortEarly: false }); - } else { - await schema.validate(appEnvs, { stripUnknown: false, abortEarly: false }); - } - - !silent && console.log('👍 All good!'); - } catch (_error) { - if (typeof _error === 'object' && _error !== null && 'errors' in _error) { - console.log('🚨 ENVs validation failed with the following errors:'); - (_error as ValidationError).errors.forEach((error) => { - console.log(' ', error); - }); - } else { - console.log('🚨 Unexpected error occurred during validation.'); - console.error(_error); - } - - throw _error; + log('🌀 Checking environment variables and their placeholders congruity...'); + if (report.placeholderErrors.length > 0) { + console.log('🚸 For the following environment variables placeholders were not generated at build-time:'); + report.placeholderErrors.forEach((name) => console.log(` ${ name }`)); + console.log(` They are either deprecated or running the app with them may lead to unexpected behavior. + Please check the documentation for more details - https://github.com/blockscout/frontend/blob/main/docs/ENVS.md + `); + console.log('🚨 Congruity check failed.\n'); + return; } + log('👍 All good!\n'); - !silent && console.log(); -} - -async function getExternalJsonContent(envName: string): Promise<string | void> { - return new Promise((resolve, reject) => { - const fileName = `./public${ buildExternalAssetFilePath(envName, 'https://foo.bar/baz.json') }`; - - fs.readFile(resolvePath(distDir, '..', fileName), 'utf8', (err, data) => { - if (err) { - console.log(`🚨 Unable to read file: ${ fileName }`); - reject(err); - return; - } - - resolve(data); - }); - }); + log('🌀 Validating ENV variables values...'); + if (report.validationErrors.length > 0) { + console.log('🚨 ENVs validation failed with the following errors:'); + report.validationErrors.forEach((error) => console.log(' ', error)); + return; + } + log('👍 All good!\n'); } -async function checkPlaceholdersCongruity(envsMap: Record<string, string>) { +async function readRootFile(fileName: string): Promise<string> { try { - !silent && console.log(`🌀 Checking environment variables and their placeholders congruity...`); - - const runTimeEnvs = await getEnvsPlaceholders(resolvePath(distDir, '..', '.env.registry')); - const buildTimeEnvs = await getEnvsPlaceholders(resolvePath(distDir, '..', '.env')); - const envs = Object.keys(envsMap).filter((env) => !buildTimeEnvs.includes(env)); - - const inconsistencies: Array<string> = []; - for (const env of envs) { - const hasPlaceholder = runTimeEnvs.includes(env); - if (!hasPlaceholder) { - inconsistencies.push(env); - } - } - - if (inconsistencies.length > 0) { - console.log('🚸 For the following environment variables placeholders were not generated at build-time:'); - inconsistencies.forEach((env) => { - console.log(` ${ env }`); - }); - console.log(` They are either deprecated or running the app with them may lead to unexpected behavior. - Please check the documentation for more details - https://github.com/blockscout/frontend/blob/main/docs/ENVS.md - `); - throw new Error(); - } - - !silent && console.log('👍 All good!\n'); + return await readFile(resolvePath(distDir, '..', fileName), 'utf8'); } catch (error) { - console.log('🚨 Congruity check failed.\n', error); + console.log(`🚨 Unable to read file: ${ fileName }`); throw error; } } -function getEnvsPlaceholders(filePath: string): Promise<Array<string>> { - return new Promise((resolve, reject) => { - fs.readFile(filePath, 'utf8', (err, data) => { - if (err) { - console.log(`🚨 Unable to read placeholders file.`); - reject(err); - return; - } - - const lines = data.split('\n'); - const variables = lines.map(line => { - const variable = line.split('=')[0]; - return variable.trim(); - }); - - resolve(variables.filter(Boolean)); - }); - }); -} - -function printDeprecationWarning(envsMap: Record<string, string>) { - // an empty value still counts as configured — the congruity check will fail on it once the variable is removed - if (envsMap.NEXT_PUBLIC_API_DOCS_ALERT_MESSAGE !== undefined) { - // eslint-disable-next-line max-len - console.warn('❗ The NEXT_PUBLIC_API_DOCS_ALERT_MESSAGE variable no longer has any effect and will be removed in the next release. The alert is not displayed on the API documentation page anymore.'); +async function readJsonConfigs(envs: EnvMap): Promise<Record<string, string>> { + const configs: Record<string, string> = {}; + for (const name of ENVS_WITH_JSON_CONFIG) { + if (envs[name]) { + configs[name] = await readRootFile(`./public${ buildExternalAssetFilePath(name, 'https://foo.bar/baz.json') }`); + } } -} - -function checkDeprecatedEnvs(envsMap: Record<string, string>) { - !silent && console.log(`🌀 Checking deprecated environment variables...`); - !silent && console.log('👍 All good!\n'); + return configs; } diff --git a/deploy/tools/envs-validator/mocks/address3rdPartyWidgets.ts b/deploy/tools/envs-validator/mocks/address3rdPartyWidgets.ts new file mode 100644 index 00000000000..048715c2e3e --- /dev/null +++ b/deploy/tools/envs-validator/mocks/address3rdPartyWidgets.ts @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { Address3rdPartyWidget } from 'src/features/address-3rd-party-widgets/types/view'; + +export const address3rdPartyWidgetsConfig: Record<string, Address3rdPartyWidget> = { + 'widget-1': { + name: 'Widget 1', + url: 'https://example.com/widget-1/{address}', + icon: 'https://example.com/icon.svg', + title: 'Widget 1', + hint: 'Widget 1 hint', + valuePath: 'result.value', + valueTitlePath: 'result.valueTitle', + pages: [ 'eoa', 'contract', 'token' ], + }, + 'widget-2': { + name: 'Widget 2', + url: 'https://example.com/widget-2/{address}', + icon: 'https://example.com/icon.svg', + title: 'Widget 2', + valuePath: 'value', + pages: [ 'eoa' ], + }, + 'widget-3': { + name: 'Widget 3', + url: 'https://example.com/widget-3/{address}?chainId={chainId}', + icon: 'https://example.com/icon.svg', + title: 'Widget 3', + valuePath: 'result.length', + pages: [ 'token' ], + chainIds: { '1': 'eth', '10': 'op' }, + }, +}; diff --git a/deploy/tools/envs-validator/mocks/ads.ts b/deploy/tools/envs-validator/mocks/ads.ts new file mode 100644 index 00000000000..2fcbae2be36 --- /dev/null +++ b/deploy/tools/envs-validator/mocks/ads.ts @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { AdButlerDeviceConfig } from 'src/features/ads/banner/types/config'; + +export const adButlerConfigDesktop: AdButlerDeviceConfig = { id: '123456', width: '728', height: '90' }; + +export const adButlerConfigMobile: AdButlerDeviceConfig = { id: '654321', width: '300', height: '100' }; + +export const sevioZones = [ '52909312-7ebb-4bd5-9006-5e4f7041ed63', '07cabd45-77f1-4203-8081-868bae776981' ]; diff --git a/deploy/tools/envs-validator/mocks/bridgedToken.ts b/deploy/tools/envs-validator/mocks/bridgedToken.ts new file mode 100644 index 00000000000..dc6023ee225 --- /dev/null +++ b/deploy/tools/envs-validator/mocks/bridgedToken.ts @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { BridgedTokenChain, TokenBridge } from 'src/features/bridged-tokens/types/client'; + +export const bridgedTokenChains: Array<BridgedTokenChain> = [ + { id: '1', title: 'Ethereum', short_title: 'ETH', base_url: 'https://example.com' }, +]; + +export const tokenBridges: Array<TokenBridge> = [ + { type: 'omni', title: 'OmniBridge', short_title: 'OMNI' }, +]; diff --git a/deploy/tools/envs-validator/mocks/defiDropdown.ts b/deploy/tools/envs-validator/mocks/defiDropdown.ts new file mode 100644 index 00000000000..da667cb6639 --- /dev/null +++ b/deploy/tools/envs-validator/mocks/defiDropdown.ts @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { DeFiDropdownButtonText, DeFiDropdownItem } from 'src/features/defi-dropdown/types/client'; + +export const deFiDropdownItems: Array<DeFiDropdownItem> = [ + { text: 'Swap', icon: 'swap', dappId: 'uniswap' }, + { text: 'Payment link', icon: 'payment_link', url: 'https://example.com' }, +]; + +export const deFiDropdownButtonText: DeFiDropdownButtonText = { desktop: 'Blockscout DeFi', mobile: 'DeFi' }; diff --git a/deploy/tools/envs-validator/mocks/highlights.ts b/deploy/tools/envs-validator/mocks/highlights.ts new file mode 100644 index 00000000000..8aee418e932 --- /dev/null +++ b/deploy/tools/envs-validator/mocks/highlights.ts @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { HighlightsBannerConfig } from 'src/slices/home/types/client'; + +export const highlightsConfig: Array<HighlightsBannerConfig> = [ + { + title: 'Duck Deep into Transactions', + description: 'Explore and track all blockchain transactions', + title_color: [ '#1a472a', '#4ade80' ], + description_color: [ '#374151', '#d1d5db' ], + background: [ '#e0f2fe', '#0f172a' ], + side_img_url: [ 'https://example.com', 'https://example.com' ], + page_path: '/txs', + }, + { + title: 'Capybara Hot Spring Pools', + description: 'Monitor liquidity and staking pools', + is_pinned: true, + redirect_url: 'https://example.com', + }, +]; diff --git a/deploy/tools/envs-validator/mocks/instance.ts b/deploy/tools/envs-validator/mocks/instance.ts new file mode 100644 index 00000000000..d524dd4b363 --- /dev/null +++ b/deploy/tools/envs-validator/mocks/instance.ts @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { StatsApiResourceNameRefetchInterval } from 'src/features/chain-stats/types/config'; +import type { TxExternalTxsConfig } from 'src/features/external-txs/types/client'; +import type { GasRefuelProviderConfig } from 'src/features/get-gas-button/types/client'; +import type { MultichainProviderConfig } from 'src/features/multichain-button/types/client'; +import type { TokenActionButtonConfig } from 'src/features/token-action-button/types/config'; +import type { HeroBannerConfig } from 'src/slices/home/types/config'; + +import { toEnvValue } from '../test-utils'; +import { address3rdPartyWidgetsConfig } from './address3rdPartyWidgets'; +import { bridgedTokenChains, tokenBridges } from './bridgedToken'; +import { deFiDropdownButtonText, deFiDropdownItems } from './defiDropdown'; +import { highlightsConfig } from './highlights'; +import { + contractCodeIdes, + featuredNetworks, + fontFamilyBody, + fontFamilyHeading, + footerLinks, + heroBannerConfig, + networkExplorers, + nftMarketplaces, + promoBannerConfigFull, +} from './ui'; + +const multichainHeroBanner: HeroBannerConfig = { + background: [ 'linear-gradient(90deg, rgb(232, 52, 53) 0%, rgb(139, 28, 232) 100%)' ], + text_color: [ 'rgb(255, 255, 255)' ], + text: 'Duck migration observer', + search: { + border_width: [ '0px' ], + border_color: { _focus: [ 'deeppink' ] }, + }, +}; + +const tokenActionButton: TokenActionButtonConfig = { + text: 'Buy on Example Portal', + url: 'https://portal.example.com/swap?chainId=1&token={hash}', + logo: [ 'https://example.com/logo-light.svg', 'https://example.com/logo-dark.svg' ], + colors: { _default: { bg: [ 'rgb(134, 86, 239)' ], text: [ 'white' ] } }, +}; + +const multichainBalanceProviders: Array<MultichainProviderConfig> = [ + { name: 'zerion', url_template: 'https://app.zerion.io/{address}/overview', logo: 'https://example.com/zerion.svg' }, +]; + +const gasRefuelProvider: GasRefuelProviderConfig = { + name: 'Need gas?', + dapp_id: 'smol-refuel', + url_template: 'https://smolrefuel.com/?outboundChain={chainId}&partner=blockscout', + logo: 'https://example.com/smolrefuel.png', +}; + +const statsRefetchInterval: Record<StatsApiResourceNameRefetchInterval, number> = { + 'stats:counters': 10_000, + 'stats:pages_main': 10_000, +}; + +export const txExternalTxsConfig: TxExternalTxsConfig = { + chain_name: 'Ethereum', + chain_logo_url: 'https://example.com/logo.png', + explorer_url_template: 'https://example.com/tx/{hash}', +}; + +export const singleChainConfig: Record<string, string> = { + NEXT_PUBLIC_API_HOST: 'blockscout.com', + NEXT_PUBLIC_APP_HOST: 'localhost', + NEXT_PUBLIC_NETWORK_ID: '1', + NEXT_PUBLIC_NETWORK_NAME: 'Testnet', + NEXT_PUBLIC_ROLLBAR_CLIENT_TOKEN: 'https://rollbar.com', + NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED: 'true', + NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID: 'xxx', + NEXT_PUBLIC_WALLET_CONNECT_FEATURED_WALLET_IDS: toEnvValue([ 'xxx' ]), + NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY: 'xxx', + NEXT_PUBLIC_GOOGLE_ANALYTICS_PROPERTY_ID: 'UA-XXXXXX-X', + NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN: 'xxx', + NEXT_PUBLIC_USERCENTRICS_CONFIG: toEnvValue({ settingsId: 'xxx', rulesetId: 'xxx' }), + NEXT_PUBLIC_USERCENTRICS_DRAFT: 'true', + NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES: toEnvValue({ record_sessions_percent: 0.5, record_heatmap_data: true }), + NEXT_PUBLIC_POSTHOG_API_KEY: 'xxx', + NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES: toEnvValue({ disable_session_recording: false }), + NEXT_PUBLIC_GROWTH_BOOK_CLIENT_KEY: 'xxx', + NEXT_PUBLIC_AD_TEXT_PROVIDER: 'sevio', + NEXT_PUBLIC_AD_BANNER_PROVIDER: 'slise', + NEXT_PUBLIC_ADMIN_SERVICE_API_HOST: 'https://example.com', + NEXT_PUBLIC_ADMIN_RS_INSTANCE_ID: '420:duck', + NEXT_PUBLIC_API_BASE_PATH: '/', + NEXT_PUBLIC_API_WEBSOCKET_PROTOCOL: 'ws', + NEXT_PUBLIC_APP_ENV: 'development', + NEXT_PUBLIC_APP_PORT: '3000', + NEXT_PUBLIC_APP_PROTOCOL: 'http', + NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS: toEnvValue(bridgedTokenChains), + NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES: toEnvValue(tokenBridges), + NEXT_PUBLIC_COLOR_THEMES: toEnvValue([ 'dim', 'dark' ]), + NEXT_PUBLIC_COLOR_THEME_DEFAULT: 'dim', + NEXT_PUBLIC_CONTRACT_CODE_IDES: toEnvValue(contractCodeIdes), + NEXT_PUBLIC_CONTRACT_INFO_API_HOST: 'https://example.com', + NEXT_PUBLIC_CONTRACT_INFO_INSTANCE_ID: '420:duck', + NEXT_PUBLIC_DATA_AVAILABILITY_ENABLED: 'true', + NEXT_PUBLIC_FEATURED_NETWORKS: JSON.stringify(featuredNetworks), + NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK: 'https://example.com', + NEXT_PUBLIC_FEATURED_NETWORKS_MODE: 'list', + NEXT_PUBLIC_NAVIGATION_HIGHLIGHTED_ROUTES: toEnvValue([ '/accounts', '/apps' ]), + NEXT_PUBLIC_NAVIGATION_LAYOUT: 'horizontal', + NEXT_PUBLIC_FONT_FAMILY_HEADING: toEnvValue(fontFamilyHeading), + NEXT_PUBLIC_FONT_FAMILY_BODY: toEnvValue(fontFamilyBody), + NEXT_PUBLIC_FOOTER_LINKS: JSON.stringify(footerLinks), + NEXT_PUBLIC_HELIA_VERIFIED_FETCH_ENABLED: 'false', + NEXT_PUBLIC_HIDE_INDEXING_ALERT_BLOCKS: 'false', + NEXT_PUBLIC_HIDE_INDEXING_ALERT_INT_TXS: 'false', + NEXT_PUBLIC_HIDE_NATIVE_COIN_PRICE: 'false', + NEXT_PUBLIC_MAX_CONTENT_WIDTH_ENABLED: 'false', + NEXT_PUBLIC_HOMEPAGE_CHARTS: toEnvValue([ 'daily_txs' ]), + NEXT_PUBLIC_HOMEPAGE_STATS: toEnvValue([ 'total_blocks', 'average_block_time', 'total_txs', 'wallet_addresses', 'gas_tracker', 'current_epoch' ]), + NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG: toEnvValue(heroBannerConfig), + NEXT_PUBLIC_HOT_CONTRACTS_ENABLED: 'true', + NEXT_PUBLIC_GAS_TRACKER_ENABLED: 'true', + NEXT_PUBLIC_GAS_TRACKER_UNITS: toEnvValue([ 'gwei' ]), + NEXT_PUBLIC_IS_TESTNET: 'true', + NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: '<a href="#">Hello</a>', + NEXT_PUBLIC_METADATA_SERVICE_API_HOST: 'https://example.com', + NEXT_PUBLIC_METASUITES_ENABLED: 'true', + NEXT_PUBLIC_NETWORK_CURRENCY_DECIMALS: '18', + NEXT_PUBLIC_NETWORK_CURRENCY_NAME: 'Ether', + NEXT_PUBLIC_NETWORK_CURRENCY_SYMBOL: 'ETH', + NEXT_PUBLIC_NETWORK_EXPLORERS: toEnvValue(networkExplorers), + NEXT_PUBLIC_NETWORK_SECONDARY_COIN_SYMBOL: 'GNO', + NEXT_PUBLIC_NETWORK_MULTIPLE_GAS_CURRENCIES: 'true', + NEXT_PUBLIC_NETWORK_ICON: 'https://example.com/icon.png', + NEXT_PUBLIC_NETWORK_ICON_DARK: 'https://example.com/icon.png', + NEXT_PUBLIC_NETWORK_LOGO: 'https://example.com/logo.png', + NEXT_PUBLIC_NETWORK_LOGO_DARK: 'https://example.com/logo.png', + NEXT_PUBLIC_NETWORK_RPC_URL: 'https://example.com', + NEXT_PUBLIC_NETWORK_SHORT_NAME: 'Test', + NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE: 'validation', + NEXT_PUBLIC_OG_DESCRIPTION: 'Hello world!', + NEXT_PUBLIC_OG_IMAGE_URL: 'https://example.com/image.png', + NEXT_PUBLIC_OG_ENHANCED_DATA_ENABLED: 'true', + NEXT_PUBLIC_SEO_ENHANCED_DATA_ENABLED: 'true', + NEXT_PUBLIC_OTHER_LINKS: toEnvValue([ { url: 'https://blockscout.com', text: 'Blockscout' } ]), + NEXT_PUBLIC_PROMOTE_BLOCKSCOUT_IN_TITLE: 'true', + NEXT_PUBLIC_SAFE_TX_SERVICE_URL: 'https://safe-transaction-mainnet.safe.global', + NEXT_PUBLIC_STATS_API_HOST: 'https://example.com', + NEXT_PUBLIC_STATS_API_BASE_PATH: '/', + NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL: toEnvValue(statsRefetchInterval), + NEXT_PUBLIC_PRO_API_SUPPORTED: 'true', + NEXT_PUBLIC_USE_NEXT_JS_PROXY: 'false', + NEXT_PUBLIC_VIEWS_ADDRESS_IDENTICON_TYPE: 'gradient_avatar', + NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT: toEnvValue([ 'base16' ]), + NEXT_PUBLIC_VIEWS_ADDRESS_HIDDEN_VIEWS: toEnvValue([ 'top_accounts' ]), + NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS: '0x471EcE3750Da237f93B8E339c536989b8978a438', + NEXT_PUBLIC_VIEWS_CONTRACT_EXTRA_VERIFICATION_METHODS: toEnvValue([ 'solidity-hardhat', 'solidity-foundry' ]), + NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_FIELDS: toEnvValue([ 'burnt_fees', 'total_reward' ]), + NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_VIEWS: toEnvValue([ 'reorgs', 'uncles' ]), + NEXT_PUBLIC_VIEWS_BLOCK_PENDING_UPDATE_ALERT_ENABLED: 'false', + NEXT_PUBLIC_VIEWS_NFT_MARKETPLACES: toEnvValue(nftMarketplaces), + NEXT_PUBLIC_VIEWS_TX_ADDITIONAL_FIELDS: toEnvValue([ 'fee_per_gas', 'set_max_gas_limit' ]), + NEXT_PUBLIC_VIEWS_TX_HIDDEN_FIELDS: toEnvValue([ 'value', 'fee_currency', 'gas_price', 'tx_fee', 'gas_fees', 'burnt_fees' ]), + NEXT_PUBLIC_VISUALIZE_API_HOST: 'https://example.com', + NEXT_PUBLIC_VISUALIZE_API_BASE_PATH: 'https://example.com', + NEXT_PUBLIC_WEB3_DISABLE_ADD_TOKEN_TO_WALLET: 'false', + NEXT_PUBLIC_WEB3_WALLETS: toEnvValue([ 'coinbase', 'metamask', 'token_pocket' ]), + NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE: 'stability', + NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS: toEnvValue(deFiDropdownItems), + NEXT_PUBLIC_DEFI_DROPDOWN_BUTTON_TEXT: toEnvValue(deFiDropdownButtonText), + NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG: toEnvValue(multichainBalanceProviders), + NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG: toEnvValue(tokenActionButton), + NEXT_PUBLIC_GAS_REFUEL_PROVIDER_CONFIG: toEnvValue(gasRefuelProvider), + NEXT_PUBLIC_REWARDS_SERVICE_API_HOST: 'https://example.com', + NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS: toEnvValue(Object.keys(address3rdPartyWidgetsConfig)), + NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL: JSON.stringify(address3rdPartyWidgetsConfig), + NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG: toEnvValue(promoBannerConfigFull), + NEXT_PUBLIC_FLASHBLOCKS_SOCKET_URL: 'wss://example.com/ws', + NEXT_PUBLIC_FLASHBLOCKS_NAME: 'flashblock', + NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG: JSON.stringify(highlightsConfig), + NEXT_PUBLIC_NAME_SERVICE_API_HOST: 'https://example.com', + NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS: toEnvValue([ 'duck', 'goose' ]), + NEXT_PUBLIC_CLUSTERS_API_HOST: 'https://example.com', + NEXT_PUBLIC_CLUSTERS_CDN_URL: 'https://example.com', +}; + +export const multichainConfig: Record<string, string> = { + NEXT_PUBLIC_APP_HOST: 'localhost', + NEXT_PUBLIC_MULTICHAIN_AGGREGATOR_API_HOST: 'https://example.com', + NEXT_PUBLIC_MULTICHAIN_STATS_API_HOST: 'http://example.com', + NEXT_PUBLIC_MULTICHAIN_ENABLED: 'true', + NEXT_PUBLIC_MULTICHAIN_CLUSTER: 'test', + NEXT_PUBLIC_HOMEPAGE_CHARTS: toEnvValue([ 'daily_txs', 'coin_price', 'market_cap' ]), + NEXT_PUBLIC_HOMEPAGE_STATS: toEnvValue([ 'total_txs', 'wallet_addresses' ]), + NEXT_PUBLIC_API_DOCS_TABS: '[]', + NEXT_PUBLIC_FEATURED_NETWORKS: JSON.stringify(featuredNetworks), + NEXT_PUBLIC_FOOTER_LINKS: JSON.stringify(footerLinks), + NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG: toEnvValue(multichainHeroBanner), + NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG: toEnvValue(multichainBalanceProviders), + NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG: toEnvValue(tokenActionButton), + NEXT_PUBLIC_NETWORK_ICON: 'http://example.com', + NEXT_PUBLIC_NETWORK_ICON_DARK: 'http://example.com', + NEXT_PUBLIC_NETWORK_LOGO: 'http://example.com', + NEXT_PUBLIC_NETWORK_LOGO_DARK: 'http://example.com', + NEXT_PUBLIC_NETWORK_NAME: 'Multichain', + NEXT_PUBLIC_NETWORK_SHORT_NAME: 'Multichain', + NEXT_PUBLIC_OG_IMAGE_URL: 'http://example.com', + NEXT_PUBLIC_GAS_TRACKER_ENABLED: 'false', + NEXT_PUBLIC_HIDE_INDEXING_ALERT_BLOCKS: 'true', + NEXT_PUBLIC_HIDE_INDEXING_ALERT_INT_TXS: 'true', + NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED: 'false', + NEXT_PUBLIC_IS_TESTNET: 'true', + NEXT_PUBLIC_USE_NEXT_JS_PROXY: 'true', + NEXT_PUBLIC_HAS_USER_OPS: 'true', + NEXT_PUBLIC_ADVANCED_FILTER_ENABLED: 'false', + NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID: 'xxx', + NEXT_PUBLIC_GOOGLE_ANALYTICS_PROPERTY_ID: 'xxx', + NEXT_PUBLIC_ROLLBAR_CLIENT_TOKEN: 'xxx', + NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN: 'xxx', + NEXT_PUBLIC_POSTHOG_API_KEY: 'xxx', +}; diff --git a/deploy/tools/envs-validator/mocks/marketplace.ts b/deploy/tools/envs-validator/mocks/marketplace.ts new file mode 100644 index 00000000000..18e4eb5441e --- /dev/null +++ b/deploy/tools/envs-validator/mocks/marketplace.ts @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { EssentialDappsConfig, MarketplaceTitles } from 'src/features/marketplace/types/client'; + +export interface MarketplaceAppConfig { + readonly id: string; + readonly external?: boolean; + readonly title: string; + readonly logo: string; + readonly logoDarkMode?: string; + readonly shortDescription: string; + readonly categories: Array<string>; + readonly url: string; + readonly author: string; + readonly description: string; + readonly site?: string; + readonly twitter?: string; + readonly telegram?: string; + readonly github?: string | Array<string>; + readonly discord?: string; + readonly internalWallet?: boolean; + readonly priority?: number; +} + +export const marketplaceApps: Array<MarketplaceAppConfig> = [ + { + author: 'Hop', + id: 'hop-exchange', + title: 'Hop', + logo: 'https://example.com/logo.svg', + categories: [ 'Bridge' ], + shortDescription: 'Hop is a bridge.', + site: 'https://example.com', + description: 'Hop is a bridge.', + external: true, + url: 'https://example.com', + }, + { + author: 'Blockscout', + id: 'token-approval-tracker', + title: 'Token Approval Tracker', + logo: 'https://example.com/logo.svg', + categories: [ 'Infra & Dev tooling' ], + shortDescription: 'Tracks approvals.', + site: 'https://example.com', + description: 'Tracks approvals.', + url: 'https://example.com', + github: [ 'https://github.com/a', 'https://github.com/b' ], + }, +]; + +export const marketplaceCategories: Array<string> = [ 'Swaps', 'Bridges', 'NFT' ]; + +export const essentialDappsConfig: EssentialDappsConfig = { + swap: { chains: [ '1', '10', '100', '11155111' ], fee: '0.004', integrator: 'blockscout' }, + revoke: { chains: [ '1', '10', '100', '11155111' ] }, + multisend: { chains: [ '1', '10', '100', '11155111' ], posthogKey: '123', posthogHost: 'https://example.com' }, +}; + +export const marketplaceTitles: Partial<MarketplaceTitles> = { + menu_item: 'Dapps', + title: 'Dappscout', +}; diff --git a/deploy/tools/envs-validator/mocks/rollup.ts b/deploy/tools/envs-validator/mocks/rollup.ts new file mode 100644 index 00000000000..20269410030 --- /dev/null +++ b/deploy/tools/envs-validator/mocks/rollup.ts @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { ParentChain } from 'src/features/rollup/common/types/config'; + +export const parentChainMinimal: ParentChain = { + baseUrl: 'https://explorer.duckchain.io', +}; + +export const parentChainFull: ParentChain = { + baseUrl: 'https://explorer.duckchain.io', + currency: { name: 'Quack', symbol: 'QUACK', decimals: 18 }, + isTestnet: true, + id: 42, + name: 'DuckChain', + rpcUrls: [ 'https://rpc.duckchain.io' ], +}; diff --git a/deploy/tools/envs-validator/mocks/ui.ts b/deploy/tools/envs-validator/mocks/ui.ts new file mode 100644 index 00000000000..9acfe89a976 --- /dev/null +++ b/deploy/tools/envs-validator/mocks/ui.ts @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { AlternativeExplorer } from 'src/features/alternative-explorers/types/client'; +import type { CustomLinksGroup } from 'src/shell/footer/types'; +import type { NavigationPromoBannerConfig } from 'src/shell/navigation/types'; +import type { FeaturedNetwork } from 'src/shell/top-bar/chain-menu/types'; +import type { ContractCodeIde } from 'src/slices/contract/types/config'; +import type { HeroBannerConfig } from 'src/slices/home/types/config'; +import type { NftMarketplaceItem } from 'src/slices/token/types/client'; + +import type { FontFamily } from 'src/config/misc'; + +export const heroBannerConfig: HeroBannerConfig = { + background: [ 'lightpink' ], + text_color: [ 'deepskyblue', 'white' ], + border: [ '3px solid black' ], + search: { + background: [ 'white', 'rgb(26,32,44)' ], + border_width: [ '2px', '2px' ], + border_color: { + _empty: [ 'rgb(203,213,224)', 'rgb(74,85,104)' ], + _hover: [ 'rgb(66,153,225)', 'rgb(99,179,237)' ], + _focus: [ 'rgb(49,130,206)', 'rgb(43,108,176)' ], + _filled: [ 'rgb(160,174,192)', 'rgb(113,128,150)' ], + }, + }, +}; + +export const featuredNetworks: Array<FeaturedNetwork> = [ + { + title: 'Ethereum', + url: 'https://eth.blockscout.com/', + group: 'Mainnets', + icon: 'https://example.com/logo.svg', + }, + { + title: 'Goerli', + url: 'https://eth-goerli.blockscout.com/', + group: 'Testnets', + isActive: true, + icon: 'https://example.com/logo.svg', + invertIconInDarkMode: true, + }, +]; + +export const promoBannerConfigFull: NavigationPromoBannerConfig = { + img_url: 'https://example.com/promo.svg', + text: 'Promo text', + bg_color: { light: 'rgb(250, 245, 255)', dark: 'rgb(68, 51, 122)' }, + text_color: { light: 'rgb(107, 70, 193)', dark: 'rgb(233, 216, 253)' }, + link_url: 'https://example.com', +}; + +export const promoBannerConfigImageOnly: NavigationPromoBannerConfig = { + img_url: { small: 'https://example.com/promo-sm.png', large: 'https://example.com/promo-lg.png' }, + link_url: 'https://example.com', +}; + +export const footerLinks: Array<CustomLinksGroup> = [ + { + title: 'Foo', + links: [ { text: 'Home', url: 'https://example.com' } ], + }, + { + title: 'Developers', + links: [ + { + text: 'Develop', + url: 'https://example.com', + iconUrl: [ 'https://example.com/mocks/image_s.jpg', 'https://example.com/mocks/image_svg.svg' ], + }, + ], + }, +]; + +export const fontFamilyHeading: FontFamily = { + name: 'Montserrat', + url: 'https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700&display=swap', +}; + +export const fontFamilyBody: FontFamily = { + name: 'Raleway', + url: 'https://fonts.googleapis.com/css2?family=Raleway:wght@400;500;600;700&display=swap', +}; + +export const networkExplorers: Array<AlternativeExplorer> = [ + { + title: 'Explorer', + baseUrl: 'https://example.com/', + paths: { tx: '/tx', address: '/address', token: '/token', block: '/block', blob: '/blob' }, + }, +]; + +export const contractCodeIdes: Array<ContractCodeIde> = [ + { + title: 'Remix IDE', + url: 'https://remix.blockscout.com/?address={hash}&blockscout={domain}', + icon_url: 'https://example.com/icon.svg', + }, +]; + +export const nftMarketplaces: Array<NftMarketplaceItem> = [ + { + name: 'NFT Marketplace', + collection_url: 'https://example.com/{hash}', + instance_url: 'https://example.com/{hash}/{id}', + logo_url: 'https://example.com/logo.png', + }, +]; diff --git a/deploy/tools/envs-validator/mocks/zetaChain.ts b/deploy/tools/envs-validator/mocks/zetaChain.ts new file mode 100644 index 00000000000..368b7813329 --- /dev/null +++ b/deploy/tools/envs-validator/mocks/zetaChain.ts @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { ZetaChainChainsConfigEnv } from 'src/features/chain-variants/zeta-chain/types/client'; + +export const zetaChainChainsConfig: Array<ZetaChainChainsConfigEnv> = [ + { + chain_id: 7000, + chain_name: 'ZetaChain Athens', + chain_logo: 'https://example.com/zetachain-logo.svg', + instance_url: 'https://zetachain-indexer.duckdns.org', + }, + { + chain_id: 7001, + chain_name: 'ZetaChain Athens Testnet', + chain_logo: 'https://example.com/zetachain-testnet-logo.svg', + instance_url: 'https://zetachain-testnet-indexer.duckdns.org', + }, +]; + +export const zetaChainExternalSearchConfig = [ + { regex: '^0x[a-f0-9]{64}$', template: 'https://example.com/{value}', name: 'Foo' }, +]; diff --git a/deploy/tools/envs-validator/package.json b/deploy/tools/envs-validator/package.json index 03d1510094c..539c8bcbc43 100644 --- a/deploy/tools/envs-validator/package.json +++ b/deploy/tools/envs-validator/package.json @@ -5,13 +5,10 @@ "main": "dist/index.js", "scripts": { "build": "vite build --logLevel error", - "validate": "node ./dist/index.js", - "test": "./test.sh" + "validate": "node ./dist/index.js" }, "devDependencies": { - "dotenv-cli": "^7.4.4", - "typescript": "7.0.2", - "vite": "6.4.3", - "yup": "^1.7.1" + "vite": "8.3.5", + "valibot": "1.2.0" } } diff --git a/deploy/tools/envs-validator/registry.spec.ts b/deploy/tools/envs-validator/registry.spec.ts new file mode 100644 index 00000000000..72870961509 --- /dev/null +++ b/deploy/tools/envs-validator/registry.spec.ts @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { extractDocumentedEnvNames, parseEnvNames } from './registry'; + +describe('parseEnvNames', () => { + it('returns the variable name of every non-empty line', () => { + const content = 'NEXT_PUBLIC_APP_HOST=localhost\n NEXT_PUBLIC_APP_PORT =3000\n\nNEXT_PUBLIC_FOO=__\n'; + expect(parseEnvNames(content)).toEqual([ 'NEXT_PUBLIC_APP_HOST', 'NEXT_PUBLIC_APP_PORT', 'NEXT_PUBLIC_FOO' ]); + }); + + it('keeps a line without a value', () => { + expect(parseEnvNames('NEXT_PUBLIC_FOO')).toEqual([ 'NEXT_PUBLIC_FOO' ]); + }); + + it('returns an empty list for empty content', () => { + expect(parseEnvNames('')).toEqual([]); + }); +}); + +describe('extractDocumentedEnvNames', () => { + it('returns only the names that open a table row', () => { + const markdown = [ + '| Variable | Type |', + '| NEXT_PUBLIC_B_VAR | `string` |', + '|NEXT_PUBLIC_A_VAR| `boolean` |', + 'The NEXT_PUBLIC_C_VAR variables are described above, see also `NEXT_PUBLIC_A_VAR`.', + ].join('\n'); + expect(extractDocumentedEnvNames(markdown)).toEqual([ 'NEXT_PUBLIC_A_VAR', 'NEXT_PUBLIC_B_VAR' ]); + }); +}); diff --git a/deploy/tools/envs-validator/registry.ts b/deploy/tools/envs-validator/registry.ts new file mode 100644 index 00000000000..29e11c06f18 --- /dev/null +++ b/deploy/tools/envs-validator/registry.ts @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +const TABLE_ROW_ENV_NAME_REGEXP = /^\| *(NEXT_PUBLIC_\w+)/gm; + +export function parseEnvNames(envFileContent: string): Array<string> { + return envFileContent + .split('\n') + .map((line) => line.split('=')[0].trim()) + .filter(Boolean); +} + +export function extractDocumentedEnvNames(markdown: string): Array<string> { + const names = new Set(Array.from(markdown.matchAll(TABLE_ROW_ENV_NAME_REGEXP), (match) => match[1])); + return Array.from(names).sort(); +} diff --git a/deploy/tools/envs-validator/schema.spec.ts b/deploy/tools/envs-validator/schema.spec.ts new file mode 100644 index 00000000000..4cebf7427a4 --- /dev/null +++ b/deploy/tools/envs-validator/schema.spec.ts @@ -0,0 +1,269 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { singleChainConfig, txExternalTxsConfig } from './mocks/instance'; +import schema from './schema'; +import { toEnvValue } from './test-utils'; +import { getValidationErrors } from './utils'; + +const REQUIRED = { + NEXT_PUBLIC_APP_HOST: 'localhost', + NEXT_PUBLIC_API_HOST: 'blockscout.com', + NEXT_PUBLIC_NETWORK_NAME: 'Testnet', + NEXT_PUBLIC_NETWORK_ID: '1', +}; + +describe('single-chain schema', () => { + it('accepts a full known-good configuration', () => { + expect(getValidationErrors(schema, singleChainConfig)).toEqual([]); + }); + + it('requires the app host, API host, network name and network id', () => { + expect(getValidationErrors(schema, {}).sort()).toEqual([ + 'NEXT_PUBLIC_API_HOST: Invalid key: Expected "NEXT_PUBLIC_API_HOST" but received undefined', + 'NEXT_PUBLIC_APP_HOST: Invalid key: Expected "NEXT_PUBLIC_APP_HOST" but received undefined', + 'NEXT_PUBLIC_NETWORK_ID: Invalid key: Expected "NEXT_PUBLIC_NETWORK_ID" but received undefined', + 'NEXT_PUBLIC_NETWORK_NAME: Invalid key: Expected "NEXT_PUBLIC_NETWORK_NAME" but received undefined', + ]); + }); + + it('rejects an unknown variable', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_DUCK: 'quack' })).toEqual([ + 'Unknown ENV variables were provided: NEXT_PUBLIC_DUCK', + ]); + }); + + describe('cross-schema dependencies', () => { + it('accepts DEX pools together with the contract info API host', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_DEX_POOLS_ENABLED: 'true', + NEXT_PUBLIC_CONTRACT_INFO_API_HOST: 'https://example.com', + })).toEqual([]); + }); + + it('rejects DEX pools without the contract info API host', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_DEX_POOLS_ENABLED: 'true' })).toEqual([ + 'NEXT_PUBLIC_DEX_POOLS_ENABLED can only be used with NEXT_PUBLIC_CONTRACT_INFO_API_HOST', + ]); + }); + + it('accepts the operational txs chart together with the stats API host', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_HOMEPAGE_CHARTS: toEnvValue([ 'daily_operational_txs' ]), + NEXT_PUBLIC_STATS_API_HOST: 'https://example.com', + })).toEqual([]); + }); + + it('rejects the operational txs chart without the stats API host', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_HOMEPAGE_CHARTS: toEnvValue([ 'daily_operational_txs' ]) })).toEqual([ + 'NEXT_PUBLIC_STATS_API_HOST is required when daily_operational_txs is enabled in NEXT_PUBLIC_HOMEPAGE_CHARTS', + ]); + }); + + it('accepts the operational txs stat together with the stats API host', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_HOMEPAGE_STATS: toEnvValue([ 'total_operational_txs' ]), + NEXT_PUBLIC_STATS_API_HOST: 'https://example.com', + })).toEqual([]); + }); + + it('rejects the operational txs stat without the stats API host', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_HOMEPAGE_STATS: toEnvValue([ 'total_operational_txs' ]) })).toEqual([ + 'NEXT_PUBLIC_STATS_API_HOST is required when total_operational_txs is enabled in NEXT_PUBLIC_HOMEPAGE_STATS', + ]); + }); + + it('accepts the verification type for a non-Arbitrum rollup', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_ROLLUP_TYPE: 'optimistic', + NEXT_PUBLIC_ROLLUP_PARENT_CHAIN: toEnvValue({ baseUrl: 'https://example.com' }), + NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE: 'validation', + })).toEqual([]); + }); + + it('rejects the verification type for an Arbitrum rollup', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_ROLLUP_TYPE: 'arbitrum', + NEXT_PUBLIC_ROLLUP_PARENT_CHAIN: toEnvValue({ baseUrl: 'https://example.com' }), + NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE: 'validation', + })).toEqual([ 'NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE can not be set for Arbitrum rollups' ]); + }); + + it('rejects the zetaChain API host without the chains config', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST: 'https://example.com' })).toEqual([ + 'NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST cannot be used without NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', + ]); + }); + }); + + describe('NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE', () => { + it('accepts text formatting and links', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE: '<b>Notice:</b> use the <a href="https://example.com" target="_blank">new API</a>', + })).toEqual([]); + }); + + it('accepts a single-quoted attribute value that holds a double quote, as the app renders it', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE: `Pay <a href="https://example.com" title='x" onclick="steal()'>here</a>`, + })).toEqual([]); + }); + + it('rejects a frame or an event handler', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE: '<a href="https://example.com" onclick="steal()">Notice</a><iframe src="https://evil.example"></iframe>', + })).toEqual([ + 'NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE: HTML contains elements that are not allowed: onclick attribute on <a>, <iframe>', + ]); + }); + }); + + describe('NEXT_PUBLIC_WEB3_WALLETS', () => { + it('accepts a list of supported wallets or the "none" literal', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_WEB3_WALLETS: toEnvValue([ 'metamask', 'coinbase' ]) })).toEqual([]); + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_WEB3_WALLETS: 'none' })).toEqual([]); + }); + + it('rejects an unsupported wallet', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_WEB3_WALLETS: toEnvValue([ 'duck_wallet' ]) })).toEqual([ + 'NEXT_PUBLIC_WEB3_WALLETS: Invalid type: Expected "none" but received "[\'duck_wallet\']"', + 'NEXT_PUBLIC_WEB3_WALLETS.0: Invalid type: Expected ("metamask" | "coinbase" | "token_pocket" | "rabby" | "okx" | "trust") but received "duck_wallet"', + ]); + }); + }); + + describe('NEXT_PUBLIC_GAS_REFUEL_PROVIDER_CONFIG', () => { + it('accepts a provider with a name and url template', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_GAS_REFUEL_PROVIDER_CONFIG: toEnvValue({ name: 'Need gas?', url_template: 'https://example.com/{chainId}' }), + })).toEqual([]); + }); + + it('rejects a provider without a url template', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_GAS_REFUEL_PROVIDER_CONFIG: toEnvValue({ name: 'Need gas?' }) })).toEqual([ + 'NEXT_PUBLIC_GAS_REFUEL_PROVIDER_CONFIG.url_template: Invalid key: Expected "url_template" but received undefined', + ]); + }); + }); + + describe('NEXT_PUBLIC_ADDRESS_USERNAME_TAG', () => { + it('accepts a config with an api url template', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_ADDRESS_USERNAME_TAG: toEnvValue({ api_url_template: 'https://example.com/{address}', tag_icon: 'https://example.com/icon.svg' }), + })).toEqual([]); + }); + + it('rejects a config without an api url template', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_ADDRESS_USERNAME_TAG: toEnvValue({ tag_icon: 'https://example.com/icon.svg' }) })).toEqual([ + 'NEXT_PUBLIC_ADDRESS_USERNAME_TAG.api_url_template: Invalid key: Expected "api_url_template" but received undefined', + ]); + }); + }); + + describe('NEXT_PUBLIC_TX_EXTERNAL_TRANSACTIONS_CONFIG', () => { + it('accepts a full config', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_TX_EXTERNAL_TRANSACTIONS_CONFIG: toEnvValue(txExternalTxsConfig) })).toEqual([]); + }); + + it('rejects a config without the explorer url template', () => { + const incomplete = { chain_name: txExternalTxsConfig.chain_name, chain_logo_url: txExternalTxsConfig.chain_logo_url }; + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_TX_EXTERNAL_TRANSACTIONS_CONFIG: toEnvValue(incomplete) })).toEqual([ + 'NEXT_PUBLIC_TX_EXTERNAL_TRANSACTIONS_CONFIG.explorer_url_template: Invalid key: Expected "explorer_url_template" but received undefined', + ]); + }); + }); + + describe('Usercentrics', () => { + it('accepts the config together with the draft flag', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_USERCENTRICS_CONFIG: toEnvValue({ settingsId: 'xxx' }), + NEXT_PUBLIC_USERCENTRICS_DRAFT: 'true', + })).toEqual([]); + }); + + it('rejects a config that is not an object', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_USERCENTRICS_CONFIG: 'xxx' })).toEqual([ + 'NEXT_PUBLIC_USERCENTRICS_CONFIG: Invalid JSON: Received "xxx"', + ]); + }); + + it('rejects the draft flag without the config', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_USERCENTRICS_DRAFT: 'true' })).toEqual([ + 'NEXT_PUBLIC_USERCENTRICS_DRAFT can only be used with NEXT_PUBLIC_USERCENTRICS_CONFIG', + ]); + }); + }); + + describe('enumerated values', () => { + it('accepts a supported value', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_TRANSACTION_INTERPRETATION_PROVIDER: 'blockscout', + NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE: 'stability', + NEXT_PUBLIC_GAS_TRACKER_UNITS: toEnvValue([ 'gwei', 'usd' ]), + NEXT_PUBLIC_APP_PROTOCOL: 'https', + NEXT_PUBLIC_APP_PORT: '3000', + })).toEqual([]); + }); + + it('rejects an unsupported transaction interpretation provider', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_TRANSACTION_INTERPRETATION_PROVIDER: 'duck' })).toEqual([ + 'NEXT_PUBLIC_TRANSACTION_INTERPRETATION_PROVIDER: Invalid type: Expected ("blockscout" | "noves" | "none") but received "duck"', + ]); + }); + + it('rejects an unsupported validators chain type', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE: 'duck' })).toEqual([ + 'NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE: Invalid type: Expected ("stability" | "blackfort" | "zilliqa") but received "duck"', + ]); + }); + + it('rejects an unsupported gas tracker unit', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_GAS_TRACKER_UNITS: toEnvValue([ 'eth' ]) })).toEqual([ + 'NEXT_PUBLIC_GAS_TRACKER_UNITS.0: Invalid type: Expected ("usd" | "gwei") but received "eth"', + ]); + }); + + it('rejects an unsupported app protocol', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_APP_PROTOCOL: 'ftp' })).toEqual([ + 'NEXT_PUBLIC_APP_PROTOCOL: Invalid type: Expected ("http" | "https") but received "ftp"', + ]); + }); + + it('rejects an app port that is not a positive integer', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_APP_PORT: '-1' })).toEqual([ + 'NEXT_PUBLIC_APP_PORT: Invalid value: Expected >=1 but received -1', + ]); + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_APP_PORT: '1.5' })).toEqual([ 'NEXT_PUBLIC_APP_PORT: Invalid integer: Received 1.5' ]); + }); + }); + + it.each([ + 'NEXT_PUBLIC_WEB3_DISABLE_ADD_TOKEN_TO_WALLET', + 'NEXT_PUBLIC_IS_SUAVE_CHAIN', + 'NEXT_PUBLIC_METASUITES_ENABLED', + 'NEXT_PUBLIC_GAS_TRACKER_ENABLED', + 'NEXT_PUBLIC_DATA_AVAILABILITY_ENABLED', + 'NEXT_PUBLIC_ADVANCED_FILTER_ENABLED', + 'NEXT_PUBLIC_CELO_ENABLED', + 'NEXT_PUBLIC_HOT_CONTRACTS_ENABLED', + 'NEXT_PUBLIC_PRO_API_SUPPORTED', + 'NEXT_PUBLIC_USE_NEXT_JS_PROXY', + ])('rejects a non-boolean %s', (name) => { + expect(getValidationErrors(schema, { ...REQUIRED, [name]: 'yes' })).toEqual([ + `${ name }: Expected "true" or "false" but received "yes"`, + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schema.ts b/deploy/tools/envs-validator/schema.ts index 6b482ff0742..40009e82b7e 100644 --- a/deploy/tools/envs-validator/schema.ts +++ b/deploy/tools/envs-validator/schema.ts @@ -1,92 +1,93 @@ -/* eslint-disable max-len */ -declare module 'yup' { - interface StringSchema { - // Yup's URL validator is not perfect so we made our own - // https://github.com/jquense/yup/pull/1859 - url(): never; - } -} +// SPDX-License-Identifier: LicenseRef-Blockscout -import * as yup from 'yup'; +import * as v from 'valibot'; -type AddressProfileAPIConfig = { - api_url_template: string; - tag_link_template?: string; - tag_icon?: string; - tag_bg_color?: string; - tag_text_color?: string; -}; +import type { TxExternalTxsConfig } from 'src/features/external-txs/types/client'; import type { GasRefuelProviderConfig } from 'src/features/get-gas-button/types/client'; -import { GAS_UNITS } from 'src/slices/gas/types/config'; -import type { GasUnit } from 'src/slices/gas/types/config'; import { PROVIDERS as TX_INTERPRETATION_PROVIDERS } from 'src/features/tx-interpretation/common/types/config'; import { VALIDATORS_CHAIN_TYPE } from 'src/features/validators/types/config'; -import type { ValidatorsChainType } from 'src/features/validators/types/config'; -import type { WalletType } from 'src/features/web3-wallet/types/config'; import { SUPPORTED_WALLETS } from 'src/features/web3-wallet/types/config'; -import type { TxExternalTxsConfig } from 'src/features/external-txs/types/client'; +import { GAS_UNITS } from 'src/slices/gas/types/config'; -import { replaceQuotes } from 'src/config/utils/envs'; -import { urlTest, protocols } from './utils'; import apisSchema from './schemas/apis'; +import { appSchema, buildTimeSchema, proxySchema } from './schemas/app'; import chainSchema from './schemas/chain'; -import metaSchema from './schemas/meta'; -import * as uiSchemas from './schemas/ui'; import * as featuresSchemas from './schemas/features'; +import metaSchema from './schemas/meta'; import servicesSchema from './schemas/services'; +import * as uiSchemas from './schemas/ui'; +import { composeSchemas, envBoolean, envHtml, envJson, envUrl, requires } from './utils'; -const schema = yup - .object() - .noUnknown(true, (params) => { - return `Unknown ENV variables were provided: ${ params.unknown }`; - }) - .shape({ - // I. Build-time ENVs - // ----------------- - NEXT_PUBLIC_GIT_TAG: yup.string(), - NEXT_PUBLIC_GIT_COMMIT_SHA: yup.string(), +type AddressProfileAPIConfig = { + api_url_template: string; + tag_link_template?: string; + tag_icon?: string; + tag_bg_color?: string; + tag_text_color?: string; +}; - // II. Run-time ENVs - // ----------------- - // App configuration - NEXT_PUBLIC_APP_HOST: yup.string().required(), - NEXT_PUBLIC_APP_PROTOCOL: yup.string().oneOf(protocols), - NEXT_PUBLIC_APP_PORT: yup.number().positive().integer(), - NEXT_PUBLIC_APP_ENV: yup.string(), - NEXT_PUBLIC_APP_INSTANCE: yup.string(), +const gasRefuelProviderConfigSchema: v.GenericSchema<GasRefuelProviderConfig> = v.object({ + name: v.pipe(v.string(), v.nonEmpty()), + url_template: v.pipe(v.string(), v.nonEmpty()), + logo: v.optional(v.string()), + dapp_id: v.optional(v.string()), +}); +const addressProfileAPIConfigSchema: v.GenericSchema<AddressProfileAPIConfig> = v.object({ + api_url_template: v.pipe(v.string(), v.nonEmpty()), + tag_link_template: v.optional(v.string()), + tag_icon: v.optional(v.string()), + tag_bg_color: v.optional(v.string()), + tag_text_color: v.optional(v.string()), +}); - // Features configuration - // NOTE: As a rule of thumb, only include features that require a single ENV variable here. - // Otherwise, consider placing them in the corresponding schema file in the "./schemas/features" directory. - NEXT_PUBLIC_WEB3_WALLETS: yup - .mixed() - .test('shape', 'Invalid schema were provided for NEXT_PUBLIC_WEB3_WALLETS, it should be either array or "none" string literal', (data) => { - const isNoneSchema = yup.string().equals([ 'none' ]); - const isArrayOfWalletsSchema = yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string<WalletType>().oneOf(SUPPORTED_WALLETS)); +const txExternalTxsConfigSchema: v.GenericSchema<TxExternalTxsConfig> = v.object({ + chain_name: v.pipe(v.string(), v.nonEmpty()), + chain_logo_url: v.pipe(v.string(), v.nonEmpty()), + explorer_url_template: v.pipe(v.string(), v.nonEmpty()), +}); - return isNoneSchema.isValidSync(data) || isArrayOfWalletsSchema.isValidSync(data); - }), - NEXT_PUBLIC_WEB3_DISABLE_ADD_TOKEN_TO_WALLET: yup.boolean(), - NEXT_PUBLIC_TRANSACTION_INTERPRETATION_PROVIDER: yup.string().oneOf(TX_INTERPRETATION_PROVIDERS), - NEXT_PUBLIC_SAFE_TX_SERVICE_URL: yup.string().test(urlTest), - NEXT_PUBLIC_IS_SUAVE_CHAIN: yup.boolean(), - NEXT_PUBLIC_METASUITES_ENABLED: yup.boolean(), - NEXT_PUBLIC_GAS_REFUEL_PROVIDER_CONFIG: yup - .mixed() - .test('shape', 'Invalid schema were provided for NEXT_PUBLIC_GAS_REFUEL_PROVIDER_CONFIG, it should have name and url template', (data) => { - const isUndefined = data === undefined; - const valueSchema = yup.object<GasRefuelProviderConfig>().transform(replaceQuotes).json().shape({ - name: yup.string().required(), - url_template: yup.string().required(), - logo: yup.string(), - dapp_id: yup.string(), - }); +const usercentricsConfigSchema = v.object({ + settingsId: v.optional(v.string()), + rulesetId: v.optional(v.string()), +}); + +const singleVariableFeaturesSchema = v.pipe( + v.looseObject({ + NEXT_PUBLIC_WEB3_WALLETS: v.optional(v.union([ v.literal('none'), envJson(v.array(v.picklist(SUPPORTED_WALLETS))) ])), + NEXT_PUBLIC_WEB3_DISABLE_ADD_TOKEN_TO_WALLET: v.optional(envBoolean()), + NEXT_PUBLIC_TRANSACTION_INTERPRETATION_PROVIDER: v.optional(v.picklist(TX_INTERPRETATION_PROVIDERS)), + NEXT_PUBLIC_SAFE_TX_SERVICE_URL: v.optional(envUrl()), + NEXT_PUBLIC_IS_SUAVE_CHAIN: v.optional(envBoolean()), + NEXT_PUBLIC_METASUITES_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_GAS_REFUEL_PROVIDER_CONFIG: v.optional(envJson(gasRefuelProviderConfigSchema)), + NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE: v.optional(v.picklist(VALIDATORS_CHAIN_TYPE)), + NEXT_PUBLIC_GAS_TRACKER_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_GAS_TRACKER_UNITS: v.optional(envJson(v.array(v.picklist(GAS_UNITS)))), + NEXT_PUBLIC_DATA_AVAILABILITY_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_ADVANCED_FILTER_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_CELO_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_DEX_POOLS_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_ADDRESS_USERNAME_TAG: v.optional(envJson(addressProfileAPIConfigSchema)), + NEXT_PUBLIC_XSTAR_SCORE_URL: v.optional(envUrl()), + NEXT_PUBLIC_GAME_BADGE_CLAIM_LINK: v.optional(envUrl()), + NEXT_PUBLIC_PUZZLE_GAME_BADGE_CLAIM_LINK: v.optional(envUrl()), + NEXT_PUBLIC_TX_EXTERNAL_TRANSACTIONS_CONFIG: v.optional(envJson(txExternalTxsConfigSchema)), + NEXT_PUBLIC_HOT_CONTRACTS_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_USERCENTRICS_CONFIG: v.optional(envJson(usercentricsConfigSchema)), + NEXT_PUBLIC_USERCENTRICS_DRAFT: v.optional(envBoolean()), + }), + requires('NEXT_PUBLIC_DEX_POOLS_ENABLED', 'NEXT_PUBLIC_CONTRACT_INFO_API_HOST'), + requires('NEXT_PUBLIC_USERCENTRICS_DRAFT', 'NEXT_PUBLIC_USERCENTRICS_CONFIG'), +); + +const miscSchema = v.object({ + NEXT_PUBLIC_PRO_API_SUPPORTED: v.optional(envBoolean()), + NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE: v.optional(envHtml()), + NEXT_PUBLIC_API_DOCS_ALERT_MESSAGE: v.optional(v.string()), +}); +<<<<<<< HEAD return isUndefined || valueSchema.isValidSync(data); }), NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE: yup.string<ValidatorsChainType>().oneOf(VALIDATORS_CHAIN_TYPE), @@ -190,5 +191,43 @@ const schema = yup .concat(featuresSchemas.userOpsSchema) .concat(featuresSchemas.zetaChainSchema) .concat(servicesSchema) +======= +const schema = composeSchemas([ + buildTimeSchema, + appSchema, + proxySchema, + singleVariableFeaturesSchema, + miscSchema, + apisSchema, + chainSchema, + metaSchema, + uiSchemas.homepageSchema, + uiSchemas.navigationSchema, + uiSchemas.footerSchema, + uiSchemas.miscSchema, + uiSchemas.viewsSchema, + featuresSchemas.accountSchema, + featuresSchemas.address3rdPartyWidgetsConfigSchema, + featuresSchemas.adsSchema, + featuresSchemas.apiDocsSchema, + featuresSchemas.beaconChainSchema, + featuresSchemas.bridgedTokensSchema, + featuresSchemas.bubblemapsSchema, + featuresSchemas.crossChainTxsSchema, + featuresSchemas.defiDropdownSchema, + featuresSchemas.flashblocksSchema, + featuresSchemas.highlightsConfigSchema, + featuresSchemas.marketplaceSchema, + featuresSchemas.megaEthSchema, + featuresSchemas.multichainButtonSchema, + featuresSchemas.nameServicesSchema, + featuresSchemas.rollupSchema, + featuresSchemas.tacSchema, + featuresSchemas.tokenActionButtonSchema, + featuresSchemas.userOpsSchema, + featuresSchemas.zetaChainSchema, + servicesSchema, +]); +>>>>>>> v2.13.0 export default schema; diff --git a/deploy/tools/envs-validator/schema_multichain.spec.ts b/deploy/tools/envs-validator/schema_multichain.spec.ts new file mode 100644 index 00000000000..4afdd3811af --- /dev/null +++ b/deploy/tools/envs-validator/schema_multichain.spec.ts @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { multichainConfig } from './mocks/instance'; +import schema from './schema_multichain'; +import { toEnvValue } from './test-utils'; +import { getValidationErrors } from './utils'; + +const REQUIRED = { + NEXT_PUBLIC_APP_HOST: 'localhost', + NEXT_PUBLIC_NETWORK_NAME: 'Multichain', +}; + +describe('multichain schema', () => { + it('accepts a full known-good configuration', () => { + expect(getValidationErrors(schema, multichainConfig)).toEqual([]); + }); + + it('requires the app host and network name only', () => { + expect(getValidationErrors(schema, {}).sort()).toEqual([ + 'NEXT_PUBLIC_APP_HOST: Invalid key: Expected "NEXT_PUBLIC_APP_HOST" but received undefined', + 'NEXT_PUBLIC_NETWORK_NAME: Invalid key: Expected "NEXT_PUBLIC_NETWORK_NAME" but received undefined', + ]); + }); + + it('rejects an unknown variable', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_DUCK: 'quack' })).toEqual([ + 'Unknown ENV variables were provided: NEXT_PUBLIC_DUCK', + ]); + }); + + it.each([ + [ 'NEXT_PUBLIC_NETWORK_ID', '1' ], + [ 'NEXT_PUBLIC_ROLLUP_TYPE', 'optimistic' ], + ])('treats the single-chain-only %s as unknown', (name, value) => { + expect(getValidationErrors(schema, { ...REQUIRED, [name]: value })).toEqual([ `Unknown ENV variables were provided: ${ name }` ]); + }); + + describe('features disabled in multichain mode', () => { + it.each([ + 'NEXT_PUBLIC_GAS_TRACKER_ENABLED', + 'NEXT_PUBLIC_ADVANCED_FILTER_ENABLED', + 'NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED', + ])('accepts %s set to false and rejects it set to true', (name) => { + expect(getValidationErrors(schema, { ...REQUIRED, [name]: 'false' })).toEqual([]); + expect(getValidationErrors(schema, { ...REQUIRED, [name]: 'true' })).toEqual([ `${ name }: Invalid type: Expected false but received true` ]); + }); + + it('accepts an empty API docs tabs list and rejects a non-empty one', () => { + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_API_DOCS_TABS: '[]' })).toEqual([]); + expect(getValidationErrors(schema, { ...REQUIRED, NEXT_PUBLIC_API_DOCS_TABS: toEnvValue([ 'rest_api' ]) })).toEqual([ + 'NEXT_PUBLIC_API_DOCS_TABS: Invalid length: Expected <=0 but received 1', + ]); + }); + }); + + describe('multichain services', () => { + it('accepts valid aggregator and stats hosts', () => { + expect(getValidationErrors(schema, { + ...REQUIRED, + NEXT_PUBLIC_MULTICHAIN_AGGREGATOR_API_HOST: 'https://example.com', + NEXT_PUBLIC_MULTICHAIN_STATS_API_HOST: 'https://example.com', + })).toEqual([]); + }); + + it.each([ + 'NEXT_PUBLIC_MULTICHAIN_AGGREGATOR_API_HOST', + 'NEXT_PUBLIC_MULTICHAIN_STATS_API_HOST', + ])('rejects a malformed %s', (name) => { + expect(getValidationErrors(schema, { ...REQUIRED, [name]: 'not a url' })).toEqual([ `${ name }: Invalid URL: Received "not a url"` ]); + }); + }); +}); diff --git a/deploy/tools/envs-validator/schema_multichain.ts b/deploy/tools/envs-validator/schema_multichain.ts index 6e8dfe4efde..47c64716c10 100644 --- a/deploy/tools/envs-validator/schema_multichain.ts +++ b/deploy/tools/envs-validator/schema_multichain.ts @@ -1,60 +1,47 @@ -declare module 'yup' { - interface StringSchema { - // Yup's URL validator is not perfect so we made our own - // https://github.com/jquense/yup/pull/1859 - url(): never; - } - } - -import * as yup from 'yup'; -import { urlTest, protocols } from './utils'; -import * as uiSchemas from './schemas/ui'; -import * as featuresSchemas from './schemas/features'; -import servicesSchemas from './schemas/services'; -import { replaceQuotes } from 'src/config/utils/envs'; +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + import { IDENTICON_TYPES } from 'src/slices/address/types/config'; -const schema = yup - .object() - .noUnknown(true, (params) => { - return `Unknown ENV variables were provided: ${ params.unknown }`; - }) - .shape({ - // I. Build-time ENVs - // ----------------- - NEXT_PUBLIC_GIT_TAG: yup.string(), - NEXT_PUBLIC_GIT_COMMIT_SHA: yup.string(), +import { appSchema, buildTimeSchema, proxySchema } from './schemas/app'; +import * as featuresSchemas from './schemas/features'; +import servicesSchema from './schemas/services'; +import * as uiSchemas from './schemas/ui'; +import { composeSchemas, envBoolean, envJson, envRequiredString, envUrl } from './utils'; - // II. Run-time ENVs - // ----------------- - // 1. App configuration - NEXT_PUBLIC_APP_HOST: yup.string().required(), - NEXT_PUBLIC_APP_PROTOCOL: yup.string().oneOf(protocols), - NEXT_PUBLIC_APP_PORT: yup.number().positive().integer(), - NEXT_PUBLIC_APP_ENV: yup.string(), - NEXT_PUBLIC_APP_INSTANCE: yup.string(), +const chainSchema = v.object({ + NEXT_PUBLIC_NETWORK_NAME: envRequiredString(), + NEXT_PUBLIC_NETWORK_SHORT_NAME: v.optional(v.string()), + NEXT_PUBLIC_IS_TESTNET: v.optional(envBoolean()), +}); - // 2. Blockchain parameters - NEXT_PUBLIC_NETWORK_NAME: yup.string().required(), - NEXT_PUBLIC_NETWORK_SHORT_NAME: yup.string(), - NEXT_PUBLIC_IS_TESTNET: yup.boolean(), +// Only the view settings that multichain mode actually supports. +const viewsSchema = v.object({ + NEXT_PUBLIC_VIEWS_ADDRESS_IDENTICON_TYPE: v.optional(v.picklist(IDENTICON_TYPES)), + NEXT_PUBLIC_INTERNAL_TXS_ENABLED: v.optional(envBoolean()), +}); - // 3. UI views configuration - // Some settings that we actually support in multichain mode - NEXT_PUBLIC_VIEWS_ADDRESS_IDENTICON_TYPE: yup.string().oneOf(IDENTICON_TYPES), - NEXT_PUBLIC_INTERNAL_TXS_ENABLED: yup.boolean(), +// Not every feature is supported in multichain mode; the ones enabled by default must be turned off +// explicitly, hence the `false`-only flags. +const featuresSchema = v.object({ + NEXT_PUBLIC_OG_DESCRIPTION: v.optional(v.string()), + NEXT_PUBLIC_OG_IMAGE_URL: v.optional(envUrl()), - // 5. Features configuration - // NOTE!: Not all features are supported in multichain mode, and some of them not relevant or enabled per chain basis - // Below listed supported features and the features that are enabled by default, so we have to turn them off - NEXT_PUBLIC_OG_DESCRIPTION: yup.string(), - NEXT_PUBLIC_OG_IMAGE_URL: yup.string().test(urlTest), + NEXT_PUBLIC_GAS_TRACKER_ENABLED: v.optional(v.pipe(envBoolean(), v.literal(false))), + NEXT_PUBLIC_ADVANCED_FILTER_ENABLED: v.optional(v.pipe(envBoolean(), v.literal(false))), + NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED: v.optional(v.pipe(envBoolean(), v.literal(false))), + NEXT_PUBLIC_API_DOCS_TABS: v.optional(envJson(v.pipe(v.array(v.unknown()), v.maxLength(0)))), +}); - NEXT_PUBLIC_GAS_TRACKER_ENABLED: yup.boolean().equals([false]), - NEXT_PUBLIC_ADVANCED_FILTER_ENABLED: yup.boolean().equals([false]), - NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED: yup.boolean().equals([false]), - NEXT_PUBLIC_API_DOCS_TABS: yup.array().transform(replaceQuotes).json().max(0), +const multichainSchema = v.object({ + NEXT_PUBLIC_MULTICHAIN_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_MULTICHAIN_CLUSTER: v.optional(v.string()), + NEXT_PUBLIC_MULTICHAIN_AGGREGATOR_API_HOST: v.optional(envUrl()), + NEXT_PUBLIC_MULTICHAIN_STATS_API_HOST: v.optional(envUrl()), +}); +<<<<<<< HEAD // 6. Multichain configuration NEXT_PUBLIC_MULTICHAIN_ENABLED: yup.boolean(), NEXT_PUBLIC_MULTICHAIN_CLUSTER: yup.string(), @@ -75,5 +62,27 @@ const schema = yup .concat(featuresSchemas.tokenActionButtonSchema) .concat(featuresSchemas.userOpsSchema) .concat(servicesSchemas); +======= +const schema = composeSchemas([ + buildTimeSchema, + appSchema, + proxySchema, + chainSchema, + viewsSchema, + featuresSchema, + multichainSchema, + uiSchemas.homepageSchema, + uiSchemas.navigationSchema, + uiSchemas.footerSchema, + uiSchemas.miscSchema, + featuresSchemas.adsSchema, + featuresSchemas.crossChainTxsSchema, + featuresSchemas.defiDropdownSchema, + featuresSchemas.multichainButtonSchema, + featuresSchemas.tokenActionButtonSchema, + featuresSchemas.userOpsSchema, + servicesSchema, +]); +>>>>>>> v2.13.0 export default schema; diff --git a/deploy/tools/envs-validator/schemas/apis.spec.ts b/deploy/tools/envs-validator/schemas/apis.spec.ts new file mode 100644 index 00000000000..aed161fd8e0 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/apis.spec.ts @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { StatsApiResourceNameRefetchInterval } from 'src/features/chain-stats/types/config'; + +import { describe, expect, it } from 'vitest'; + +import { toEnvValue } from '../test-utils'; +import { getValidationErrors } from '../utils'; +import apisSchema from './apis'; + +const REQUIRED = { NEXT_PUBLIC_API_HOST: 'blockscout.com' }; + +const refetchInterval: Record<StatsApiResourceNameRefetchInterval, number> = { + 'stats:counters': 10_000, + 'stats:pages_main': 10_000, +}; + +describe('apisSchema', () => { + it('accepts the core API settings', () => { + expect(getValidationErrors(apisSchema, { + ...REQUIRED, + NEXT_PUBLIC_API_PROTOCOL: 'https', + NEXT_PUBLIC_API_PORT: '443', + NEXT_PUBLIC_API_BASE_PATH: '/', + NEXT_PUBLIC_API_WEBSOCKET_PROTOCOL: 'wss', + })).toEqual([]); + }); + + it('requires the API host', () => { + expect(getValidationErrors(apisSchema, {})).toEqual([ 'NEXT_PUBLIC_API_HOST: Invalid key: Expected "NEXT_PUBLIC_API_HOST" but received undefined' ]); + }); + + it('rejects an unsupported protocol', () => { + expect(getValidationErrors(apisSchema, { ...REQUIRED, NEXT_PUBLIC_API_PROTOCOL: 'ftp' })).toEqual([ + 'NEXT_PUBLIC_API_PROTOCOL: Invalid type: Expected ("http" | "https") but received "ftp"', + ]); + expect(getValidationErrors(apisSchema, { ...REQUIRED, NEXT_PUBLIC_API_WEBSOCKET_PROTOCOL: 'http' })).toEqual([ + 'NEXT_PUBLIC_API_WEBSOCKET_PROTOCOL: Invalid type: Expected ("ws" | "wss") but received "http"', + ]); + }); + + it('rejects a port that is not a positive integer', () => { + expect(getValidationErrors(apisSchema, { ...REQUIRED, NEXT_PUBLIC_API_PORT: '-1' })).toEqual([ + 'NEXT_PUBLIC_API_PORT: Invalid value: Expected >=1 but received -1', + ]); + expect(getValidationErrors(apisSchema, { ...REQUIRED, NEXT_PUBLIC_API_PORT: '1.5' })).toEqual([ + 'NEXT_PUBLIC_API_PORT: Invalid integer: Received 1.5', + ]); + }); + + describe('stats API', () => { + it('accepts the host with a refetch interval', () => { + expect(getValidationErrors(apisSchema, { + ...REQUIRED, + NEXT_PUBLIC_STATS_API_HOST: 'https://stats.example.com', + NEXT_PUBLIC_STATS_API_BASE_PATH: '/', + NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL: toEnvValue(refetchInterval), + })).toEqual([]); + }); + + it('rejects a refetch interval that is not a positive integer', () => { + expect(getValidationErrors(apisSchema, { + ...REQUIRED, + NEXT_PUBLIC_STATS_API_HOST: 'https://stats.example.com', + NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL: toEnvValue({ 'stats:counters': -1 }), + })).toEqual([ + 'NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL.stats:counters: Invalid value: Expected >=1 but received -1', + ]); + }); + + it('rejects an unknown resource in the refetch interval', () => { + expect(getValidationErrors(apisSchema, { + ...REQUIRED, + NEXT_PUBLIC_STATS_API_HOST: 'https://stats.example.com', + NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL: toEnvValue({ 'stats:unknown': 1 }), + })).toEqual([ + 'NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL.stats:unknown: Invalid key: Expected never but received "stats:unknown"', + ]); + }); + + it('rejects the refetch interval without the host', () => { + expect(getValidationErrors(apisSchema, { + ...REQUIRED, + NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL: toEnvValue(refetchInterval), + })).toEqual([ 'NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL can only be used with NEXT_PUBLIC_STATS_API_HOST' ]); + }); + }); + + describe.each([ + [ 'NEXT_PUBLIC_CONTRACT_INFO_INSTANCE_ID', 'NEXT_PUBLIC_CONTRACT_INFO_API_HOST', '420:duck' ], + [ 'NEXT_PUBLIC_ADMIN_RS_INSTANCE_ID', 'NEXT_PUBLIC_ADMIN_SERVICE_API_HOST', '420:duck' ], + ])('%s', (dependent, host, value) => { + it(`is accepted together with ${ host }`, () => { + expect(getValidationErrors(apisSchema, { ...REQUIRED, [host]: 'https://example.com', [dependent]: value })).toEqual([]); + }); + + it(`is rejected without ${ host }`, () => { + expect(getValidationErrors(apisSchema, { ...REQUIRED, [dependent]: value })).toEqual([ + `${ dependent } can only be used with ${ host }`, + ]); + }); + }); + + describe('metadata service', () => { + it('accepts the tags update flag together with the host', () => { + expect(getValidationErrors(apisSchema, { + ...REQUIRED, + NEXT_PUBLIC_METADATA_SERVICE_API_HOST: 'https://example.com', + NEXT_PUBLIC_METADATA_ADDRESS_TAGS_UPDATE_ENABLED: 'false', + })).toEqual([]); + }); + + it('rejects the tags update flag without the host', () => { + expect(getValidationErrors(apisSchema, { ...REQUIRED, NEXT_PUBLIC_METADATA_ADDRESS_TAGS_UPDATE_ENABLED: 'true' })).toEqual([ + 'NEXT_PUBLIC_METADATA_ADDRESS_TAGS_UPDATE_ENABLED cannot not be used if NEXT_PUBLIC_METADATA_SERVICE_API_HOST is not defined', + ]); + }); + }); + + it.each([ + 'NEXT_PUBLIC_STATS_API_HOST', + 'NEXT_PUBLIC_VISUALIZE_API_HOST', + 'NEXT_PUBLIC_CONTRACT_INFO_API_HOST', + 'NEXT_PUBLIC_ADMIN_SERVICE_API_HOST', + 'NEXT_PUBLIC_REWARDS_SERVICE_API_HOST', + 'NEXT_PUBLIC_METADATA_SERVICE_API_HOST', + ])('rejects a malformed %s', (name) => { + expect(getValidationErrors(apisSchema, { ...REQUIRED, [name]: 'not a url' })).toEqual([ `${ name }: Invalid URL: Received "not a url"` ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/apis.ts b/deploy/tools/envs-validator/schemas/apis.ts index d6f53ac04f6..fc331ba18f9 100644 --- a/deploy/tools/envs-validator/schemas/apis.ts +++ b/deploy/tools/envs-validator/schemas/apis.ts @@ -1,94 +1,44 @@ -import * as yup from 'yup'; -import { getYupValidationErrorMessage, protocols, urlTest } from '../utils'; -import { replaceQuotes } from 'src/config/utils/envs'; -import { StatsApiResourceNameRefetchInterval } from 'src/features/chain-stats/types/config'; - -const statsApiRefetchIntervalSchema = yup.object<Record<StatsApiResourceNameRefetchInterval, number>>() - .transform(replaceQuotes) - .json() - .shape({ - 'stats:counters': yup.number().integer().positive(), - 'stats:pages_main': yup.number().integer().positive(), - }) - .exact(); - -export default yup.object({ - NEXT_PUBLIC_API_PROTOCOL: yup.string().oneOf(protocols), - NEXT_PUBLIC_API_HOST: yup.string().required(), - NEXT_PUBLIC_API_PORT: yup.number().integer().positive(), - NEXT_PUBLIC_API_BASE_PATH: yup.string(), - NEXT_PUBLIC_API_WEBSOCKET_PROTOCOL: yup.string().oneOf([ 'ws', 'wss' ]), - - NEXT_PUBLIC_STATS_API_HOST: yup.string().test(urlTest), - NEXT_PUBLIC_STATS_API_BASE_PATH: yup.string(), - NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL: yup - .mixed() - .test( - 'shape', - (ctx) => { - try { - statsApiRefetchIntervalSchema.validateSync(ctx.originalValue); - throw new Error('Unknown validation error'); - } catch (error: unknown) { - const message = getYupValidationErrorMessage(error); - return 'Invalid schema was provided for NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL' + (message ? `: ${ message }` : ''); - } - }, - (data) => { - const isUndefined = data === undefined; - return isUndefined || statsApiRefetchIntervalSchema.isValidSync(data); - }) - .when('NEXT_PUBLIC_STATS_API_HOST', { - is: (value: string) => Boolean(value), - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL can only be used with NEXT_PUBLIC_STATS_API_HOST', - value => value === undefined, - ), - }), - - NEXT_PUBLIC_VISUALIZE_API_HOST: yup.string().test(urlTest), - NEXT_PUBLIC_VISUALIZE_API_BASE_PATH: yup.string(), - - NEXT_PUBLIC_CONTRACT_INFO_API_HOST: yup.string().test(urlTest), - NEXT_PUBLIC_CONTRACT_INFO_INSTANCE_ID: yup.string() - .when('NEXT_PUBLIC_CONTRACT_INFO_API_HOST', { - is: (value: string) => Boolean(value), - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_CONTRACT_INFO_INSTANCE_ID can only be used with NEXT_PUBLIC_CONTRACT_INFO_API_HOST', - value => value === undefined, - ), - }), - - NEXT_PUBLIC_ADMIN_SERVICE_API_HOST: yup.string().test(urlTest), - NEXT_PUBLIC_ADMIN_RS_INSTANCE_ID: yup.string() - .when('NEXT_PUBLIC_ADMIN_SERVICE_API_HOST', { - is: (value: string) => Boolean(value), - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_ADMIN_RS_INSTANCE_ID can only be used with NEXT_PUBLIC_ADMIN_SERVICE_API_HOST', - value => value === undefined, - ), - }), - - NEXT_PUBLIC_REWARDS_SERVICE_API_HOST: yup.string().test(urlTest), - - NEXT_PUBLIC_METADATA_SERVICE_API_HOST: yup - .string() - .test(urlTest), - NEXT_PUBLIC_METADATA_ADDRESS_TAGS_UPDATE_ENABLED: yup - .boolean() - .when('NEXT_PUBLIC_METADATA_SERVICE_API_HOST', { - is: (value: string) => Boolean(value), - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_METADATA_ADDRESS_TAGS_UPDATE_ENABLED cannot not be used if NEXT_PUBLIC_METADATA_SERVICE_API_HOST is not defined', - value => value === undefined, - ), - }), -}); \ No newline at end of file +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + +import { envBoolean, envJson, envPositiveInteger, envRequiredString, envUrl, protocols, requires } from '../utils'; + +const statsApiRefetchIntervalSchema = envJson(v.strictObject({ + 'stats:counters': v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))), + 'stats:pages_main': v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))), +})); + +export default v.pipe( + v.object({ + NEXT_PUBLIC_API_PROTOCOL: v.optional(v.picklist(protocols)), + NEXT_PUBLIC_API_HOST: envRequiredString(), + NEXT_PUBLIC_API_PORT: v.optional(envPositiveInteger()), + NEXT_PUBLIC_API_BASE_PATH: v.optional(v.string()), + NEXT_PUBLIC_API_WEBSOCKET_PROTOCOL: v.optional(v.picklist([ 'ws', 'wss' ])), + + NEXT_PUBLIC_STATS_API_HOST: v.optional(envUrl()), + NEXT_PUBLIC_STATS_API_BASE_PATH: v.optional(v.string()), + NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL: v.optional(statsApiRefetchIntervalSchema), + + NEXT_PUBLIC_VISUALIZE_API_HOST: v.optional(envUrl()), + NEXT_PUBLIC_VISUALIZE_API_BASE_PATH: v.optional(v.string()), + + NEXT_PUBLIC_CONTRACT_INFO_API_HOST: v.optional(envUrl()), + NEXT_PUBLIC_CONTRACT_INFO_INSTANCE_ID: v.optional(v.string()), + + NEXT_PUBLIC_ADMIN_SERVICE_API_HOST: v.optional(envUrl()), + NEXT_PUBLIC_ADMIN_RS_INSTANCE_ID: v.optional(v.string()), + + NEXT_PUBLIC_REWARDS_SERVICE_API_HOST: v.optional(envUrl()), + + NEXT_PUBLIC_METADATA_SERVICE_API_HOST: v.optional(envUrl()), + NEXT_PUBLIC_METADATA_ADDRESS_TAGS_UPDATE_ENABLED: v.optional(envBoolean()), + }), + requires('NEXT_PUBLIC_STATS_API_REFETCH_INTERVAL', 'NEXT_PUBLIC_STATS_API_HOST'), + requires('NEXT_PUBLIC_CONTRACT_INFO_INSTANCE_ID', 'NEXT_PUBLIC_CONTRACT_INFO_API_HOST'), + requires('NEXT_PUBLIC_ADMIN_RS_INSTANCE_ID', 'NEXT_PUBLIC_ADMIN_SERVICE_API_HOST'), + requires('NEXT_PUBLIC_METADATA_ADDRESS_TAGS_UPDATE_ENABLED', 'NEXT_PUBLIC_METADATA_SERVICE_API_HOST', { + message: 'NEXT_PUBLIC_METADATA_ADDRESS_TAGS_UPDATE_ENABLED cannot not be used if NEXT_PUBLIC_METADATA_SERVICE_API_HOST is not defined', + }), +); diff --git a/deploy/tools/envs-validator/schemas/app.ts b/deploy/tools/envs-validator/schemas/app.ts new file mode 100644 index 00000000000..bf3214f68ac --- /dev/null +++ b/deploy/tools/envs-validator/schemas/app.ts @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + +import { envBoolean, envPositiveInteger, envRequiredString, protocols } from '../utils'; + +export const buildTimeSchema = v.object({ + NEXT_PUBLIC_GIT_TAG: v.optional(v.string()), + NEXT_PUBLIC_GIT_COMMIT_SHA: v.optional(v.string()), +}); + +export const appSchema = v.object({ + NEXT_PUBLIC_APP_HOST: envRequiredString(), + NEXT_PUBLIC_APP_PROTOCOL: v.optional(v.picklist(protocols)), + NEXT_PUBLIC_APP_PORT: v.optional(envPositiveInteger()), + NEXT_PUBLIC_APP_ENV: v.optional(v.string()), + NEXT_PUBLIC_APP_INSTANCE: v.optional(v.string()), +}); + +export const proxySchema = v.object({ + NEXT_PUBLIC_USE_NEXT_JS_PROXY: v.optional(envBoolean()), +}); diff --git a/deploy/tools/envs-validator/schemas/chain.spec.ts b/deploy/tools/envs-validator/schemas/chain.spec.ts new file mode 100644 index 00000000000..924bccaebc1 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/chain.spec.ts @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { toEnvValue } from '../test-utils'; +import { getValidationErrors } from '../utils'; +import chainSchema from './chain'; + +const REQUIRED = { NEXT_PUBLIC_NETWORK_ID: '1', NEXT_PUBLIC_NETWORK_NAME: 'Testnet' }; + +describe('chainSchema', () => { + it('accepts the full network configuration', () => { + expect(getValidationErrors(chainSchema, { + ...REQUIRED, + NEXT_PUBLIC_NETWORK_SHORT_NAME: 'Test', + NEXT_PUBLIC_NETWORK_RPC_URL: 'https://example.com', + NEXT_PUBLIC_NETWORK_CURRENCY_NAME: 'Ether', + NEXT_PUBLIC_NETWORK_CURRENCY_WEI_NAME: 'wei', + NEXT_PUBLIC_NETWORK_CURRENCY_GWEI_NAME: 'gwei', + NEXT_PUBLIC_NETWORK_CURRENCY_SYMBOL: 'ETH', + NEXT_PUBLIC_NETWORK_CURRENCY_DECIMALS: '18', + NEXT_PUBLIC_NETWORK_SECONDARY_COIN_SYMBOL: 'GNO', + NEXT_PUBLIC_NETWORK_MULTIPLE_GAS_CURRENCIES: 'true', + NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE: 'validation', + NEXT_PUBLIC_NETWORK_TOKEN_STANDARD_NAME: 'ERC', + NEXT_PUBLIC_NETWORK_ADDITIONAL_TOKEN_TYPES: toEnvValue([ { id: 'ERC-404', name: 'ERC-404' } ]), + NEXT_PUBLIC_IS_TESTNET: 'true', + })).toEqual([]); + }); + + it('requires the network id and name', () => { + expect(getValidationErrors(chainSchema, {})).toEqual([ + 'NEXT_PUBLIC_NETWORK_NAME: Invalid key: Expected "NEXT_PUBLIC_NETWORK_NAME" but received undefined', + 'NEXT_PUBLIC_NETWORK_ID: Invalid key: Expected "NEXT_PUBLIC_NETWORK_ID" but received undefined', + ]); + }); + + it('rejects a network id that is not a positive integer', () => { + expect(getValidationErrors(chainSchema, { ...REQUIRED, NEXT_PUBLIC_NETWORK_ID: '-1' })).toEqual([ + 'NEXT_PUBLIC_NETWORK_ID: Invalid value: Expected >=1 but received -1', + ]); + expect(getValidationErrors(chainSchema, { ...REQUIRED, NEXT_PUBLIC_NETWORK_ID: '1.5' })).toEqual([ + 'NEXT_PUBLIC_NETWORK_ID: Invalid integer: Received 1.5', + ]); + expect(getValidationErrors(chainSchema, { ...REQUIRED, NEXT_PUBLIC_NETWORK_ID: 'one' })).toEqual([ + 'NEXT_PUBLIC_NETWORK_ID: Expected a decimal number but received "one"', + ]); + }); + + it('rejects currency decimals that are not a positive integer', () => { + expect(getValidationErrors(chainSchema, { ...REQUIRED, NEXT_PUBLIC_NETWORK_CURRENCY_DECIMALS: '0' })).toEqual([ + 'NEXT_PUBLIC_NETWORK_CURRENCY_DECIMALS: Invalid value: Expected >=1 but received 0', + ]); + }); + + it.each([ + 'NEXT_PUBLIC_NETWORK_MULTIPLE_GAS_CURRENCIES', + 'NEXT_PUBLIC_IS_TESTNET', + ])('rejects a non-boolean %s', (name) => { + expect(getValidationErrors(chainSchema, { ...REQUIRED, [name]: 'yes' })).toEqual([ + `${ name }: Expected "true" or "false" but received "yes"`, + ]); + }); + + describe('RPC URL', () => { + it('accepts a single URL', () => { + expect(getValidationErrors(chainSchema, { ...REQUIRED, NEXT_PUBLIC_NETWORK_RPC_URL: 'https://example.com' })).toEqual([]); + }); + + it('accepts an array of URLs', () => { + expect(getValidationErrors(chainSchema, { + ...REQUIRED, + NEXT_PUBLIC_NETWORK_RPC_URL: toEnvValue([ 'https://example.com', 'https://example2.com' ]), + })).toEqual([]); + }); + + it('rejects an array containing a malformed URL', () => { + expect(getValidationErrors(chainSchema, { + ...REQUIRED, + NEXT_PUBLIC_NETWORK_RPC_URL: toEnvValue([ 'https://example.com', 'not a url' ]), + })).toEqual([ + 'NEXT_PUBLIC_NETWORK_RPC_URL: Invalid URL: Received "[\'https://example.com\',\'not a url\']"', + 'NEXT_PUBLIC_NETWORK_RPC_URL.1: Invalid URL: Received "not a url"', + ]); + }); + }); + + describe('verification type', () => { + it('rejects an unknown value', () => { + expect(getValidationErrors(chainSchema, { ...REQUIRED, NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE: 'staking' })).toEqual([ + 'NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE: Invalid type: Expected ("validation" | "mining" | "fee reception") but received "staking"', + ]); + }); + + it('rejects the value for Arbitrum rollups', () => { + expect(getValidationErrors(chainSchema, { + ...REQUIRED, + NEXT_PUBLIC_ROLLUP_TYPE: 'arbitrum', + NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE: 'validation', + })).toEqual([ 'NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE can not be set for Arbitrum rollups' ]); + }); + }); + + describe('additional token types', () => { + it('rejects an entry without a name', () => { + expect(getValidationErrors(chainSchema, { + ...REQUIRED, + NEXT_PUBLIC_NETWORK_ADDITIONAL_TOKEN_TYPES: toEnvValue([ { id: 'ERC-404' } ]), + })).toEqual([ 'NEXT_PUBLIC_NETWORK_ADDITIONAL_TOKEN_TYPES.0.name: Invalid key: Expected "name" but received undefined' ]); + }); + + it('rejects an entry with an unknown property', () => { + expect(getValidationErrors(chainSchema, { + ...REQUIRED, + NEXT_PUBLIC_NETWORK_ADDITIONAL_TOKEN_TYPES: toEnvValue([ { id: 'ERC-404', name: 'ERC-404', symbol: 'X' } ]), + })).toEqual([ 'NEXT_PUBLIC_NETWORK_ADDITIONAL_TOKEN_TYPES.0.symbol: Invalid key: Expected never but received "symbol"' ]); + }); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/chain.ts b/deploy/tools/envs-validator/schemas/chain.ts index 9e5b9aa72f0..051132dcd77 100644 --- a/deploy/tools/envs-validator/schemas/chain.ts +++ b/deploy/tools/envs-validator/schemas/chain.ts @@ -1,54 +1,35 @@ -import * as yup from 'yup'; -import { urlTest } from '../utils'; -import { replaceQuotes } from 'src/config/utils/envs'; -import type { NetworkVerificationTypeEnvs } from 'src/slices/chain/verification-type/types/config'; +// SPDX-License-Identifier: LicenseRef-Blockscout -// Blockchain parameters schema -export default yup.object({ - NEXT_PUBLIC_NETWORK_NAME: yup.string().required(), - NEXT_PUBLIC_NETWORK_SHORT_NAME: yup.string(), - NEXT_PUBLIC_NETWORK_ID: yup.number().positive().integer().required(), - NEXT_PUBLIC_NETWORK_RPC_URL: yup - .mixed() - .test( - 'shape', - 'Invalid schema were provided for NEXT_PUBLIC_NETWORK_RPC_URL, it should be either array of URLs or URL string', - (data) => { - const isUrlSchema = yup.string().test(urlTest); - const isArrayOfUrlsSchema = yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string().test(urlTest)); +import * as v from 'valibot'; - return isUrlSchema.isValidSync(data) || isArrayOfUrlsSchema.isValidSync(data); - }), - NEXT_PUBLIC_NETWORK_CURRENCY_NAME: yup.string(), - NEXT_PUBLIC_NETWORK_CURRENCY_WEI_NAME: yup.string(), - NEXT_PUBLIC_NETWORK_CURRENCY_GWEI_NAME: yup.string(), - NEXT_PUBLIC_NETWORK_CURRENCY_SYMBOL: yup.string(), - NEXT_PUBLIC_NETWORK_CURRENCY_DECIMALS: yup.number().integer().positive(), - NEXT_PUBLIC_NETWORK_SECONDARY_COIN_SYMBOL: yup.string(), - NEXT_PUBLIC_NETWORK_MULTIPLE_GAS_CURRENCIES: yup.boolean(), - NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE: yup - .string<NetworkVerificationTypeEnvs>().oneOf([ 'validation', 'mining', 'fee reception' ]) - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: (value: string) => value === 'arbitrum', - then: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE can not be set for Arbitrum rollups', - value => value === undefined, - ), - otherwise: (schema) => schema, - }), - NEXT_PUBLIC_NETWORK_TOKEN_STANDARD_NAME: yup.string(), - NEXT_PUBLIC_NETWORK_ADDITIONAL_TOKEN_TYPES: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.object({ - id: yup.string().required(), - name: yup.string().required(), - }).noUnknown(true)), - NEXT_PUBLIC_IS_TESTNET: yup.boolean(), -}); \ No newline at end of file +import { envBoolean, envJson, envPositiveInteger, envRequiredString, envUrl, requires } from '../utils'; + +export default v.pipe( + v.looseObject({ + NEXT_PUBLIC_NETWORK_NAME: envRequiredString(), + NEXT_PUBLIC_NETWORK_SHORT_NAME: v.optional(v.string()), + NEXT_PUBLIC_NETWORK_ID: envPositiveInteger(), + NEXT_PUBLIC_NETWORK_RPC_URL: v.optional(v.union([ + envUrl(), + envJson(v.array(v.pipe(v.string(), v.url()))), + ])), + NEXT_PUBLIC_NETWORK_CURRENCY_NAME: v.optional(v.string()), + NEXT_PUBLIC_NETWORK_CURRENCY_WEI_NAME: v.optional(v.string()), + NEXT_PUBLIC_NETWORK_CURRENCY_GWEI_NAME: v.optional(v.string()), + NEXT_PUBLIC_NETWORK_CURRENCY_SYMBOL: v.optional(v.string()), + NEXT_PUBLIC_NETWORK_CURRENCY_DECIMALS: v.optional(envPositiveInteger()), + NEXT_PUBLIC_NETWORK_SECONDARY_COIN_SYMBOL: v.optional(v.string()), + NEXT_PUBLIC_NETWORK_MULTIPLE_GAS_CURRENCIES: v.optional(envBoolean()), + NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE: v.optional(v.picklist([ 'validation', 'mining', 'fee reception' ])), + NEXT_PUBLIC_NETWORK_TOKEN_STANDARD_NAME: v.optional(v.string()), + NEXT_PUBLIC_NETWORK_ADDITIONAL_TOKEN_TYPES: v.optional(envJson(v.array(v.strictObject({ + id: v.pipe(v.string(), v.nonEmpty()), + name: v.pipe(v.string(), v.nonEmpty()), + })))), + NEXT_PUBLIC_IS_TESTNET: v.optional(envBoolean()), + }), + requires('NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE', 'NEXT_PUBLIC_ROLLUP_TYPE', { + when: (rollupType) => rollupType !== 'arbitrum', + message: 'NEXT_PUBLIC_NETWORK_VERIFICATION_TYPE can not be set for Arbitrum rollups', + }), +); diff --git a/deploy/tools/envs-validator/schemas/features/account.spec.ts b/deploy/tools/envs-validator/schemas/features/account.spec.ts new file mode 100644 index 00000000000..a6ce883f851 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/account.spec.ts @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getValidationErrors } from '../../utils'; +import { accountSchema } from './account'; + +const SUPPORTED = { NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED: 'true' }; + +describe('accountSchema', () => { + it('accepts the auth0 provider without an environment id', () => { + expect(getValidationErrors(accountSchema, { ...SUPPORTED, NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER: 'auth0' })).toEqual([]); + }); + + it('accepts the dynamic provider with an environment id', () => { + expect(getValidationErrors(accountSchema, { + ...SUPPORTED, + NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER: 'dynamic', + NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID: 'xxx', + })).toEqual([]); + }); + + it('accepts the expedited review HTML when the account is supported', () => { + expect(getValidationErrors(accountSchema, { + ...SUPPORTED, + NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML: '<p>Contact us</p>', + })).toEqual([]); + }); + + it('accepts a disabled account alone', () => { + expect(getValidationErrors(accountSchema, { NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED: 'false' })).toEqual([]); + }); + + it('rejects a malformed account flag', () => { + expect(getValidationErrors(accountSchema, { NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED: 'yes' })).toEqual([ + 'NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED: Expected "true" or "false" but received "yes"', + ]); + }); + + it('rejects an unsupported auth provider', () => { + expect(getValidationErrors(accountSchema, { ...SUPPORTED, NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER: 'okta' })).toEqual([ + 'NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER: Invalid type: Expected ("auth0" | "dynamic") but received "okta"', + ]); + }); + + it('rejects the auth provider when the account is not supported', () => { + expect(getValidationErrors(accountSchema, { NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER: 'auth0' })).toEqual([ + 'NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER can only be used if NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED is set to \'true\'', + ]); + }); + + it('rejects the dynamic provider without an environment id', () => { + expect(getValidationErrors(accountSchema, { ...SUPPORTED, NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER: 'dynamic' })).toEqual([ + 'NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID is required when NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER is set', + ]); + expect(getValidationErrors(accountSchema, { + ...SUPPORTED, + NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER: 'dynamic', + NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID: '', + })).toEqual([ + 'NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID is required when NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER is set', + ]); + }); + + it('rejects the environment id with a provider other than dynamic', () => { + expect(getValidationErrors(accountSchema, { + ...SUPPORTED, + NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER: 'auth0', + NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID: 'xxx', + })).toEqual([ + 'NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID can only be used if NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER is set to \'dynamic\' ', + ]); + }); + + it('rejects the expedited review HTML with a frame or an inline style', () => { + expect(getValidationErrors(accountSchema, { + ...SUPPORTED, + NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML: '<div style="position:fixed">Pay <iframe srcdoc="<script></script>"></iframe></div>', + })).toEqual([ + 'NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML: HTML contains elements that are not allowed: style attribute on <div>, <iframe>', + ]); + }); + + it('rejects the expedited review HTML when the account is not supported', () => { + expect(getValidationErrors(accountSchema, { NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML: '<p>Contact us</p>' })).toEqual([ + 'NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML can only be used if NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED is set to \'true\'', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/account.ts b/deploy/tools/envs-validator/schemas/features/account.ts index 8b2ef05acd2..e8ad42f9e34 100644 --- a/deploy/tools/envs-validator/schemas/features/account.ts +++ b/deploy/tools/envs-validator/schemas/features/account.ts @@ -1,29 +1,27 @@ -import { AuthProvider } from 'src/features/account/types/client'; -import * as yup from 'yup'; +// SPDX-License-Identifier: LicenseRef-Blockscout -export const accountSchema = yup - .object() - .shape({ - NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED: yup.boolean(), - NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER: yup - .string<AuthProvider>() - .when('NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED', { - is: (value: boolean) => value === true, - then: (schema) => schema.oneOf([ 'auth0', 'dynamic' ]), - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER can only be used if NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED is set to \'true\''), - }), - NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID: yup - .string() - .when('NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER', { - is: (value: AuthProvider) => value === 'dynamic', - then: (schema) => schema.required(), - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID can only be used if NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER is set to \'dynamic\' '), - }), - NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML: yup - .string() - .when('NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED', { - is: (value: boolean) => value === true, - then: (schema) => schema, - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML can only be used if NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED is set to \'true\''), - }), - }); \ No newline at end of file +import * as v from 'valibot'; + +import { envBoolean, envHtml, requiredIf, requires } from '../../utils'; + +const isDynamicProvider = (provider: unknown) => provider === 'dynamic'; + +export const accountSchema = v.pipe( + v.object({ + NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED: v.optional(envBoolean()), + NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER: v.optional(v.picklist([ 'auth0', 'dynamic' ])), + NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID: v.optional(v.string()), + NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML: v.optional(envHtml()), + }), + requires('NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER', 'NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED', { + message: 'NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER can only be used if NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED is set to \'true\'', + }), + requires('NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID', 'NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER', { + when: isDynamicProvider, + message: 'NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID can only be used if NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER is set to \'dynamic\' ', + }), + requiredIf('NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID', 'NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER', { when: isDynamicProvider }), + requires('NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML', 'NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED', { + message: 'NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML can only be used if NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED is set to \'true\'', + }), +); diff --git a/deploy/tools/envs-validator/schemas/features/address3rdPartyWidgets.spec.ts b/deploy/tools/envs-validator/schemas/features/address3rdPartyWidgets.spec.ts new file mode 100644 index 00000000000..fd0ec3cbaca --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/address3rdPartyWidgets.spec.ts @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { address3rdPartyWidgetsConfig } from '../../mocks/address3rdPartyWidgets'; +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { address3rdPartyWidgetsConfigSchema } from './address3rdPartyWidgets'; + +const CONFIG = { NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL: JSON.stringify(address3rdPartyWidgetsConfig) }; + +describe('address3rdPartyWidgetsConfigSchema', () => { + it('accepts the widget list together with the downloaded config', () => { + expect(getValidationErrors(address3rdPartyWidgetsConfigSchema, { + ...CONFIG, + NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS: toEnvValue([ 'widget-1', 'widget-2' ]), + })).toEqual([]); + }); + + it('accepts the downloaded config alone', () => { + expect(getValidationErrors(address3rdPartyWidgetsConfigSchema, CONFIG)).toEqual([]); + }); + + it('rejects the widget list without the config', () => { + expect(getValidationErrors(address3rdPartyWidgetsConfigSchema, { + NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS: toEnvValue([ 'widget-1' ]), + })).toEqual([ + 'NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS cannot not be used if NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL is not provided', + ]); + }); + + it('rejects a widget list entry that is not a string', () => { + expect(getValidationErrors(address3rdPartyWidgetsConfigSchema, { + ...CONFIG, + NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS: toEnvValue([ {} ]), + })).toEqual([ 'NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS.0: Invalid type: Expected string but received Object' ]); + }); + + it('rejects a widget config missing a required field', () => { + const { valuePath, ...widget } = address3rdPartyWidgetsConfig['widget-2']; + expect(getValidationErrors(address3rdPartyWidgetsConfigSchema, { + NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL: JSON.stringify({ 'widget-2': widget }), + })).toEqual([ 'NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL.widget-2.valuePath: Invalid key: Expected "valuePath" but received undefined' ]); + }); + + it('rejects a widget config with an unknown page', () => { + expect(getValidationErrors(address3rdPartyWidgetsConfigSchema, { + NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL: JSON.stringify({ + 'widget-2': { ...address3rdPartyWidgetsConfig['widget-2'], pages: [ 'block' ] }, + }), + })).toEqual([ + 'NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL.widget-2.pages.0: Invalid type: Expected ("eoa" | "contract" | "token") but received "block"', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/address3rdPartyWidgets.ts b/deploy/tools/envs-validator/schemas/features/address3rdPartyWidgets.ts index a5286cdbe8b..b8ecb44482d 100644 --- a/deploy/tools/envs-validator/schemas/features/address3rdPartyWidgets.ts +++ b/deploy/tools/envs-validator/schemas/features/address3rdPartyWidgets.ts @@ -1,44 +1,29 @@ -import { replaceQuotes } from "src/config/utils/envs"; -import { Address3rdPartyWidget, ADDRESS_3RD_PARTY_WIDGET_PAGES } from "src/features/address-3rd-party-widgets/types/view"; -import * as yup from 'yup'; +// SPDX-License-Identifier: LicenseRef-Blockscout -export const address3rdPartyWidgetsConfigSchema = yup - .object() - .shape({ - NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL: yup - .mixed() - .test('shape', 'Invalid schema were provided for NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL, it should have name, url, icon, title, value', (data) => { - const isUndefined = data === undefined; - const parsedData = typeof data === 'string' ? JSON.parse(data) : data; - const valueSchema = yup.lazy((objValue) => { - let schema = yup.object(); - Object.keys(objValue).forEach((key) => { - schema = schema.shape({ - [key]: yup.object<Address3rdPartyWidget>().shape({ - name: yup.string().required(), - url: yup.string().required(), - icon: yup.string().required(), - title: yup.string().required(), - hint: yup.string().optional(), - valuePath: yup.string().required(), - valueTitlePath: yup.string().optional(), - pages: yup.array().of(yup.string().oneOf(ADDRESS_3RD_PARTY_WIDGET_PAGES)).required(), - chainIds: yup.object<Record<string, string>>().optional(), - }), - }); - }); - return schema; - }); - return isUndefined || valueSchema.isValidSync(parsedData); - }), - NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string()) - .when('NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL', { - is: (value: string) => value, - then: (schema) => schema, - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS cannot not be used if NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL is not provided'), - }), - }); \ No newline at end of file +import * as v from 'valibot'; + +import { ADDRESS_3RD_PARTY_WIDGET_PAGES } from 'src/features/address-3rd-party-widgets/types/view'; + +import { envJson, requires } from '../../utils'; + +const widgetSchema = v.object({ + name: v.pipe(v.string(), v.nonEmpty()), + url: v.pipe(v.string(), v.nonEmpty()), + icon: v.pipe(v.string(), v.nonEmpty()), + title: v.pipe(v.string(), v.nonEmpty()), + hint: v.optional(v.string()), + valuePath: v.pipe(v.string(), v.nonEmpty()), + valueTitlePath: v.optional(v.string()), + pages: v.array(v.picklist(ADDRESS_3RD_PARTY_WIDGET_PAGES)), + chainIds: v.optional(v.record(v.string(), v.string())), +}); + +export const address3rdPartyWidgetsConfigSchema = v.pipe( + v.looseObject({ + NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL: v.optional(envJson(v.record(v.string(), widgetSchema))), + NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS: v.optional(envJson(v.array(v.string()))), + }), + requires('NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS', 'NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL', { + message: 'NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS cannot not be used if NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL is not provided', + }), +); diff --git a/deploy/tools/envs-validator/schemas/features/ads.spec.ts b/deploy/tools/envs-validator/schemas/features/ads.spec.ts new file mode 100644 index 00000000000..545f647ff11 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/ads.spec.ts @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { adButlerConfigDesktop, adButlerConfigMobile, sevioZones } from '../../mocks/ads'; +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { adsSchema } from './ads'; + +const ADBUTLER_CONFIGS = { + NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP: toEnvValue(adButlerConfigDesktop), + NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE: toEnvValue(adButlerConfigMobile), +}; + +describe('adsSchema', () => { + it('accepts the text and banner providers', () => { + expect(getValidationErrors(adsSchema, { + NEXT_PUBLIC_AD_TEXT_PROVIDER: 'sevio', + NEXT_PUBLIC_AD_BANNER_PROVIDER: 'slise', + NEXT_PUBLIC_AD_BANNER_ENABLE_SPECIFY: 'true', + })).toEqual([]); + }); + + it('accepts adbutler as the banner provider with both device configs', () => { + expect(getValidationErrors(adsSchema, { NEXT_PUBLIC_AD_BANNER_PROVIDER: 'adbutler', ...ADBUTLER_CONFIGS })).toEqual([]); + }); + + it('accepts adbutler as the additional banner provider with both device configs', () => { + expect(getValidationErrors(adsSchema, { + NEXT_PUBLIC_AD_BANNER_PROVIDER: 'slise', + NEXT_PUBLIC_AD_BANNER_ADDITIONAL_PROVIDER: 'adbutler', + ...ADBUTLER_CONFIGS, + })).toEqual([]); + }); + + it('accepts sevio as the banner provider with two zones', () => { + expect(getValidationErrors(adsSchema, { + NEXT_PUBLIC_AD_BANNER_PROVIDER: 'sevio', + NEXT_PUBLIC_AD_BANNER_SEVIO_ZONES: toEnvValue(sevioZones), + })).toEqual([]); + }); + + it.each([ + [ 'NEXT_PUBLIC_AD_TEXT_PROVIDER', '("sevio" | "none")' ], + [ 'NEXT_PUBLIC_AD_BANNER_PROVIDER', '("slise" | "adbutler" | "sevio" | "none")' ], + [ 'NEXT_PUBLIC_AD_BANNER_ADDITIONAL_PROVIDER', '"adbutler"' ], + ])('rejects an unsupported %s', (name, values) => { + expect(getValidationErrors(adsSchema, { [name]: 'unknown' })).toEqual([ `${ name }: Invalid type: Expected ${ values } but received "unknown"` ]); + }); + + it('rejects a malformed specify flag', () => { + expect(getValidationErrors(adsSchema, { NEXT_PUBLIC_AD_BANNER_ENABLE_SPECIFY: 'yes' })).toEqual([ + 'NEXT_PUBLIC_AD_BANNER_ENABLE_SPECIFY: Expected "true" or "false" but received "yes"', + ]); + }); + + describe.each([ + [ 'NEXT_PUBLIC_AD_BANNER_PROVIDER', {} ], + [ 'NEXT_PUBLIC_AD_BANNER_ADDITIONAL_PROVIDER', { NEXT_PUBLIC_AD_BANNER_PROVIDER: 'slise' } ], + ])('adbutler as %s', (name, base) => { + it('rejects missing device configs', () => { + expect(getValidationErrors(adsSchema, { ...base, [name]: 'adbutler' })).toEqual([ + `NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP is required when ${ name } is set`, + `NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE is required when ${ name } is set`, + ]); + }); + + it('rejects a device config with a non-positive size', () => { + expect(getValidationErrors(adsSchema, { + ...base, + [name]: 'adbutler', + ...ADBUTLER_CONFIGS, + NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE: toEnvValue({ ...adButlerConfigMobile, width: '0' }), + })).toEqual([ 'NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE.width: Invalid value: Expected >0 but received 0' ]); + }); + + it('rejects a device config with a non-numeric size', () => { + expect(getValidationErrors(adsSchema, { + ...base, + [name]: 'adbutler', + ...ADBUTLER_CONFIGS, + NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP: toEnvValue({ ...adButlerConfigDesktop, height: 'tall' }), + })).toEqual([ 'NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP.height: Expected a decimal number but received "tall"' ]); + }); + + it('rejects a device config missing the id', () => { + const { id, ...config } = adButlerConfigDesktop; + expect(getValidationErrors(adsSchema, { + ...base, + [name]: 'adbutler', + ...ADBUTLER_CONFIGS, + NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP: toEnvValue(config), + })).toEqual([ 'NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP.id: Invalid key: Expected "id" but received undefined' ]); + }); + }); + + it('does not count sevio zones when the banner provider is not sevio', () => { + expect(getValidationErrors(adsSchema, { + NEXT_PUBLIC_AD_BANNER_PROVIDER: 'slise', + NEXT_PUBLIC_AD_BANNER_SEVIO_ZONES: toEnvValue([ sevioZones[0] ]), + })).toEqual([]); + }); + + it('rejects sevio zones that are not exactly two', () => { + expect(getValidationErrors(adsSchema, { + NEXT_PUBLIC_AD_BANNER_PROVIDER: 'sevio', + NEXT_PUBLIC_AD_BANNER_SEVIO_ZONES: toEnvValue([ sevioZones[0] ]), + })).toEqual([ 'NEXT_PUBLIC_AD_BANNER_SEVIO_ZONES must have 2 items' ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/ads.ts b/deploy/tools/envs-validator/schemas/features/ads.ts index f40d1060128..6cd89174fdd 100644 --- a/deploy/tools/envs-validator/schemas/features/ads.ts +++ b/deploy/tools/envs-validator/schemas/features/ads.ts @@ -1,50 +1,42 @@ -import * as yup from 'yup'; -import { replaceQuotes } from 'src/config/utils/envs'; -import type { AdBannerProviders, AdBannerAdditionalProviders, AdButlerDeviceConfig } from 'src/features/ads/banner/types/config'; +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + import { SUPPORTED_AD_BANNER_PROVIDERS, SUPPORTED_AD_BANNER_ADDITIONAL_PROVIDERS } from 'src/features/ads/banner/types/config'; -import { AdTextProviders, SUPPORTED_AD_TEXT_PROVIDERS } from 'src/features/ads/text/types/config'; - -const adButlerConfigSchema = yup - .object<AdButlerDeviceConfig>() - .transform(replaceQuotes) - .json() - .when('NEXT_PUBLIC_AD_BANNER_PROVIDER', { - is: (value: AdBannerProviders) => value === 'adbutler', - then: (schema) => schema - .shape({ - id: yup.string().required(), - width: yup.number().positive().required(), - height: yup.number().positive().required(), - }) - .required(), - }) - .when('NEXT_PUBLIC_AD_BANNER_ADDITIONAL_PROVIDER', { - is: (value: AdBannerProviders) => value === 'adbutler', - then: (schema) => schema - .shape({ - id: yup.string().required(), - width: yup.number().positive().required(), - height: yup.number().positive().required(), - }) - .required(), - }); - -const sevioZonesSchema = yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string().required()) - .when('NEXT_PUBLIC_AD_BANNER_PROVIDER', { - is: (value: AdBannerProviders) => value === 'sevio', - then: (schema) => schema.length(2), - }); - -export const adsSchema = yup.object({ - NEXT_PUBLIC_AD_TEXT_PROVIDER: yup.string<AdTextProviders>().oneOf(SUPPORTED_AD_TEXT_PROVIDERS), - NEXT_PUBLIC_AD_BANNER_PROVIDER: yup.string<AdBannerProviders>().oneOf(SUPPORTED_AD_BANNER_PROVIDERS), - NEXT_PUBLIC_AD_BANNER_ADDITIONAL_PROVIDER: yup.string<AdBannerAdditionalProviders>().oneOf(SUPPORTED_AD_BANNER_ADDITIONAL_PROVIDERS), - NEXT_PUBLIC_AD_BANNER_SEVIO_ZONES: sevioZonesSchema, - NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP: adButlerConfigSchema, - NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE: adButlerConfigSchema, - NEXT_PUBLIC_AD_BANNER_ENABLE_SPECIFY: yup.boolean(), -}); +import { SUPPORTED_AD_TEXT_PROVIDERS } from 'src/features/ads/text/types/config'; + +import { companionRule, envBoolean, envJson, envNumber, requiredIf } from '../../utils'; + +const SEVIO_ZONES_COUNT = 2; + +const adButlerConfigSchema = envJson(v.object({ + id: v.pipe(v.string(), v.nonEmpty()), + width: v.pipe(envNumber(), v.gtValue(0)), + height: v.pipe(envNumber(), v.gtValue(0)), +})); + +const sevioZonesSchema = envJson(v.array(v.pipe(v.string(), v.nonEmpty()))); + +const isAdButler = (provider: unknown) => provider === 'adbutler'; + +export const adsSchema = v.pipe( + v.object({ + NEXT_PUBLIC_AD_TEXT_PROVIDER: v.optional(v.picklist(SUPPORTED_AD_TEXT_PROVIDERS)), + NEXT_PUBLIC_AD_BANNER_PROVIDER: v.optional(v.picklist(SUPPORTED_AD_BANNER_PROVIDERS)), + NEXT_PUBLIC_AD_BANNER_ADDITIONAL_PROVIDER: v.optional(v.picklist(SUPPORTED_AD_BANNER_ADDITIONAL_PROVIDERS)), + NEXT_PUBLIC_AD_BANNER_SEVIO_ZONES: v.optional(sevioZonesSchema), + NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP: v.optional(adButlerConfigSchema), + NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE: v.optional(adButlerConfigSchema), + NEXT_PUBLIC_AD_BANNER_ENABLE_SPECIFY: v.optional(envBoolean()), + }), + requiredIf('NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP', 'NEXT_PUBLIC_AD_BANNER_PROVIDER', { when: isAdButler }), + requiredIf('NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE', 'NEXT_PUBLIC_AD_BANNER_PROVIDER', { when: isAdButler }), + requiredIf('NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP', 'NEXT_PUBLIC_AD_BANNER_ADDITIONAL_PROVIDER', { when: isAdButler }), + requiredIf('NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE', 'NEXT_PUBLIC_AD_BANNER_ADDITIONAL_PROVIDER', { when: isAdButler }), + companionRule( + [ 'NEXT_PUBLIC_AD_BANNER_SEVIO_ZONES', 'NEXT_PUBLIC_AD_BANNER_PROVIDER' ], + ({ NEXT_PUBLIC_AD_BANNER_SEVIO_ZONES: zones, NEXT_PUBLIC_AD_BANNER_PROVIDER: provider }) => + provider !== 'sevio' || !Array.isArray(zones) || zones.length === SEVIO_ZONES_COUNT, + `NEXT_PUBLIC_AD_BANNER_SEVIO_ZONES must have ${ SEVIO_ZONES_COUNT } items`, + ), +); diff --git a/deploy/tools/envs-validator/schemas/features/apiDocs.spec.ts b/deploy/tools/envs-validator/schemas/features/apiDocs.spec.ts new file mode 100644 index 00000000000..7763ec92211 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/apiDocs.spec.ts @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { API_DOCS_TABS } from 'src/features/api-docs/types/config'; + +import { describe, expect, it } from 'vitest'; + +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { apiDocsSchema } from './apiDocs'; + +describe('apiDocsSchema', () => { + it('accepts an empty tab list', () => { + expect(getValidationErrors(apiDocsSchema, { NEXT_PUBLIC_API_DOCS_TABS: toEnvValue([]) })).toEqual([]); + }); + + it('accepts every known tab id', () => { + expect(getValidationErrors(apiDocsSchema, { NEXT_PUBLIC_API_DOCS_TABS: toEnvValue(API_DOCS_TABS) })).toEqual([]); + }); + + it('rejects an unknown tab id', () => { + expect(getValidationErrors(apiDocsSchema, { NEXT_PUBLIC_API_DOCS_TABS: toEnvValue([ 'rest_api', 'soap_api' ]) })).toEqual([ + 'NEXT_PUBLIC_API_DOCS_TABS.1: Invalid type: Expected ("rest_api" | "eth_rpc_api" | "rpc_api" | "graphql_api") but received "soap_api"', + ]); + }); + + it('rejects a value that is not a JSON array', () => { + expect(getValidationErrors(apiDocsSchema, { NEXT_PUBLIC_API_DOCS_TABS: 'rest_api' })).toEqual([ + 'NEXT_PUBLIC_API_DOCS_TABS: Invalid JSON: Received "rest_api"', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/apiDocs.ts b/deploy/tools/envs-validator/schemas/features/apiDocs.ts index 79a1ff27d2a..4cc74b3d6a8 100644 --- a/deploy/tools/envs-validator/schemas/features/apiDocs.ts +++ b/deploy/tools/envs-validator/schemas/features/apiDocs.ts @@ -1,13 +1,11 @@ -import * as yup from 'yup'; -import { replaceQuotes } from 'src/config/utils/envs'; -import type { ApiDocsTabId } from 'src/features/api-docs/types/config'; +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + import { API_DOCS_TABS } from 'src/features/api-docs/types/config'; -export const apiDocsSchema = yup - .object() - .shape({ - NEXT_PUBLIC_API_DOCS_TABS: yup.array() - .transform(replaceQuotes) - .json() - .of(yup.string<ApiDocsTabId>().oneOf(API_DOCS_TABS)), - }); \ No newline at end of file +import { envJson } from '../../utils'; + +export const apiDocsSchema = v.object({ + NEXT_PUBLIC_API_DOCS_TABS: v.optional(envJson(v.array(v.picklist(API_DOCS_TABS)))), +}); diff --git a/deploy/tools/envs-validator/schemas/features/beaconChain.spec.ts b/deploy/tools/envs-validator/schemas/features/beaconChain.spec.ts new file mode 100644 index 00000000000..09a806bd86a --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/beaconChain.spec.ts @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getValidationErrors } from '../../utils'; +import { beaconChainSchema } from './beaconChain'; + +const ENABLED = { NEXT_PUBLIC_HAS_BEACON_CHAIN: 'true' }; + +describe('beaconChainSchema', () => { + it('accepts the beacon chain settings together with the flag', () => { + expect(getValidationErrors(beaconChainSchema, { + ...ENABLED, + NEXT_PUBLIC_BEACON_CHAIN_WITHDRAWALS_ONLY: 'false', + NEXT_PUBLIC_BEACON_CHAIN_CURRENCY_SYMBOL: 'aETH', + NEXT_PUBLIC_BEACON_CHAIN_VALIDATOR_URL_TEMPLATE: 'https://beacon.example.com/validator/{pk}', + })).toEqual([]); + }); + + it('rejects a malformed flag', () => { + expect(getValidationErrors(beaconChainSchema, { NEXT_PUBLIC_HAS_BEACON_CHAIN: 'yes' })).toEqual([ + 'NEXT_PUBLIC_HAS_BEACON_CHAIN: Expected "true" or "false" but received "yes"', + ]); + }); + + it('rejects an empty currency symbol', () => { + expect(getValidationErrors(beaconChainSchema, { ...ENABLED, NEXT_PUBLIC_BEACON_CHAIN_CURRENCY_SYMBOL: '' })).toEqual([ + 'NEXT_PUBLIC_BEACON_CHAIN_CURRENCY_SYMBOL: Invalid length: Expected !0 but received 0', + ]); + }); + + it.each([ + [ 'NEXT_PUBLIC_BEACON_CHAIN_WITHDRAWALS_ONLY', 'true', 'can only be used if NEXT_PUBLIC_HAS_BEACON_CHAIN is set to "true"' ], + [ 'NEXT_PUBLIC_BEACON_CHAIN_CURRENCY_SYMBOL', 'aETH', 'cannot not be used if NEXT_PUBLIC_HAS_BEACON_CHAIN is not set to "true"' ], + [ + 'NEXT_PUBLIC_BEACON_CHAIN_VALIDATOR_URL_TEMPLATE', + 'https://beacon.example.com/{pk}', + 'cannot not be used if NEXT_PUBLIC_HAS_BEACON_CHAIN is not set to "true"', + ], + ])('rejects %s without the flag', (name, value, message) => { + expect(getValidationErrors(beaconChainSchema, { [name]: value })).toEqual([ `${ name } ${ message }` ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/beaconChain.ts b/deploy/tools/envs-validator/schemas/features/beaconChain.ts index 63ee48d4bd0..8fd357a3286 100644 --- a/deploy/tools/envs-validator/schemas/features/beaconChain.ts +++ b/deploy/tools/envs-validator/schemas/features/beaconChain.ts @@ -1,35 +1,23 @@ -import * as yup from 'yup'; +// SPDX-License-Identifier: LicenseRef-Blockscout -export const beaconChainSchema = yup - .object() - .shape({ - NEXT_PUBLIC_HAS_BEACON_CHAIN: yup.boolean(), - NEXT_PUBLIC_BEACON_CHAIN_WITHDRAWALS_ONLY: yup - .boolean() - .when('NEXT_PUBLIC_HAS_BEACON_CHAIN', { - is: (value: boolean) => value, - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_BEACON_CHAIN_WITHDRAWALS_ONLY can only be used if NEXT_PUBLIC_HAS_BEACON_CHAIN is set to "true"', - value => value === undefined, - ), - }), - NEXT_PUBLIC_BEACON_CHAIN_CURRENCY_SYMBOL: yup - .string() - .when('NEXT_PUBLIC_HAS_BEACON_CHAIN', { - is: (value: boolean) => value, - then: (schema) => schema.min(1).optional(), - otherwise: (schema) => schema.max( - -1, - 'NEXT_PUBLIC_BEACON_CHAIN_CURRENCY_SYMBOL cannot not be used if NEXT_PUBLIC_HAS_BEACON_CHAIN is not set to "true"', - ), - }), - NEXT_PUBLIC_BEACON_CHAIN_VALIDATOR_URL_TEMPLATE: yup - .string() - .when('NEXT_PUBLIC_HAS_BEACON_CHAIN', { - is: (value: boolean) => value, - then: (schema) => schema, - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_BEACON_CHAIN_VALIDATOR_URL_TEMPLATE cannot not be used if NEXT_PUBLIC_HAS_BEACON_CHAIN is not set to "true"'), - }), - }); \ No newline at end of file +import * as v from 'valibot'; + +import { envBoolean, requires } from '../../utils'; + +export const beaconChainSchema = v.pipe( + v.object({ + NEXT_PUBLIC_HAS_BEACON_CHAIN: v.optional(envBoolean()), + NEXT_PUBLIC_BEACON_CHAIN_WITHDRAWALS_ONLY: v.optional(envBoolean()), + NEXT_PUBLIC_BEACON_CHAIN_CURRENCY_SYMBOL: v.optional(v.pipe(v.string(), v.nonEmpty())), + NEXT_PUBLIC_BEACON_CHAIN_VALIDATOR_URL_TEMPLATE: v.optional(v.string()), + }), + requires('NEXT_PUBLIC_BEACON_CHAIN_WITHDRAWALS_ONLY', 'NEXT_PUBLIC_HAS_BEACON_CHAIN', { + message: 'NEXT_PUBLIC_BEACON_CHAIN_WITHDRAWALS_ONLY can only be used if NEXT_PUBLIC_HAS_BEACON_CHAIN is set to "true"', + }), + requires('NEXT_PUBLIC_BEACON_CHAIN_CURRENCY_SYMBOL', 'NEXT_PUBLIC_HAS_BEACON_CHAIN', { + message: 'NEXT_PUBLIC_BEACON_CHAIN_CURRENCY_SYMBOL cannot not be used if NEXT_PUBLIC_HAS_BEACON_CHAIN is not set to "true"', + }), + requires('NEXT_PUBLIC_BEACON_CHAIN_VALIDATOR_URL_TEMPLATE', 'NEXT_PUBLIC_HAS_BEACON_CHAIN', { + message: 'NEXT_PUBLIC_BEACON_CHAIN_VALIDATOR_URL_TEMPLATE cannot not be used if NEXT_PUBLIC_HAS_BEACON_CHAIN is not set to "true"', + }), +); diff --git a/deploy/tools/envs-validator/schemas/features/bridgedToken.spec.ts b/deploy/tools/envs-validator/schemas/features/bridgedToken.spec.ts new file mode 100644 index 00000000000..3450f1b1431 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/bridgedToken.spec.ts @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { bridgedTokenChains, tokenBridges } from '../../mocks/bridgedToken'; +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { bridgedTokensSchema } from './bridgedToken'; + +const CHAINS = { NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS: toEnvValue(bridgedTokenChains) }; +const BRIDGES = { NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES: toEnvValue(tokenBridges) }; + +describe('bridgedTokensSchema', () => { + it('accepts chains together with bridges', () => { + expect(getValidationErrors(bridgedTokensSchema, { ...CHAINS, ...BRIDGES })).toEqual([]); + }); + + it('rejects chains without bridges', () => { + expect(getValidationErrors(bridgedTokensSchema, CHAINS)).toEqual([ + 'NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES is required when NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS is set', + ]); + }); + + it('rejects bridges without chains', () => { + expect(getValidationErrors(bridgedTokensSchema, BRIDGES)).toEqual([ + 'NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES cannot not be used without NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS', + ]); + expect(getValidationErrors(bridgedTokensSchema, { ...BRIDGES, NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS: toEnvValue([]) })).toEqual([ + 'NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES cannot not be used without NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS', + ]); + }); + + it('rejects a chain with a malformed base URL', () => { + expect(getValidationErrors(bridgedTokensSchema, { + ...BRIDGES, + NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS: toEnvValue([ { ...bridgedTokenChains[0], base_url: 'not a url' } ]), + })).toEqual([ 'NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS.0.base_url: Invalid URL: Received "not a url"' ]); + }); + + it('rejects a chain missing a required field', () => { + const { title, ...chain } = bridgedTokenChains[0]; + expect(getValidationErrors(bridgedTokensSchema, { + ...BRIDGES, + NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS: toEnvValue([ chain ]), + })).toEqual([ 'NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS.0.title: Invalid key: Expected "title" but received undefined' ]); + }); + + it('rejects a bridge missing a required field', () => { + const { type, ...bridge } = tokenBridges[0]; + expect(getValidationErrors(bridgedTokensSchema, { + ...CHAINS, + NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES: toEnvValue([ bridge ]), + })).toEqual([ 'NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES.0.type: Invalid key: Expected "type" but received undefined' ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/bridgedToken.ts b/deploy/tools/envs-validator/schemas/features/bridgedToken.ts index f1c9b0ee173..9cd2303f32b 100644 --- a/deploy/tools/envs-validator/schemas/features/bridgedToken.ts +++ b/deploy/tools/envs-validator/schemas/features/bridgedToken.ts @@ -1,39 +1,32 @@ -import * as yup from 'yup'; -import { urlTest } from '../../utils'; -import { replaceQuotes } from 'src/config/utils/envs'; -import type { BridgedTokenChain, TokenBridge } from 'src/slices/token/types/client'; +// SPDX-License-Identifier: LicenseRef-Blockscout -const bridgedTokenChainSchema: yup.ObjectSchema<BridgedTokenChain> = yup - .object({ - id: yup.string().required(), - title: yup.string().required(), - short_title: yup.string().required(), - base_url: yup.string().test(urlTest).required(), - }); +import * as v from 'valibot'; -const tokenBridgeSchema: yup.ObjectSchema<TokenBridge> = yup - .object({ - type: yup.string().required(), - title: yup.string().required(), - short_title: yup.string().required(), - }); +import { envJson, envUrl, requiredIf, requires } from '../../utils'; -export const bridgedTokensSchema = yup - .object() - .shape({ - NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS: yup - .array() - .transform(replaceQuotes) - .json() - .of(bridgedTokenChainSchema), - NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES: yup - .array() - .transform(replaceQuotes) - .json() - .of(tokenBridgeSchema) - .when('NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS', { - is: (value: Array<unknown>) => value && value.length > 0, - then: (schema) => schema.required(), - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES cannot not be used without NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS'), - }), - }); \ No newline at end of file +const bridgedTokenChainSchema = v.object({ + id: v.pipe(v.string(), v.nonEmpty()), + title: v.pipe(v.string(), v.nonEmpty()), + short_title: v.pipe(v.string(), v.nonEmpty()), + base_url: v.pipe(envUrl(), v.nonEmpty()), +}); + +const tokenBridgeSchema = v.object({ + type: v.pipe(v.string(), v.nonEmpty()), + title: v.pipe(v.string(), v.nonEmpty()), + short_title: v.pipe(v.string(), v.nonEmpty()), +}); + +const hasItems = (value: unknown) => Array.isArray(value) && value.length > 0; + +export const bridgedTokensSchema = v.pipe( + v.object({ + NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS: v.optional(envJson(v.array(bridgedTokenChainSchema))), + NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES: v.optional(envJson(v.array(tokenBridgeSchema))), + }), + requires('NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES', 'NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS', { + when: hasItems, + message: 'NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES cannot not be used without NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS', + }), + requiredIf('NEXT_PUBLIC_BRIDGED_TOKENS_BRIDGES', 'NEXT_PUBLIC_BRIDGED_TOKENS_CHAINS', { when: hasItems }), +); diff --git a/deploy/tools/envs-validator/schemas/features/bubblemaps.spec.ts b/deploy/tools/envs-validator/schemas/features/bubblemaps.spec.ts new file mode 100644 index 00000000000..da2eb3f161c --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/bubblemaps.spec.ts @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getValidationErrors } from '../../utils'; +import { bubblemapsSchema } from './bubblemaps'; + +describe('bubblemapsSchema', () => { + it('accepts the chain slug together with the partner id', () => { + expect(getValidationErrors(bubblemapsSchema, { + NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG: 'eth', + NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID: 'demo', + })).toEqual([]); + }); + + it('rejects the chain slug without the partner id', () => { + expect(getValidationErrors(bubblemapsSchema, { NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG: 'eth' })).toEqual([ + 'NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG can only be used with NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID', + ]); + }); + + it('rejects the partner id without the chain slug', () => { + expect(getValidationErrors(bubblemapsSchema, { NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID: 'demo' })).toEqual([ + 'NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID can only be used with NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG', + ]); + }); + + it('rejects an empty chain slug', () => { + expect(getValidationErrors(bubblemapsSchema, { + NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG: '', + NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID: 'demo', + })).toEqual([ + 'NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG: Invalid length: Expected !0 but received 0', + 'NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID can only be used with NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG', + ]); + }); + + it('rejects an empty partner id', () => { + expect(getValidationErrors(bubblemapsSchema, { + NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG: 'eth', + NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID: '', + })).toEqual([ + 'NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID: Invalid length: Expected !0 but received 0', + 'NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG can only be used with NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/bubblemaps.ts b/deploy/tools/envs-validator/schemas/features/bubblemaps.ts new file mode 100644 index 00000000000..5c0b722ff2c --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/bubblemaps.ts @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + +import { requires } from '../../utils'; + +export const bubblemapsSchema = v.pipe( + v.object({ + NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG: v.optional(v.pipe(v.string(), v.nonEmpty())), + NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID: v.optional(v.pipe(v.string(), v.nonEmpty())), + }), + requires('NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG', 'NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID'), + requires('NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID', 'NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG'), +); diff --git a/deploy/tools/envs-validator/schemas/features/crossChainTxs.spec.ts b/deploy/tools/envs-validator/schemas/features/crossChainTxs.spec.ts new file mode 100644 index 00000000000..9bc35007188 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/crossChainTxs.spec.ts @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { crossChainTxsSchema } from './crossChainTxs'; + +const ENABLED = { NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED: 'true' }; +const BRIDGE_IDS = { NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS: toEnvValue([ 1, 2 ]) }; + +describe('crossChainTxsSchema', () => { + it('accepts the full feature config', () => { + expect(getValidationErrors(crossChainTxsSchema, { + ...ENABLED, + ...BRIDGE_IDS, + NEXT_PUBLIC_CROSS_CHAIN_TXS_INCLUDE_UNINDEXED_CHAINS: 'true', + NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST: 'https://api.example.com', + })).toEqual([]); + }); + + it('rejects a malformed enabled flag', () => { + expect(getValidationErrors(crossChainTxsSchema, { NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED: 'yes', ...BRIDGE_IDS })).toEqual([ + 'NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED: Expected "true" or "false" but received "yes"', + ]); + }); + + it('rejects the enabled flag without bridge ids', () => { + expect(getValidationErrors(crossChainTxsSchema, ENABLED)).toEqual([ + 'NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS is required when NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED is set', + ]); + }); + + it('rejects a bridge id that is not a number', () => { + expect(getValidationErrors(crossChainTxsSchema, { + ...ENABLED, + NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS: toEnvValue([ 'omni' ]), + })).toEqual([ 'NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS.0: Invalid type: Expected number but received "omni"' ]); + }); + + it('rejects a malformed indexer API host', () => { + expect(getValidationErrors(crossChainTxsSchema, { + ...ENABLED, + ...BRIDGE_IDS, + NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST: 'not a url', + })).toEqual([ 'NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST: Invalid URL: Received "not a url"' ]); + }); + + it.each([ + [ 'NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS', BRIDGE_IDS.NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS ], + [ 'NEXT_PUBLIC_CROSS_CHAIN_TXS_INCLUDE_UNINDEXED_CHAINS', 'true' ], + [ 'NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST', 'https://api.example.com' ], + ])('rejects %s without the enabled flag', (name, value) => { + expect(getValidationErrors(crossChainTxsSchema, { [name]: value })).toEqual([ + `${ name } can only be used with NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED`, + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/crossChainTxs.ts b/deploy/tools/envs-validator/schemas/features/crossChainTxs.ts index ebb16e6de99..9e45a5370b2 100644 --- a/deploy/tools/envs-validator/schemas/features/crossChainTxs.ts +++ b/deploy/tools/envs-validator/schemas/features/crossChainTxs.ts @@ -1,19 +1,18 @@ -import * as yup from 'yup'; -import { urlTest } from '../../utils'; +// SPDX-License-Identifier: LicenseRef-Blockscout -export const crossChainTxsSchema = yup - .object() - .shape({ - NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED: yup.boolean(), - NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST: yup - .string() - .when('NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED', { - is: (value: boolean) => value, - then: (schema) => schema.test(urlTest), - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST can only be used with NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED', - value => value === undefined, - ), - }), - }); \ No newline at end of file +import * as v from 'valibot'; + +import { envBoolean, envJson, envUrl, requiredIf, requires } from '../../utils'; + +export const crossChainTxsSchema = v.pipe( + v.object({ + NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS: v.optional(envJson(v.array(v.number()))), + NEXT_PUBLIC_CROSS_CHAIN_TXS_INCLUDE_UNINDEXED_CHAINS: v.optional(envBoolean()), + NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST: v.optional(envUrl()), + }), + requires('NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS', 'NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED'), + requiredIf('NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS', 'NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED'), + requires('NEXT_PUBLIC_CROSS_CHAIN_TXS_INCLUDE_UNINDEXED_CHAINS', 'NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED'), + requires('NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST', 'NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED'), +); diff --git a/deploy/tools/envs-validator/schemas/features/defiDropdown.spec.ts b/deploy/tools/envs-validator/schemas/features/defiDropdown.spec.ts new file mode 100644 index 00000000000..a47b6bf8f17 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/defiDropdown.spec.ts @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { deFiDropdownButtonText, deFiDropdownItems } from '../../mocks/defiDropdown'; +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { defiDropdownSchema } from './defiDropdown'; + +const ITEMS = { NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS: toEnvValue(deFiDropdownItems) }; +const BUTTON_TEXT = { NEXT_PUBLIC_DEFI_DROPDOWN_BUTTON_TEXT: toEnvValue(deFiDropdownButtonText) }; + +describe('defiDropdownSchema', () => { + it('accepts two items together with the button text', () => { + expect(getValidationErrors(defiDropdownSchema, { ...ITEMS, ...BUTTON_TEXT })).toEqual([]); + }); + + it('accepts a single item without the button text', () => { + expect(getValidationErrors(defiDropdownSchema, { NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS: toEnvValue([ deFiDropdownItems[0] ]) })).toEqual([]); + }); + + it('rejects the button text with fewer than two items', () => { + expect(getValidationErrors(defiDropdownSchema, { + NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS: toEnvValue([ deFiDropdownItems[0] ]), + ...BUTTON_TEXT, + })).toEqual([ 'NEXT_PUBLIC_DEFI_DROPDOWN_BUTTON_TEXT can only be used when NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS contains at least 2 items' ]); + }); + + it('rejects the button text without the desktop label', () => { + expect(getValidationErrors(defiDropdownSchema, { + ...ITEMS, + NEXT_PUBLIC_DEFI_DROPDOWN_BUTTON_TEXT: toEnvValue({ mobile: 'DeFi' }), + })).toEqual([ + 'NEXT_PUBLIC_DEFI_DROPDOWN_BUTTON_TEXT.desktop: Invalid key: Expected "desktop" but received undefined', + ]); + }); + + it('rejects an item with neither dappId nor url', () => { + expect(getValidationErrors(defiDropdownSchema, { + NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS: toEnvValue([ { text: 'Swap', icon: 'swap' } ]), + })).toEqual([ 'NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS.0: Either dappId or url is required' ]); + }); + + it('rejects an item with a malformed url', () => { + expect(getValidationErrors(defiDropdownSchema, { + NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS: toEnvValue([ { text: 'Payment link', url: 'not a url' } ]), + })).toEqual([ 'NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS.0.url: Invalid URL: Received "not a url"' ]); + }); + + it('rejects an item without text', () => { + expect(getValidationErrors(defiDropdownSchema, { + NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS: toEnvValue([ { dappId: 'uniswap' } ]), + })).toEqual([ 'NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS.0.text: Invalid key: Expected "text" but received undefined' ]); + }); + + it('rejects an item with a malformed essential flag', () => { + expect(getValidationErrors(defiDropdownSchema, { + NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS: toEnvValue([ { text: 'Swap', dappId: 'uniswap', isEssentialDapp: 'yes' } ]), + })).toEqual([ 'NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS.0.isEssentialDapp: Invalid type: Expected boolean but received "yes"' ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/defiDropdown.ts b/deploy/tools/envs-validator/schemas/features/defiDropdown.ts index b40e2e2be75..aed35880ebf 100644 --- a/deploy/tools/envs-validator/schemas/features/defiDropdown.ts +++ b/deploy/tools/envs-validator/schemas/features/defiDropdown.ts @@ -1,3 +1,4 @@ +<<<<<<< HEAD import * as yup from 'yup'; import type { DeFiDropdownButtonText, DeFiDropdownItem } from 'src/features/defi-dropdown/types/client'; import type { IconName } from 'public/icons/name'; @@ -48,4 +49,39 @@ export const defiDropdownSchema = yup.object({ value => value === undefined, ), }), +======= +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + +import { envJson, requires } from '../../utils'; + +const MIN_ITEMS_FOR_DROPDOWN = 2; + +const deFiDropdownItemSchema = v.pipe( + v.object({ + text: v.pipe(v.string(), v.nonEmpty()), + icon: v.optional(v.string()), + dappId: v.optional(v.string()), + isEssentialDapp: v.optional(v.boolean()), + url: v.optional(v.pipe(v.string(), v.url())), + }), + v.check((item) => Boolean(item.dappId) || Boolean(item.url), 'Either dappId or url is required'), +); + +const deFiDropdownButtonTextSchema = v.object({ + desktop: v.pipe(v.string(), v.nonEmpty()), + mobile: v.optional(v.string()), +>>>>>>> v2.13.0 }); + +export const defiDropdownSchema = v.pipe( + v.object({ + NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS: v.optional(envJson(v.array(deFiDropdownItemSchema))), + NEXT_PUBLIC_DEFI_DROPDOWN_BUTTON_TEXT: v.optional(envJson(deFiDropdownButtonTextSchema)), + }), + requires('NEXT_PUBLIC_DEFI_DROPDOWN_BUTTON_TEXT', 'NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS', { + when: (items) => Array.isArray(items) && items.length >= MIN_ITEMS_FOR_DROPDOWN, + message: `NEXT_PUBLIC_DEFI_DROPDOWN_BUTTON_TEXT can only be used when NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS contains at least ${ MIN_ITEMS_FOR_DROPDOWN } items`, + }), +); diff --git a/deploy/tools/envs-validator/schemas/features/flashblocks.spec.ts b/deploy/tools/envs-validator/schemas/features/flashblocks.spec.ts new file mode 100644 index 00000000000..85030cef4aa --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/flashblocks.spec.ts @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getValidationErrors } from '../../utils'; +import { flashblocksSchema } from './flashblocks'; + +const SOCKET_URL = { NEXT_PUBLIC_FLASHBLOCKS_SOCKET_URL: 'wss://example.com/ws' }; + +describe('flashblocksSchema', () => { + it('accepts the socket URL together with a name', () => { + expect(getValidationErrors(flashblocksSchema, { ...SOCKET_URL, NEXT_PUBLIC_FLASHBLOCKS_NAME: 'flashblock' })).toEqual([]); + }); + + it('accepts the socket URL alone', () => { + expect(getValidationErrors(flashblocksSchema, SOCKET_URL)).toEqual([]); + }); + + it('rejects a malformed socket URL', () => { + expect(getValidationErrors(flashblocksSchema, { NEXT_PUBLIC_FLASHBLOCKS_SOCKET_URL: 'not a url' })).toEqual([ + 'NEXT_PUBLIC_FLASHBLOCKS_SOCKET_URL: Invalid URL: Received "not a url"', + ]); + }); + + it('rejects an unsupported name', () => { + expect(getValidationErrors(flashblocksSchema, { ...SOCKET_URL, NEXT_PUBLIC_FLASHBLOCKS_NAME: 'miniblock' })).toEqual([ + 'NEXT_PUBLIC_FLASHBLOCKS_NAME: Invalid type: Expected ("flashblock" | "subblock") but received "miniblock"', + ]); + }); + + it('rejects the name without the socket URL', () => { + expect(getValidationErrors(flashblocksSchema, { NEXT_PUBLIC_FLASHBLOCKS_NAME: 'flashblock' })).toEqual([ + 'NEXT_PUBLIC_FLASHBLOCKS_NAME can only be used with NEXT_PUBLIC_FLASHBLOCKS_SOCKET_URL', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/flashblocks.ts b/deploy/tools/envs-validator/schemas/features/flashblocks.ts index 55d974549c8..dc261ccd658 100644 --- a/deploy/tools/envs-validator/schemas/features/flashblocks.ts +++ b/deploy/tools/envs-validator/schemas/features/flashblocks.ts @@ -1,3 +1,4 @@ +<<<<<<< HEAD import * as yup from 'yup'; import { FLASHBLOCKS_NAMES } from 'src/features/flashblocks/types/config'; import type { FlashblocksName } from 'src/features/flashblocks/types/config'; @@ -17,3 +18,20 @@ export const flashblocksSchema = yup ), }), }); +======= +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + +import { FLASHBLOCKS_NAMES } from 'src/features/flashblocks/types/config'; + +import { envUrl, requires } from '../../utils'; + +export const flashblocksSchema = v.pipe( + v.object({ + NEXT_PUBLIC_FLASHBLOCKS_SOCKET_URL: v.optional(envUrl()), + NEXT_PUBLIC_FLASHBLOCKS_NAME: v.optional(v.picklist(FLASHBLOCKS_NAMES)), + }), + requires('NEXT_PUBLIC_FLASHBLOCKS_NAME', 'NEXT_PUBLIC_FLASHBLOCKS_SOCKET_URL'), +); +>>>>>>> v2.13.0 diff --git a/deploy/tools/envs-validator/schemas/features/highlights.spec.ts b/deploy/tools/envs-validator/schemas/features/highlights.spec.ts new file mode 100644 index 00000000000..3fc5dd54f07 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/highlights.spec.ts @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { highlightsConfig } from '../../mocks/highlights'; +import { getValidationErrors } from '../../utils'; +import { highlightsConfigSchema } from './highlights'; + +describe('highlightsConfigSchema', () => { + it('accepts a config with two banners', () => { + expect(getValidationErrors(highlightsConfigSchema, { + NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG: JSON.stringify(highlightsConfig), + })).toEqual([]); + }); + + it('rejects a config with fewer than two banners', () => { + expect(getValidationErrors(highlightsConfigSchema, { + NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG: JSON.stringify([ highlightsConfig[0] ]), + })).toEqual([ 'NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG: Invalid length: Expected >=2 but received 1' ]); + }); + + it('rejects a banner without a title', () => { + const { title, ...banner } = highlightsConfig[0]; + expect(getValidationErrors(highlightsConfigSchema, { + NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG: JSON.stringify([ banner, highlightsConfig[1] ]), + })).toEqual([ 'NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG.0.title: Invalid key: Expected "title" but received undefined' ]); + }); + + it('rejects a banner with more than two colors', () => { + expect(getValidationErrors(highlightsConfigSchema, { + NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG: JSON.stringify([ { ...highlightsConfig[0], background: [ '#fff', '#000', '#ccc' ] }, highlightsConfig[1] ]), + })).toEqual([ 'NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG.0.background: Invalid length: Expected <=2 but received 3' ]); + }); + + it('rejects a banner with a malformed redirect URL', () => { + expect(getValidationErrors(highlightsConfigSchema, { + NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG: JSON.stringify([ highlightsConfig[0], { ...highlightsConfig[1], redirect_url: 'not a url' } ]), + })).toEqual([ 'NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG.1.redirect_url: Invalid URL: Received "not a url"' ]); + }); + + it('rejects a banner with a non-boolean pinned flag', () => { + expect(getValidationErrors(highlightsConfigSchema, { + NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG: JSON.stringify([ highlightsConfig[0], { ...highlightsConfig[1], is_pinned: 'yes' } ]), + })).toEqual([ + 'NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG.1.is_pinned: Invalid type: Expected boolean but received "yes"', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/highlights.ts b/deploy/tools/envs-validator/schemas/features/highlights.ts index d58e70cb7eb..6bf38a8964d 100644 --- a/deploy/tools/envs-validator/schemas/features/highlights.ts +++ b/deploy/tools/envs-validator/schemas/features/highlights.ts @@ -1,25 +1,23 @@ -import { HighlightsBannerConfig } from "types/homepage"; -import { urlTest } from "../../utils"; -import * as yup from 'yup'; +// SPDX-License-Identifier: LicenseRef-Blockscout -const highlightsBannerConfigSchema: yup.ObjectSchema<HighlightsBannerConfig> = yup.object({ - title: yup.string().required(), - description: yup.string().required(), - title_color: yup.array().max(2).of(yup.string()), - description_color: yup.array().max(2).of(yup.string()), - background: yup.array().max(2).of(yup.string()), - side_img_url: yup.array().max(2).of(yup.string()), - is_pinned: yup.boolean(), - page_path: yup.string(), - redirect_url: yup.string().test(urlTest), +import * as v from 'valibot'; + +import { envJson } from '../../utils'; + +const colorPairSchema = v.optional(v.pipe(v.array(v.string()), v.maxLength(2))); + +const highlightsBannerConfigSchema = v.object({ + title: v.pipe(v.string(), v.nonEmpty()), + description: v.pipe(v.string(), v.nonEmpty()), + title_color: colorPairSchema, + description_color: colorPairSchema, + background: colorPairSchema, + side_img_url: colorPairSchema, + is_pinned: v.optional(v.boolean()), + page_path: v.optional(v.string()), + redirect_url: v.optional(v.pipe(v.string(), v.url())), }); -export const highlightsConfigSchema = yup - .object() - .shape({ - NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG: yup - .array() - .json() - .of(highlightsBannerConfigSchema) - .min(2) - }); \ No newline at end of file +export const highlightsConfigSchema = v.object({ + NEXT_PUBLIC_HOMEPAGE_HIGHLIGHTS_CONFIG: v.optional(envJson(v.pipe(v.array(highlightsBannerConfigSchema), v.minLength(2)))), +}); diff --git a/deploy/tools/envs-validator/schemas/features/index.ts b/deploy/tools/envs-validator/schemas/features/index.ts index 234c7bccb75..a3d03f80e80 100644 --- a/deploy/tools/envs-validator/schemas/features/index.ts +++ b/deploy/tools/envs-validator/schemas/features/index.ts @@ -1,9 +1,12 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + export * from './account'; export * from './address3rdPartyWidgets'; export * from './ads'; export * from './apiDocs'; export * from './beaconChain'; export * from './bridgedToken'; +export * from './bubblemaps'; export * from './crossChainTxs'; export * from './defiDropdown'; export * from './flashblocks'; @@ -16,4 +19,4 @@ export * from './rollup'; export * from './tac'; export * from './tokenActionButton'; export * from './userOps'; -export * from './zetaChain'; \ No newline at end of file +export * from './zetaChain'; diff --git a/deploy/tools/envs-validator/schemas/features/marketplace.spec.ts b/deploy/tools/envs-validator/schemas/features/marketplace.spec.ts new file mode 100644 index 00000000000..0465ea36014 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/marketplace.spec.ts @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { essentialDappsConfig, marketplaceApps, marketplaceCategories, marketplaceTitles } from '../../mocks/marketplace'; +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { marketplaceSchema } from './marketplace'; + +const ENABLED = { NEXT_PUBLIC_MARKETPLACE_ENABLED: 'true', NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM: 'https://example.com' }; + +const dependents: Array<[ string, string ]> = [ + [ 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', JSON.stringify(marketplaceApps) ], + [ 'NEXT_PUBLIC_MARKETPLACE_CATEGORIES_URL', JSON.stringify(marketplaceCategories) ], + [ 'NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM', 'https://example.com' ], + [ 'NEXT_PUBLIC_MARKETPLACE_SUGGEST_IDEAS_FORM', 'https://example.com' ], + [ 'NEXT_PUBLIC_MARKETPLACE_FEATURED_APP', 'aave' ], + [ 'NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL', 'https://example.com/banner.html' ], + [ 'NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL', 'https://www.basename.app' ], + [ 'NEXT_PUBLIC_MARKETPLACE_GRAPH_LINKS_URL', 'https://example.com' ], + [ 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG', toEnvValue(essentialDappsConfig) ], + [ 'NEXT_PUBLIC_MARKETPLACE_TITLES', toEnvValue(marketplaceTitles) ], + [ 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_AD_ENABLED', 'true' ], +]; + +describe('marketplaceSchema', () => { + it('accepts the full marketplace setup', () => { + expect(getValidationErrors(marketplaceSchema, { ...ENABLED, ...Object.fromEntries(dependents) })).toEqual([]); + }); + + it('accepts an empty config', () => { + expect(getValidationErrors(marketplaceSchema, {})).toEqual([]); + }); + + it('requires the submit form when the marketplace is enabled', () => { + expect(getValidationErrors(marketplaceSchema, { NEXT_PUBLIC_MARKETPLACE_ENABLED: 'true' })).toEqual([ + 'NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM is required when NEXT_PUBLIC_MARKETPLACE_ENABLED is set', + ]); + expect(getValidationErrors(marketplaceSchema, { NEXT_PUBLIC_MARKETPLACE_ENABLED: 'true', NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM: '' })).toEqual([ + 'NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM is required when NEXT_PUBLIC_MARKETPLACE_ENABLED is set', + ]); + }); + + it('rejects a non-boolean enabled flag', () => { + expect(getValidationErrors(marketplaceSchema, { NEXT_PUBLIC_MARKETPLACE_ENABLED: 'yes' })).toEqual([ + 'NEXT_PUBLIC_MARKETPLACE_ENABLED: Expected "true" or "false" but received "yes"', + ]); + }); + + describe.each(dependents)('%s', (name, value) => { + it('is accepted when the marketplace is enabled', () => { + expect(getValidationErrors(marketplaceSchema, { ...ENABLED, [name]: value })).toEqual([]); + }); + + it('is rejected when the marketplace is not enabled', () => { + expect(getValidationErrors(marketplaceSchema, { [name]: value })).toEqual([ + `${ name } cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED`, + ]); + }); + }); + + it.each([ + 'NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM', + 'NEXT_PUBLIC_MARKETPLACE_SUGGEST_IDEAS_FORM', + 'NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL', + 'NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL', + ])('rejects a malformed %s', (name) => { + expect(getValidationErrors(marketplaceSchema, { ...ENABLED, [name]: 'not a url' })).toEqual([ `${ name }: Invalid URL: Received "not a url"` ]); + }); + + describe('NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', () => { + it('accepts an app with a single github link', () => { + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_CONFIG_URL: JSON.stringify([ { ...marketplaceApps[0], github: 'https://github.com/a' } ]), + })).toEqual([]); + }); + + it('rejects an app without an id', () => { + const { id, ...app } = marketplaceApps[0]; + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_CONFIG_URL: JSON.stringify([ app ]), + })).toEqual([ 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL.0.id: Invalid key: Expected "id" but received undefined' ]); + }); + + it('rejects an app with a malformed logo URL', () => { + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_CONFIG_URL: JSON.stringify([ { ...marketplaceApps[0], logo: 'not a url' } ]), + })).toEqual([ 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL.0.logo: Invalid URL: Received "not a url"' ]); + }); + + it('rejects an app with a malformed github link in the list', () => { + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_CONFIG_URL: JSON.stringify([ { ...marketplaceApps[0], github: [ 'not a url' ] } ]), + })).toEqual([ 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL.0.github.0: Invalid URL: Received "not a url"' ]); + }); + + it('rejects an app with a non-boolean external flag', () => { + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_CONFIG_URL: JSON.stringify([ { ...marketplaceApps[0], external: 'yes' } ]), + })).toEqual([ 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL.0.external: Invalid type: Expected boolean but received "yes"' ]); + }); + + it('rejects an app with a non-numeric priority', () => { + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_CONFIG_URL: JSON.stringify([ { ...marketplaceApps[0], priority: 'high' } ]), + })).toEqual([ 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL.0.priority: Invalid type: Expected number but received "high"' ]); + }); + }); + + describe('NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG', () => { + it('accepts a single section', () => { + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG: toEnvValue({ revoke: essentialDappsConfig.revoke }), + })).toEqual([]); + }); + + it('rejects a swap section without the integrator', () => { + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG: toEnvValue({ swap: { chains: [ '1' ], fee: '0.004' } }), + })).toEqual([ 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG.swap.integrator: Invalid key: Expected "integrator" but received undefined' ]); + }); + + it('rejects a section with an empty chain list', () => { + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG: toEnvValue({ revoke: { chains: [] } }), + })).toEqual([ 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG.revoke.chains: Invalid length: Expected >=1 but received 0' ]); + }); + + it('rejects a multisend section with a malformed posthog host', () => { + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG: toEnvValue({ multisend: { chains: [ '1' ], posthogHost: 'not a url' } }), + })).toEqual([ 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG.multisend.posthogHost: Invalid URL: Received "not a url"' ]); + }); + }); + + describe('NEXT_PUBLIC_MARKETPLACE_TITLES', () => { + it('rejects a non-string title', () => { + expect(getValidationErrors(marketplaceSchema, { + ...ENABLED, + NEXT_PUBLIC_MARKETPLACE_TITLES: toEnvValue({ title: [ 'Dappscout' ] }), + })).toEqual([ 'NEXT_PUBLIC_MARKETPLACE_TITLES.title: Invalid type: Expected string but received Array' ]); + }); + }); + + it('rejects a non-boolean essential dapps ad flag', () => { + expect(getValidationErrors(marketplaceSchema, { ...ENABLED, NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_AD_ENABLED: 'yes' })).toEqual([ + 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_AD_ENABLED: Expected "true" or "false" but received "yes"', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/marketplace.ts b/deploy/tools/envs-validator/schemas/features/marketplace.ts index 066d905d114..62de2cb2602 100644 --- a/deploy/tools/envs-validator/schemas/features/marketplace.ts +++ b/deploy/tools/envs-validator/schemas/features/marketplace.ts @@ -1,174 +1,86 @@ -import * as yup from 'yup'; -import type { MarketplaceAppBase, MarketplaceAppSocialInfo, EssentialDappsConfig, MarketplaceTitles } from 'src/features/marketplace/types/client'; -import { urlTest } from '../../utils'; -import { replaceQuotes } from 'src/config/utils/envs'; +// SPDX-License-Identifier: LicenseRef-Blockscout -const marketplaceAppSchema: yup.ObjectSchema<MarketplaceAppBase & MarketplaceAppSocialInfo> = yup - .object({ - id: yup.string().required(), - external: yup.boolean(), - title: yup.string().required(), - logo: yup.string().test(urlTest).required(), - logoDarkMode: yup.string().test(urlTest), - shortDescription: yup.string().required(), - categories: yup.array().of(yup.string().required()).required(), - url: yup.string().test(urlTest).required(), - author: yup.string().required(), - description: yup.string().required(), - site: yup.string().test(urlTest), - twitter: yup.string().test(urlTest), - telegram: yup.string().test(urlTest), - github: yup.lazy(value => - Array.isArray(value) ? - yup.array().of(yup.string().required().test(urlTest)) : - yup.string().test(urlTest), - ), - discord: yup.string().test(urlTest), - internalWallet: yup.boolean(), - priority: yup.number(), - }); +import * as v from 'valibot'; -export const marketplaceSchema = yup - .object() - .shape({ - NEXT_PUBLIC_MARKETPLACE_ENABLED: yup.boolean(), - NEXT_PUBLIC_MARKETPLACE_CONFIG_URL: yup - .array() - .json() - .of(marketplaceAppSchema) - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema, - // eslint-disable-next-line max-len - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED'), - }), - NEXT_PUBLIC_MARKETPLACE_CATEGORIES_URL: yup - .array() - .json() - .of(yup.string()) - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema, - // eslint-disable-next-line max-len - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_MARKETPLACE_CATEGORIES_URL cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED'), - }), - NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM: yup - .string() - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema.test(urlTest).required(), - // eslint-disable-next-line max-len - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED'), - }), - NEXT_PUBLIC_MARKETPLACE_SUGGEST_IDEAS_FORM: yup - .string() - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema.test(urlTest), - // eslint-disable-next-line max-len - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_MARKETPLACE_SUGGEST_IDEAS_FORM cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED'), - }), - NEXT_PUBLIC_MARKETPLACE_FEATURED_APP: yup - .string() - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema, - // eslint-disable-next-line max-len - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_MARKETPLACE_FEATURED_APP cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED'), - }), - NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL: yup - .string() - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema.test(urlTest), - // eslint-disable-next-line max-len - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED'), - }), - NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL: yup - .string() - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema.test(urlTest), - // eslint-disable-next-line max-len - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED'), - }), - NEXT_PUBLIC_MARKETPLACE_GRAPH_LINKS_URL: yup - .string() - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema, - // eslint-disable-next-line max-len - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_MARKETPLACE_GRAPH_LINKS_URL cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED'), - }), - NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG: yup - .mixed() - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema.test('shape', 'Invalid schema were provided for NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG, it should contain optional swap/revoke/multisend sections with required fields', (data) => { - const isUndefined = data === undefined; - const chainsSchema = yup.array().of(yup.string().required()).min(1).required(); - const valueSchema = yup.object<EssentialDappsConfig>().transform(replaceQuotes).json().shape({ - swap: yup.lazy(value => value ? - yup.object<EssentialDappsConfig['swap']>().shape({ - url: yup.string().test(urlTest).required(), - chains: chainsSchema, - fee: yup.string().required(), - integrator: yup.string().required(), - }) : - yup.object().nullable(), - ), - revoke: yup.lazy(value => value ? - yup.object<EssentialDappsConfig['revoke']>().shape({ chains: chainsSchema }) : - yup.object().nullable(), - ), - multisend: yup.lazy(value => value ? - yup.object<EssentialDappsConfig['multisend']>().shape({ - chains: chainsSchema, - posthogKey: yup.string(), - posthogHost: yup.string().test(urlTest), - }) : - yup.object().nullable(), - ), - }); - return isUndefined || valueSchema.isValidSync(data); - }), - // eslint-disable-next-line max-len - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED', - value => value === undefined, - ), - }), - NEXT_PUBLIC_MARKETPLACE_TITLES: yup - .mixed() - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema.test('shape', 'Invalid schema were provided for NEXT_PUBLIC_MARKETPLACE_TITLES', (data) => { - const isUndefined = data === undefined; - const valueSchema = yup.object<MarketplaceTitles>().transform(replaceQuotes).json().shape({ - menu_item: yup.string(), - title: yup.string(), - subtitle_essential_dapps: yup.string(), - subtitle_list: yup.string(), - }); +import { envBoolean, envJson, envUrl, requiredIf, requires } from '../../utils'; - return isUndefined || valueSchema.isValidSync(data); - }), - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_MARKETPLACE_TITLES cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED', - value => value === undefined, - ), - }), - NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_AD_ENABLED: yup - .boolean() - .when('NEXT_PUBLIC_MARKETPLACE_ENABLED', { - is: true, - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_AD_ENABLED cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED', - value => value === undefined, - ), - }), - }); +const nestedUrlSchema = v.pipe(v.string(), v.url()); +const nestedRequiredStringSchema = v.pipe(v.string(), v.nonEmpty()); + +const marketplaceAppSchema = v.object({ + id: nestedRequiredStringSchema, + external: v.optional(v.boolean()), + title: nestedRequiredStringSchema, + logo: nestedUrlSchema, + logoDarkMode: v.optional(nestedUrlSchema), + shortDescription: nestedRequiredStringSchema, + categories: v.array(nestedRequiredStringSchema), + url: nestedUrlSchema, + author: nestedRequiredStringSchema, + description: nestedRequiredStringSchema, + site: v.optional(nestedUrlSchema), + twitter: v.optional(nestedUrlSchema), + telegram: v.optional(nestedUrlSchema), + github: v.optional(v.union([ v.array(nestedUrlSchema), nestedUrlSchema ])), + discord: v.optional(nestedUrlSchema), + internalWallet: v.optional(v.boolean()), + priority: v.optional(v.number()), +}); + +const essentialDappChainsSchema = v.pipe(v.array(nestedRequiredStringSchema), v.minLength(1)); + +const essentialDappsConfigSchema = v.object({ + swap: v.optional(v.nullable(v.object({ + chains: essentialDappChainsSchema, + fee: nestedRequiredStringSchema, + integrator: nestedRequiredStringSchema, + }))), + revoke: v.optional(v.nullable(v.object({ + chains: essentialDappChainsSchema, + }))), + multisend: v.optional(v.nullable(v.object({ + chains: essentialDappChainsSchema, + posthogKey: v.optional(v.string()), + posthogHost: v.optional(nestedUrlSchema), + }))), +}); + +const marketplaceTitlesSchema = v.object({ + menu_item: v.optional(v.string()), + title: v.optional(v.string()), + subtitle_essential_dapps: v.optional(v.string()), + subtitle_list: v.optional(v.string()), +}); + +const dependentOnMarketplaceEnabled = (name: string) => requires(name, 'NEXT_PUBLIC_MARKETPLACE_ENABLED', { + message: `${ name } cannot not be used without NEXT_PUBLIC_MARKETPLACE_ENABLED`, +}); + +export const marketplaceSchema = v.pipe( + v.object({ + NEXT_PUBLIC_MARKETPLACE_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_MARKETPLACE_CONFIG_URL: v.optional(envJson(v.array(marketplaceAppSchema))), + NEXT_PUBLIC_MARKETPLACE_CATEGORIES_URL: v.optional(envJson(v.array(v.string()))), + NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM: v.optional(envUrl()), + NEXT_PUBLIC_MARKETPLACE_SUGGEST_IDEAS_FORM: v.optional(envUrl()), + NEXT_PUBLIC_MARKETPLACE_FEATURED_APP: v.optional(v.string()), + NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL: v.optional(envUrl()), + NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL: v.optional(envUrl()), + NEXT_PUBLIC_MARKETPLACE_GRAPH_LINKS_URL: v.optional(v.string()), + NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG: v.optional(envJson(essentialDappsConfigSchema)), + NEXT_PUBLIC_MARKETPLACE_TITLES: v.optional(envJson(marketplaceTitlesSchema)), + NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_AD_ENABLED: v.optional(envBoolean()), + }), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_CONFIG_URL'), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_CATEGORIES_URL'), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM'), + requiredIf('NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM', 'NEXT_PUBLIC_MARKETPLACE_ENABLED'), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_SUGGEST_IDEAS_FORM'), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_FEATURED_APP'), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL'), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL'), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_GRAPH_LINKS_URL'), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG'), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_TITLES'), + dependentOnMarketplaceEnabled('NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_AD_ENABLED'), +); diff --git a/deploy/tools/envs-validator/schemas/features/megaEth.spec.ts b/deploy/tools/envs-validator/schemas/features/megaEth.spec.ts new file mode 100644 index 00000000000..3078c7adabb --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/megaEth.spec.ts @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getValidationErrors } from '../../utils'; +import { megaEthSchema } from './megaEth'; + +describe('megaEthSchema', () => { + it('accepts both socket URLs', () => { + expect(getValidationErrors(megaEthSchema, { + NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_METRICS: 'wss://example.com', + NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_RPC: 'wss://example.com', + })).toEqual([]); + }); + + it.each([ + 'NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_METRICS', + 'NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_RPC', + ])('rejects a malformed %s', (name) => { + expect(getValidationErrors(megaEthSchema, { [name]: 'not a url' })).toEqual([ `${ name }: Invalid URL: Received "not a url"` ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/megaEth.ts b/deploy/tools/envs-validator/schemas/features/megaEth.ts index d2a235ccc27..5736405192e 100644 --- a/deploy/tools/envs-validator/schemas/features/megaEth.ts +++ b/deploy/tools/envs-validator/schemas/features/megaEth.ts @@ -1,9 +1,10 @@ -import * as yup from 'yup'; -import { urlTest } from '../../utils'; +// SPDX-License-Identifier: LicenseRef-Blockscout -export const megaEthSchema = yup - .object() - .shape({ - NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_METRICS: yup.string().test(urlTest), - NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_RPC: yup.string().test(urlTest), - }); \ No newline at end of file +import * as v from 'valibot'; + +import { envUrl } from '../../utils'; + +export const megaEthSchema = v.object({ + NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_METRICS: v.optional(envUrl()), + NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_RPC: v.optional(envUrl()), +}); diff --git a/deploy/tools/envs-validator/schemas/features/multichainButton.spec.ts b/deploy/tools/envs-validator/schemas/features/multichainButton.spec.ts new file mode 100644 index 00000000000..bed3943d8d7 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/multichainButton.spec.ts @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { MultichainProviderConfig } from 'src/features/multichain-button/types/client'; + +import { describe, expect, it } from 'vitest'; + +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { multichainButtonSchema } from './multichainButton'; + +const provider: MultichainProviderConfig = { + name: 'zerion', + url_template: 'https://app.zerion.io/{address}/overview', + logo: 'https://example.com/zerion.svg', +}; + +describe('multichainButtonSchema', () => { + it('accepts a provider list', () => { + expect(getValidationErrors(multichainButtonSchema, { + NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG: toEnvValue([ provider, { ...provider, dapp_id: 'zerion', view: 'icon' } ]), + })).toEqual([]); + }); + + it('rejects a provider without a URL template', () => { + expect(getValidationErrors(multichainButtonSchema, { + NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG: toEnvValue([ { name: provider.name, logo: provider.logo } ]), + })).toEqual([ 'NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG.0.url_template: Invalid key: Expected "url_template" but received undefined' ]); + }); + + it('rejects a provider with an unsupported view', () => { + expect(getValidationErrors(multichainButtonSchema, { + NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG: toEnvValue([ { ...provider, view: 'compact' } ]), + })).toEqual([ 'NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG.0.view: Invalid type: Expected ("full" | "icon") but received "compact"' ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/multichainButton.ts b/deploy/tools/envs-validator/schemas/features/multichainButton.ts index f00b884444f..b6ba96a52f9 100644 --- a/deploy/tools/envs-validator/schemas/features/multichainButton.ts +++ b/deploy/tools/envs-validator/schemas/features/multichainButton.ts @@ -1,21 +1,17 @@ -import { replaceQuotes } from 'src/config/utils/envs'; -import { MultichainProviderConfig } from 'src/features/multichain-button/types/client'; -import * as yup from 'yup'; +// SPDX-License-Identifier: LicenseRef-Blockscout -const multichainProviderConfigSchema: yup.ObjectSchema<MultichainProviderConfig> = yup.object({ - name: yup.string().required(), - url_template: yup.string().required(), - logo: yup.string().required(), - dapp_id: yup.string(), - promo: yup.boolean(), +import * as v from 'valibot'; + +import { envJson } from '../../utils'; + +const multichainProviderConfigSchema = v.object({ + name: v.pipe(v.string(), v.nonEmpty()), + url_template: v.pipe(v.string(), v.nonEmpty()), + logo: v.pipe(v.string(), v.nonEmpty()), + dapp_id: v.optional(v.string()), + view: v.optional(v.picklist([ 'full', 'icon' ])), }); -export const multichainButtonSchema = yup - .object() - .shape({ - NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG: yup - .array() - .transform(replaceQuotes) - .json() - .of(multichainProviderConfigSchema) - }); \ No newline at end of file +export const multichainButtonSchema = v.looseObject({ + NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG: v.optional(envJson(v.array(multichainProviderConfigSchema))), +}); diff --git a/deploy/tools/envs-validator/schemas/features/nameServices.spec.ts b/deploy/tools/envs-validator/schemas/features/nameServices.spec.ts new file mode 100644 index 00000000000..b9a00643015 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/nameServices.spec.ts @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { nameServicesSchema } from './nameServices'; + +describe('nameServicesSchema', () => { + it('accepts the name service and clusters settings', () => { + expect(getValidationErrors(nameServicesSchema, { + NEXT_PUBLIC_NAME_SERVICE_API_HOST: 'https://example.com', + NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS: toEnvValue([ 'duck', 'goose' ]), + NEXT_PUBLIC_CLUSTERS_API_HOST: 'https://example.com', + NEXT_PUBLIC_CLUSTERS_CDN_URL: 'https://example.com', + })).toEqual([]); + }); + + it.each([ + 'NEXT_PUBLIC_NAME_SERVICE_API_HOST', + 'NEXT_PUBLIC_CLUSTERS_API_HOST', + ])('rejects a malformed %s', (name) => { + expect(getValidationErrors(nameServicesSchema, { [name]: 'not a url' })).toEqual([ `${ name }: Invalid URL: Received "not a url"` ]); + }); + + describe('NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS', () => { + it('is rejected without the API host', () => { + expect(getValidationErrors(nameServicesSchema, { NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS: toEnvValue([ 'duck' ]) })).toEqual([ + 'NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS cannot not be used if NEXT_PUBLIC_NAME_SERVICE_API_HOST is not set', + ]); + }); + + it('is rejected when empty', () => { + expect(getValidationErrors(nameServicesSchema, { + NEXT_PUBLIC_NAME_SERVICE_API_HOST: 'https://example.com', + NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS: toEnvValue([]), + })).toEqual([ 'NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS: Invalid length: Expected >=1 but received 0' ]); + }); + }); + + describe('NEXT_PUBLIC_CLUSTERS_CDN_URL', () => { + it('is rejected without the API host', () => { + expect(getValidationErrors(nameServicesSchema, { NEXT_PUBLIC_CLUSTERS_CDN_URL: 'https://example.com' })).toEqual([ + 'NEXT_PUBLIC_CLUSTERS_CDN_URL cannot not be used if NEXT_PUBLIC_CLUSTERS_API_HOST is not set', + ]); + }); + + it('is rejected when malformed', () => { + expect(getValidationErrors(nameServicesSchema, { + NEXT_PUBLIC_CLUSTERS_API_HOST: 'https://example.com', + NEXT_PUBLIC_CLUSTERS_CDN_URL: 'not a url', + })).toEqual([ 'NEXT_PUBLIC_CLUSTERS_CDN_URL: Invalid URL: Received "not a url"' ]); + }); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/nameServices.ts b/deploy/tools/envs-validator/schemas/features/nameServices.ts index 2c3a6c8dcbb..e56682cf345 100644 --- a/deploy/tools/envs-validator/schemas/features/nameServices.ts +++ b/deploy/tools/envs-validator/schemas/features/nameServices.ts @@ -1,35 +1,21 @@ -import { urlTest } from "../../utils"; -import * as yup from 'yup'; -import { replaceQuotes } from 'src/config/utils/envs'; +// SPDX-License-Identifier: LicenseRef-Blockscout -export const nameServicesSchema = yup - .object() - .shape({ - NEXT_PUBLIC_NAME_SERVICE_API_HOST: yup.string().test(urlTest), - NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS: yup - .array() - .transform(replaceQuotes) - .json() - .when('NEXT_PUBLIC_NAME_SERVICE_API_HOST', { - is: (value: string) => Boolean(value), - then: (schema) => schema.of(yup.string()).min(1).optional(), - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS cannot not be used if NEXT_PUBLIC_NAME_SERVICE_API_HOST is not set', - value => value === undefined, - ), - }), +import * as v from 'valibot'; - NEXT_PUBLIC_CLUSTERS_API_HOST: yup.string().test(urlTest), - NEXT_PUBLIC_CLUSTERS_CDN_URL: yup - .string() - .when('NEXT_PUBLIC_CLUSTERS_API_HOST', { - is: (value: string) => Boolean(value), - then: (schema) => schema.test(urlTest).optional(), - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_CLUSTERS_CDN_URL cannot not be used if NEXT_PUBLIC_CLUSTERS_API_HOST is not set', - value => value === undefined, - ), - }), - }); \ No newline at end of file +import { envJson, envUrl, requires } from '../../utils'; + +export const nameServicesSchema = v.pipe( + v.looseObject({ + NEXT_PUBLIC_NAME_SERVICE_API_HOST: v.optional(envUrl()), + NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS: v.optional(envJson(v.pipe(v.array(v.string()), v.minLength(1)))), + + NEXT_PUBLIC_CLUSTERS_API_HOST: v.optional(envUrl()), + NEXT_PUBLIC_CLUSTERS_CDN_URL: v.optional(envUrl()), + }), + requires('NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS', 'NEXT_PUBLIC_NAME_SERVICE_API_HOST', { + message: 'NEXT_PUBLIC_NAME_SERVICE_PROTOCOLS cannot not be used if NEXT_PUBLIC_NAME_SERVICE_API_HOST is not set', + }), + requires('NEXT_PUBLIC_CLUSTERS_CDN_URL', 'NEXT_PUBLIC_CLUSTERS_API_HOST', { + message: 'NEXT_PUBLIC_CLUSTERS_CDN_URL cannot not be used if NEXT_PUBLIC_CLUSTERS_API_HOST is not set', + }), +); diff --git a/deploy/tools/envs-validator/schemas/features/rollup.spec.ts b/deploy/tools/envs-validator/schemas/features/rollup.spec.ts new file mode 100644 index 00000000000..59d26b88fe3 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/rollup.spec.ts @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { parentChainFull, parentChainMinimal } from '../../mocks/rollup'; +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { rollupSchema } from './rollup'; + +const PARENT_CHAIN = { NEXT_PUBLIC_ROLLUP_PARENT_CHAIN: toEnvValue(parentChainMinimal) }; +const OPTIMISTIC = { NEXT_PUBLIC_ROLLUP_TYPE: 'optimistic', ...PARENT_CHAIN }; +const ARBITRUM = { NEXT_PUBLIC_ROLLUP_TYPE: 'arbitrum', ...PARENT_CHAIN }; +const SCROLL = { NEXT_PUBLIC_ROLLUP_TYPE: 'scroll', ...PARENT_CHAIN }; + +describe('rollupSchema', () => { + it('accepts the optimistic rollup setup', () => { + expect(getValidationErrors(rollupSchema, { + ...OPTIMISTIC, + NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL: 'https://example.com', + NEXT_PUBLIC_FAULT_PROOF_ENABLED: 'true', + NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS: 'true', + NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED: 'false', + NEXT_PUBLIC_INTEROP_ENABLED: 'true', + NEXT_PUBLIC_ROLLUP_STAGE_INDEX: '1', + NEXT_PUBLIC_ROLLUP_LAYER_NUMBER: '5', + })).toEqual([]); + }); + + it('accepts the arbitrum rollup setup', () => { + expect(getValidationErrors(rollupSchema, { + ...ARBITRUM, + NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS: 'true', + NEXT_PUBLIC_ROLLUP_PARENT_CHAIN: toEnvValue(parentChainFull), + NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE: '0x00000000000000000000000000000000000000ca1de12a9905be97beaf', + NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL: 'https://mocha.celenium.io/blob', + })).toEqual([]); + }); + + it('requires the parent chain once a rollup type is set', () => { + expect(getValidationErrors(rollupSchema, { NEXT_PUBLIC_ROLLUP_TYPE: 'scroll' })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_PARENT_CHAIN is required when NEXT_PUBLIC_ROLLUP_TYPE is set', + ]); + }); + + it('rejects an unsupported rollup type', () => { + expect(getValidationErrors(rollupSchema, { NEXT_PUBLIC_ROLLUP_TYPE: 'duck', ...PARENT_CHAIN })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_TYPE: Invalid type: Expected ("optimistic" | "arbitrum" | "shibarium" | "zkSync" | "scroll") but received "duck"', + ]); + }); + + describe('NEXT_PUBLIC_ROLLUP_PARENT_CHAIN', () => { + it('is rejected without a rollup type', () => { + expect(getValidationErrors(rollupSchema, PARENT_CHAIN)).toEqual([ + 'NEXT_PUBLIC_ROLLUP_PARENT_CHAIN cannot not be used if NEXT_PUBLIC_ROLLUP_TYPE is not defined', + ]); + }); + + it('rejects a chain without a base URL', () => { + const { baseUrl, ...chain } = parentChainFull; + expect(getValidationErrors(rollupSchema, { ...SCROLL, NEXT_PUBLIC_ROLLUP_PARENT_CHAIN: toEnvValue(chain) })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_PARENT_CHAIN.baseUrl: Invalid key: Expected "baseUrl" but received undefined', + ]); + }); + + it('rejects a chain with a malformed RPC URL', () => { + expect(getValidationErrors(rollupSchema, { + ...SCROLL, + NEXT_PUBLIC_ROLLUP_PARENT_CHAIN: toEnvValue({ ...parentChainFull, rpcUrls: [ 'not a url' ] }), + })).toEqual([ 'NEXT_PUBLIC_ROLLUP_PARENT_CHAIN.rpcUrls.0: Invalid URL: Received "not a url"' ]); + }); + + it('rejects a chain with a non-numeric id', () => { + expect(getValidationErrors(rollupSchema, { + ...SCROLL, + NEXT_PUBLIC_ROLLUP_PARENT_CHAIN: toEnvValue({ ...parentChainFull, id: 'duck' }), + })).toEqual([ 'NEXT_PUBLIC_ROLLUP_PARENT_CHAIN.id: Invalid type: Expected number but received "duck"' ]); + }); + + it('rejects a currency without a symbol', () => { + expect(getValidationErrors(rollupSchema, { + ...SCROLL, + NEXT_PUBLIC_ROLLUP_PARENT_CHAIN: toEnvValue({ ...parentChainFull, currency: { name: 'Quack', decimals: 18 } }), + })).toEqual([ 'NEXT_PUBLIC_ROLLUP_PARENT_CHAIN.currency.symbol: Invalid key: Expected "symbol" but received undefined' ]); + }); + }); + + describe.each([ + [ + 'NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL', + 'https://example.com', + 'NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL can be used only if NEXT_PUBLIC_ROLLUP_TYPE is set to \'optimistic\' ', + ], + [ + 'NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED', + 'true', + 'NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'optimistic\' ', + ], + [ 'NEXT_PUBLIC_INTEROP_ENABLED', 'true', 'NEXT_PUBLIC_INTEROP_ENABLED can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'optimistic\' ' ], + [ 'NEXT_PUBLIC_FAULT_PROOF_ENABLED', 'true', 'NEXT_PUBLIC_FAULT_PROOF_ENABLED can only be used with NEXT_PUBLIC_ROLLUP_TYPE=optimistic' ], + ])('%s', (name, value, message) => { + it('is accepted for the optimistic rollup', () => { + expect(getValidationErrors(rollupSchema, { ...OPTIMISTIC, [name]: value })).toEqual([]); + }); + + it('is rejected for the arbitrum rollup', () => { + expect(getValidationErrors(rollupSchema, { ...ARBITRUM, [name]: value })).toEqual([ message ]); + }); + }); + + describe.each([ + [ + 'NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS', + 'true', + 'NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS cannot not be used if NEXT_PUBLIC_ROLLUP_TYPE is not defined', + ], + [ 'NEXT_PUBLIC_ROLLUP_STAGE_INDEX', '2', 'NEXT_PUBLIC_ROLLUP_STAGE_INDEX can only be used with NEXT_PUBLIC_ROLLUP_TYPE' ], + [ 'NEXT_PUBLIC_ROLLUP_LAYER_NUMBER', '3', 'NEXT_PUBLIC_ROLLUP_LAYER_NUMBER can only be used with NEXT_PUBLIC_ROLLUP_TYPE' ], + ])('%s', (name, value, message) => { + it('is accepted for any rollup type', () => { + expect(getValidationErrors(rollupSchema, { ...SCROLL, [name]: value })).toEqual([]); + }); + + it('is rejected without a rollup type', () => { + expect(getValidationErrors(rollupSchema, { [name]: value })).toEqual([ message ]); + }); + }); + + it('rejects a malformed L2 withdrawal URL', () => { + expect(getValidationErrors(rollupSchema, { ...OPTIMISTIC, NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL: 'not a url' })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL: Invalid URL: Received "not a url"', + ]); + }); + + it('rejects a non-boolean fault proof flag', () => { + expect(getValidationErrors(rollupSchema, { ...OPTIMISTIC, NEXT_PUBLIC_FAULT_PROOF_ENABLED: 'yes' })).toEqual([ + 'NEXT_PUBLIC_FAULT_PROOF_ENABLED: Expected "true" or "false" but received "yes"', + ]); + }); + + describe('NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE', () => { + it('is rejected for the optimistic rollup', () => { + expect(getValidationErrors(rollupSchema, { + ...OPTIMISTIC, + NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE: '0x00000000000000000000000000000000000000ca1de12a9905be97beaf', + })).toEqual([ 'NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'arbitrum\' ' ]); + }); + + it('rejects a namespace of the wrong length', () => { + expect(getValidationErrors(rollupSchema, { ...ARBITRUM, NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE: '0xca1de12a' })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE: Invalid length: Expected 60 but received 10', + ]); + }); + + it('rejects a namespace that is not a hex string', () => { + expect(getValidationErrors(rollupSchema, { + ...ARBITRUM, + NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE: '0x0000000000000000000000000000000000000000ca1de12a9905be97zzzz', + })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE: Invalid length: Expected 60 but received 62', + 'NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE: Invalid format: Expected /^0x[\\da-fA-F]+$/ but received ' + + '"0x0000000000000000000000000000000000000000ca1de12a9905be97zzzz"', + ]); + }); + }); + + describe('NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL', () => { + it.each([ 'optimistic', 'arbitrum' ])('is accepted for the %s rollup', (type) => { + expect(getValidationErrors(rollupSchema, { + ...PARENT_CHAIN, + NEXT_PUBLIC_ROLLUP_TYPE: type, + NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL: 'https://mocha.celenium.io/blob', + })).toEqual([]); + }); + + it('is rejected for the scroll rollup', () => { + expect(getValidationErrors(rollupSchema, { ...SCROLL, NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL: 'https://mocha.celenium.io/blob' })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'arbitrum\' or \'optimistic\'', + ]); + }); + + it('is rejected when malformed', () => { + expect(getValidationErrors(rollupSchema, { ...ARBITRUM, NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL: 'not a url' })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL: Invalid URL: Received "not a url"', + ]); + }); + }); + + it('rejects an unsupported stage index', () => { + expect(getValidationErrors(rollupSchema, { ...OPTIMISTIC, NEXT_PUBLIC_ROLLUP_STAGE_INDEX: '3' })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_STAGE_INDEX: Invalid type: Expected (1 | 2) but received 3', + ]); + }); + + it('rejects a layer number below 2', () => { + expect(getValidationErrors(rollupSchema, { ...OPTIMISTIC, NEXT_PUBLIC_ROLLUP_LAYER_NUMBER: '1' })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_LAYER_NUMBER: Invalid value: Expected >=2 but received 1', + ]); + }); + + it('rejects a non-integer layer number', () => { + expect(getValidationErrors(rollupSchema, { ...OPTIMISTIC, NEXT_PUBLIC_ROLLUP_LAYER_NUMBER: '2.5' })).toEqual([ + 'NEXT_PUBLIC_ROLLUP_LAYER_NUMBER: Invalid integer: Received 2.5', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/rollup.ts b/deploy/tools/envs-validator/schemas/features/rollup.ts index edbf2253cef..aeed894ffdb 100644 --- a/deploy/tools/envs-validator/schemas/features/rollup.ts +++ b/deploy/tools/envs-validator/schemas/features/rollup.ts @@ -1,147 +1,76 @@ -import * as yup from 'yup'; -import { urlTest, getYupValidationErrorMessage } from '../../utils'; -import { replaceQuotes } from 'src/config/utils/envs'; -import * as regexp from 'src/toolkit/utils/regexp'; +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + import { ROLLUP_TYPES } from 'src/features/rollup/common/types/config'; -const parentChainCurrencySchema = yup - .object() - .shape({ - name: yup.string().required(), - symbol: yup.string().required(), - decimals: yup.number().required(), - }); +import * as regexp from 'src/toolkit/utils/regexp'; + +import { envBoolean, envJson, envNumber, envPositiveInteger, envUrl, requiredIf, requires } from '../../utils'; + +const parentChainCurrencySchema = v.object({ + name: v.pipe(v.string(), v.nonEmpty()), + symbol: v.pipe(v.string(), v.nonEmpty()), + decimals: v.number(), +}); + +const parentChainSchema = v.object({ + id: v.optional(v.number()), + name: v.optional(v.string()), + baseUrl: v.pipe(v.string(), v.nonEmpty(), v.url()), + rpcUrls: v.optional(v.array(v.pipe(v.string(), v.url()))), + currency: v.optional(parentChainCurrencySchema), + isTestnet: v.optional(v.boolean()), +}); + +const isOptimistic = (type: unknown) => type === 'optimistic'; +const isArbitrum = (type: unknown) => type === 'arbitrum'; -export const rollupSchema = yup - .object() - .shape({ - NEXT_PUBLIC_ROLLUP_TYPE: yup.string().oneOf(ROLLUP_TYPES), - NEXT_PUBLIC_ROLLUP_PARENT_CHAIN: yup - .object() - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: (value: string) => value, - then: (schema) => { - return schema.transform(replaceQuotes).json().shape({ - id: yup.number(), - name: yup.string(), - baseUrl: yup.string().test(urlTest).required(), - rpcUrls: yup.array().of(yup.string().test(urlTest)), - currency: yup - .mixed() - .test( - 'shape', - (ctx) => { - try { - parentChainCurrencySchema.validateSync(ctx.originalValue); - throw new Error('Unknown validation error'); - } catch (error: unknown) { - const message = getYupValidationErrorMessage(error); - return 'in \"currency\" property ' + (message ? `${ message }` : ''); - } - }, - (data) => { - const isUndefined = data === undefined; - return isUndefined || parentChainCurrencySchema.isValidSync(data); - }, - ), - isTestnet: yup.boolean(), - }) - }, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_ROLLUP_PARENT_CHAIN cannot not be used if NEXT_PUBLIC_ROLLUP_TYPE is not defined', - value => value === undefined, - ), - }), - NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL: yup - .string() - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: (value: string) => value === 'optimistic', - then: (schema) => schema.test(urlTest), - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL can be used only if NEXT_PUBLIC_ROLLUP_TYPE is set to \'optimistic\' '), - }), - NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED: yup - .boolean() - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: 'optimistic', - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'optimistic\' ', - value => value === undefined, - ), - }), - NEXT_PUBLIC_INTEROP_ENABLED: yup - .boolean() - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: 'optimistic', - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_INTEROP_ENABLED can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'optimistic\' ', - value => value === undefined, - ), - }), - NEXT_PUBLIC_FAULT_PROOF_ENABLED: yup.boolean() - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: 'optimistic', - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_FAULT_PROOF_ENABLED can only be used with NEXT_PUBLIC_ROLLUP_TYPE=optimistic', - value => value === undefined, - ), - }), - NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS: yup - .boolean() - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: (value: string) => value, - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS cannot not be used if NEXT_PUBLIC_ROLLUP_TYPE is not defined', - value => value === undefined, - ), - }), - NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE: yup - .string() - .min(60) - .max(60) - .matches(regexp.HEX_REGEXP_WITH_0X) - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: (value: string) => value === 'arbitrum', - then: (schema) => schema, - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'arbitrum\' '), - }), - NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL: yup - .string() - .test(urlTest) - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: (value: string) => value === 'arbitrum' || value === 'optimistic', - then: (schema) => schema, - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'arbitrum\' or \'optimistic\''), - }), - NEXT_PUBLIC_ROLLUP_STAGE_INDEX: yup.number().oneOf([ 1, 2 ]) - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: (value: string) => Boolean(value), - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_ROLLUP_STAGE_INDEX can only be used with NEXT_PUBLIC_ROLLUP_TYPE', - value => value === undefined, - ), - }), - NEXT_PUBLIC_ROLLUP_LAYER_NUMBER: yup.number() - .positive() - .integer() - .min(2) - .when('NEXT_PUBLIC_ROLLUP_TYPE', { - is: (value: string) => Boolean(value), - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_ROLLUP_LAYER_NUMBER can only be used with NEXT_PUBLIC_ROLLUP_TYPE', - value => value === undefined, - ), - }), - }); \ No newline at end of file +export const rollupSchema = v.pipe( + v.looseObject({ + NEXT_PUBLIC_ROLLUP_TYPE: v.optional(v.picklist(ROLLUP_TYPES)), + NEXT_PUBLIC_ROLLUP_PARENT_CHAIN: v.optional(envJson(parentChainSchema)), + NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL: v.optional(envUrl()), + NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_INTEROP_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_FAULT_PROOF_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS: v.optional(envBoolean()), + NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE: v.optional(v.pipe(v.string(), v.length(60), v.regex(regexp.HEX_REGEXP_WITH_0X))), + NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL: v.optional(envUrl()), + NEXT_PUBLIC_ROLLUP_STAGE_INDEX: v.optional(v.pipe(envNumber(), v.picklist([ 1, 2 ]))), + NEXT_PUBLIC_ROLLUP_LAYER_NUMBER: v.optional(v.pipe(envPositiveInteger(), v.minValue(2))), + }), + requires('NEXT_PUBLIC_ROLLUP_PARENT_CHAIN', 'NEXT_PUBLIC_ROLLUP_TYPE', { + message: 'NEXT_PUBLIC_ROLLUP_PARENT_CHAIN cannot not be used if NEXT_PUBLIC_ROLLUP_TYPE is not defined', + }), + requiredIf('NEXT_PUBLIC_ROLLUP_PARENT_CHAIN', 'NEXT_PUBLIC_ROLLUP_TYPE'), + requires('NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL', 'NEXT_PUBLIC_ROLLUP_TYPE', { + when: isOptimistic, + message: 'NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL can be used only if NEXT_PUBLIC_ROLLUP_TYPE is set to \'optimistic\' ', + }), + requires('NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED', 'NEXT_PUBLIC_ROLLUP_TYPE', { + when: isOptimistic, + message: 'NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'optimistic\' ', + }), + requires('NEXT_PUBLIC_INTEROP_ENABLED', 'NEXT_PUBLIC_ROLLUP_TYPE', { + when: isOptimistic, + message: 'NEXT_PUBLIC_INTEROP_ENABLED can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'optimistic\' ', + }), + requires('NEXT_PUBLIC_FAULT_PROOF_ENABLED', 'NEXT_PUBLIC_ROLLUP_TYPE', { + when: isOptimistic, + message: 'NEXT_PUBLIC_FAULT_PROOF_ENABLED can only be used with NEXT_PUBLIC_ROLLUP_TYPE=optimistic', + }), + requires('NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS', 'NEXT_PUBLIC_ROLLUP_TYPE', { + message: 'NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS cannot not be used if NEXT_PUBLIC_ROLLUP_TYPE is not defined', + }), + requires('NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE', 'NEXT_PUBLIC_ROLLUP_TYPE', { + when: isArbitrum, + message: 'NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'arbitrum\' ', + }), + requires('NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL', 'NEXT_PUBLIC_ROLLUP_TYPE', { + when: (type) => isArbitrum(type) || isOptimistic(type), + message: 'NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL can only be used if NEXT_PUBLIC_ROLLUP_TYPE is set to \'arbitrum\' or \'optimistic\'', + }), + requires('NEXT_PUBLIC_ROLLUP_STAGE_INDEX', 'NEXT_PUBLIC_ROLLUP_TYPE'), + requires('NEXT_PUBLIC_ROLLUP_LAYER_NUMBER', 'NEXT_PUBLIC_ROLLUP_TYPE'), +); diff --git a/deploy/tools/envs-validator/schemas/features/tac.spec.ts b/deploy/tools/envs-validator/schemas/features/tac.spec.ts new file mode 100644 index 00000000000..ad3116f474d --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/tac.spec.ts @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getValidationErrors } from '../../utils'; +import { tacSchema } from './tac'; + +describe('tacSchema', () => { + it('accepts the API host alone', () => { + expect(getValidationErrors(tacSchema, { NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST: 'https://tac.blockscout.com' })).toEqual([]); + }); + + it('accepts the TON explorer URL together with the API host', () => { + expect(getValidationErrors(tacSchema, { + NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST: 'https://tac.blockscout.com', + NEXT_PUBLIC_TAC_TON_EXPLORER_URL: 'https://tonscan.org', + })).toEqual([]); + }); + + it('rejects a malformed API host', () => { + expect(getValidationErrors(tacSchema, { NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST: 'not a url' })).toEqual([ + 'NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST: Invalid URL: Received "not a url"', + ]); + }); + + it('rejects a malformed TON explorer URL', () => { + expect(getValidationErrors(tacSchema, { + NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST: 'https://tac.blockscout.com', + NEXT_PUBLIC_TAC_TON_EXPLORER_URL: 'not a url', + })).toEqual([ 'NEXT_PUBLIC_TAC_TON_EXPLORER_URL: Invalid URL: Received "not a url"' ]); + }); + + it('rejects the TON explorer URL without the API host', () => { + expect(getValidationErrors(tacSchema, { NEXT_PUBLIC_TAC_TON_EXPLORER_URL: 'https://tonscan.org' })).toEqual([ + 'NEXT_PUBLIC_TAC_TON_EXPLORER_URL can only be used with NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/tac.ts b/deploy/tools/envs-validator/schemas/features/tac.ts index c7fced500ba..83f5afb8d4a 100644 --- a/deploy/tools/envs-validator/schemas/features/tac.ts +++ b/deploy/tools/envs-validator/schemas/features/tac.ts @@ -1,19 +1,13 @@ -import * as yup from 'yup'; -import { urlTest } from '../../utils'; +// SPDX-License-Identifier: LicenseRef-Blockscout -export const tacSchema = yup - .object() - .shape({ - NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST: yup.string().test(urlTest), - NEXT_PUBLIC_TAC_TON_EXPLORER_URL: yup - .string() - .when('NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST', { - is: (value: string) => Boolean(value), - then: (schema) => schema.test(urlTest), - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_TAC_TON_EXPLORER_URL can only be used with NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST', - value => value === undefined, - ), - }), - }); \ No newline at end of file +import * as v from 'valibot'; + +import { envUrl, requires } from '../../utils'; + +export const tacSchema = v.pipe( + v.looseObject({ + NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST: v.optional(envUrl()), + NEXT_PUBLIC_TAC_TON_EXPLORER_URL: v.optional(envUrl()), + }), + requires('NEXT_PUBLIC_TAC_TON_EXPLORER_URL', 'NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST'), +); diff --git a/deploy/tools/envs-validator/schemas/features/tokenActionButton.spec.ts b/deploy/tools/envs-validator/schemas/features/tokenActionButton.spec.ts new file mode 100644 index 00000000000..dd2ccbb370b --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/tokenActionButton.spec.ts @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { TokenActionButtonConfig } from 'src/features/token-action-button/types/config'; + +import { describe, expect, it } from 'vitest'; + +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { tokenActionButtonSchema } from './tokenActionButton'; + +const button: TokenActionButtonConfig = { + text: 'Buy on Example Portal', + url: 'https://portal.example.com/swap?chainId=1&token={hash}', +}; + +describe('tokenActionButtonSchema', () => { + it('accepts a button with logo and colors', () => { + expect(getValidationErrors(tokenActionButtonSchema, { + NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG: toEnvValue({ + ...button, + logo: [ 'https://example.com/logo-light.svg', 'https://example.com/logo-dark.svg' ], + colors: { _default: { bg: [ 'rgb(134, 86, 239)' ], text: [ 'white' ] } }, + }), + })).toEqual([]); + }); + + it('rejects a button without text', () => { + expect(getValidationErrors(tokenActionButtonSchema, { + NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG: toEnvValue({ url: button.url }), + })).toEqual([ 'NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG.text: Invalid key: Expected "text" but received undefined' ]); + }); + + it('rejects a button with a malformed url', () => { + expect(getValidationErrors(tokenActionButtonSchema, { + NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG: toEnvValue({ ...button, url: 'not a url' }), + })).toEqual([ 'NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG.url: Invalid URL: Received "not a url"' ]); + }); + + it('rejects more than two logo urls', () => { + expect(getValidationErrors(tokenActionButtonSchema, { + NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG: toEnvValue({ ...button, logo: [ 'https://a.com/1.svg', 'https://a.com/2.svg', 'https://a.com/3.svg' ] }), + })).toEqual([ 'NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG.logo: Invalid length: Expected <=2 but received 3' ]); + }); + + it('rejects a button with empty text', () => { + expect(getValidationErrors(tokenActionButtonSchema, { + NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG: toEnvValue({ ...button, text: '' }), + })).toEqual([ 'NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG.text: Invalid length: Expected !0 but received 0' ]); + }); + + it('rejects a logo entry that is not a url', () => { + expect(getValidationErrors(tokenActionButtonSchema, { + NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG: toEnvValue({ ...button, logo: [ 'not a url' ] }), + })).toEqual([ 'NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG.logo.0: Invalid URL: Received "not a url"' ]); + }); + + it('rejects more than two colors in a pair', () => { + expect(getValidationErrors(tokenActionButtonSchema, { + NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG: toEnvValue({ ...button, colors: { _default: { bg: [ 'red', 'green', 'blue' ] } } }), + })).toEqual([ 'NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG.colors._default.bg: Invalid length: Expected <=2 but received 3' ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/tokenActionButton.ts b/deploy/tools/envs-validator/schemas/features/tokenActionButton.ts index 3618885cb10..bedcd82dff7 100644 --- a/deploy/tools/envs-validator/schemas/features/tokenActionButton.ts +++ b/deploy/tools/envs-validator/schemas/features/tokenActionButton.ts @@ -1,3 +1,4 @@ +<<<<<<< HEAD import { replaceQuotes } from 'src/config/utils/envs'; import { TokenActionButtonColorState, TokenActionButtonConfig } from 'src/features/token-action-button/types/config'; import * as yup from 'yup'; @@ -43,3 +44,30 @@ export const tokenActionButtonSchema = yup return isUndefined || buttonSchema.isValidSync(data); }), }); +======= +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + +import type { TokenActionButtonConfig } from 'src/features/token-action-button/types/config'; + +import { envJson } from '../../utils'; + +const colorPairSchema = v.optional(v.pipe(v.array(v.string()), v.maxLength(2))); + +const tokenActionButtonConfigSchema: v.GenericSchema<TokenActionButtonConfig> = v.object({ + text: v.pipe(v.string(), v.nonEmpty()), + url: v.pipe(v.string(), v.url()), + logo: v.optional(v.pipe(v.array(v.pipe(v.string(), v.url())), v.maxLength(2))), + colors: v.optional(v.object({ + _default: v.optional(v.object({ + bg: colorPairSchema, + text: colorPairSchema, + })), + })), +}); + +export const tokenActionButtonSchema = v.object({ + NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG: v.optional(envJson(tokenActionButtonConfigSchema)), +}); +>>>>>>> v2.13.0 diff --git a/deploy/tools/envs-validator/schemas/features/userOps.spec.ts b/deploy/tools/envs-validator/schemas/features/userOps.spec.ts new file mode 100644 index 00000000000..09c358330fd --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/userOps.spec.ts @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getValidationErrors } from '../../utils'; +import { userOpsSchema } from './userOps'; + +describe('userOpsSchema', () => { + it('accepts the indexer host when user ops are enabled', () => { + expect(getValidationErrors(userOpsSchema, { + NEXT_PUBLIC_HAS_USER_OPS: 'true', + NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST: 'https://example.com', + })).toEqual([]); + }); + + it('rejects the indexer host when user ops are not enabled', () => { + expect(getValidationErrors(userOpsSchema, { NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST: 'https://example.com' })).toEqual([ + 'NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST can only be used if NEXT_PUBLIC_HAS_USER_OPS is set to \'true\'', + ]); + }); + + it('rejects a malformed indexer host', () => { + expect(getValidationErrors(userOpsSchema, { + NEXT_PUBLIC_HAS_USER_OPS: 'true', + NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST: 'not a url', + })).toEqual([ 'NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST: Invalid URL: Received "not a url"' ]); + }); + + it('rejects a non-boolean flag', () => { + expect(getValidationErrors(userOpsSchema, { NEXT_PUBLIC_HAS_USER_OPS: 'yes' })).toEqual([ + 'NEXT_PUBLIC_HAS_USER_OPS: Expected "true" or "false" but received "yes"', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/userOps.ts b/deploy/tools/envs-validator/schemas/features/userOps.ts index 4ca30672d4f..dbd0784aa49 100644 --- a/deploy/tools/envs-validator/schemas/features/userOps.ts +++ b/deploy/tools/envs-validator/schemas/features/userOps.ts @@ -1,16 +1,15 @@ -import * as yup from 'yup'; -import { urlTest } from '../../utils'; +// SPDX-License-Identifier: LicenseRef-Blockscout -export const userOpsSchema = yup - .object() - .shape({ - NEXT_PUBLIC_HAS_USER_OPS: yup.boolean(), - NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST: yup - .string() - .test(urlTest) - .when('NEXT_PUBLIC_HAS_USER_OPS', { - is: (value: boolean) => value, - then: (schema) => schema, - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST can only be used if NEXT_PUBLIC_HAS_USER_OPS is set to \'true\''), - }), - }); \ No newline at end of file +import * as v from 'valibot'; + +import { envBoolean, envUrl, requires } from '../../utils'; + +export const userOpsSchema = v.pipe( + v.looseObject({ + NEXT_PUBLIC_HAS_USER_OPS: v.optional(envBoolean()), + NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST: v.optional(envUrl()), + }), + requires('NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST', 'NEXT_PUBLIC_HAS_USER_OPS', { + message: 'NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST can only be used if NEXT_PUBLIC_HAS_USER_OPS is set to \'true\'', + }), +); diff --git a/deploy/tools/envs-validator/schemas/features/zetaChain.spec.ts b/deploy/tools/envs-validator/schemas/features/zetaChain.spec.ts new file mode 100644 index 00000000000..73733b1cb31 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/features/zetaChain.spec.ts @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { zetaChainChainsConfig, zetaChainExternalSearchConfig } from '../../mocks/zetaChain'; +import { toEnvValue } from '../../test-utils'; +import { getValidationErrors } from '../../utils'; +import { zetaChainSchema } from './zetaChain'; + +const REQUIRED = { + NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST: 'https://zetachain-indexer.duckdns.org', + NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL: JSON.stringify(zetaChainChainsConfig), +}; + +describe('zetaChainSchema', () => { + it('accepts the API host with the chains config and the external search config', () => { + expect(getValidationErrors(zetaChainSchema, { + ...REQUIRED, + NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG: toEnvValue(zetaChainExternalSearchConfig), + })).toEqual([]); + }); + + it('rejects the API host without the chains config', () => { + expect(getValidationErrors(zetaChainSchema, { NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST: 'https://zetachain-indexer.duckdns.org' })).toEqual([ + 'NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST cannot be used without NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', + ]); + expect(getValidationErrors(zetaChainSchema, { ...REQUIRED, NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL: JSON.stringify([]) })).toEqual([ + 'NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST cannot be used without NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', + ]); + }); + + it('rejects a malformed API host', () => { + expect(getValidationErrors(zetaChainSchema, { ...REQUIRED, NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST: 'not a url' })).toEqual([ + 'NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST: Invalid URL: Received "not a url"', + ]); + }); + + describe('NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', () => { + it('is rejected without the API host', () => { + expect(getValidationErrors(zetaChainSchema, { + NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL: JSON.stringify(zetaChainChainsConfig), + })).toEqual([ 'NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL cannot be used if NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST is not set' ]); + }); + + it('rejects a chain without an id', () => { + expect(getValidationErrors(zetaChainSchema, { + ...REQUIRED, + NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL: JSON.stringify([ { chain_name: 'ZetaChain Athens' } ]), + })).toEqual([ 'NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL.0.chain_id: Invalid key: Expected "chain_id" but received undefined' ]); + }); + + it('rejects a chain with a non-numeric id', () => { + expect(getValidationErrors(zetaChainSchema, { + ...REQUIRED, + NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL: JSON.stringify([ { ...zetaChainChainsConfig[0], chain_id: 'athens' } ]), + })).toEqual([ + 'NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL.0.chain_id: Invalid type: Expected number but received "athens"', + ]); + }); + + it('rejects a chain with a malformed instance URL', () => { + expect(getValidationErrors(zetaChainSchema, { + ...REQUIRED, + NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL: JSON.stringify([ { ...zetaChainChainsConfig[0], instance_url: 'not a url' } ]), + })).toEqual([ 'NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL.0.instance_url: Invalid URL: Received "not a url"' ]); + }); + }); + + describe('NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG', () => { + it('is rejected without the API host', () => { + expect(getValidationErrors(zetaChainSchema, { + NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG: toEnvValue(zetaChainExternalSearchConfig), + })).toEqual([ 'NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG cannot be used if NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST is not set' ]); + }); + + it('rejects an entry without a template', () => { + const { template, ...entry } = zetaChainExternalSearchConfig[0]; + expect(getValidationErrors(zetaChainSchema, { + ...REQUIRED, + NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG: toEnvValue([ entry ]), + })).toEqual([ 'NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG.0.template: Invalid key: Expected "template" but received undefined' ]); + }); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/features/zetaChain.ts b/deploy/tools/envs-validator/schemas/features/zetaChain.ts index a60f78b4914..3a51f583235 100644 --- a/deploy/tools/envs-validator/schemas/features/zetaChain.ts +++ b/deploy/tools/envs-validator/schemas/features/zetaChain.ts @@ -1,64 +1,42 @@ -import * as yup from 'yup'; -import { urlTest } from '../../utils'; -import { replaceQuotes } from 'src/config/utils/envs'; -import type { ZetaChainChainsConfigEnv } from 'src/features/chain-variants/zeta-chain/types/client'; - -const zetaChainCCTXConfigSchema: yup.ObjectSchema<ZetaChainChainsConfigEnv> = yup.object({ - chain_id: yup.number().required(), - chain_name: yup.string().required(), - chain_logo: yup.string(), - instance_url: yup.string().test(urlTest), - address_url_template: yup.string(), - tx_url_template: yup.string(), +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + +import { companionRule, envJson, envUrl, requires } from '../../utils'; + +const zetaChainCCTXConfigSchema = v.object({ + chain_id: v.number(), + chain_name: v.pipe(v.string(), v.nonEmpty()), + chain_logo: v.optional(v.string()), + instance_url: v.optional(v.pipe(v.string(), v.url())), + address_url_template: v.optional(v.string()), + tx_url_template: v.optional(v.string()), }); - -export const zetaChainSchema = yup - .object() - .shape({ - NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST: yup.string().test(urlTest), - NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL: yup - .array() - .transform(replaceQuotes) - .json() - .of(zetaChainCCTXConfigSchema) - .when('NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST', { - is: (value: string) => Boolean(value), - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL cannot be used if NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST is not set', - value => value === undefined, - ), - }), - NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG: yup - .array() - .transform(replaceQuotes) - .json() - .of( - yup.object({ - regex: yup.string().required(), - template: yup.string().required(), - name: yup.string().required(), - }) - ) - .when('NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST', { - is: (value: string) => Boolean(value), - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG cannot be used if NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST is not set', - value => value === undefined, - ), - }), - }) - .test('zetachain-api-host-dependency', 'NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST cannot be used without NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', function(value) { - const hasApiHost = Boolean(value?.NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST); - const hasChainsConfig = Boolean(value?.NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL?.length); - if (hasApiHost && !hasChainsConfig) { - return this.createError({ message: 'NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST cannot be used without NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL' }); - } +const externalSearchItemSchema = v.object({ + regex: v.pipe(v.string(), v.nonEmpty()), + template: v.pipe(v.string(), v.nonEmpty()), + name: v.pipe(v.string(), v.nonEmpty()), +}); - return true; - }); - \ No newline at end of file +export const zetaChainSchema = v.pipe( + v.looseObject({ + NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST: v.optional(envUrl()), + NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL: v.optional(envJson(v.array(zetaChainCCTXConfigSchema))), + NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG: v.optional(envJson(v.array(externalSearchItemSchema))), + }), + requires('NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', 'NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST', { + message: 'NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL cannot be used if NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST is not set', + }), + requires('NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG', 'NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST', { + message: 'NEXT_PUBLIC_ZETACHAIN_EXTERNAL_SEARCH_CONFIG cannot be used if NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST is not set', + }), + companionRule( + [ 'NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST', 'NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL' ], + (input) => { + const chainsConfig = input.NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL; + return !input.NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST || (Array.isArray(chainsConfig) && chainsConfig.length > 0); + }, + 'NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST cannot be used without NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', + ), +); diff --git a/deploy/tools/envs-validator/schemas/meta.spec.ts b/deploy/tools/envs-validator/schemas/meta.spec.ts new file mode 100644 index 00000000000..c71792ced44 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/meta.spec.ts @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getValidationErrors } from '../utils'; +import metaSchema from './meta'; + +describe('metaSchema', () => { + it('accepts the Open Graph and SEO settings', () => { + expect(getValidationErrors(metaSchema, { + NEXT_PUBLIC_PROMOTE_BLOCKSCOUT_IN_TITLE: 'true', + NEXT_PUBLIC_OG_DESCRIPTION: 'Hello world!', + NEXT_PUBLIC_OG_IMAGE_URL: 'https://example.com/image.png', + NEXT_PUBLIC_OG_ENHANCED_DATA_ENABLED: 'true', + NEXT_PUBLIC_SEO_ENHANCED_DATA_ENABLED: 'true', + })).toEqual([]); + }); + + it('rejects a malformed Open Graph image URL', () => { + expect(getValidationErrors(metaSchema, { NEXT_PUBLIC_OG_IMAGE_URL: 'not a url' })).toEqual([ + 'NEXT_PUBLIC_OG_IMAGE_URL: Invalid URL: Received "not a url"', + ]); + }); + + it.each([ + 'NEXT_PUBLIC_PROMOTE_BLOCKSCOUT_IN_TITLE', + 'NEXT_PUBLIC_OG_ENHANCED_DATA_ENABLED', + 'NEXT_PUBLIC_SEO_ENHANCED_DATA_ENABLED', + ])('rejects a non-boolean %s', (name) => { + expect(getValidationErrors(metaSchema, { [name]: 'yes' })).toEqual([ + `${ name }: Expected "true" or "false" but received "yes"`, + ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/meta.ts b/deploy/tools/envs-validator/schemas/meta.ts index 3a5871ec3ff..9459a83ce3d 100644 --- a/deploy/tools/envs-validator/schemas/meta.ts +++ b/deploy/tools/envs-validator/schemas/meta.ts @@ -1,10 +1,13 @@ -import { urlTest } from '../utils'; -import * as yup from 'yup'; +// SPDX-License-Identifier: LicenseRef-Blockscout -export default yup.object({ - NEXT_PUBLIC_PROMOTE_BLOCKSCOUT_IN_TITLE: yup.boolean(), - NEXT_PUBLIC_OG_DESCRIPTION: yup.string(), - NEXT_PUBLIC_OG_IMAGE_URL: yup.string().test(urlTest), - NEXT_PUBLIC_OG_ENHANCED_DATA_ENABLED: yup.boolean(), - NEXT_PUBLIC_SEO_ENHANCED_DATA_ENABLED: yup.boolean(), -}); \ No newline at end of file +import * as v from 'valibot'; + +import { envBoolean, envUrl } from '../utils'; + +export default v.object({ + NEXT_PUBLIC_PROMOTE_BLOCKSCOUT_IN_TITLE: v.optional(envBoolean()), + NEXT_PUBLIC_OG_DESCRIPTION: v.optional(v.string()), + NEXT_PUBLIC_OG_IMAGE_URL: v.optional(envUrl()), + NEXT_PUBLIC_OG_ENHANCED_DATA_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_SEO_ENHANCED_DATA_ENABLED: v.optional(envBoolean()), +}); diff --git a/deploy/tools/envs-validator/schemas/services.spec.ts b/deploy/tools/envs-validator/schemas/services.spec.ts new file mode 100644 index 00000000000..5c3f2c38991 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/services.spec.ts @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { toEnvValue } from '../test-utils'; +import { getValidationErrors } from '../utils'; +import servicesSchema from './services'; + +const mixpanelOverrides = { record_sessions_percent: 0.5, record_heatmap_data: true }; +const posthogOverrides = { disable_session_recording: false }; + +describe('servicesSchema', () => { + it('accepts the external service keys', () => { + expect(getValidationErrors(servicesSchema, { + NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID: 'xxx', + NEXT_PUBLIC_WALLET_CONNECT_FEATURED_WALLET_IDS: toEnvValue([ 'xxx' ]), + NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY: 'xxx', + NEXT_PUBLIC_GOOGLE_ANALYTICS_PROPERTY_ID: 'UA-XXXXXX-X', + NEXT_PUBLIC_GROWTH_BOOK_CLIENT_KEY: 'xxx', + NEXT_PUBLIC_ROLLBAR_CLIENT_TOKEN: 'https://rollbar.com', + NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN: 'xxx', + NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES: toEnvValue(mixpanelOverrides), + NEXT_PUBLIC_POSTHOG_API_KEY: 'xxx', + NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES: toEnvValue(posthogOverrides), + })).toEqual([]); + }); + + it('rejects featured wallet ids that are not a JSON array', () => { + expect(getValidationErrors(servicesSchema, { NEXT_PUBLIC_WALLET_CONNECT_FEATURED_WALLET_IDS: 'xxx' })).toEqual([ + 'NEXT_PUBLIC_WALLET_CONNECT_FEATURED_WALLET_IDS: Invalid JSON: Received "xxx"', + ]); + }); + + describe('Mixpanel config overrides', () => { + it('rejects the overrides without the project token', () => { + expect(getValidationErrors(servicesSchema, { NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES: toEnvValue(mixpanelOverrides) })).toEqual([ + 'NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES can only be used if NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN is set to a non-empty string', + ]); + }); + + it('rejects overrides that are not a JSON object', () => { + expect(getValidationErrors(servicesSchema, { + NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN: 'xxx', + NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES: 'not json', + })).toEqual([ + 'NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES: Invalid JSON: Received "not json"', + ]); + }); + }); + + describe('PostHog config overrides', () => { + it('rejects the overrides without the API key', () => { + expect(getValidationErrors(servicesSchema, { NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES: toEnvValue(posthogOverrides) })).toEqual([ + 'NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES can only be used if NEXT_PUBLIC_POSTHOG_API_KEY is set to a non-empty string', + ]); + }); + + it('rejects overrides that are not a JSON object', () => { + expect(getValidationErrors(servicesSchema, { + NEXT_PUBLIC_POSTHOG_API_KEY: 'xxx', + NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES: 'not json', + })).toEqual([ + 'NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES: Invalid JSON: Received "not json"', + ]); + }); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/services.ts b/deploy/tools/envs-validator/schemas/services.ts index cb49c53a2ce..ff2964a5540 100644 --- a/deploy/tools/envs-validator/schemas/services.ts +++ b/deploy/tools/envs-validator/schemas/services.ts @@ -1,29 +1,29 @@ -import { replaceQuotes } from 'src/config/utils/envs'; -import * as yup from 'yup'; +// SPDX-License-Identifier: LicenseRef-Blockscout -// External services envs -export default yup.object({ - NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID: yup.string(), - NEXT_PUBLIC_WALLET_CONNECT_FEATURED_WALLET_IDS: yup.array().transform(replaceQuotes).json().of(yup.string()), +import * as v from 'valibot'; - NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY: yup.string(), - NEXT_PUBLIC_GOOGLE_ANALYTICS_PROPERTY_ID: yup.string(), - NEXT_PUBLIC_GROWTH_BOOK_CLIENT_KEY: yup.string(), - NEXT_PUBLIC_ROLLBAR_CLIENT_TOKEN: yup.string(), +import { envJson, requires } from '../utils'; - // mixpanel - NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN: yup.string(), - NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES: yup - .object() - .transform(replaceQuotes) - .json() - .when('NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', { - is: (value: string) => Boolean(value), - then: (schema) => schema, - otherwise: (schema) => schema.test( - 'not-exist', - 'NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES can only be used if NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN is set to a non-empty string', - value => value === undefined, - ), - }), -}); \ No newline at end of file +export default v.pipe( + v.object({ + NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID: v.optional(v.string()), + NEXT_PUBLIC_WALLET_CONNECT_FEATURED_WALLET_IDS: v.optional(envJson(v.array(v.string()))), + + NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY: v.optional(v.string()), + NEXT_PUBLIC_GOOGLE_ANALYTICS_PROPERTY_ID: v.optional(v.string()), + NEXT_PUBLIC_GROWTH_BOOK_CLIENT_KEY: v.optional(v.string()), + NEXT_PUBLIC_ROLLBAR_CLIENT_TOKEN: v.optional(v.string()), + + NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN: v.optional(v.string()), + NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES: v.optional(envJson(v.record(v.string(), v.unknown()))), + + NEXT_PUBLIC_POSTHOG_API_KEY: v.optional(v.string()), + NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES: v.optional(envJson(v.record(v.string(), v.unknown()))), + }), + requires('NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES', 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', { + message: 'NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES can only be used if NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN is set to a non-empty string', + }), + requires('NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES', 'NEXT_PUBLIC_POSTHOG_API_KEY', { + message: 'NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES can only be used if NEXT_PUBLIC_POSTHOG_API_KEY is set to a non-empty string', + }), +); diff --git a/deploy/tools/envs-validator/schemas/ui.spec.ts b/deploy/tools/envs-validator/schemas/ui.spec.ts new file mode 100644 index 00000000000..25423317913 --- /dev/null +++ b/deploy/tools/envs-validator/schemas/ui.spec.ts @@ -0,0 +1,504 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { + contractCodeIdes, + featuredNetworks, + fontFamilyBody, + fontFamilyHeading, + footerLinks, + heroBannerConfig, + networkExplorers, + nftMarketplaces, + promoBannerConfigFull, + promoBannerConfigImageOnly, +} from '../mocks/ui'; +import { toEnvValue } from '../test-utils'; +import { getValidationErrors } from '../utils'; +import { footerSchema, homepageSchema, miscSchema, navigationSchema, viewsSchema } from './ui'; + +const nonBooleanMessage = (name: string) => `${ name }: Expected "true" or "false" but received "yes"`; +const picklistMessage = (name: string, allowed: Array<string>, received: string) => + `${ name }: Invalid type: Expected (${ allowed.map((item) => `"${ item }"`).join(' | ') }) but received "${ received }"`; + +describe('homepageSchema', () => { + it('accepts the charts, stats and hero banner settings', () => { + expect(getValidationErrors(homepageSchema, { + NEXT_PUBLIC_HOMEPAGE_CHARTS: toEnvValue([ 'daily_txs' ]), + NEXT_PUBLIC_HOMEPAGE_STATS: toEnvValue([ 'total_blocks', 'average_block_time', 'total_txs', 'wallet_addresses', 'gas_tracker', 'current_epoch' ]), + NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG: toEnvValue(heroBannerConfig), + })).toEqual([]); + }); + + it('accepts an empty stats list', () => { + expect(getValidationErrors(homepageSchema, { NEXT_PUBLIC_HOMEPAGE_STATS: toEnvValue([]) })).toEqual([]); + }); + + it('rejects an unknown chart id', () => { + expect(getValidationErrors(homepageSchema, { NEXT_PUBLIC_HOMEPAGE_CHARTS: toEnvValue([ 'weekly_txs' ]) })).toEqual([ + picklistMessage( + 'NEXT_PUBLIC_HOMEPAGE_CHARTS.0', + [ 'daily_txs', 'daily_operational_txs', 'coin_price', 'secondary_coin_price', 'market_cap', 'tvl' ], + 'weekly_txs', + ), + ]); + }); + + it('rejects an unknown stats widget id', () => { + expect(getValidationErrors(homepageSchema, { NEXT_PUBLIC_HOMEPAGE_STATS: toEnvValue([ 'unknown' ]) })).toEqual([ + picklistMessage('NEXT_PUBLIC_HOMEPAGE_STATS.0', [ + 'latest_batch', 'total_blocks', 'average_block_time', 'total_txs', 'total_operational_txs', + 'latest_l1_state_batch', 'wallet_addresses', 'gas_tracker', 'btc_locked', 'current_epoch', + ], 'unknown'), + ]); + }); + + describe('stats-service-only ids', () => { + it('accepts daily_operational_txs together with the stats API host', () => { + expect(getValidationErrors(homepageSchema, { + NEXT_PUBLIC_STATS_API_HOST: 'https://stats.example.com', + NEXT_PUBLIC_HOMEPAGE_CHARTS: toEnvValue([ 'daily_operational_txs' ]), + })).toEqual([]); + }); + + it('rejects daily_operational_txs without the stats API host', () => { + expect(getValidationErrors(homepageSchema, { NEXT_PUBLIC_HOMEPAGE_CHARTS: toEnvValue([ 'daily_operational_txs' ]) })).toEqual([ + 'NEXT_PUBLIC_STATS_API_HOST is required when daily_operational_txs is enabled in NEXT_PUBLIC_HOMEPAGE_CHARTS', + ]); + }); + + it('accepts total_operational_txs together with the stats API host', () => { + expect(getValidationErrors(homepageSchema, { + NEXT_PUBLIC_STATS_API_HOST: 'https://stats.example.com', + NEXT_PUBLIC_HOMEPAGE_STATS: toEnvValue([ 'total_operational_txs' ]), + })).toEqual([]); + }); + + it('rejects total_operational_txs without the stats API host', () => { + expect(getValidationErrors(homepageSchema, { NEXT_PUBLIC_HOMEPAGE_STATS: toEnvValue([ 'total_operational_txs' ]) })).toEqual([ + 'NEXT_PUBLIC_STATS_API_HOST is required when total_operational_txs is enabled in NEXT_PUBLIC_HOMEPAGE_STATS', + ]); + }); + }); + + describe('hero banner config', () => { + it('rejects a color list with more than two entries', () => { + expect(getValidationErrors(homepageSchema, { + NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG: toEnvValue({ background: [ 'red', 'green', 'blue' ] }), + })).toEqual([ + 'NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG.background: Invalid length: Expected <=2 but received 3', + ]); + }); + + it('rejects a value that is not a JSON object', () => { + expect(getValidationErrors(homepageSchema, { NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG: 'lightpink' })).toEqual([ + 'NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG: Invalid JSON: Received "lightpink"', + ]); + }); + }); +}); + +describe('navigationSchema', () => { + const FEATURED = { NEXT_PUBLIC_FEATURED_NETWORKS: JSON.stringify(featuredNetworks) }; + + it('accepts the navigation, featured networks and logo settings', () => { + expect(getValidationErrors(navigationSchema, { + ...FEATURED, + NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK: 'https://example.com', + NEXT_PUBLIC_FEATURED_NETWORKS_MODE: 'list', + NEXT_PUBLIC_OTHER_LINKS: toEnvValue([ { url: 'https://blockscout.com', text: 'Blockscout' } ]), + NEXT_PUBLIC_NAVIGATION_HIGHLIGHTED_ROUTES: toEnvValue([ '/accounts', '/apps' ]), + NEXT_PUBLIC_NAVIGATION_LAYOUT: 'horizontal', + NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG: toEnvValue(promoBannerConfigFull), + NEXT_PUBLIC_NETWORK_LOGO: 'https://example.com/logo.png', + NEXT_PUBLIC_NETWORK_LOGO_DARK: 'https://example.com/logo-dark.png', + NEXT_PUBLIC_NETWORK_ICON: 'https://example.com/icon.png', + NEXT_PUBLIC_NETWORK_ICON_DARK: 'https://example.com/icon-dark.png', + })).toEqual([]); + }); + + it('rejects an unsupported layout', () => { + expect(getValidationErrors(navigationSchema, { NEXT_PUBLIC_NAVIGATION_LAYOUT: 'diagonal' })).toEqual([ + picklistMessage('NEXT_PUBLIC_NAVIGATION_LAYOUT', [ 'horizontal', 'vertical' ], 'diagonal'), + ]); + }); + + it.each([ + 'NEXT_PUBLIC_NETWORK_LOGO', + 'NEXT_PUBLIC_NETWORK_LOGO_DARK', + 'NEXT_PUBLIC_NETWORK_ICON', + 'NEXT_PUBLIC_NETWORK_ICON_DARK', + ])('rejects a malformed %s', (name) => { + expect(getValidationErrors(navigationSchema, { [name]: 'not a url' })).toEqual([ `${ name }: Invalid URL: Received "not a url"` ]); + }); + + describe('featured networks', () => { + it('rejects a network with an unknown group', () => { + expect(getValidationErrors(navigationSchema, { + NEXT_PUBLIC_FEATURED_NETWORKS: JSON.stringify([ { ...featuredNetworks[0], group: 'Devnets' } ]), + })).toEqual([ picklistMessage('NEXT_PUBLIC_FEATURED_NETWORKS.0.group', [ 'Mainnets', 'Testnets', 'Other' ], 'Devnets') ]); + }); + + it('rejects a network with a malformed URL', () => { + expect(getValidationErrors(navigationSchema, { + NEXT_PUBLIC_FEATURED_NETWORKS: JSON.stringify([ { ...featuredNetworks[0], url: 'not a url' } ]), + })).toEqual([ 'NEXT_PUBLIC_FEATURED_NETWORKS.0.url: Invalid URL: Received "not a url"' ]); + }); + + it('rejects a network with an empty icon URL', () => { + expect(getValidationErrors(navigationSchema, { + NEXT_PUBLIC_FEATURED_NETWORKS: JSON.stringify([ { ...featuredNetworks[0], icon: '' } ]), + })).toEqual([ 'NEXT_PUBLIC_FEATURED_NETWORKS.0.icon: Invalid URL: Received ""' ]); + }); + + it('rejects the all-networks link when the featured networks list is empty', () => { + expect(getValidationErrors(navigationSchema, { + NEXT_PUBLIC_FEATURED_NETWORKS: JSON.stringify([]), + NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK: 'https://example.com', + })).toEqual([ 'NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK can only be set when NEXT_PUBLIC_FEATURED_NETWORKS is configured' ]); + }); + + it('rejects a malformed all-networks link', () => { + expect(getValidationErrors(navigationSchema, { ...FEATURED, NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK: 'not a url' })).toEqual([ + 'NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK: Invalid URL: Received "not a url"', + ]); + }); + + it('rejects an unsupported mode', () => { + expect(getValidationErrors(navigationSchema, { ...FEATURED, NEXT_PUBLIC_FEATURED_NETWORKS_MODE: 'grid' })).toEqual([ + picklistMessage('NEXT_PUBLIC_FEATURED_NETWORKS_MODE', [ 'tabs', 'list' ], 'grid'), + ]); + }); + + it('rejects the all-networks link without the networks', () => { + expect(getValidationErrors(navigationSchema, { NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK: 'https://example.com' })).toEqual([ + 'NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK can only be set when NEXT_PUBLIC_FEATURED_NETWORKS is configured', + ]); + }); + + it('rejects the mode without the networks', () => { + expect(getValidationErrors(navigationSchema, { NEXT_PUBLIC_FEATURED_NETWORKS_MODE: 'list' })).toEqual([ + 'NEXT_PUBLIC_FEATURED_NETWORKS_MODE can only be set when NEXT_PUBLIC_FEATURED_NETWORKS is configured', + ]); + }); + }); + + it('rejects an other link with a malformed URL', () => { + expect(getValidationErrors(navigationSchema, { + NEXT_PUBLIC_OTHER_LINKS: toEnvValue([ { url: 'not a url', text: 'Blockscout' } ]), + })).toEqual([ 'NEXT_PUBLIC_OTHER_LINKS.0.url: Invalid URL: Received "not a url"' ]); + }); + + describe('promo banner config', () => { + it('accepts the image-only variant', () => { + expect(getValidationErrors(navigationSchema, { + NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG: toEnvValue(promoBannerConfigImageOnly), + })).toEqual([]); + }); + + it('rejects a config without the link URL', () => { + expect(getValidationErrors(navigationSchema, { + NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG: toEnvValue({ img_url: 'https://example.com/promo.svg', text: 'Promo text' }), + })).toEqual([ + 'NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG.bg_color: Invalid key: Expected "bg_color" but received undefined', + 'NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG.text_color: Invalid key: Expected "text_color" but received undefined', + 'NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG.link_url: Invalid key: Expected "link_url" but received undefined', + 'NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG.img_url: Invalid type: Expected Object but received "https://example.com/promo.svg"', + ]); + }); + }); +}); + +describe('footerSchema', () => { + it('accepts the footer links', () => { + expect(getValidationErrors(footerSchema, { NEXT_PUBLIC_FOOTER_LINKS: JSON.stringify(footerLinks) })).toEqual([]); + }); + + it('rejects a group without links', () => { + expect(getValidationErrors(footerSchema, { NEXT_PUBLIC_FOOTER_LINKS: JSON.stringify([ { title: 'Foo' } ]) })).toEqual([ + 'NEXT_PUBLIC_FOOTER_LINKS.0.links: Invalid key: Expected "links" but received undefined', + ]); + }); + + it('rejects a link with a malformed icon URL', () => { + expect(getValidationErrors(footerSchema, { + NEXT_PUBLIC_FOOTER_LINKS: JSON.stringify([ { title: 'Foo', links: [ { text: 'Home', url: 'https://example.com', iconUrl: [ 'not a url' ] } ] } ]), + })).toEqual([ 'NEXT_PUBLIC_FOOTER_LINKS.0.links.0.iconUrl.0: Invalid URL: Received "not a url"' ]); + }); +}); + +describe('miscSchema', () => { + it('accepts the theme, font and alert settings', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_HIDE_INDEXING_ALERT_BLOCKS: 'false', + NEXT_PUBLIC_HIDE_INDEXING_ALERT_INT_TXS: 'false', + NEXT_PUBLIC_HIDE_NATIVE_COIN_PRICE: 'false', + NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: '<a href="#">Hello</a>', + NEXT_PUBLIC_COLOR_THEMES: toEnvValue([ 'dim', 'dark' ]), + NEXT_PUBLIC_COLOR_THEME_DEFAULT: 'dim', + NEXT_PUBLIC_COLOR_THEME_OVERRIDES: toEnvValue({ light: { colors: { link: 'red' } } }), + NEXT_PUBLIC_FONT_FAMILY_HEADING: toEnvValue(fontFamilyHeading), + NEXT_PUBLIC_FONT_FAMILY_BODY: toEnvValue(fontFamilyBody), + NEXT_PUBLIC_MAX_CONTENT_WIDTH_ENABLED: 'false', + })).toEqual([]); + }); + + it.each([ + 'NEXT_PUBLIC_HIDE_INDEXING_ALERT_BLOCKS', + 'NEXT_PUBLIC_HIDE_INDEXING_ALERT_INT_TXS', + 'NEXT_PUBLIC_HIDE_NATIVE_COIN_PRICE', + 'NEXT_PUBLIC_MAX_CONTENT_WIDTH_ENABLED', + ])('rejects a non-boolean %s', (name) => { + expect(getValidationErrors(miscSchema, { [name]: 'yes' })).toEqual([ nonBooleanMessage(name) ]); + }); + + it('accepts an array of maintenance alert messages', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: `['<a href="https://example.com">Hello</a>','Duck me']`, + })).toEqual([]); + }); + + it('rejects a maintenance alert message with a frame or an inline style', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: '<div style="position:fixed">Hello <iframe srcdoc="<script></script>"></iframe></div>', + })).toEqual([ + 'NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: HTML contains elements that are not allowed: style attribute on <div>, <iframe>', + ]); + }); + + it('rejects an array of maintenance alert messages when one item has an event handler', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: `['Plain','<a href="https://example.com" onclick="steal()">Hello</a>']`, + })).toEqual([ + 'NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: HTML contains elements that are not allowed: onclick attribute on <a>', + ]); + }); + + it('rejects an item of a single-quoted array whose attributes escape their double quotes', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: String.raw`['Plain','<a href=\"https://example.com\" onclick=\"steal()\">Hello</a>']`, + })).toEqual([ + 'NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: HTML contains elements that are not allowed: onclick attribute on <a>', + ]); + }); + + it('accepts a single-quoted attribute value that holds a double quote, as the app renders it', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: `Pay <a href="https://example.com" title='x" onclick="steal()'>here</a>`, + })).toEqual([]); + }); + + it('checks the items of a double-quoted array whose apostrophe breaks the quote-rewritten JSON', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: String.raw`["It's down", "\u003ciframe srcdoc='https://evil.example'\u003e\u003c/iframe\u003e"]`, + })).toEqual([ + 'NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: HTML contains elements that are not allowed: <iframe>', + ]); + }); + + describe('color themes', () => { + it('rejects an unknown theme id', () => { + expect(getValidationErrors(miscSchema, { NEXT_PUBLIC_COLOR_THEMES: toEnvValue([ 'sepia' ]) })).toEqual([ + picklistMessage('NEXT_PUBLIC_COLOR_THEMES.0', [ 'light', 'dim', 'midnight', 'dark', 'system' ], 'sepia'), + ]); + }); + + it('rejects an unknown default theme', () => { + expect(getValidationErrors(miscSchema, { NEXT_PUBLIC_COLOR_THEME_DEFAULT: 'sepia' })).toEqual([ + picklistMessage('NEXT_PUBLIC_COLOR_THEME_DEFAULT', [ 'light', 'dim', 'midnight', 'dark', 'system' ], 'sepia'), + ]); + }); + + it('accepts the system theme when the listed themes cover both color modes', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_COLOR_THEMES: toEnvValue([ 'light', 'midnight', 'system' ]), + NEXT_PUBLIC_COLOR_THEME_DEFAULT: 'system', + })).toEqual([]); + }); + + it('accepts the system default theme without a themes list', () => { + expect(getValidationErrors(miscSchema, { NEXT_PUBLIC_COLOR_THEME_DEFAULT: 'system' })).toEqual([]); + }); + + it('rejects the system theme when the listed themes are all of one color mode', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_COLOR_THEMES: toEnvValue([ 'dim', 'dark', 'system' ]), + })).toEqual([ 'The system color theme requires NEXT_PUBLIC_COLOR_THEMES to list at least one light and one dark theme' ]); + }); + + it('rejects a system default theme when the listed themes are all of one color mode', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_COLOR_THEMES: toEnvValue([ 'dim', 'dark' ]), + NEXT_PUBLIC_COLOR_THEME_DEFAULT: 'system', + })).toEqual([ + 'NEXT_PUBLIC_COLOR_THEME_DEFAULT must be one of the themes listed in NEXT_PUBLIC_COLOR_THEMES', + 'The system color theme requires NEXT_PUBLIC_COLOR_THEMES to list at least one light and one dark theme', + ]); + }); + + it('accepts a one-color-mode themes list that does not involve the system theme', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_COLOR_THEMES: toEnvValue([ 'dim', 'dark' ]), + NEXT_PUBLIC_COLOR_THEME_DEFAULT: 'dark', + })).toEqual([]); + }); + + it('accepts a default theme without a themes list', () => { + expect(getValidationErrors(miscSchema, { NEXT_PUBLIC_COLOR_THEME_DEFAULT: 'dim' })).toEqual([]); + }); + + it('rejects a default theme that is not among the listed themes', () => { + expect(getValidationErrors(miscSchema, { + NEXT_PUBLIC_COLOR_THEMES: toEnvValue([ 'dim', 'dark' ]), + NEXT_PUBLIC_COLOR_THEME_DEFAULT: 'light', + })).toEqual([ 'NEXT_PUBLIC_COLOR_THEME_DEFAULT must be one of the themes listed in NEXT_PUBLIC_COLOR_THEMES' ]); + }); + + it('rejects theme overrides that are not a JSON object', () => { + expect(getValidationErrors(miscSchema, { NEXT_PUBLIC_COLOR_THEME_OVERRIDES: 'not json' })).toEqual([ + 'NEXT_PUBLIC_COLOR_THEME_OVERRIDES: Invalid JSON: Received "not json"', + ]); + }); + }); + + it.each([ + 'NEXT_PUBLIC_FONT_FAMILY_HEADING', + 'NEXT_PUBLIC_FONT_FAMILY_BODY', + ])('rejects a %s with a malformed URL', (name) => { + expect(getValidationErrors(miscSchema, { [name]: toEnvValue({ name: 'Montserrat', url: 'not a url' }) })).toEqual([ + `${ name }.url: Invalid URL: Received "not a url"`, + ]); + }); +}); + +describe('viewsSchema', () => { + it('accepts the block, address, contract, tx and token view settings', () => { + expect(getValidationErrors(viewsSchema, { + NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_FIELDS: toEnvValue([ 'burnt_fees', 'total_reward' ]), + NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_VIEWS: toEnvValue([ 'reorgs', 'uncles' ]), + NEXT_PUBLIC_VIEWS_BLOCK_PENDING_UPDATE_ALERT_ENABLED: 'false', + NEXT_PUBLIC_VIEWS_ADDRESS_IDENTICON_TYPE: 'gradient_avatar', + NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT: toEnvValue([ 'base16' ]), + NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS: '0x471EcE3750Da237f93B8E339c536989b8978a438', + NEXT_PUBLIC_VIEWS_ADDRESS_HIDDEN_VIEWS: toEnvValue([ 'top_accounts' ]), + NEXT_PUBLIC_VIEWS_CONTRACT_SOLIDITYSCAN_ENABLED: 'true', + NEXT_PUBLIC_VIEWS_CONTRACT_DECODED_BYTECODE_ENABLED: 'true', + NEXT_PUBLIC_VIEWS_CONTRACT_EXTRA_VERIFICATION_METHODS: toEnvValue([ 'solidity-hardhat', 'solidity-foundry' ]), + NEXT_PUBLIC_VIEWS_TX_HIDDEN_FIELDS: toEnvValue([ 'value', 'fee_currency', 'gas_price', 'tx_fee', 'gas_fees', 'burnt_fees' ]), + NEXT_PUBLIC_VIEWS_TX_ADDITIONAL_FIELDS: toEnvValue([ 'fee_per_gas', 'set_max_gas_limit' ]), + NEXT_PUBLIC_VIEWS_TX_GROUPED_FEES: 'true', + NEXT_PUBLIC_VIEWS_TX_HIDDEN_VIEWS: toEnvValue([ 'pending_txs' ]), + NEXT_PUBLIC_INTERNAL_TXS_ENABLED: 'false', + NEXT_PUBLIC_VIEWS_NFT_MARKETPLACES: toEnvValue(nftMarketplaces), + NEXT_PUBLIC_VIEWS_TOKEN_SCAM_TOGGLE_ENABLED: 'true', + NEXT_PUBLIC_HELIA_VERIFIED_FETCH_ENABLED: 'false', + NEXT_PUBLIC_NETWORK_EXPLORERS: toEnvValue(networkExplorers), + NEXT_PUBLIC_CONTRACT_CODE_IDES: toEnvValue(contractCodeIdes), + NEXT_PUBLIC_HAS_CONTRACT_AUDIT_REPORTS: 'true', + })).toEqual([]); + }); + + it.each([ + 'NEXT_PUBLIC_VIEWS_BLOCK_PENDING_UPDATE_ALERT_ENABLED', + 'NEXT_PUBLIC_VIEWS_CONTRACT_SOLIDITYSCAN_ENABLED', + 'NEXT_PUBLIC_VIEWS_CONTRACT_DECODED_BYTECODE_ENABLED', + 'NEXT_PUBLIC_VIEWS_TX_GROUPED_FEES', + 'NEXT_PUBLIC_INTERNAL_TXS_ENABLED', + 'NEXT_PUBLIC_VIEWS_TOKEN_SCAM_TOGGLE_ENABLED', + 'NEXT_PUBLIC_HELIA_VERIFIED_FETCH_ENABLED', + 'NEXT_PUBLIC_HAS_CONTRACT_AUDIT_REPORTS', + ])('rejects a non-boolean %s', (name) => { + expect(getValidationErrors(viewsSchema, { [name]: 'yes' })).toEqual([ nonBooleanMessage(name) ]); + }); + + it.each([ + [ 'NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_FIELDS', '("base_fee" | "burnt_fees" | "total_reward" | "nonce" | "miner" | "L1_status" | "batch")' ], + [ 'NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_VIEWS', '("reorgs" | "uncles")' ], + [ 'NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT', '("base16" | "bech32")' ], + [ 'NEXT_PUBLIC_VIEWS_ADDRESS_HIDDEN_VIEWS', '"top_accounts"' ], + [ + 'NEXT_PUBLIC_VIEWS_TX_HIDDEN_FIELDS', + '("value" | "fee_currency" | "gas_price" | "tx_fee" | "gas_fees" | "burnt_fees" | "batch" | "L1_status" | ' + + '"L1_gas_used" | "L1_gas_price" | "L1_fee" | "L1_fee_scalar")', + ], + [ 'NEXT_PUBLIC_VIEWS_TX_ADDITIONAL_FIELDS', '("fee_per_gas" | "set_max_gas_limit")' ], + [ 'NEXT_PUBLIC_VIEWS_TX_HIDDEN_VIEWS', '"pending_txs"' ], + ])('rejects an unknown id in %s', (name, allowed) => { + expect(getValidationErrors(viewsSchema, { [name]: toEnvValue([ 'unknown' ]) })).toEqual([ + `${ name }.0: Invalid type: Expected ${ allowed } but received "unknown"`, + ]); + }); + + it('rejects an unknown identicon type', () => { + expect(getValidationErrors(viewsSchema, { NEXT_PUBLIC_VIEWS_ADDRESS_IDENTICON_TYPE: 'robohash' })).toEqual([ + picklistMessage('NEXT_PUBLIC_VIEWS_ADDRESS_IDENTICON_TYPE', [ 'github', 'jazzicon', 'gradient_avatar', 'blockie', 'nouns' ], 'robohash'), + ]); + }); + + describe('bech32 prefix', () => { + it('is accepted together with the bech32 address format', () => { + expect(getValidationErrors(viewsSchema, { + NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT: toEnvValue([ 'base16', 'bech32' ]), + NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX: 'foo', + })).toEqual([]); + }); + + it('is required when the bech32 address format is enabled', () => { + expect(getValidationErrors(viewsSchema, { NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT: toEnvValue([ 'base16', 'bech32' ]) })).toEqual([ + 'NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX is required when NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT contains "bech32"', + ]); + }); + + it('is rejected without the bech32 address format', () => { + expect(getValidationErrors(viewsSchema, { NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX: 'foo' })).toEqual([ + 'NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX is required if NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT contains "bech32"', + ]); + }); + }); + + describe('native token address', () => { + it('rejects an address of the wrong length', () => { + expect(getValidationErrors(viewsSchema, { NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS: '0x471EcE3750Da237f' })).toEqual([ + 'NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS: Invalid length: Expected 42 but received 18', + ]); + }); + + it('rejects a non-hex address', () => { + expect(getValidationErrors(viewsSchema, { NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS: '0xZZZEcE3750Da237f93B8E339c536989b8978a438' })).toEqual([ + 'NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS: Invalid format: Expected /^0x[\\da-fA-F]+$/ but received "0xZZZEcE3750Da237f93B8E339c536989b8978a438"', + ]); + }); + }); + + describe('extra contract verification methods', () => { + it('accepts the "none" literal', () => { + expect(getValidationErrors(viewsSchema, { NEXT_PUBLIC_VIEWS_CONTRACT_EXTRA_VERIFICATION_METHODS: 'none' })).toEqual([]); + }); + + it('rejects an unknown method id', () => { + expect(getValidationErrors(viewsSchema, { NEXT_PUBLIC_VIEWS_CONTRACT_EXTRA_VERIFICATION_METHODS: toEnvValue([ 'vyper-brownie' ]) })).toEqual([ + 'NEXT_PUBLIC_VIEWS_CONTRACT_EXTRA_VERIFICATION_METHODS: Invalid type: Expected "none" but received "[\'vyper-brownie\']"', + picklistMessage('NEXT_PUBLIC_VIEWS_CONTRACT_EXTRA_VERIFICATION_METHODS.0', [ 'solidity-hardhat', 'solidity-foundry' ], 'vyper-brownie'), + ]); + }); + }); + + it('rejects an NFT marketplace without a logo URL', () => { + expect(getValidationErrors(viewsSchema, { + NEXT_PUBLIC_VIEWS_NFT_MARKETPLACES: toEnvValue([ { name: 'NFT Marketplace', collection_url: 'https://example.com/{hash}' } ]), + })).toEqual([ 'NEXT_PUBLIC_VIEWS_NFT_MARKETPLACES.0.logo_url: Invalid key: Expected "logo_url" but received undefined' ]); + }); + + it('rejects a network explorer with a malformed base URL', () => { + expect(getValidationErrors(viewsSchema, { + NEXT_PUBLIC_NETWORK_EXPLORERS: toEnvValue([ { ...networkExplorers[0], baseUrl: 'not a url' } ]), + })).toEqual([ 'NEXT_PUBLIC_NETWORK_EXPLORERS.0.baseUrl: Invalid URL: Received "not a url"' ]); + }); + + it('rejects a contract code IDE without an icon URL', () => { + expect(getValidationErrors(viewsSchema, { + NEXT_PUBLIC_CONTRACT_CODE_IDES: toEnvValue([ { title: 'Remix IDE', url: 'https://remix.blockscout.com' } ]), + })).toEqual([ 'NEXT_PUBLIC_CONTRACT_CODE_IDES.0.icon_url: Invalid key: Expected "icon_url" but received undefined' ]); + }); +}); diff --git a/deploy/tools/envs-validator/schemas/ui.ts b/deploy/tools/envs-validator/schemas/ui.ts index 7db567fd715..1e3969a823c 100644 --- a/deploy/tools/envs-validator/schemas/ui.ts +++ b/deploy/tools/envs-validator/schemas/ui.ts @@ -1,10 +1,11 @@ -import * as yup from 'yup'; -import { CHAIN_INDICATOR_IDS, type ChainIndicatorId, type HeroBannerConfig, type HeroBannerButtonState, type HeroBannerSearchBorderColorState, HOME_STATS_WIDGET_IDS, type HomeStatsWidgetId } from 'src/slices/home/types/config'; -import { replaceQuotes } from 'src/config/utils/envs'; -import { getYupValidationErrorMessage, urlTest } from '../utils'; -import { NavigationLayout, NavigationPromoBannerConfig, NavItemExternal } from 'src/shell/navigation/types'; -import type { FeaturedNetwork } from 'src/shell/top-bar/chain-menu/types'; +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + +import type { AlternativeExplorer } from 'src/features/alternative-explorers/types/client'; +import type { CustomLink, CustomLinksGroup } from 'src/shell/footer/types'; import { NETWORK_GROUPS } from 'src/shell/top-bar/chain-menu/types'; +<<<<<<< HEAD import { AlternativeExplorer } from 'src/features/alternative-explorers/types/client'; import { CustomLink, CustomLinksGroup } from 'src/shell/footer/types'; import type { ColorThemeId } from 'src/shell/top-bar/settings/color-theme/config'; @@ -13,181 +14,44 @@ import type { FontFamily } from 'src/config/misc'; import type { ContractCodeIde } from 'src/slices/contract/types/config'; import { SMART_CONTRACT_EXTRA_VERIFICATION_METHODS, type SmartContractVerificationMethodExtra } from 'src/slices/contract/types/config'; import type { AddressFormat, AddressViewId } from 'src/slices/address/types/config'; +======= +import type { FeaturedNetwork } from 'src/shell/top-bar/chain-menu/types'; +import type { AddressFormat } from 'src/slices/address/types/config'; +>>>>>>> v2.13.0 import { ADDRESS_FORMATS, ADDRESS_VIEWS_IDS, IDENTICON_TYPES } from 'src/slices/address/types/config'; -import { BLOCK_FIELDS_IDS } from 'src/slices/block/types/config'; -import type { BlockFieldId } from 'src/slices/block/types/config'; -import type { TxAdditionalFieldsId, TxFieldsId, TxViewId } from 'src/slices/tx/types/config'; +import { BLOCK_FIELDS_IDS, BLOCK_VIEWS_IDS } from 'src/slices/block/types/config'; +import type { ContractCodeIde } from 'src/slices/contract/types/config'; +import { SMART_CONTRACT_EXTRA_VERIFICATION_METHODS } from 'src/slices/contract/types/config'; +import type { HeroBannerButtonState, HeroBannerSearchBorderColorState } from 'src/slices/home/types/config'; +import { CHAIN_INDICATOR_IDS, HOME_STATS_WIDGET_IDS } from 'src/slices/home/types/config'; +import type { NftMarketplaceItem } from 'src/slices/token/types/client'; import { TX_ADDITIONAL_FIELDS_IDS, TX_FIELDS_IDS, TX_VIEWS_IDS } from 'src/slices/tx/types/config'; -import * as regexp from 'src/toolkit/utils/regexp'; -import { NftMarketplaceItem } from 'src/slices/token/types/client'; -const heroBannerButtonStateSchema: yup.ObjectSchema<HeroBannerButtonState> = yup.object({ - background: yup.array().max(2).of(yup.string()), - text_color: yup.array().max(2).of(yup.string()), - }); +import type { ColorThemeId } from 'src/shell/top-bar/settings/fields/color-theme/config'; +import { COLOR_THEME_IDS, COLOR_THEMES, SYSTEM_COLOR_THEME_ID, coversBothColorModes } from 'src/shell/top-bar/settings/fields/color-theme/config'; -const heroBannerSearchBorderColorSchema: yup.ObjectSchema<HeroBannerSearchBorderColorState> = yup.object({ - _empty: yup.array().max(2).of(yup.string()), - _hover: yup.array().max(2).of(yup.string()), - _focus: yup.array().max(2).of(yup.string()), - _filled: yup.array().max(2).of(yup.string()), - }); +import * as regexp from 'src/toolkit/utils/regexp'; -const heroBannerSchema: yup.ObjectSchema<HeroBannerConfig> = yup.object() - .transform(replaceQuotes) - .json() - .shape({ - background: yup.array().max(2).of(yup.string()), - text_color: yup.array().max(2).of(yup.string()), - border: yup.array().max(2).of(yup.string()), - button: yup.object({ - _default: heroBannerButtonStateSchema, - _hover: heroBannerButtonStateSchema, - _selected: heroBannerButtonStateSchema, - }), - search: yup.object({ - background: yup.array().max(2).of(yup.string()), - border_width: yup.array().max(2).of(yup.string()), - border_color: heroBannerSearchBorderColorSchema, - }), - text: yup.string(), - }); +import { companionRule, envBoolean, envHtmlList, envJson, envUrl, requiredIf, requires } from '../utils'; -export const homepageSchema = yup.object({ - NEXT_PUBLIC_HOMEPAGE_CHARTS: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string<ChainIndicatorId>().oneOf(CHAIN_INDICATOR_IDS)) - .test( - 'stats-api-required', - 'NEXT_PUBLIC_STATS_API_HOST is required when daily_operational_txs is enabled in NEXT_PUBLIC_HOMEPAGE_CHARTS', - function(value) { - // daily_operational_txs is presented only in stats microservice - if (value?.includes('daily_operational_txs')) { - return Boolean(this.parent.NEXT_PUBLIC_STATS_API_HOST); - } - return true; - } - ), - NEXT_PUBLIC_HOMEPAGE_STATS: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string<HomeStatsWidgetId>().oneOf(HOME_STATS_WIDGET_IDS)) - .test( - 'stats-api-required', - 'NEXT_PUBLIC_STATS_API_HOST is required when total_operational_txs is enabled in NEXT_PUBLIC_HOMEPAGE_STATS', - function(value) { - // total_operational_txs is presented only in stats microservice - if (value?.includes('total_operational_txs')) { - return Boolean(this.parent.NEXT_PUBLIC_STATS_API_HOST); - } - return true; - } - ), - NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG: yup - .mixed() - .test( - 'shape', - (ctx) => { - try { - heroBannerSchema.validateSync(ctx.originalValue); - throw new Error('Unknown validation error'); - } catch (error: unknown) { - const message = getYupValidationErrorMessage(error); - return 'Invalid schema were provided for NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG' + (message ? `: ${ message }` : ''); - } - }, - (data) => { - const isUndefined = data === undefined; - return isUndefined || heroBannerSchema.isValidSync(data); - }), -}); +const requiredString = () => v.pipe(v.string(), v.nonEmpty()); +const requiredUrl = () => v.pipe(v.string(), v.nonEmpty(), v.url()); +const optionalUrl = () => v.optional(v.pipe(v.string(), v.url())); +const colorPair = () => v.optional(v.pipe(v.array(v.string()), v.maxLength(2))); -const featuredNetworkSchema: yup.ObjectSchema<FeaturedNetwork> = yup - .object() - .shape({ - title: yup.string().required(), - url: yup.string().test(urlTest).required(), - group: yup.string().oneOf(NETWORK_GROUPS).required(), - icon: yup.string().test(urlTest), - isActive: yup.boolean(), - invertIconInDarkMode: yup.boolean(), - }); - -const navItemExternalSchema: yup.ObjectSchema<NavItemExternal> = yup - .object({ - text: yup.string().required(), - url: yup.string().test(urlTest).required(), - }); +const heroBannerButtonStateSchema: v.GenericSchema<HeroBannerButtonState> = v.object({ + background: colorPair(), + text_color: colorPair(), +}); -export const navigationSchema = yup.object({ - NEXT_PUBLIC_FEATURED_NETWORKS: yup - .array() - .json() - .of(featuredNetworkSchema), - NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK: yup - .string() - .when('NEXT_PUBLIC_FEATURED_NETWORKS', { - is: (value: Array<unknown> | undefined) => value && value.length > 0, - then: (schema) => schema.test(urlTest), - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK can only be set when NEXT_PUBLIC_FEATURED_NETWORKS is configured'), - }), - NEXT_PUBLIC_FEATURED_NETWORKS_MODE: yup - .string() - .when('NEXT_PUBLIC_FEATURED_NETWORKS', { - is: (value: Array<unknown> | undefined) => value && value.length > 0, - then: (schema) => schema.oneOf([ 'tabs', 'list' ]), - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_FEATURED_NETWORKS_MODE can only be set when NEXT_PUBLIC_FEATURED_NETWORKS is configured'), - }), - NEXT_PUBLIC_OTHER_LINKS: yup - .array() - .transform(replaceQuotes) - .json() - .of(navItemExternalSchema), - NEXT_PUBLIC_NAVIGATION_HIGHLIGHTED_ROUTES: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string()), - NEXT_PUBLIC_NAVIGATION_LAYOUT: yup.string<NavigationLayout>().oneOf([ 'horizontal', 'vertical' ]), - NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG: yup - .mixed() - .test('shape', 'Invalid schema were provided for NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG, it should be either object with img_url, text, bg_color, text_color, link_url or object with img_url and link_url', (data) => { - const isUndefined = data === undefined; - const jsonSchema = yup.object<NavigationPromoBannerConfig>().transform(replaceQuotes).json(); - - const valueSchema1 = jsonSchema.shape({ - img_url: yup.string().required(), - text: yup.string().required(), - bg_color: yup.object().shape({ - light: yup.string().required(), - dark: yup.string().required(), - }).required(), - text_color: yup.object().shape({ - light: yup.string().required(), - dark: yup.string().required(), - }).required(), - link_url: yup.string().required(), - }); - - const valueSchema2 = jsonSchema.shape({ - img_url: yup.object().shape({ - small: yup.string().required(), - large: yup.string().required(), - }).required(), - link_url: yup.string().required(), - }); - - return isUndefined || valueSchema1.isValidSync(data) || valueSchema2.isValidSync(data); - }), - NEXT_PUBLIC_NETWORK_LOGO: yup.string().test(urlTest), - NEXT_PUBLIC_NETWORK_LOGO_DARK: yup.string().test(urlTest), - NEXT_PUBLIC_NETWORK_ICON: yup.string().test(urlTest), - NEXT_PUBLIC_NETWORK_ICON_DARK: yup.string().test(urlTest), +const heroBannerSearchBorderColorSchema: v.GenericSchema<HeroBannerSearchBorderColorState> = v.object({ + _empty: colorPair(), + _hover: colorPair(), + _focus: colorPair(), + _filled: colorPair(), }); +<<<<<<< HEAD const footerLinkSchema: yup.ObjectSchema<CustomLink> = yup .object({ text: yup.string().required(), @@ -212,34 +76,46 @@ export const footerSchema = yup.object({ .json() .of(footerLinkGroupSchema), NEXT_PUBLIC_VERSION_LINK_TYPE: yup.string().oneOf([ 'tree', 'release' ]), +======= +const heroBannerSchema = v.object({ + background: colorPair(), + text_color: colorPair(), + border: colorPair(), + button: v.optional(v.object({ + _default: v.optional(heroBannerButtonStateSchema), + _hover: v.optional(heroBannerButtonStateSchema), + _selected: v.optional(heroBannerButtonStateSchema), + })), + search: v.optional(v.object({ + background: colorPair(), + border_width: colorPair(), + border_color: v.optional(heroBannerSearchBorderColorSchema), + })), + text: v.optional(v.string()), +>>>>>>> v2.13.0 }); -const fontFamilySchema: yup.ObjectSchema<FontFamily> = yup - .object() - .transform(replaceQuotes) - .json() - .shape({ - name: yup.string().required(), - url: yup.string().test(urlTest).required(), - }); +const hasListItem = (value: unknown, item: string) => Array.isArray(value) && value.includes(item); -export const miscSchema = yup.object({ - NEXT_PUBLIC_HIDE_INDEXING_ALERT_BLOCKS: yup.boolean(), - NEXT_PUBLIC_HIDE_INDEXING_ALERT_INT_TXS: yup.boolean(), - NEXT_PUBLIC_HIDE_NATIVE_COIN_PRICE: yup.boolean(), - NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: yup - .mixed() - .test( - 'shape', - 'Invalid schema were provided for NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE, it should be either an array of strings or a string', - (data) => { - const isStringSchema = yup.string(); - const isArrayOfStringsSchema = yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string()); +export const homepageSchema = v.pipe( + v.looseObject({ + NEXT_PUBLIC_HOMEPAGE_CHARTS: v.optional(envJson(v.array(v.picklist(CHAIN_INDICATOR_IDS)))), + NEXT_PUBLIC_HOMEPAGE_STATS: v.optional(envJson(v.array(v.picklist(HOME_STATS_WIDGET_IDS)))), + NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG: v.optional(envJson(heroBannerSchema)), + }), + companionRule( + [ 'NEXT_PUBLIC_HOMEPAGE_CHARTS', 'NEXT_PUBLIC_STATS_API_HOST' ], + (input) => !hasListItem(input.NEXT_PUBLIC_HOMEPAGE_CHARTS, 'daily_operational_txs') || Boolean(input.NEXT_PUBLIC_STATS_API_HOST), + 'NEXT_PUBLIC_STATS_API_HOST is required when daily_operational_txs is enabled in NEXT_PUBLIC_HOMEPAGE_CHARTS', + ), + companionRule( + [ 'NEXT_PUBLIC_HOMEPAGE_STATS', 'NEXT_PUBLIC_STATS_API_HOST' ], + (input) => !hasListItem(input.NEXT_PUBLIC_HOMEPAGE_STATS, 'total_operational_txs') || Boolean(input.NEXT_PUBLIC_STATS_API_HOST), + 'NEXT_PUBLIC_STATS_API_HOST is required when total_operational_txs is enabled in NEXT_PUBLIC_HOMEPAGE_STATS', + ), +); +<<<<<<< HEAD return isStringSchema.isValidSync(data) || isArrayOfStringsSchema.isValidSync(data); }), NEXT_PUBLIC_COLOR_THEMES: yup @@ -277,125 +153,192 @@ export const miscSchema = yup.object({ return isUndefined || fontFamilySchema.isValidSync(data); }), NEXT_PUBLIC_MAX_CONTENT_WIDTH_ENABLED: yup.boolean(), +======= +const featuredNetworkSchema: v.GenericSchema<FeaturedNetwork> = v.object({ + title: requiredString(), + url: requiredUrl(), + group: v.picklist(NETWORK_GROUPS), + icon: optionalUrl(), + isActive: v.optional(v.boolean()), + invertIconInDarkMode: v.optional(v.boolean()), +>>>>>>> v2.13.0 }); -const networkExplorerSchema: yup.ObjectSchema<AlternativeExplorer> = yup - .object({ - title: yup.string().required(), - logo: yup.string().test(urlTest), - baseUrl: yup.string().test(urlTest).required(), - paths: yup - .object() - .shape({ - tx: yup.string(), - address: yup.string(), - token: yup.string(), - block: yup.string(), - blob: yup.string(), - }), - }); +const navItemExternalSchema = v.object({ + text: requiredString(), + url: requiredUrl(), +}); -const contractCodeIdeSchema: yup.ObjectSchema<ContractCodeIde> = yup - .object({ - title: yup.string().required(), - url: yup.string().test(urlTest).required(), - icon_url: yup.string().test(urlTest).required(), - }); +const colorModePairSchema = v.object({ + light: requiredString(), + dark: requiredString(), +}); -const nftMarketplaceSchema: yup.ObjectSchema<NftMarketplaceItem> = yup - .object({ - name: yup.string().required(), - collection_url: yup.string().test(urlTest), - instance_url: yup.string().test(urlTest), - logo_url: yup.string().test(urlTest).required(), - }); +const promoBannerConfigSchema = v.union([ + v.object({ + img_url: requiredString(), + text: requiredString(), + bg_color: colorModePairSchema, + text_color: colorModePairSchema, + link_url: requiredString(), + }), + v.object({ + img_url: v.object({ + small: requiredString(), + large: requiredString(), + }), + link_url: requiredString(), + }), +]); +const hasItems = (value: unknown) => Array.isArray(value) && value.length > 0; -export const viewsSchema = yup.object({ - NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_FIELDS: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string<BlockFieldId>().oneOf(BLOCK_FIELDS_IDS)), - NEXT_PUBLIC_VIEWS_BLOCK_PENDING_UPDATE_ALERT_ENABLED: yup.boolean(), - NEXT_PUBLIC_VIEWS_ADDRESS_IDENTICON_TYPE: yup.string().oneOf(IDENTICON_TYPES), - NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string<AddressFormat>().oneOf(ADDRESS_FORMATS)), - NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX: yup - .string() - .when('NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT', { - is: (value: Array<AddressFormat> | undefined) => value && value.includes('bech32'), - then: (schema) => schema.required().min(1).max(83), - otherwise: (schema) => schema.max(-1, 'NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX is required if NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT contains "bech32"'), - }), - NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS: yup - .string() - .min(42) - .max(42) - .matches(regexp.HEX_REGEXP_WITH_0X), +export const navigationSchema = v.pipe( + v.object({ + NEXT_PUBLIC_FEATURED_NETWORKS: v.optional(envJson(v.array(featuredNetworkSchema))), + NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK: v.optional(envUrl()), + NEXT_PUBLIC_FEATURED_NETWORKS_MODE: v.optional(v.picklist([ 'tabs', 'list' ])), + NEXT_PUBLIC_OTHER_LINKS: v.optional(envJson(v.array(navItemExternalSchema))), + NEXT_PUBLIC_NAVIGATION_HIGHLIGHTED_ROUTES: v.optional(envJson(v.array(v.string()))), + NEXT_PUBLIC_NAVIGATION_LAYOUT: v.optional(v.picklist([ 'horizontal', 'vertical' ])), + NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG: v.optional(envJson(promoBannerConfigSchema)), + NEXT_PUBLIC_NETWORK_LOGO: v.optional(envUrl()), + NEXT_PUBLIC_NETWORK_LOGO_DARK: v.optional(envUrl()), + NEXT_PUBLIC_NETWORK_ICON: v.optional(envUrl()), + NEXT_PUBLIC_NETWORK_ICON_DARK: v.optional(envUrl()), + }), + requires('NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK', 'NEXT_PUBLIC_FEATURED_NETWORKS', { + when: hasItems, + message: 'NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK can only be set when NEXT_PUBLIC_FEATURED_NETWORKS is configured', + }), + requires('NEXT_PUBLIC_FEATURED_NETWORKS_MODE', 'NEXT_PUBLIC_FEATURED_NETWORKS', { + when: hasItems, + message: 'NEXT_PUBLIC_FEATURED_NETWORKS_MODE can only be set when NEXT_PUBLIC_FEATURED_NETWORKS is configured', + }), +); - NEXT_PUBLIC_VIEWS_ADDRESS_HIDDEN_VIEWS: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string<AddressViewId>().oneOf(ADDRESS_VIEWS_IDS)), - NEXT_PUBLIC_VIEWS_CONTRACT_SOLIDITYSCAN_ENABLED: yup.boolean(), - NEXT_PUBLIC_VIEWS_CONTRACT_DECODED_BYTECODE_ENABLED: yup.boolean(), - NEXT_PUBLIC_VIEWS_CONTRACT_EXTRA_VERIFICATION_METHODS: yup - .mixed() - .test( - 'shape', - 'Invalid schema were provided for NEXT_PUBLIC_VIEWS_CONTRACT_EXTRA_VERIFICATION_METHODS, it should be either array of method ids or "none" string literal', - (data) => { - const isNoneSchema = yup.string().oneOf([ 'none' ]); - const isArrayOfMethodsSchema = yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string<SmartContractVerificationMethodExtra>().oneOf(SMART_CONTRACT_EXTRA_VERIFICATION_METHODS)); - - return isNoneSchema.isValidSync(data) || isArrayOfMethodsSchema.isValidSync(data); - }), - - NEXT_PUBLIC_VIEWS_TX_HIDDEN_FIELDS: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string<TxFieldsId>().oneOf(TX_FIELDS_IDS)), - NEXT_PUBLIC_VIEWS_TX_ADDITIONAL_FIELDS: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string<TxAdditionalFieldsId>().oneOf(TX_ADDITIONAL_FIELDS_IDS)), - NEXT_PUBLIC_VIEWS_TX_GROUPED_FEES: yup.boolean(), - NEXT_PUBLIC_VIEWS_TX_HIDDEN_VIEWS: yup - .array() - .transform(replaceQuotes) - .json() - .of(yup.string<TxViewId>().oneOf(TX_VIEWS_IDS)), +const footerLinkSchema: v.GenericSchema<CustomLink> = v.object({ + text: requiredString(), + url: requiredUrl(), + iconUrl: v.optional(v.array(requiredUrl())), +}); - NEXT_PUBLIC_INTERNAL_TXS_ENABLED: yup.boolean(), +const footerLinkGroupSchema: v.GenericSchema<CustomLinksGroup> = v.object({ + title: requiredString(), + links: v.array(footerLinkSchema), +}); - NEXT_PUBLIC_VIEWS_NFT_MARKETPLACES: yup - .array() - .transform(replaceQuotes) - .json() - .of(nftMarketplaceSchema), - NEXT_PUBLIC_VIEWS_TOKEN_SCAM_TOGGLE_ENABLED: yup.boolean(), - NEXT_PUBLIC_HELIA_VERIFIED_FETCH_ENABLED: yup.boolean(), +export const footerSchema = v.object({ + NEXT_PUBLIC_FOOTER_LINKS: v.optional(envJson(v.array(footerLinkGroupSchema))), +}); - NEXT_PUBLIC_NETWORK_EXPLORERS: yup - .array() - .transform(replaceQuotes) - .json() - .of(networkExplorerSchema), - NEXT_PUBLIC_CONTRACT_CODE_IDES: yup - .array() - .transform(replaceQuotes) - .json() - .of(contractCodeIdeSchema), - NEXT_PUBLIC_HAS_CONTRACT_AUDIT_REPORTS: yup.boolean(), +const fontFamilySchema = v.object({ + name: requiredString(), + url: requiredUrl(), +}); + +export const miscSchema = v.pipe( + v.object({ + NEXT_PUBLIC_HIDE_INDEXING_ALERT_BLOCKS: v.optional(envBoolean()), + NEXT_PUBLIC_HIDE_INDEXING_ALERT_INT_TXS: v.optional(envBoolean()), + NEXT_PUBLIC_HIDE_NATIVE_COIN_PRICE: v.optional(envBoolean()), + NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE: v.optional(envHtmlList()), + NEXT_PUBLIC_COLOR_THEMES: v.optional(envJson(v.array(v.picklist(COLOR_THEME_IDS)))), + NEXT_PUBLIC_COLOR_THEME_DEFAULT: v.optional(v.picklist(COLOR_THEME_IDS)), + NEXT_PUBLIC_COLOR_THEME_OVERRIDES: v.optional(envJson(v.record(v.string(), v.unknown()))), + NEXT_PUBLIC_FONT_FAMILY_HEADING: v.optional(envJson(fontFamilySchema)), + NEXT_PUBLIC_FONT_FAMILY_BODY: v.optional(envJson(fontFamilySchema)), + NEXT_PUBLIC_MAX_CONTENT_WIDTH_ENABLED: v.optional(envBoolean()), + }), + companionRule( + [ 'NEXT_PUBLIC_COLOR_THEME_DEFAULT', 'NEXT_PUBLIC_COLOR_THEMES' ], + (input) => { + const defaultTheme = input.NEXT_PUBLIC_COLOR_THEME_DEFAULT as ColorThemeId | undefined; + const themes = input.NEXT_PUBLIC_COLOR_THEMES as Array<ColorThemeId> | undefined; + return !defaultTheme || !themes?.length || themes.includes(defaultTheme); + }, + 'NEXT_PUBLIC_COLOR_THEME_DEFAULT must be one of the themes listed in NEXT_PUBLIC_COLOR_THEMES', + ), + companionRule( + [ 'NEXT_PUBLIC_COLOR_THEME_DEFAULT', 'NEXT_PUBLIC_COLOR_THEMES' ], + (input) => { + const defaultTheme = input.NEXT_PUBLIC_COLOR_THEME_DEFAULT as ColorThemeId | undefined; + const themes = input.NEXT_PUBLIC_COLOR_THEMES as Array<ColorThemeId> | undefined; + const usesSystemTheme = defaultTheme === SYSTEM_COLOR_THEME_ID || Boolean(themes?.includes(SYSTEM_COLOR_THEME_ID)); + if (!usesSystemTheme || !themes?.length) { + return true; + } + return coversBothColorModes(COLOR_THEMES.filter((theme) => themes.includes(theme.id))); + }, + 'The system color theme requires NEXT_PUBLIC_COLOR_THEMES to list at least one light and one dark theme', + ), +); + +const networkExplorerSchema: v.GenericSchema<AlternativeExplorer> = v.object({ + title: requiredString(), + logo: optionalUrl(), + baseUrl: requiredUrl(), + paths: v.object({ + tx: v.optional(v.string()), + address: v.optional(v.string()), + token: v.optional(v.string()), + block: v.optional(v.string()), + blob: v.optional(v.string()), + }), }); + +const contractCodeIdeSchema: v.GenericSchema<ContractCodeIde> = v.object({ + title: requiredString(), + url: requiredUrl(), + icon_url: requiredUrl(), +}); + +const nftMarketplaceSchema: v.GenericSchema<NftMarketplaceItem> = v.object({ + name: requiredString(), + collection_url: optionalUrl(), + instance_url: optionalUrl(), + logo_url: requiredUrl(), +}); + +const BECH32_PREFIX_MAX_LENGTH = 83; +const ADDRESS_LENGTH = 42; + +const hasBech32Format = (value: unknown) => Array.isArray(value) && (value as Array<AddressFormat>).includes('bech32'); + +export const viewsSchema = v.pipe( + v.object({ + NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_FIELDS: v.optional(envJson(v.array(v.picklist(BLOCK_FIELDS_IDS)))), + NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_VIEWS: v.optional(envJson(v.array(v.picklist(BLOCK_VIEWS_IDS)))), + NEXT_PUBLIC_VIEWS_BLOCK_PENDING_UPDATE_ALERT_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_VIEWS_ADDRESS_IDENTICON_TYPE: v.optional(v.picklist(IDENTICON_TYPES)), + NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT: v.optional(envJson(v.array(v.picklist(ADDRESS_FORMATS)))), + NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX: v.optional(v.pipe(v.string(), v.nonEmpty(), v.maxLength(BECH32_PREFIX_MAX_LENGTH))), + NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS: v.optional(v.pipe(v.string(), v.length(ADDRESS_LENGTH), v.regex(regexp.HEX_REGEXP_WITH_0X))), + NEXT_PUBLIC_VIEWS_ADDRESS_HIDDEN_VIEWS: v.optional(envJson(v.array(v.picklist(ADDRESS_VIEWS_IDS)))), + NEXT_PUBLIC_VIEWS_CONTRACT_SOLIDITYSCAN_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_VIEWS_CONTRACT_DECODED_BYTECODE_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_VIEWS_CONTRACT_EXTRA_VERIFICATION_METHODS: v.optional(v.union([ + v.literal('none'), + envJson(v.array(v.picklist(SMART_CONTRACT_EXTRA_VERIFICATION_METHODS))), + ])), + NEXT_PUBLIC_VIEWS_TX_HIDDEN_FIELDS: v.optional(envJson(v.array(v.picklist(TX_FIELDS_IDS)))), + NEXT_PUBLIC_VIEWS_TX_ADDITIONAL_FIELDS: v.optional(envJson(v.array(v.picklist(TX_ADDITIONAL_FIELDS_IDS)))), + NEXT_PUBLIC_VIEWS_TX_GROUPED_FEES: v.optional(envBoolean()), + NEXT_PUBLIC_VIEWS_TX_HIDDEN_VIEWS: v.optional(envJson(v.array(v.picklist(TX_VIEWS_IDS)))), + NEXT_PUBLIC_INTERNAL_TXS_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_VIEWS_NFT_MARKETPLACES: v.optional(envJson(v.array(nftMarketplaceSchema))), + NEXT_PUBLIC_VIEWS_TOKEN_SCAM_TOGGLE_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_HELIA_VERIFIED_FETCH_ENABLED: v.optional(envBoolean()), + NEXT_PUBLIC_NETWORK_EXPLORERS: v.optional(envJson(v.array(networkExplorerSchema))), + NEXT_PUBLIC_CONTRACT_CODE_IDES: v.optional(envJson(v.array(contractCodeIdeSchema))), + NEXT_PUBLIC_HAS_CONTRACT_AUDIT_REPORTS: v.optional(envBoolean()), + }), + requires('NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX', 'NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT', { + when: hasBech32Format, + message: 'NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX is required if NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT contains "bech32"', + }), + requiredIf('NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX', 'NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT', { + when: hasBech32Format, + message: 'NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX is required when NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT contains "bech32"', + }), +); diff --git a/deploy/tools/envs-validator/test-utils.ts b/deploy/tools/envs-validator/test-utils.ts new file mode 100644 index 00000000000..2e2b4f355fc --- /dev/null +++ b/deploy/tools/envs-validator/test-utils.ts @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +export const toEnvValue = (value: unknown): string => JSON.stringify(value).replaceAll('"', '\''); diff --git a/deploy/tools/envs-validator/test.sh b/deploy/tools/envs-validator/test.sh deleted file mode 100755 index a3b8ce8a09a..00000000000 --- a/deploy/tools/envs-validator/test.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/bin/bash - -test_folder="./test" -common_file="${test_folder}/.env.common" - -# Generate ENV registry file -export NEXT_PUBLIC_GIT_COMMIT_SHA=$(git rev-parse --short HEAD) -export NEXT_PUBLIC_GIT_TAG=$(git describe --tags --abbrev=0) -../../scripts/collect_envs.sh ../../../docs/ENVS.md - -# Copy test assets -mkdir -p "./public/assets/configs" -cp -r ${test_folder}/assets ./public/ - -# Build validator script -pnpm run build - -validate_file() { - local test_file="$1" - local with_common="$2" - - echo - echo "🧿 Validating file '$test_file'..." - - if [ "$with_common" = "true" ]; then - dotenv -e "$test_file" -e "$common_file" pnpm run validate -- --silent - else - dotenv -e "$test_file" pnpm run validate -- --silent - fi - - if [ $? -eq 0 ]; then - echo "👍 All good!" - return 0 - else - echo "🛑 The file is invalid. Please fix errors and run script again." - echo - return 1 - fi -} - -test_files=($(find "$test_folder" -maxdepth 1 -type f | grep -vE '\/\.env\.common$')) - -for file in "${test_files[@]}"; do - if [[ "$file" == *".env.multichain" ]]; then - validate_file "$file" false - else - validate_file "$file" true - fi - - if [ $? -eq 1 ]; then - exit 1 - fi -done diff --git a/deploy/tools/envs-validator/test/.env.adbutler b/deploy/tools/envs-validator/test/.env.adbutler deleted file mode 100644 index 7877a7740c0..00000000000 --- a/deploy/tools/envs-validator/test/.env.adbutler +++ /dev/null @@ -1,3 +0,0 @@ -NEXT_PUBLIC_AD_BANNER_PROVIDER=adbutler -NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP={'id':'123456','width':'728','height':'90'} -NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE={'id':'654321','width':'300','height':'100'} \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.adbutler_add b/deploy/tools/envs-validator/test/.env.adbutler_add deleted file mode 100644 index 7f1968e4bb9..00000000000 --- a/deploy/tools/envs-validator/test/.env.adbutler_add +++ /dev/null @@ -1,4 +0,0 @@ -NEXT_PUBLIC_AD_BANNER_PROVIDER='slise' -NEXT_PUBLIC_AD_BANNER_ADDITIONAL_PROVIDER='adbutler' -NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP={'id':'123456','width':'728','height':'90'} -NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE={'id':'654321','width':'300','height':'100'} \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.alt b/deploy/tools/envs-validator/test/.env.alt deleted file mode 100644 index 52324722354..00000000000 --- a/deploy/tools/envs-validator/test/.env.alt +++ /dev/null @@ -1,18 +0,0 @@ -NEXT_PUBLIC_API_DOCS_TABS=[] -NEXT_PUBLIC_VIEWS_CONTRACT_EXTRA_VERIFICATION_METHODS=none -NEXT_PUBLIC_HOMEPAGE_STATS=[] -NEXT_PUBLIC_VIEWS_ADDRESS_FORMAT=['base16','bech32'] -NEXT_PUBLIC_VIEWS_ADDRESS_BECH_32_PREFIX=foo -NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY=xxx -NEXT_PUBLIC_NETWORK_RPC_URL=['https://example.com','https://example2.com'] -NEXT_PUBLIC_METADATA_SERVICE_API_HOST=https://example.com -NEXT_PUBLIC_METADATA_ADDRESS_TAGS_UPDATE_ENABLED=false -NEXT_PUBLIC_HAS_USER_OPS=true -NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST=https://example.com -NEXT_PUBLIC_NAVIGATION_PROMO_BANNER_CONFIG={'img_url': {'small': 'https://example.com/promo-sm.png', 'large': 'https://example.com/promo-lg.png'}, 'link_url': 'https://example.com'} -NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED=true -NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER=dynamic -NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID=xxx -NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE=['<a href=\"https://example.com\">Hello</a>','Duck me'] -NEXT_PUBLIC_INTERNAL_TXS_ENABLED=false -NEXT_PUBLIC_VIEWS_TX_HIDDEN_VIEWS=['pending_txs'] \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.arbitrum b/deploy/tools/envs-validator/test/.env.arbitrum deleted file mode 100644 index 1cf856f0531..00000000000 --- a/deploy/tools/envs-validator/test/.env.arbitrum +++ /dev/null @@ -1,6 +0,0 @@ -NEXT_PUBLIC_ROLLUP_TYPE=arbitrum -NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS=true -NEXT_PUBLIC_ROLLUP_PARENT_CHAIN={'baseUrl':'https://explorer.duckchain.io','currency':{'name':'Quack','symbol':'QUACK','decimals':18},'isTestnet':true,'id':42,'name':'DuckChain','rpcUrls':['https://rpc.duckchain.io']} - -NEXT_PUBLIC_ROLLUP_DA_CELESTIA_NAMESPACE=0x00000000000000000000000000000000000000ca1de12a9905be97beaf -NEXT_PUBLIC_ROLLUP_DA_CELESTIA_CELENIUM_URL=https://mocha.celenium.io/blob \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.beacon_chain b/deploy/tools/envs-validator/test/.env.beacon_chain deleted file mode 100644 index f0800e9af33..00000000000 --- a/deploy/tools/envs-validator/test/.env.beacon_chain +++ /dev/null @@ -1,2 +0,0 @@ -NEXT_PUBLIC_HAS_BEACON_CHAIN=true -NEXT_PUBLIC_BEACON_CHAIN_CURRENCY_SYMBOL=aETH \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.celo b/deploy/tools/envs-validator/test/.env.celo deleted file mode 100644 index 6c9015d8229..00000000000 --- a/deploy/tools/envs-validator/test/.env.celo +++ /dev/null @@ -1 +0,0 @@ -NEXT_PUBLIC_CELO_ENABLED=true \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.common b/deploy/tools/envs-validator/test/.env.common deleted file mode 100644 index 5788f392d31..00000000000 --- a/deploy/tools/envs-validator/test/.env.common +++ /dev/null @@ -1,4 +0,0 @@ -NEXT_PUBLIC_API_HOST=blockscout.com -NEXT_PUBLIC_APP_HOST=localhost -NEXT_PUBLIC_NETWORK_ID=1 -NEXT_PUBLIC_NETWORK_NAME=Testnet diff --git a/deploy/tools/envs-validator/test/.env.cross_chain_txs b/deploy/tools/envs-validator/test/.env.cross_chain_txs deleted file mode 100644 index 333ca6054a1..00000000000 --- a/deploy/tools/envs-validator/test/.env.cross_chain_txs +++ /dev/null @@ -1,2 +0,0 @@ -NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED=true -NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST=https://api.example.com \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.external_txs b/deploy/tools/envs-validator/test/.env.external_txs deleted file mode 100644 index 97129b0e6b8..00000000000 --- a/deploy/tools/envs-validator/test/.env.external_txs +++ /dev/null @@ -1 +0,0 @@ -NEXT_PUBLIC_TX_EXTERNAL_TRANSACTIONS_CONFIG={'chain_name':'Solana','chain_logo_url':'https://raw.githubusercontent.com/blockscout/frontend-configs/refs/heads/main/configs/network-icons/solana.svg','explorer_url_template':'https://solscan.io/tx/{hash}'} \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.marketplace b/deploy/tools/envs-validator/test/.env.marketplace deleted file mode 100644 index 280d887184d..00000000000 --- a/deploy/tools/envs-validator/test/.env.marketplace +++ /dev/null @@ -1,12 +0,0 @@ -NEXT_PUBLIC_MARKETPLACE_ENABLED=true -NEXT_PUBLIC_MARKETPLACE_CONFIG_URL=https://example.com -NEXT_PUBLIC_MARKETPLACE_CATEGORIES_URL=https://example.com -NEXT_PUBLIC_MARKETPLACE_SUBMIT_FORM=https://example.com -NEXT_PUBLIC_MARKETPLACE_SUGGEST_IDEAS_FORM=https://example.com -NEXT_PUBLIC_ADMIN_SERVICE_API_HOST=https://example.com -NEXT_PUBLIC_MARKETPLACE_FEATURED_APP=aave -NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL=https://gist.githubusercontent.com/maxaleks/36f779fd7d74877b57ec7a25a9a3a6c9/raw/746a8a59454c0537235ee44616c4690ce3bbf3c8/banner.html -NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL=https://www.basename.app -NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG={'swap': {'url': 'https://example.com', 'chains': ['1', '10', '100', '11155111'], 'fee': '0.004', 'integrator': 'blockscout'}, 'revoke': {'chains': ['1', '10', '100', '11155111']}, 'multisend': {'chains': ['1', '10', '100', '11155111'], 'posthogKey': '123', 'posthogHost': 'https://example.com'}} -NEXT_PUBLIC_MARKETPLACE_TITLES={'menu_item': 'Dapps', 'title': 'Dappscout'} -NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_AD_ENABLED=true diff --git a/deploy/tools/envs-validator/test/.env.mega_eth b/deploy/tools/envs-validator/test/.env.mega_eth deleted file mode 100644 index 0e5bbc34b9d..00000000000 --- a/deploy/tools/envs-validator/test/.env.mega_eth +++ /dev/null @@ -1,2 +0,0 @@ -NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_METRICS=wss://example.com -NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_RPC=wss://example.com \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.optimism b/deploy/tools/envs-validator/test/.env.optimism deleted file mode 100644 index f717685f3f2..00000000000 --- a/deploy/tools/envs-validator/test/.env.optimism +++ /dev/null @@ -1,9 +0,0 @@ -NEXT_PUBLIC_ROLLUP_TYPE=optimistic -NEXT_PUBLIC_ROLLUP_L2_WITHDRAWAL_URL=https://example.com -NEXT_PUBLIC_FAULT_PROOF_ENABLED=true -NEXT_PUBLIC_ROLLUP_HOMEPAGE_SHOW_LATEST_BLOCKS=true -NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED=false -NEXT_PUBLIC_ROLLUP_PARENT_CHAIN={'baseUrl':'https://explorer.duckchain.io'} -NEXT_PUBLIC_INTEROP_ENABLED=true -NEXT_PUBLIC_ROLLUP_STAGE_INDEX=1 -NEXT_PUBLIC_ROLLUP_LAYER_NUMBER=5 \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.sevio b/deploy/tools/envs-validator/test/.env.sevio deleted file mode 100644 index 468c3302f7f..00000000000 --- a/deploy/tools/envs-validator/test/.env.sevio +++ /dev/null @@ -1,2 +0,0 @@ -NEXT_PUBLIC_AD_BANNER_PROVIDER=sevio -NEXT_PUBLIC_AD_BANNER_SEVIO_ZONES=['52909312-7ebb-4bd5-9006-5e4f7041ed63','07cabd45-77f1-4203-8081-868bae776981'] diff --git a/deploy/tools/envs-validator/test/.env.tac b/deploy/tools/envs-validator/test/.env.tac deleted file mode 100644 index 16b4862a3a4..00000000000 --- a/deploy/tools/envs-validator/test/.env.tac +++ /dev/null @@ -1,2 +0,0 @@ -NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST=https://tac-operation-lifecycle.blockscout.com -NEXT_PUBLIC_TAC_TON_EXPLORER_URL=https://tonscan.org \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/.env.zetachain b/deploy/tools/envs-validator/test/.env.zetachain deleted file mode 100644 index d75d446c93d..00000000000 --- a/deploy/tools/envs-validator/test/.env.zetachain +++ /dev/null @@ -1,3 +0,0 @@ - -NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST=https://zetachain-indexer.duckdns.org -NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL=https://example.com \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/assets/configs/address_3rd_party_widgets_config.json b/deploy/tools/envs-validator/test/assets/configs/address_3rd_party_widgets_config.json deleted file mode 100644 index 05f93a55d2e..00000000000 --- a/deploy/tools/envs-validator/test/assets/configs/address_3rd_party_widgets_config.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "widget-1": { - "name": "Widget 1", - "url": "https://example.com/widget-1/{address}", - "icon": "https://example.com/icon.svg", - "title": "Widget 1", - "hint": "Widget 1 hint", - "valuePath": "result.value", - "valueTitlePath": "result.valueTitle", - "pages": [ "eoa", "contract", "token" ] - }, - "widget-2": { - "name": "Widget 2", - "url": "https://example.com/widget-2/{address}", - "icon": "https://example.com/icon.svg", - "title": "Widget 2", - "valuePath": "value", - "pages": [ "eoa" ] - }, - "widget-3": { - "name": "Widget 3", - "url": "https://example.com/widget-3/{address}?chainId={chainId}", - "icon": "https://example.com/icon.svg", - "title": "Widget 3", - "valuePath": "result.length", - "pages": [ "token" ], - "chainIds": { - "1": "eth", - "10": "op" - } - } -} diff --git a/deploy/tools/envs-validator/test/assets/configs/cross_chain_txs_config.json b/deploy/tools/envs-validator/test/assets/configs/cross_chain_txs_config.json deleted file mode 100644 index b8b734c395c..00000000000 --- a/deploy/tools/envs-validator/test/assets/configs/cross_chain_txs_config.json +++ /dev/null @@ -1,18 +0,0 @@ -[ - { - "id": "8021", - "name": "Numine", - "explorer_url": "https://example.com/blockchain/numine", - "route_templates": { - "tx": "/transaction/{hash}", - "address": "/wallet/{hash}", - "token": "/address/{hash}" - } - }, - { - "id": "43114", - "name": "C-Chain", - "logo": "https://example.com/logo.svg", - "explorer_url": "https://example.com/blockchain/c" - } -] \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/assets/configs/featured_networks.json b/deploy/tools/envs-validator/test/assets/configs/featured_networks.json deleted file mode 100644 index 83b90888435..00000000000 --- a/deploy/tools/envs-validator/test/assets/configs/featured_networks.json +++ /dev/null @@ -1,22 +0,0 @@ -[ - { - "title": "Ethereum", - "url": "https://eth.blockscout.com/", - "group": "Mainnets", - "icon": "https://example.com/logo.svg" - }, - { - "title": "Goerli", - "url": "https://eth-goerli.blockscout.com/", - "group": "Testnets", - "isActive": true, - "icon": "https://example.com/logo.svg", - "invertIconInDarkMode": true - }, - { - "title": "POA Sokol", - "url": "https://blockscout.com/poa/sokol", - "group": "Other", - "icon": "https://example.com/logo.svg" - } -] \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/assets/configs/footer_links.json b/deploy/tools/envs-validator/test/assets/configs/footer_links.json deleted file mode 100644 index 864295b9527..00000000000 --- a/deploy/tools/envs-validator/test/assets/configs/footer_links.json +++ /dev/null @@ -1,32 +0,0 @@ -[ - { - "title": "Foo", - "links": [ - { - "text": "Home", - "url": "https://example.com" - }, - { - "text": "Brand", - "url": "https://example.com" - } - ] - }, - { - "title": "Developers", - "links": [ - { - "text": "Develop", - "url": "https://example.com", - "iconUrl": [ - "https://example.com/mocks/image_s.jpg", - "https://example.com/mocks/image_svg.svg" - ] - }, - { - "text": "Grants", - "url": "https://example.com" - } - ] - } - ] \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/assets/configs/homepage_highlights_config.json b/deploy/tools/envs-validator/test/assets/configs/homepage_highlights_config.json deleted file mode 100644 index 00db871e2eb..00000000000 --- a/deploy/tools/envs-validator/test/assets/configs/homepage_highlights_config.json +++ /dev/null @@ -1,21 +0,0 @@ -[ - { - "title": "Duck Deep into Transactions", - "description": "Explore and track all blockchain transactions", - "title_color": ["#1a472a", "#4ade80"], - "description_color": ["#374151", "#d1d5db"], - "background": ["#e0f2fe", "#0f172a"], - "side_img_url": [ - "https://example.com", - "https://example.com" - ], - "page_path": "/txs" - }, - { - "title": "Capybara Hot Spring Pools", - "description": "Monitor liquidity and staking pools", - "is_pinned": true, - "redirect_url": "https://example.com" - } - ] - \ No newline at end of file diff --git a/deploy/tools/envs-validator/test/assets/configs/marketplace_categories.json b/deploy/tools/envs-validator/test/assets/configs/marketplace_categories.json deleted file mode 100644 index 15b31a55576..00000000000 --- a/deploy/tools/envs-validator/test/assets/configs/marketplace_categories.json +++ /dev/null @@ -1,5 +0,0 @@ -[ - "Swaps", - "Bridges", - "NFT" -] diff --git a/deploy/tools/envs-validator/test/assets/configs/marketplace_config.json b/deploy/tools/envs-validator/test/assets/configs/marketplace_config.json deleted file mode 100644 index 0b142b7a247..00000000000 --- a/deploy/tools/envs-validator/test/assets/configs/marketplace_config.json +++ /dev/null @@ -1,25 +0,0 @@ -[ - { - "author": "Hop", - "id": "hop-exchange", - "title": "Hop", - "logo": "https://example.com/logo.svg", - "categories": ["Bridge"], - "shortDescription": "Hop is a scalable rollup-to-rollup general token bridge.", - "site": "https://example.com", - "description": "Hop is a scalable rollup-to-rollup general token bridge.", - "external": true, - "url": "https://example.com" - }, - { - "author": "Blockscout", - "id": "token-approval-tracker", - "title": "Token Approval Tracker", - "logo": "https://example.com/logo.svg", - "categories": ["Infra & Dev tooling"], - "shortDescription": "Token Approval Tracker shows all approvals for any ERC20-compliant tokens and NFTs and lets to revoke them or adjust the approved amount.", - "site": "https://example.com", - "description": "Token Approval Tracker shows all approvals for any ERC20-compliant tokens and NFTs and lets to revoke them or adjust the approved amount.", - "url": "https://example.com" - } - ] diff --git a/deploy/tools/envs-validator/test/assets/configs/zetachain_service_chains_config.json b/deploy/tools/envs-validator/test/assets/configs/zetachain_service_chains_config.json deleted file mode 100644 index 5f83cad4ddd..00000000000 --- a/deploy/tools/envs-validator/test/assets/configs/zetachain_service_chains_config.json +++ /dev/null @@ -1,14 +0,0 @@ -[ - { - "chain_id": 7000, - "chain_name": "ZetaChain Athens", - "chain_logo": "https://example.com/zetachain-logo.svg", - "instance_url": "https://zetachain-indexer.duckdns.org" - }, - { - "chain_id": 7001, - "chain_name": "ZetaChain Athens Testnet", - "chain_logo": "https://example.com/zetachain-testnet-logo.svg", - "instance_url": "https://zetachain-testnet-indexer.duckdns.org" - } -] diff --git a/deploy/tools/envs-validator/tsconfig.json b/deploy/tools/envs-validator/tsconfig.json deleted file mode 100644 index 6e15ca0e9b7..00000000000 --- a/deploy/tools/envs-validator/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "ESNext", - "moduleResolution": "bundler", - "esModuleInterop": true, - "strict": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "outDir": "./dist", - "rootDir": "../../../", - "paths": { - "src/*": ["../../../src/*"], - "public/*": ["../../../public/*"] - }, - "types": ["node"], - "allowImportingTsExtensions": true, - "noEmit": true - }, - "include": [ - "**/*.ts" - ], - "exclude": [ - "node_modules", - "dist" - ] - } \ No newline at end of file diff --git a/deploy/tools/envs-validator/utils.spec.ts b/deploy/tools/envs-validator/utils.spec.ts new file mode 100644 index 00000000000..23640683052 --- /dev/null +++ b/deploy/tools/envs-validator/utils.spec.ts @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as v from 'valibot'; + +import { describe, expect, it } from 'vitest'; + +import { + composeSchemas, + envBoolean, + envJson, + envNumber, + envPositiveInteger, + envUrl, + getValidationErrors, + requiredIf, + requires, +} from './utils'; + +const withEntry = (schema: v.GenericSchema) => v.object({ NEXT_PUBLIC_X: v.optional(schema) }); + +describe('envBoolean', () => { + it('parses only the literal strings true and false', () => { + expect(v.parse(envBoolean(), 'true')).toBe(true); + expect(v.parse(envBoolean(), 'false')).toBe(false); + }); + + it.each([ 'TRUE', '1', '0', 'yes', '', ' true ' ])('rejects %j', (value) => { + expect(getValidationErrors(withEntry(envBoolean()), { NEXT_PUBLIC_X: value })).toEqual([ + `NEXT_PUBLIC_X: Expected "true" or "false" but received ${ JSON.stringify(value) }`, + ]); + }); +}); + +describe('envNumber', () => { + it.each([ + [ '3000', 3000 ], + [ '-1.5', -1.5 ], + [ '0', 0 ], + ])('parses the plain decimal %j', (value, expected) => { + expect(v.parse(envNumber(), value)).toBe(expected); + }); + + it.each([ '0x10', '1e3', ' 3000 ', 'abc', '' ])('rejects %j', (value) => { + expect(getValidationErrors(withEntry(envNumber()), { NEXT_PUBLIC_X: value })).toEqual([ + `NEXT_PUBLIC_X: Expected a decimal number but received ${ JSON.stringify(value) }`, + ]); + }); + + it('requires a positive integer where one is expected', () => { + expect(getValidationErrors(withEntry(envPositiveInteger()), { NEXT_PUBLIC_X: '1.5' })).toEqual([ 'NEXT_PUBLIC_X: Invalid integer: Received 1.5' ]); + expect(getValidationErrors(withEntry(envPositiveInteger()), { NEXT_PUBLIC_X: '0' })).toEqual([ + 'NEXT_PUBLIC_X: Invalid value: Expected >=1 but received 0', + ]); + }); +}); + +describe('envUrl', () => { + it('accepts a URL and the empty string', () => { + expect(getValidationErrors(withEntry(envUrl()), { NEXT_PUBLIC_X: 'https://example.com/path?q=1' })).toEqual([]); + expect(getValidationErrors(withEntry(envUrl()), { NEXT_PUBLIC_X: '' })).toEqual([]); + }); + + it('rejects anything new URL() cannot parse', () => { + expect(getValidationErrors(withEntry(envUrl()), { NEXT_PUBLIC_X: 'example.com' })).toEqual([ 'NEXT_PUBLIC_X: Invalid URL: Received "example.com"' ]); + }); +}); + +describe('envJson', () => { + const schema = withEntry(envJson(v.array(v.object({ name: v.string() })))); + + it('accepts the single-quoted form operators use', () => { + expect(getValidationErrors(schema, { NEXT_PUBLIC_X: '[{\'name\':\'a\'}]' })).toEqual([]); + }); + + it('reports a nested problem with its dot path', () => { + expect(getValidationErrors(schema, { NEXT_PUBLIC_X: '[{\'title\':\'a\'}]' })).toEqual([ + 'NEXT_PUBLIC_X.0.name: Invalid key: Expected "name" but received undefined', + ]); + }); + + it('rejects a value that is not JSON', () => { + expect(getValidationErrors(schema, { NEXT_PUBLIC_X: 'nope' })).toEqual([ 'NEXT_PUBLIC_X: Invalid JSON: Received "nope"' ]); + }); +}); + +describe('companion rules', () => { + const entries = v.looseObject({ + NEXT_PUBLIC_A: v.optional(envBoolean()), + NEXT_PUBLIC_B: v.optional(v.string()), + }); + + describe('requires', () => { + const schema = v.pipe(entries, requires('NEXT_PUBLIC_B', 'NEXT_PUBLIC_A')); + + it('accepts the dependent together with a truthy parsed dependency', () => { + expect(getValidationErrors(schema, { NEXT_PUBLIC_A: 'true', NEXT_PUBLIC_B: 'x' })).toEqual([]); + expect(getValidationErrors(schema, {})).toEqual([]); + }); + + it('rejects the dependent when the dependency is unset or parses to false', () => { + expect(getValidationErrors(schema, { NEXT_PUBLIC_B: 'x' })).toEqual([ 'NEXT_PUBLIC_B can only be used with NEXT_PUBLIC_A' ]); + expect(getValidationErrors(schema, { NEXT_PUBLIC_A: 'false', NEXT_PUBLIC_B: 'x' })).toEqual([ 'NEXT_PUBLIC_B can only be used with NEXT_PUBLIC_A' ]); + }); + + it('does not fire while the dependency itself is invalid', () => { + expect(getValidationErrors(schema, { NEXT_PUBLIC_A: 'maybe', NEXT_PUBLIC_B: 'x' })).toEqual([ + 'NEXT_PUBLIC_A: Expected "true" or "false" but received "maybe"', + ]); + }); + + it('takes a custom predicate and message', () => { + const custom = v.pipe(entries, requires('NEXT_PUBLIC_B', 'NEXT_PUBLIC_C', { when: (value) => value === 'on', message: 'B needs C=on' })); + expect(getValidationErrors(custom, { NEXT_PUBLIC_C: 'on', NEXT_PUBLIC_B: 'x' })).toEqual([]); + expect(getValidationErrors(custom, { NEXT_PUBLIC_C: 'off', NEXT_PUBLIC_B: 'x' })).toEqual([ 'B needs C=on' ]); + }); + }); + + describe('requiredIf', () => { + const schema = v.pipe(entries, requiredIf('NEXT_PUBLIC_B', 'NEXT_PUBLIC_A')); + + it('demands the dependent once the dependency is set', () => { + expect(getValidationErrors(schema, { NEXT_PUBLIC_A: 'true' })).toEqual([ 'NEXT_PUBLIC_B is required when NEXT_PUBLIC_A is set' ]); + expect(getValidationErrors(schema, { NEXT_PUBLIC_A: 'true', NEXT_PUBLIC_B: '' })).toEqual([ 'NEXT_PUBLIC_B is required when NEXT_PUBLIC_A is set' ]); + expect(getValidationErrors(schema, { NEXT_PUBLIC_A: 'true', NEXT_PUBLIC_B: 'x' })).toEqual([]); + expect(getValidationErrors(schema, { NEXT_PUBLIC_A: 'false' })).toEqual([]); + }); + }); +}); + +describe('composeSchemas', () => { + const first = v.pipe( + v.looseObject({ NEXT_PUBLIC_A: v.optional(envBoolean()) }), + requires('NEXT_PUBLIC_A', 'NEXT_PUBLIC_B'), + ); + const second = v.object({ NEXT_PUBLIC_B: v.optional(envUrl()) }); + const schema = composeSchemas([ first, second ]); + + it('lists every variable of every member', () => { + expect(schema.envNames).toEqual([ 'NEXT_PUBLIC_A', 'NEXT_PUBLIC_B' ]); + }); + + it('resolves a rule that names a variable another member declares', () => { + expect(getValidationErrors(schema, { NEXT_PUBLIC_A: 'true', NEXT_PUBLIC_B: 'https://example.com' })).toEqual([]); + expect(getValidationErrors(schema, { NEXT_PUBLIC_A: 'true' })).toEqual([ 'NEXT_PUBLIC_A can only be used with NEXT_PUBLIC_B' ]); + }); + + it('reports only the type error for a value that is not an object', () => { + expect(getValidationErrors(schema, null)).toEqual([ 'Invalid type: Expected Object but received null' ]); + }); + + it('reports unknown variables once, alongside the other errors', () => { + expect(getValidationErrors(schema, { NEXT_PUBLIC_B: 'nope', NEXT_PUBLIC_C: '1', NEXT_PUBLIC_D: '2' })).toEqual([ + 'Unknown ENV variables were provided: NEXT_PUBLIC_C, NEXT_PUBLIC_D', + 'NEXT_PUBLIC_B: Invalid URL: Received "nope"', + ]); + }); +}); diff --git a/deploy/tools/envs-validator/utils.ts b/deploy/tools/envs-validator/utils.ts index 7e5e73a7b3f..8a6006f5550 100644 --- a/deploy/tools/envs-validator/utils.ts +++ b/deploy/tools/envs-validator/utils.ts @@ -1,31 +1,202 @@ -import * as yup from 'yup'; +// SPDX-License-Identifier: LicenseRef-Blockscout -export const protocols = [ 'http', 'https' ]; +import * as v from 'valibot'; -export const urlTest: yup.TestConfig = { - name: 'url', - test: (value: unknown) => { - if (!value) { - return true; - } +import { parseEnvHtmlList, replaceQuotes } from 'src/config/utils/envs'; +import { findDisallowedHtml } from 'src/shared/texts/sanitize-html'; - try { - if (typeof value === 'string') { - new URL(value); - return true; - } - } catch (error) {} +export const protocols = [ 'http', 'https' ] as const; + +// The app reads flags with `=== 'true'`, so `1` / `TRUE` must fail here rather than silently mean false. +export const envBoolean = (): v.GenericSchema<string, boolean> => v.pipe( + v.string(), + v.picklist([ 'true', 'false' ], (issue) => `Expected "true" or "false" but received ${ JSON.stringify(issue.input) }`), + v.transform((value) => value === 'true'), +); + +const DECIMAL_NUMBER_REGEXP = /^-?\d+(\.\d+)?$/; +export const envNumber = (): v.GenericSchema<string, number> => v.pipe( + v.string(), + v.regex(DECIMAL_NUMBER_REGEXP, (issue) => `Expected a decimal number but received ${ JSON.stringify(issue.input) }`), + v.transform(Number), + v.number(), +); + +export const envPositiveInteger = (): v.GenericSchema<string, number> => v.pipe(envNumber(), v.integer(), v.minValue(1)); + +const isUrl = (value: string): boolean => { + try { + new URL(value); + return true; + } catch { return false; - }, - message: '${path} is not a valid URL', - exclusive: true, + } }; -export const getYupValidationErrorMessage = (error: unknown) => - typeof error === 'object' && - error !== null && - 'errors' in error && - Array.isArray(error.errors) ? - error.errors.join(', ') : - ''; \ No newline at end of file +// Operators unset a variable with `FOO=`, which the container delivers as '', so '' is not a URL error. +export const envUrl = (): v.GenericSchema<string, string> => v.pipe( + v.string(), + v.check((value) => value === '' || isUrl(value), (issue) => `Invalid URL: Received ${ JSON.stringify(issue.input) }`), +); + +export const envRequiredString = (): v.GenericSchema<string, string> => v.pipe(v.string(), v.nonEmpty()); + +const disallowedHtmlMessage = (values: Array<string>): string => { + const disallowed = new Set(values.flatMap(findDisallowedHtml)); + return `HTML contains elements that are not allowed: ${ Array.from(disallowed).join(', ') }`; +}; + +const isAllowedHtml = (values: Array<string>): boolean => values.every((value) => findDisallowedHtml(value).length === 0); + +// The value is rendered as HTML on the app's origin and the app strips what the sanitizer rejects; the operator +// is told at startup instead of finding quietly reduced markup. Both schemas check the string the app reads, +// which is the value as set (src/config/utils/envs.ts, getEnvHtmlValue and parseEnvHtmlList). +export const envHtml = (): v.GenericSchema<string, string> => v.pipe( + v.string(), + v.check((value) => isAllowedHtml([ value ]), (issue) => disallowedHtmlMessage([ issue.input ])), +); + +export const envHtmlList = (): v.GenericSchema<string, string> => v.pipe( + v.string(), + v.check((value) => isAllowedHtml(parseEnvHtmlList(value)), (issue) => disallowedHtmlMessage(parseEnvHtmlList(issue.input))), +); + +export const envJson = <TSchema extends v.GenericSchema>(schema: TSchema): v.GenericSchema<string, v.InferOutput<TSchema>> => v.pipe( + v.string(), + v.rawTransform(({ dataset, addIssue, NEVER }): unknown => { + try { + return JSON.parse(replaceQuotes(dataset.value) as string); + } catch { + addIssue({ message: `Invalid JSON: Received ${ JSON.stringify(dataset.value) }` }); + return NEVER; + } + }), + schema, +); + +type EnvRecord = Record<string, unknown>; + +type DependencyPredicate = (dependencyValue: unknown) => boolean; + +const isSet: DependencyPredicate = (value) => Boolean(value); + +// The container delivers an unset variable as '', so '' is "not provided" for a companion rule. +const isProvided = (value: unknown): boolean => value !== undefined && value !== ''; + +interface CompanionRuleOptions { + readonly when?: DependencyPredicate; + readonly message?: string; +} + +// Typed for the whole env map rather than one object shape, so a rule may name a variable that another +// sub-schema declares (the sub-schema must be a `looseObject` for that key to reach the rule, unparsed); +// `partialCheck` skips the rule while either variable is itself invalid. The cast re-attaches the pipe's +// own object type, which `partialCheck`'s generics cannot express for a string-keyed selection. +export function companionRule<TInput extends EnvRecord = EnvRecord>( + names: ReadonlyArray<string>, + requirement: (input: TInput) => boolean, + message: string, +): v.GenericValidation<TInput, TInput> { + const paths = names.map((name): [ string ] => [ name ]) as [ [ string ], ...Array<[ string ]> ]; + const rule = v.partialCheck<EnvRecord, typeof paths, EnvRecord, string>(paths, requirement as (input: EnvRecord) => boolean, message); + return rule as unknown as v.GenericValidation<TInput, TInput>; +} + +export function requires<TInput extends EnvRecord = EnvRecord>( + dependent: string, + dependency: string, + { when = isSet, message }: CompanionRuleOptions = {}, +): v.GenericValidation<TInput, TInput> { + return companionRule<TInput>( + [ dependent, dependency ], + (input) => input[dependent] === undefined || when(input[dependency]), + message ?? `${ dependent } can only be used with ${ dependency }`, + ); +} + +export function requiredIf<TInput extends EnvRecord = EnvRecord>( + dependent: string, + dependency: string, + { when = isSet, message }: CompanionRuleOptions = {}, +): v.GenericValidation<TInput, TInput> { + return companionRule<TInput>( + [ dependent, dependency ], + (input) => !when(input[dependency]) || isProvided(input[dependent]), + message ?? `${ dependent } is required when ${ dependency } is set`, + ); +} + +export interface EnvSchema extends v.GenericSchema<EnvRecord, EnvRecord> { + readonly entries: Record<string, v.GenericSchema>; +} + +export interface ComposedSchema extends v.GenericSchema<EnvRecord, EnvRecord> { + readonly envNames: ReadonlyArray<string>; +} + +interface FlatIssue { + readonly message: string; + readonly input: unknown; + readonly path: ReadonlyArray<v.IssuePathItem>; +} + +// A `v.union` reports one issue for the whole value and keeps each option's real failure in `issue.issues`, +// with paths relative to the union's input; those nested issues are the ones worth printing. +function flattenIssues(issues: ReadonlyArray<v.BaseIssue<unknown>>, parentPath: ReadonlyArray<v.IssuePathItem> = []): Array<FlatIssue> { + return issues.flatMap((issue) => { + const path = [ ...parentPath, ...(issue.path ?? []) ]; + if (issue.issues) { + return flattenIssues(issue.issues, path); + } + return [ { message: issue.message, input: issue.input, path } ]; + }); +} + +const toDotPath = (path: ReadonlyArray<v.IssuePathItem>): string => path.map((item) => String(item.key)).join('.'); + +// Each sub-schema validates the whole env map on its own (that is what lets a companion rule name a +// variable another file declares). `v.intersect` would do the same but then merges the members' outputs, +// and a `looseObject` member hands the raw string through while the owning member hands the parsed +// value, which the merge reports as a type clash. +export function composeSchemas(schemas: ReadonlyArray<EnvSchema>): ComposedSchema { + const envNames = schemas.flatMap((schema) => Object.keys(schema.entries)); + const knownNames = new Set(envNames); + + const schema = v.pipe( + v.looseObject({}), + v.rawCheck(({ dataset, addIssue }) => { + if (!dataset.typed) { + return; + } + const unknown = Object.keys(dataset.value).filter((name) => !knownNames.has(name)); + if (unknown.length > 0) { + addIssue({ message: `Unknown ENV variables were provided: ${ unknown.join(', ') }` }); + } + for (const subSchema of schemas) { + const result = v.safeParse(subSchema, dataset.value); + flattenIssues(result.issues ?? []).forEach((issue) => addIssue({ + message: issue.message, + // Stryker disable next-line ConditionalExpression,EqualityOperator: an empty path prints like no path; the branch only satisfies the tuple type + path: issue.path.length > 0 ? [ ...issue.path ] as [ v.IssuePathItem, ...Array<v.IssuePathItem> ] : undefined, + input: issue.input, + })); + } + }), + ); + + return { ...schema, envNames }; +} + +export function getValidationErrors(schema: v.GenericSchema, value: unknown): Array<string> { + const result = v.safeParse(schema, value); + if (result.success) { + return []; + } + const lines = flattenIssues(result.issues).map((issue) => { + const path = toDotPath(issue.path); + return path ? `${ path }: ${ issue.message }` : issue.message; + }); + // Two union options can fail on the same key for the same reason. + return [ ...new Set(lines) ]; +} diff --git a/deploy/tools/envs-validator/vite.config.ts b/deploy/tools/envs-validator/vite.config.ts index 52eb83aff86..7ba75b0d129 100644 --- a/deploy/tools/envs-validator/vite.config.ts +++ b/deploy/tools/envs-validator/vite.config.ts @@ -10,8 +10,8 @@ export default defineConfig({ formats: [ 'es' ], fileName: (format, entryName) => `${ entryName }.js`, }, - rollupOptions: { - external: [ 'node:worker_threads', 'node:url', 'node:path', 'node:fs' ], + rolldownOptions: { + external: [ 'node:worker_threads', 'node:url', 'node:path', 'node:fs', 'node:fs/promises' ], output: { dir: 'dist', entryFileNames: '[name].js', @@ -23,7 +23,7 @@ export default defineConfig({ resolve: { alias: { src: resolve(__dirname, '../../../src'), - public: resolve(__dirname, '../../../public'), + 'public': resolve(__dirname, '../../../public'), }, }, }); diff --git a/deploy/tools/essential-dapps-chains-config-generator/index.ts b/deploy/tools/essential-dapps-chains-config-generator/index.ts index f0b1f38e321..6436f601789 100644 --- a/deploy/tools/essential-dapps-chains-config-generator/index.ts +++ b/deploy/tools/essential-dapps-chains-config-generator/index.ts @@ -1,22 +1,22 @@ -/* eslint-disable no-console */ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { pick, uniq, delay } from 'es-toolkit'; import { mkdirSync, writeFileSync } from 'node:fs'; import { dirname, resolve as resolvePath } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Worker } from 'node:worker_threads'; import * as viemChains from 'viem/chains'; -import { pick, uniq, delay } from 'es-toolkit'; -import { EssentialDappsConfig } from 'src/features/marketplace/types/client'; -import { getEnvValue, parseEnvJson } from 'src/config/utils/envs'; +import type { EssentialDappsConfig, EssentialDappsChainConfig } from 'src/features/marketplace/types/client'; + import currentChainConfig from 'src/config'; -import appConfig from 'src/config'; -import { EssentialDappsChainConfig } from 'src/features/marketplace/types/client'; +import type appConfig from 'src/config'; +import { getEnvValue, parseEnvJson } from 'src/config/utils/envs'; const currentFilePath = fileURLToPath(import.meta.url); const currentDir = dirname(currentFilePath); async function getChainscoutInfo(externalChainIds: Array<string>, currentChainId: string | undefined) { - const controller = new AbortController(); const timeout = setTimeout(() => { controller.abort(`Request to Chainscout API timed out`); @@ -24,14 +24,14 @@ async function getChainscoutInfo(externalChainIds: Array<string>, currentChainId try { const response = await fetch( - `https://chains.blockscout.com/api/chains?chain_ids=${ [currentChainId, ...externalChainIds].filter(Boolean).join(',') }`, - { signal: controller.signal } + `https://chains.blockscout.com/api/chains?chain_ids=${ [ currentChainId, ...externalChainIds ].filter(Boolean).join(',') }`, + { signal: controller.signal }, ); if (!response.ok) { throw new Error(`Failed to fetch chains info from Chainscout API`); } - const chainsInfo = await response.json() as Record<string, { explorers: [ { url: string } ], logo: string }>; - + const chainsInfo = await response.json() as Record<string, { explorers: [ { url: string } ]; logo: string }>; + return { externals: externalChainIds.map((chainId) => ({ id: chainId, @@ -43,16 +43,13 @@ async function getChainscoutInfo(externalChainIds: Array<string>, currentChainId explorerUrl: chainsInfo[currentChainId]?.explorers[0]?.url, logoUrl: chainsInfo[currentChainId]?.logo, } : undefined, - } - - } catch (error) { - throw error; + }; } finally { clearTimeout(timeout); } } -function trimChainConfig(config: typeof appConfig, logoUrl: string | undefined) { +function trimChainConfig(config: typeof appConfig) { return { ...pick(config, [ 'app', 'chain' ]), apis: pick(config.apis || {}, [ 'core' ]), @@ -64,7 +61,7 @@ async function computeChainConfig(url: string): Promise<unknown> { const worker = new Worker(workerPath, { workerData: { url }, - env: {} // Start with empty environment + env: {}, // Start with empty environment }); const controller = new AbortController(); @@ -86,10 +83,32 @@ async function computeChainConfig(url: string): Promise<unknown> { return Promise.race([ configPromise, - delay(30_000, { signal: controller.signal }) + delay(30_000, { signal: controller.signal }), ]).finally(() => { worker.terminate(); - }) + }); +} + +function getEnabledChainIds(featureConfig: EssentialDappsConfig | null, currentChainId: string | undefined): Array<string> { + return uniq([ + ...Object.values(featureConfig?.swap?.chains ?? []), + ...Object.values(featureConfig?.revoke?.chains ?? []), + ...Object.values(featureConfig?.multisend?.chains ?? []), + ].filter((chain) => chain !== currentChainId)); +} + +async function fetchChainConfigs(explorerUrls: Array<string>): Promise<Array<typeof appConfig>> { + const chainConfigs: Array<typeof appConfig> = []; + + for (const explorerUrl of explorerUrls) { + const chainConfig = (await computeChainConfig(explorerUrl)) as typeof appConfig | undefined; + if (!chainConfig) { + throw new Error(`Failed to fetch chain config for ${ explorerUrl }`); + } + chainConfigs.push(chainConfig); + } + + return chainConfigs; } async function run() { @@ -102,11 +121,7 @@ async function run() { console.log('🌀 Generating essential dapps chains config...'); const featureConfig = parseEnvJson<EssentialDappsConfig>(getEnvValue('NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG')); - const enabledChains = uniq([ - ...Object.values(featureConfig?.swap?.chains ?? []), - ...Object.values(featureConfig?.revoke?.chains ?? []), - ...Object.values(featureConfig?.multisend?.chains ?? []), - ].filter((chain) => chain !== currentChainConfig.chain.id)) + const enabledChains = getEnabledChainIds(featureConfig, currentChainConfig.chain.id); if (enabledChains.length === 0) { console.log('⚠️ No chains are enabled. Skipping essential dapps chains config generation.\n'); @@ -117,34 +132,26 @@ async function run() { const chainsWithoutUrl = chainscoutInfo.externals.filter(({ explorerUrl }) => !explorerUrl); if (chainsWithoutUrl.length > 0) { - console.log(`⚠️ For the following chains explorer url was not found: ${ chainsWithoutUrl.map(({ id }) => id).join(', ') }. Therefore, they will not be enabled.`); + const ids = chainsWithoutUrl.map(({ id }) => id).join(', '); + console.log(`⚠️ For the following chains explorer url was not found: ${ ids }. Therefore, they will not be enabled.`); } const explorerUrls = chainscoutInfo.externals.map(({ explorerUrl }) => explorerUrl).filter(Boolean); console.log(`ℹ️ For ${ explorerUrls.length } chains explorer url was found in static config. Fetching parameters for each chain...`); - const chainConfigs: Array<typeof appConfig> = []; - - for (const explorerUrl of explorerUrls) { - const chainConfig = (await computeChainConfig(explorerUrl)) as typeof appConfig | undefined; - if (!chainConfig) { - throw new Error(`Failed to fetch chain config for ${ explorerUrl }`); - } - chainConfigs.push(chainConfig); - } + const chainConfigs = await fetchChainConfigs(explorerUrls); const result = { chains: [ currentChainConfig, ...chainConfigs ].map((config) => { const chainId = config.chain.id; - const chainInfo = [...chainscoutInfo.externals, chainscoutInfo.current].find((chain) => chain?.id === chainId); - const logoUrl = [...chainscoutInfo.externals, chainscoutInfo.current].find((chain) => chain?.id === config.chain.id)?.logoUrl; + const chainInfo = [ ...chainscoutInfo.externals, chainscoutInfo.current ].find((chain) => chain?.id === chainId); const chainName = (config as { chain: { name: string } })?.chain?.name ?? `Chain ${ chainId }`; return { id: chainId || '', name: chainName, logo: chainInfo?.logoUrl, explorer_url: chainInfo?.explorerUrl || '', - app_config: trimChainConfig(config, logoUrl), - contracts: Object.values(viemChains).find(({ id }) => id === Number(config.chain.id))?.contracts + app_config: trimChainConfig(config), + contracts: Object.values(viemChains).find(({ id }) => id === Number(config.chain.id))?.contracts, } satisfies EssentialDappsChainConfig; }), }; diff --git a/deploy/tools/essential-dapps-chains-config-generator/package.json b/deploy/tools/essential-dapps-chains-config-generator/package.json index 373dba12f8a..530a2ce23fc 100644 --- a/deploy/tools/essential-dapps-chains-config-generator/package.json +++ b/deploy/tools/essential-dapps-chains-config-generator/package.json @@ -13,9 +13,8 @@ "viem": "2.38.6" }, "devDependencies": { - "@types/node": "22.12.0", + "@types/node": "24.13.4", "dotenv-cli": "10.0.0", - "typescript": "7.0.2", - "vite": "6.4.3" + "vite": "8.3.5" } } diff --git a/deploy/tools/essential-dapps-chains-config-generator/tsconfig.json b/deploy/tools/essential-dapps-chains-config-generator/tsconfig.json deleted file mode 100644 index 020809b1920..00000000000 --- a/deploy/tools/essential-dapps-chains-config-generator/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "ESNext", - "moduleResolution": "bundler", - "esModuleInterop": true, - "strict": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "outDir": "./dist", - "rootDir": "../../../", - "paths": { - "src/*": ["../../../src/*"], - }, - "types": ["node"], - "allowImportingTsExtensions": true, - "noEmit": true - }, - "include": [ - "index.ts", - "worker.ts", - ], - "exclude": [ - "node_modules", - "dist" - ] -} \ No newline at end of file diff --git a/deploy/tools/essential-dapps-chains-config-generator/vite.config.ts b/deploy/tools/essential-dapps-chains-config-generator/vite.config.ts index 4449d3a1039..504c2e1ba3f 100644 --- a/deploy/tools/essential-dapps-chains-config-generator/vite.config.ts +++ b/deploy/tools/essential-dapps-chains-config-generator/vite.config.ts @@ -11,7 +11,7 @@ export default defineConfig({ formats: [ 'es' ], fileName: (format, entryName) => `${ entryName }.js`, }, - rollupOptions: { + rolldownOptions: { external: [ 'node:url', 'node:path', 'node:fs', 'node:worker_threads' ], output: { dir: 'dist', diff --git a/deploy/tools/essential-dapps-chains-config-generator/worker.ts b/deploy/tools/essential-dapps-chains-config-generator/worker.ts index 6d461d1032c..39de98324ac 100644 --- a/deploy/tools/essential-dapps-chains-config-generator/worker.ts +++ b/deploy/tools/essential-dapps-chains-config-generator/worker.ts @@ -1,4 +1,5 @@ -/* eslint-disable no-console */ +// SPDX-License-Identifier: LicenseRef-Blockscout + import { parentPort, workerData } from 'node:worker_threads'; interface WorkerData { @@ -22,8 +23,6 @@ async function fetchChainConfig(url: string): Promise<ChainConfig> { } const config = await response.json(); return config as ChainConfig; - } catch (error) { - throw error; } finally { clearTimeout(timeout); } @@ -39,7 +38,7 @@ async function computeConfig() { // 2. Set environment variables Object.entries(chainConfig.envs).forEach(([ key, value ]) => { - // eslint-disable-next-line no-restricted-properties + process.env[key] = value; }); diff --git a/deploy/tools/favicon-generator/dev.sh b/deploy/tools/favicon-generator/dev.sh new file mode 100755 index 00000000000..51af549204d --- /dev/null +++ b/deploy/tools/favicon-generator/dev.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# Regenerates the default favicon pack committed under public/assets/favicon/ from the Blockscout +# master favicon.svg beside this script. The container runs the same generator from the network icon +# instead (deploy/scripts/favicon_generator.sh). + +favicon_folder="../../../public/assets/favicon/" + +MASTER_FILE="$(pwd)/favicon.svg" node ./index.js || exit 1 + +if [ -d "$favicon_folder" ]; then + rm -r "$favicon_folder" +fi +mkdir -p "$favicon_folder" +cp -r ./output/* "$favicon_folder" diff --git a/tools/scripts/favicon.svg b/deploy/tools/favicon-generator/favicon.svg similarity index 100% rename from tools/scripts/favicon.svg rename to deploy/tools/favicon-generator/favicon.svg diff --git a/deploy/tools/favicon-generator/index.js b/deploy/tools/favicon-generator/index.js index 0a132a21146..7740f7b85c3 100644 --- a/deploy/tools/favicon-generator/index.js +++ b/deploy/tools/favicon-generator/index.js @@ -1,21 +1,54 @@ -/* eslint-disable no-console */ +// SPDX-License-Identifier: LicenseRef-Blockscout + const { favicons } = require('favicons'); const fs = require('fs/promises'); const path = require('path'); generateFavicons(); +const isKeptImage = (name) => name === 'apple-touch-icon-180x180.png' || name === 'android-chrome-192x192.png' || + (!name.startsWith('apple-touch-icon') && !name.startsWith('android-chrome')); + +async function writeOutput(result, outputDir) { + await fs.mkdir(outputDir, { recursive: true }); + + for (const image of result.images) { + if (isKeptImage(image.name)) { + await fs.writeFile(path.join(outputDir, image.name), image.contents); + } + + // marketing assets reuse the 192px android icon under a stable name + if (image.name === 'android-chrome-192x192.png') { + await fs.writeFile(path.join(outputDir, 'logo-icon.png'), image.contents); + } + } + + for (const file of result.files) { + if (file.name !== 'manifest.webmanifest') { + await fs.writeFile(path.join(outputDir, file.name), file.contents); + } + } +} + +async function readMasterImage() { + const masterFile = process.env.MASTER_FILE; + if (masterFile) { + return fs.readFile(masterFile); + } + + const masterUrl = process.env.MASTER_URL; + if (!masterUrl) { + throw new Error('FAVICON_MASTER_URL or NEXT_PUBLIC_NETWORK_ICON must be set'); + } + + const response = await fetch(masterUrl); + return Buffer.from(await response.arrayBuffer()); +} + async function generateFavicons() { console.log('Generating favicons...'); - const masterUrl = process.env.MASTER_URL; try { - if (!masterUrl) { - throw new Error('FAVICON_MASTER_URL or NEXT_PUBLIC_NETWORK_ICON must be set'); - } - - const response = await fetch(masterUrl); - const buffer = await response.arrayBuffer(); - const source = Buffer.from(buffer); + const source = await readMasterImage(); const configuration = { path: '/output', @@ -34,29 +67,7 @@ async function generateFavicons() { try { const result = await favicons(source, configuration); - - const outputDir = path.resolve(process.cwd(), 'output'); - await fs.mkdir(outputDir, { recursive: true }); - - for (const image of result.images) { - // keep only necessary files - if (image.name === 'apple-touch-icon-180x180.png' || image.name === 'android-chrome-192x192.png' || - (!image.name.startsWith('apple-touch-icon') && !image.name.startsWith('android-chrome')) - ) { - await fs.writeFile(path.join(outputDir, image.name), image.contents); - } - - // copy android-chrome-192x192.png to logo-icon.png for marketing purposes - if (image.name === 'android-chrome-192x192.png') { - await fs.writeFile(path.join(outputDir, 'logo-icon.png'), image.contents); - } - } - - for (const file of result.files) { - if (file.name !== 'manifest.webmanifest') { - await fs.writeFile(path.join(outputDir, file.name), file.contents); - } - } + await writeOutput(result, path.resolve(process.cwd(), 'output')); console.log('Favicons generated successfully!'); } catch (faviconError) { diff --git a/deploy/tools/favicon-generator/package.json b/deploy/tools/favicon-generator/package.json index a50830febc4..867f9cd7fee 100644 --- a/deploy/tools/favicon-generator/package.json +++ b/deploy/tools/favicon-generator/package.json @@ -5,6 +5,9 @@ "keywords": [], "author": "", "description": "", + "scripts": { + "dev": "./dev.sh" + }, "dependencies": { "favicons": "^7.2.0" } diff --git a/deploy/tools/feature-reporter/index.ts b/deploy/tools/feature-reporter/index.ts index b509dee0739..179417417ea 100644 --- a/deploy/tools/feature-reporter/index.ts +++ b/deploy/tools/feature-reporter/index.ts @@ -1,4 +1,5 @@ -/* eslint-disable no-console */ +// SPDX-License-Identifier: LicenseRef-Blockscout + import config from 'src/config'; run(); diff --git a/deploy/tools/feature-reporter/package.json b/deploy/tools/feature-reporter/package.json index edd88931656..490adb0586a 100644 --- a/deploy/tools/feature-reporter/package.json +++ b/deploy/tools/feature-reporter/package.json @@ -10,9 +10,8 @@ "dev": "./dev.sh" }, "devDependencies": { - "@types/node": "22.12.0", + "@types/node": "24.13.4", "dotenv-cli": "^7.4.4", - "typescript": "7.0.2", - "vite": "6.4.3" + "vite": "8.3.5" } } diff --git a/deploy/tools/feature-reporter/tsconfig.json b/deploy/tools/feature-reporter/tsconfig.json deleted file mode 100644 index d96186912e8..00000000000 --- a/deploy/tools/feature-reporter/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "ESNext", - "moduleResolution": "bundler", - "esModuleInterop": true, - "strict": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "outDir": "./dist", - "rootDir": "../../../", - "paths": { - "src/*": ["../../../src/*"] - }, - "types": ["node"], - "allowImportingTsExtensions": true, - "noEmit": true - }, - "include": [ - "index.ts", - "vite.config.ts" - ], - "exclude": [ - "node_modules", - "dist" - ] -} diff --git a/deploy/tools/feature-reporter/vite.config.ts b/deploy/tools/feature-reporter/vite.config.ts index b92cdb9ab8e..373b5222bff 100644 --- a/deploy/tools/feature-reporter/vite.config.ts +++ b/deploy/tools/feature-reporter/vite.config.ts @@ -10,7 +10,7 @@ export default defineConfig({ formats: [ 'es' ], fileName: (format, entryName) => `${ entryName }.js`, }, - rollupOptions: { + rolldownOptions: { external: [ 'node:worker_threads', 'node:url', 'node:path', 'node:fs' ], output: { dir: 'dist', diff --git a/deploy/tools/llms-txt-generator/generate-pro-api.ts b/deploy/tools/llms-txt-generator/generate-pro-api.ts index ce039b090ff..f061dd4fb61 100644 --- a/deploy/tools/llms-txt-generator/generate-pro-api.ts +++ b/deploy/tools/llms-txt-generator/generate-pro-api.ts @@ -1,347 +1,379 @@ -import config from 'src/config'; +// SPDX-License-Identifier: LicenseRef-Blockscout + +/* eslint-disable max-len -- the long lines are the generated document's prose; wrapping them would change llms.txt */ + import dedent from 'dedent'; + import { layerLabels } from 'src/features/rollup/common/utils/layer'; +import config from 'src/config'; + const PRO_API_URL = 'https://api.blockscout.com'; -export function generateProApi(): string { - const chainName = config.chain.name ?? ''; - const chainId = config.chain.id ?? ''; +const chainName = config.chain.name ?? ''; +const chainId = config.chain.id ?? ''; - const rollupFeature = config.features.rollup; - const parentChainUrl = rollupFeature.isEnabled ? rollupFeature.parentChain.baseUrl : undefined; - const currentToParentLayerLabel = layerLabels.current + '→' + layerLabels.parent; - const parentToCurrentLayerLabel = layerLabels.parent + '→' + layerLabels.current; +const rollupFeature = config.features.rollup; +const parentChainUrl = rollupFeature.isEnabled ? rollupFeature.parentChain.baseUrl : undefined; +const currentToParentLayerLabel = layerLabels.current + '→' + layerLabels.parent; +const parentToCurrentLayerLabel = layerLabels.parent + '→' + layerLabels.current; - const validatorsFeature = config.features.validators; +const validatorsFeature = config.features.validators; - const GENERAL_COUNTERS_TEMPLATE = chainId ? ` +function generalCountersSection(): string | undefined { + return chainId ? ` ### General Counters \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/stats-service/api/v1/counters' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/stats-service/api/v1/counters' \`\`\` ` : '{blank}'; +} - const USER_OPS_TEMPLATE = config.features.userOps.isEnabled ? ` +function userOpsSection(): string | undefined { + return config.features.userOps.isEnabled ? ` ### Account Abstraction info \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/proxy/account-abstraction/accounts/{account_address}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/proxy/account-abstraction/accounts/{account_address}' \`\`\` ### User Operations by Address \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/proxy/account-abstraction/operations?sender={account_address}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/proxy/account-abstraction/operations?sender={account_address}' \`\`\` ### User Operations by Transaction \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/proxy/account-abstraction/operations?transaction_hash={transaction_hash}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/proxy/account-abstraction/operations?transaction_hash={transaction_hash}' \`\`\` ### User Operation Details \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/proxy/account-abstraction/operations/{user_operation_hash}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/proxy/account-abstraction/operations/{user_operation_hash}' \`\`\` ` : '{blank}'; +} - const BEACON_CHAIN_TEMPLATE = config.features.beaconChain.isEnabled ? ` +function beaconChainSection(): string | undefined { + return config.features.beaconChain.isEnabled ? ` ### Deposits by Address \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/addresses/{account_address}/beacon/deposits' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/addresses/{account_address}/beacon/deposits' \`\`\` ### Deposits by Block \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/blocks/{block_hash_or_number}/beacon/deposits' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/blocks/{block_hash_or_number}/beacon/deposits' \`\`\` ### Withdrawals by Address \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/addresses/{account_address}/withdrawals' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/addresses/{account_address}/withdrawals' \`\`\` ### Withdrawals by Block \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/blocks/{block_hash_or_number}/withdrawals' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/blocks/{block_hash_or_number}/withdrawals' \`\`\` ` : undefined; +} - const ARBITRUM_CHAIN_TEMPLATE = rollupFeature.isEnabled && rollupFeature.type === 'arbitrum' ? ` +function arbitrumChainSection(): string | undefined { + return rollupFeature.isEnabled && rollupFeature.type === 'arbitrum' ? ` ### Latest Committed Batch Number \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/main-page/arbitrum/batches/latest-number' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/main-page/arbitrum/batches/latest-number' \`\`\` ### Batch Info \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/arbitrum/batches/{batch_number}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/arbitrum/batches/{batch_number}' \`\`\` ### Blocks By Batch \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/blocks/arbitrum-batch/{batch_number}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/blocks/arbitrum-batch/{batch_number}' \`\`\` - ### Get ${parentToCurrentLayerLabel} messages + ### Get ${ parentToCurrentLayerLabel } messages \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/arbitrum/messages/to-rollup' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/arbitrum/messages/to-rollup' \`\`\` - ### Get ${currentToParentLayerLabel} messages + ### Get ${ currentToParentLayerLabel } messages \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/arbitrum/messages/from-rollup' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/arbitrum/messages/from-rollup' \`\`\` - ### ${currentToParentLayerLabel} messages by transaction: + ### ${ currentToParentLayerLabel } messages by transaction: \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/arbitrum/messages/withdrawals/{transactions_hash}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/arbitrum/messages/withdrawals/{transactions_hash}' \`\`\` ` : undefined; +} - const OPTIMISM_CHAIN_TEMPLATE = rollupFeature.isEnabled && rollupFeature.type === 'optimistic' ? ` +function optimismChainSection(): string | undefined { + return rollupFeature.isEnabled && rollupFeature.type === 'optimistic' ? ` ### Latest Committed Batch Number (top of) \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/optimism/batches' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/optimism/batches' \`\`\` ### Batch Info \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/optimism/batches/{batch_number}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/optimism/batches/{batch_number}' \`\`\` ### Blocks By Batch (TODO: not needed if the batch returns blocks range) \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/blocks/optimism-batch/{batch_number}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/blocks/optimism-batch/{batch_number}' \`\`\` ### Dispute Games \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/optimism/games' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/optimism/games' \`\`\` - ### Get ${parentToCurrentLayerLabel} messages + ### Get ${ parentToCurrentLayerLabel } messages \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/optimism/deposits' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/optimism/deposits' \`\`\` - ### Get ${currentToParentLayerLabel} messages + ### Get ${ currentToParentLayerLabel } messages \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/optimism/withdrawals' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/optimism/withdrawals' \`\`\` ` : undefined; +} - const CELO_CHAIN_TEMPLATE = config.features.celo.isEnabled ? ` +function celoChainSection(): string | undefined { + return config.features.celo.isEnabled ? ` ### Latest Finalized Epoch (top of) \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/celo/epochs' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/celo/epochs' \`\`\` ### Get Epoch Information \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/celo/epochs/{epoch_number}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/celo/epochs/{epoch_number}' \`\`\` ### Validator Group Reward by Epoch \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/celo/epochs/{epoch_number}/election-rewards/group' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/celo/epochs/{epoch_number}/election-rewards/group' \`\`\` ### Validator Rewards by Epoch \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/celo/epochs/{epoch_number}/election-rewards/validator' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/celo/epochs/{epoch_number}/election-rewards/validator' \`\`\` ### Voting Rewards by Epoch \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/celo/epochs/{epoch_number}/election-rewards/voter' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/celo/epochs/{epoch_number}/election-rewards/voter' \`\`\` ` : undefined; +} - const ZKSYNC_CHAIN_TEMPLATE = rollupFeature.isEnabled && rollupFeature.type === 'zkSync' ? ` +function zksyncChainSection(): string | undefined { + return rollupFeature.isEnabled && rollupFeature.type === 'zkSync' ? ` ### Latest Committed Batch Number \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/main-page/zksync/batches/latest-number' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/main-page/zksync/batches/latest-number' \`\`\` ### Batch info \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/zksync/batches/{batch_number}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/zksync/batches/{batch_number}' \`\`\` ` : undefined; +} - const TAC_CHAIN_TEMPLATE = config.features.tac.isEnabled && config.apis.tac ? ` - > **Note:** TAC operations endpoints below are served by a separate microservice and are **not** part of the Blockscout PRO API. The \`Authorization: Bearer {api_key}\` requirement stated in the introduction does not apply here. +function tacChainSection(): string | undefined { + return config.features.tac.isEnabled && config.apis.tac ? ` + > **Note:** TAC operations endpoints below are served by a separate microservice and are **not** part of the Blockscout API. The \`Authorization: Bearer {api_key}\` requirement stated in the introduction does not apply here. ### TAC Operations: \`\`\`bash - curl --request GET --url '${config.apis.tac.endpoint}/api/v2/tac/operations' + curl --request GET --url '${ config.apis.tac.endpoint }/api/v2/tac/operations' \`\`\` ### TAC Operation Info: \`\`\`bash - curl --request GET --url '${config.apis.tac.endpoint}/api/v2/tac/operations/{operation_id}' + curl --request GET --url '${ config.apis.tac.endpoint }/api/v2/tac/operations/{operation_id}' \`\`\` ` : undefined; +} - const SCROLL_CHAIN_TEMPLATE = rollupFeature.isEnabled && rollupFeature.type === 'scroll' ? ` +function scrollChainSection(): string | undefined { + return rollupFeature.isEnabled && rollupFeature.type === 'scroll' ? ` ### Latest Committed Batch Number (top of) \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/scroll/batches' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/scroll/batches' \`\`\` ### Batch Info \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/scroll/batches/{batch_number}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/scroll/batches/{batch_number}' \`\`\` ### Blocks By Batch \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/blocks/scroll-batch/{batch_number}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/blocks/scroll-batch/{batch_number}' \`\`\` - ### Deposits (${parentToCurrentLayerLabel}) + ### Deposits (${ parentToCurrentLayerLabel }) \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/scroll/deposits' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/scroll/deposits' \`\`\` - ### Withdrawals (${currentToParentLayerLabel}) + ### Withdrawals (${ currentToParentLayerLabel }) \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/scroll/withdrawals' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/scroll/withdrawals' \`\`\` ` : undefined; +} - // Shibarium endpoints are not yet listed in the PRO API index (tracked in blockscout/blockscout#14322); the indexer exposes them and the OpenAPI listing is forthcoming. - const SHIBARIUM_CHAIN_TEMPLATE = rollupFeature.isEnabled && rollupFeature.type === 'shibarium' ? ` - ### Deposits (${parentToCurrentLayerLabel}) +function shibariumChainSection(): string | undefined { + return rollupFeature.isEnabled && rollupFeature.type === 'shibarium' ? ` + ### Deposits (${ parentToCurrentLayerLabel }) \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/shibarium/deposits' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/shibarium/deposits' \`\`\` - ### Withdrawals (${currentToParentLayerLabel}) + ### Withdrawals (${ currentToParentLayerLabel }) \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/shibarium/withdrawals' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/shibarium/withdrawals' \`\`\` ` : undefined; +} - const ZILLIQA_CHAIN_TEMPLATE = validatorsFeature.isEnabled && validatorsFeature.chainType === 'zilliqa' ? ` +function zilliqaChainSection(): string | undefined { + return validatorsFeature.isEnabled && validatorsFeature.chainType === 'zilliqa' ? ` ### Validators list: \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/validators/zilliqa' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/validators/zilliqa' \`\`\` ### Validator Info: \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/validators/zilliqa/{validator_public_key}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/validators/zilliqa/{validator_public_key}' \`\`\` ` : undefined; +} - // Stability validators endpoint is not yet listed in the PRO API index (tracked in blockscout/blockscout#14323); the indexer exposes it and the OpenAPI listing is forthcoming. - const STABILITY_CHAIN_TEMPLATE = validatorsFeature.isEnabled && validatorsFeature.chainType === 'stability' ? ` +function stabilityChainSection(): string | undefined { + return validatorsFeature.isEnabled && validatorsFeature.chainType === 'stability' ? ` ### Validators list: \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/validators/stability' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/validators/stability' \`\`\` ` : undefined; +} - const CHAIN_SPECIFIC_DATA = [ - BEACON_CHAIN_TEMPLATE, - ARBITRUM_CHAIN_TEMPLATE, - OPTIMISM_CHAIN_TEMPLATE, - CELO_CHAIN_TEMPLATE, - ZKSYNC_CHAIN_TEMPLATE, - TAC_CHAIN_TEMPLATE, - SCROLL_CHAIN_TEMPLATE, - ZILLIQA_CHAIN_TEMPLATE, - STABILITY_CHAIN_TEMPLATE, - SHIBARIUM_CHAIN_TEMPLATE, - ].filter(Boolean); - - const CHAIN_SPECIFIC_TEMPLATE = CHAIN_SPECIFIC_DATA.length > 0 ? ` +function chainSpecificSection(): string { + const sections = [ + beaconChainSection(), + arbitrumChainSection(), + optimismChainSection(), + celoChainSection(), + zksyncChainSection(), + tacChainSection(), + scrollChainSection(), + zilliqaChainSection(), + stabilityChainSection(), + shibariumChainSection(), + ].filter(Boolean); + + return sections.length > 0 ? ` ## Chain-Specific Data - ${ CHAIN_SPECIFIC_DATA.join('\n') } + ${ sections.join('\n') } ` : '{blank}'; +} - const MAIN_TEMPLATE = dedent` - # Blockscout - ${chainName} +export function generateProApi(): string { + // Shibarium endpoints are not yet listed in the Blockscout API index (tracked in blockscout/blockscout#14322); the indexer exposes them and the OpenAPI listing is forthcoming. + // Stability validators endpoint is not yet listed in the Blockscout API index (tracked in blockscout/blockscout#14323); the indexer exposes it and the OpenAPI listing is forthcoming. + return dedent` + # Blockscout - ${ chainName } Blockscout is a human-friendly blockchain explorer for EVM-compatible networks. It lets users browse blocks, transactions, addresses, tokens (ERC-20/721/1155), logs, contract ABIs, and decoded contract interactions. While the site is primarily designed for people, all rendered information is backed by API endpoints that machines can consume. - All endpoint examples below target the **Blockscout PRO API** at \`${PRO_API_URL}\` — a single HTTP API spanning 100+ EVM chains. Every request requires the header \`Authorization: Bearer {api_key}\`; for brevity it is omitted from the individual \`curl\` examples and must be added by the caller. Generate an API key at the Blockscout developer portal: \`https://dev.blockscout.com\` (free tier, no credit card required). For the full set of conventions (additional headers, response shape, pagination, plan limits) consult the public \`web3-dev\` agent skill linked from the "Additional Info" section at the bottom of this document. + All endpoint examples below target the **Blockscout API** at \`${ PRO_API_URL }\` — a single HTTP API spanning 100+ EVM chains. Every request requires the header \`Authorization: Bearer {api_key}\`; for brevity it is omitted from the individual \`curl\` examples and must be added by the caller. Generate an API key at the Blockscout developer portal: \`https://dev.blockscout.com\` (free tier, no credit card required). For the full set of conventions (additional headers, response shape, pagination, plan limits) consult the public \`web3-dev\` agent skill linked from the "Additional Info" section at the bottom of this document. - Chain name: ${chainName} - Chain ID: ${chainId} - ${parentChainUrl ? `Settlement layer Blockscout URL: ${parentChainUrl}` : '{blank}'} + Chain name: ${ chainName } + Chain ID: ${ chainId } + ${ parentChainUrl ? `Settlement layer Blockscout URL: ${ parentChainUrl }` : '{blank}' } ## General Blockchain Data ### Specific Block Info \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/blocks/{block_hash_or_number}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/blocks/{block_hash_or_number}' \`\`\` ### Specific Transaction Info \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/transactions/{transaction_hash}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/transactions/{transaction_hash}' \`\`\` ### Get Transaction Logs \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/transactions/{transaction_hash}/logs' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/transactions/{transaction_hash}/logs' \`\`\` ### Transaction Summary \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/transactions/{transaction_hash}/summary' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/transactions/{transaction_hash}/summary' \`\`\` ### Specific Account Info \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/addresses/{account_address}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/addresses/{account_address}' \`\`\` ### Get Address by ENS Name @@ -349,7 +381,7 @@ export function generateProApi(): string { Cross-chain ENS resolution is served by the multichain aggregator service; the path intentionally has no \`{chain_id}\` segment. \`\`\`bash - curl --request GET --url '${PRO_API_URL}/services/multichain/api/v1/search:quick?q={ens_name}' + curl --request GET --url '${ PRO_API_URL }/services/multichain/api/v1/search:quick?q={ens_name}' \`\`\` ### Get Transactions By Address @@ -357,7 +389,7 @@ export function generateProApi(): string { Use the \`advanced-filters\` endpoint with \`address_relation=or\` to match the address on either side of a transaction. \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/advanced-filters?from_address_hashes_to_include={account_address}&to_address_hashes_to_include={account_address}&address_relation=or&transaction_types=COIN_TRANSFER,CONTRACT_INTERACTION,CONTRACT_CREATION&age_from={YYYY-MM-DDTHH:MM:SSZ}&age_to={YYYY-MM-DDTHH:MM:SSZ}&methods={comma_separated_4byte_selectors_optional}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/advanced-filters?from_address_hashes_to_include={account_address}&to_address_hashes_to_include={account_address}&address_relation=or&transaction_types=COIN_TRANSFER,CONTRACT_INTERACTION,CONTRACT_CREATION&age_from={YYYY-MM-DDTHH:MM:SSZ}&age_to={YYYY-MM-DDTHH:MM:SSZ}&methods={comma_separated_4byte_selectors_optional}' \`\`\` ### Get Token Transfers by Address @@ -365,25 +397,25 @@ export function generateProApi(): string { Use the \`advanced-filters\` endpoint with token-flavoured \`transaction_types\` and \`address_relation=or\`. \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/advanced-filters?from_address_hashes_to_include={account_address}&to_address_hashes_to_include={account_address}&address_relation=or&transaction_types=ERC-20,ERC-721,ERC-1155&age_from={YYYY-MM-DDTHH:MM:SSZ}&age_to={YYYY-MM-DDTHH:MM:SSZ}&token_contract_address_hashes_to_include={token_contract_address_optional}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/advanced-filters?from_address_hashes_to_include={account_address}&to_address_hashes_to_include={account_address}&address_relation=or&transaction_types=ERC-20,ERC-721,ERC-1155&age_from={YYYY-MM-DDTHH:MM:SSZ}&age_to={YYYY-MM-DDTHH:MM:SSZ}&token_contract_address_hashes_to_include={token_contract_address_optional}' \`\`\` ### Get ERC20 Tokens By Address \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/addresses/{account_address}/tokens' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/addresses/{account_address}/tokens' \`\`\` ### Get NFT Tokens By Address \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/addresses/{account_address}/nft' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/addresses/{account_address}/nft' \`\`\` ### Lookup Token By Symbol \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/search/quick?q={token_symbol}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/search/quick?q={token_symbol}' \`\`\` ### Get Contract ABI @@ -391,7 +423,7 @@ export function generateProApi(): string { The verified-contract response includes the ABI as a field; no separate ABI-only endpoint is needed. \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/smart-contracts/{contract_address}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/smart-contracts/{contract_address}' \`\`\` ### Read Contract Data @@ -399,70 +431,70 @@ export function generateProApi(): string { Read calls go through the JSON-RPC gateway as \`eth_call\`. This is the only example in this document that uses \`POST\`. \`\`\`bash - curl --request POST --url '${PRO_API_URL}/${chainId}/json-rpc' --header 'Content-Type: application/json' --data '{"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":"{contract_address}","data":"{encoded_calldata}"},"latest"]}' + curl --request POST --url '${ PRO_API_URL }/${ chainId }/json-rpc' --header 'Content-Type: application/json' --data '{"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":"{contract_address}","data":"{encoded_calldata}"},"latest"]}' \`\`\` ### Inspect Source Tree of Verified Contract \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/smart-contracts/{contract_address}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/smart-contracts/{contract_address}' \`\`\` ## Miscellaneous Blockchain Data - ${GENERAL_COUNTERS_TEMPLATE} + ${ generalCountersSection() } ### Gas Tracker \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/stats' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/stats' \`\`\` ### Coin Balance History by Address \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/addresses/{account_address}/coin-balance-history-by-day' - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/addresses/{account_address}/coin-balance-history' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/addresses/{account_address}/coin-balance-history-by-day' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/addresses/{account_address}/coin-balance-history' \`\`\` ### Logs Emitted by Address \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/addresses/{account_address}/logs' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/addresses/{account_address}/logs' \`\`\` ### Blocks Validated by Address \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/addresses/{account_address}/blocks-validated' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/addresses/{account_address}/blocks-validated' \`\`\` - ${USER_OPS_TEMPLATE} + ${ userOpsSection() } ### Holders By Token Address \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/tokens/{token_contract_address}/holders' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/tokens/{token_contract_address}/holders' \`\`\` ### NFT Inventory By Token Address \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/tokens/{token_contract_address}/instances' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/tokens/{token_contract_address}/instances' \`\`\` ### NFT Instance Info \`\`\`bash - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/tokens/{token_contract_address}/instances/{instance_id}' - curl --request GET --url '${PRO_API_URL}/${chainId}/api/v2/tokens/{token_contract_address}/instances/{instance_id}/transfers' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/tokens/{token_contract_address}/instances/{instance_id}' + curl --request GET --url '${ PRO_API_URL }/${ chainId }/api/v2/tokens/{token_contract_address}/instances/{instance_id}/transfers' \`\`\` - ${CHAIN_SPECIFIC_TEMPLATE} + ${ chainSpecificSection() } ## Additional Info - ### Blockscout PRO API — deterministic workflow construction + ### Blockscout API — deterministic workflow construction - The Blockscout PRO API is the recommended surface for building repeatable services, tools, and automations on top of indexed blockchain data. A single HTTP API spans 100+ EVM chains; one Bearer token authenticates every call. + The Blockscout API is the recommended surface for building repeatable services, tools, and automations on top of indexed blockchain data. A single HTTP API spans 100+ EVM chains; one Bearer token authenticates every call. - Generate an API key at the Blockscout developer portal: https://dev.blockscout.com (free tier, no credit card). - - For AI agents, install the \`web3-dev\` skill — it encodes the conventions, headers, pagination, and pre-flight checks needed to call the PRO API correctly. Installation instructions: https://raw.githubusercontent.com/blockscout/agent-skills/refs/heads/main/README.md + - For AI agents, install the \`web3-dev\` skill — it encodes the conventions, headers, pagination, and pre-flight checks needed to call the Blockscout API correctly. Installation instructions: https://raw.githubusercontent.com/blockscout/agent-skills/refs/heads/main/README.md ### Blockscout MCP server — ad-hoc agent interaction @@ -478,7 +510,5 @@ export function generateProApi(): string { \`\`\`bash curl --request GET --url 'https://chains.blockscout.com/api/chains' \`\`\` - `; - - return MAIN_TEMPLATE.replace('{blank}\n', ''); + `.replaceAll('{blank}\n', ''); } diff --git a/deploy/tools/llms-txt-generator/generate-standard.ts b/deploy/tools/llms-txt-generator/generate-standard.ts index 400e8eadc96..2fc00ff2914 100644 --- a/deploy/tools/llms-txt-generator/generate-standard.ts +++ b/deploy/tools/llms-txt-generator/generate-standard.ts @@ -1,312 +1,344 @@ -import config from 'src/config'; +// SPDX-License-Identifier: LicenseRef-Blockscout + +/* eslint-disable max-len -- the long lines are the generated document's prose; wrapping them would change llms.txt */ + import dedent from 'dedent'; + import { layerLabels } from 'src/features/rollup/common/utils/layer'; +import config from 'src/config'; + const MCP_SERVER_URL = 'https://mcp.blockscout.com'; -export function generateStandard(): string { - const chainName = config.chain.name ?? ''; - const chainId = config.chain.id ?? ''; - const coreApiUrl = config.apis.core ? config.apis.core.endpoint + config.apis.core.basePath : ''; - const statsApiUrl = config.apis.stats ? config.apis.stats.endpoint + config.apis.stats.basePath : undefined; +const chainName = config.chain.name ?? ''; +const chainId = config.chain.id ?? ''; +const coreApiUrl = config.apis.core ? config.apis.core.endpoint + config.apis.core.basePath : ''; +const statsApiUrl = config.apis.stats ? config.apis.stats.endpoint + config.apis.stats.basePath : undefined; - const rollupFeature = config.features.rollup; - const parentChainUrl = rollupFeature.isEnabled ? rollupFeature.parentChain.baseUrl : undefined; - const currentToParentLayerLabel = layerLabels.current + '→' + layerLabels.parent; - const parentToCurrentLayerLabel = layerLabels.parent + '→' + layerLabels.current; +const rollupFeature = config.features.rollup; +const parentChainUrl = rollupFeature.isEnabled ? rollupFeature.parentChain.baseUrl : undefined; +const currentToParentLayerLabel = layerLabels.current + '→' + layerLabels.parent; +const parentToCurrentLayerLabel = layerLabels.parent + '→' + layerLabels.current; - const validatorsFeature = config.features.validators; +const validatorsFeature = config.features.validators; - const GENERAL_COUNTERS_TEMPLATE = statsApiUrl ? ` +function generalCountersSection(): string | undefined { + return statsApiUrl ? ` ### General Counters \`\`\`bash - curl --request GET --url '${statsApiUrl}/api/v1/counters' + curl --request GET --url '${ statsApiUrl }/api/v1/counters' \`\`\` ` : '{blank}'; +} - const USER_OPS_TEMPLATE = config.features.userOps.isEnabled ? ` +function userOpsSection(): string | undefined { + return config.features.userOps.isEnabled ? ` ### Account Abstraction info \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/proxy/account-abstraction/accounts/{account_address}' + curl --request GET --url '${ coreApiUrl }/api/v2/proxy/account-abstraction/accounts/{account_address}' \`\`\` ### User Operations by Address \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/proxy/account-abstraction/operations?sender={account_address}' + curl --request GET --url '${ coreApiUrl }/api/v2/proxy/account-abstraction/operations?sender={account_address}' \`\`\` ### User Operations by Transaction \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/proxy/account-abstraction/operations?transaction_hash={transaction_hash}' + curl --request GET --url '${ coreApiUrl }/api/v2/proxy/account-abstraction/operations?transaction_hash={transaction_hash}' \`\`\` ### User Operation Details \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/proxy/account-abstraction/operations/{user_operation_hash}' + curl --request GET --url '${ coreApiUrl }/api/v2/proxy/account-abstraction/operations/{user_operation_hash}' \`\`\` ` : '{blank}'; +} - const BEACON_CHAIN_TEMPLATE = config.features.beaconChain.isEnabled ? ` +function beaconChainSection(): string | undefined { + return config.features.beaconChain.isEnabled ? ` ### Deposits by Address \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/addresses/{account_address}/beacon/deposits' + curl --request GET --url '${ coreApiUrl }/api/v2/addresses/{account_address}/beacon/deposits' \`\`\` ### Deposits by Block \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/blocks/{block_hash_or_number}/beacon/deposits' + curl --request GET --url '${ coreApiUrl }/api/v2/blocks/{block_hash_or_number}/beacon/deposits' \`\`\` ### Withdrawals by Address \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/addresses/{account_address}/withdrawals' + curl --request GET --url '${ coreApiUrl }/api/v2/addresses/{account_address}/withdrawals' \`\`\` ### Withdrawals by Block \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/blocks/{block_number}/withdrawals' + curl --request GET --url '${ coreApiUrl }/api/v2/blocks/{block_number}/withdrawals' \`\`\` ` : undefined; +} - const ARBITRUM_CHAIN_TEMPLATE = rollupFeature.isEnabled && rollupFeature.type === 'arbitrum' ? ` +function arbitrumChainSection(): string | undefined { + return rollupFeature.isEnabled && rollupFeature.type === 'arbitrum' ? ` ### Latest Committed Batch Number \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/main-page/arbitrum/batches/latest-number' + curl --request GET --url '${ coreApiUrl }/api/v2/main-page/arbitrum/batches/latest-number' \`\`\` ### Batch Info \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/arbitrum/batches/{batch_number}' + curl --request GET --url '${ coreApiUrl }/api/v2/arbitrum/batches/{batch_number}' \`\`\` ### Blocks By Batch \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/blocks/arbitrum-batch/{batch_number}' + curl --request GET --url '${ coreApiUrl }/api/v2/blocks/arbitrum-batch/{batch_number}' \`\`\` - ### Get ${parentToCurrentLayerLabel} messages + ### Get ${ parentToCurrentLayerLabel } messages \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/arbitrum/messages/to-rollup' + curl --request GET --url '${ coreApiUrl }/api/v2/arbitrum/messages/to-rollup' \`\`\` - ### Get ${currentToParentLayerLabel} messages + ### Get ${ currentToParentLayerLabel } messages \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/arbitrum/messages/from-rollup' + curl --request GET --url '${ coreApiUrl }/api/v2/arbitrum/messages/from-rollup' \`\`\` - ### ${currentToParentLayerLabel} messages by transaction: + ### ${ currentToParentLayerLabel } messages by transaction: \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/arbitrum/messages/withdrawals/{transactions_hash}' + curl --request GET --url '${ coreApiUrl }/api/v2/arbitrum/messages/withdrawals/{transactions_hash}' \`\`\` ` : undefined; +} - const OPTIMISM_CHAIN_TEMPLATE = rollupFeature.isEnabled && rollupFeature.type === 'optimistic' ? ` +function optimismChainSection(): string | undefined { + return rollupFeature.isEnabled && rollupFeature.type === 'optimistic' ? ` ### Latest Committed Batch Number (top of) \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/optimism/batches' + curl --request GET --url '${ coreApiUrl }/api/v2/optimism/batches' \`\`\` ### Batch Info \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/optimism/batches/{batch_number}' + curl --request GET --url '${ coreApiUrl }/api/v2/optimism/batches/{batch_number}' \`\`\` ### Blocks By Batch (TODO: not needed if the batch returns blocks range) \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/blocks/optimism-batch/{batch_number}' + curl --request GET --url '${ coreApiUrl }/api/v2/blocks/optimism-batch/{batch_number}' \`\`\` ### Dispute Games \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/optimism/games' + curl --request GET --url '${ coreApiUrl }/api/v2/optimism/games' \`\`\` - ### Get ${parentToCurrentLayerLabel} messages + ### Get ${ parentToCurrentLayerLabel } messages \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/optimism/deposits' + curl --request GET --url '${ coreApiUrl }/api/v2/optimism/deposits' \`\`\` - ### Get ${currentToParentLayerLabel} messages + ### Get ${ currentToParentLayerLabel } messages \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/optimism/withdrawals' + curl --request GET --url '${ coreApiUrl }/api/v2/optimism/withdrawals' \`\`\` ` : undefined; +} - const CELO_CHAIN_TEMPLATE = config.features.celo.isEnabled ? ` +function celoChainSection(): string | undefined { + return config.features.celo.isEnabled ? ` ### Latest Finalized Epoch (top of) \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/celo/epochs' + curl --request GET --url '${ coreApiUrl }/api/v2/celo/epochs' \`\`\` ### Get Epoch Information \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/celo/epochs/{epoch_number}' + curl --request GET --url '${ coreApiUrl }/api/v2/celo/epochs/{epoch_number}' \`\`\` ### Validator Group Reward by Epoch \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/celo/epochs/{epoch_number}/election-rewards/group' + curl --request GET --url '${ coreApiUrl }/api/v2/celo/epochs/{epoch_number}/election-rewards/group' \`\`\` ### Validator Rewards by Epoch \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/celo/epochs/{epoch_number}/election-rewards/validator' + curl --request GET --url '${ coreApiUrl }/api/v2/celo/epochs/{epoch_number}/election-rewards/validator' \`\`\` ### Voting Rewards by Epoch \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/celo/epochs/{epoch_number}/election-rewards/voter' + curl --request GET --url '${ coreApiUrl }/api/v2/celo/epochs/{epoch_number}/election-rewards/voter' \`\`\` ` : undefined; +} - const ZKSYNC_CHAIN_TEMPLATE = rollupFeature.isEnabled && rollupFeature.type === 'zkSync' ? ` +function zksyncChainSection(): string | undefined { + return rollupFeature.isEnabled && rollupFeature.type === 'zkSync' ? ` ### Latest Committed Batch Number \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/main-page/zksync/batches/latest-number' + curl --request GET --url '${ coreApiUrl }/api/v2/main-page/zksync/batches/latest-number' \`\`\` ### Batch info \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/zksync/batches/{batch_number}' + curl --request GET --url '${ coreApiUrl }/api/v2/zksync/batches/{batch_number}' \`\`\` ` : undefined; +} - const TAC_CHAIN_TEMPLATE = config.features.tac.isEnabled && config.apis.tac ? ` +function tacChainSection(): string | undefined { + return config.features.tac.isEnabled && config.apis.tac ? ` ### TAC Operations: \`\`\`bash - curl --request GET --url '${config.apis.tac.endpoint}/api/v2/tac/operations' + curl --request GET --url '${ config.apis.tac.endpoint }/api/v2/tac/operations' \`\`\` ### TAC Operation Info: \`\`\`bash - curl --request GET --url '${config.apis.tac.endpoint}/api/v2/tac/operations/{operation_id}' + curl --request GET --url '${ config.apis.tac.endpoint }/api/v2/tac/operations/{operation_id}' \`\`\` ` : undefined; +} - const SCROLL_CHAIN_TEMPLATE = rollupFeature.isEnabled && rollupFeature.type === 'scroll' ? ` +function scrollChainSection(): string | undefined { + return rollupFeature.isEnabled && rollupFeature.type === 'scroll' ? ` ### Latest Committed Batch Number (top of) \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/scroll/batches' + curl --request GET --url '${ coreApiUrl }/api/v2/scroll/batches' \`\`\` ### Batch Info \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/scroll/batches/{batch_number}' + curl --request GET --url '${ coreApiUrl }/api/v2/scroll/batches/{batch_number}' \`\`\` ### Blocks By Batch \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/blocks/scroll-batch/{batch_number}' + curl --request GET --url '${ coreApiUrl }/api/v2/blocks/scroll-batch/{batch_number}' \`\`\` - ### Deposits (${parentToCurrentLayerLabel}) + ### Deposits (${ parentToCurrentLayerLabel }) \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/scroll/deposits' + curl --request GET --url '${ coreApiUrl }/api/v2/scroll/deposits' \`\`\` - ### Withdrawals (${currentToParentLayerLabel}) + ### Withdrawals (${ currentToParentLayerLabel }) \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/scroll/withdrawals' + curl --request GET --url '${ coreApiUrl }/api/v2/scroll/withdrawals' \`\`\` ` : undefined; +} - const SHIBARIUM_CHAIN_TEMPLATE = rollupFeature.isEnabled && rollupFeature.type === 'shibarium' ? ` - ### Deposits (${parentToCurrentLayerLabel}) +function shibariumChainSection(): string | undefined { + return rollupFeature.isEnabled && rollupFeature.type === 'shibarium' ? ` + ### Deposits (${ parentToCurrentLayerLabel }) \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/shibarium/deposits' + curl --request GET --url '${ coreApiUrl }/api/v2/shibarium/deposits' \`\`\` - ### Withdrawals (${currentToParentLayerLabel}) + ### Withdrawals (${ currentToParentLayerLabel }) \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/shibarium/withdrawals' + curl --request GET --url '${ coreApiUrl }/api/v2/shibarium/withdrawals' \`\`\` ` : undefined; +} - const ZILLIQA_CHAIN_TEMPLATE = validatorsFeature.isEnabled && validatorsFeature.chainType === 'zilliqa' ? ` +function zilliqaChainSection(): string | undefined { + return validatorsFeature.isEnabled && validatorsFeature.chainType === 'zilliqa' ? ` ### Validators list: \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/validators/zilliqa' + curl --request GET --url '${ coreApiUrl }/api/v2/validators/zilliqa' \`\`\` ### Validator Info: \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/validators/zilliqa/{validator_public_key}' + curl --request GET --url '${ coreApiUrl }/api/v2/validators/zilliqa/{validator_public_key}' \`\`\` ` : undefined; +} - const STABILITY_CHAIN_TEMPLATE = validatorsFeature.isEnabled && validatorsFeature.chainType === 'stability' ? ` +function stabilityChainSection(): string | undefined { + return validatorsFeature.isEnabled && validatorsFeature.chainType === 'stability' ? ` ### Validators list: \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/validators/stability' + curl --request GET --url '${ coreApiUrl }/api/v2/validators/stability' \`\`\` ` : undefined; +} - const CHAIN_SPECIFIC_DATA = [ - BEACON_CHAIN_TEMPLATE, - ARBITRUM_CHAIN_TEMPLATE, - OPTIMISM_CHAIN_TEMPLATE, - CELO_CHAIN_TEMPLATE, - ZKSYNC_CHAIN_TEMPLATE, - TAC_CHAIN_TEMPLATE, - SCROLL_CHAIN_TEMPLATE, - ZILLIQA_CHAIN_TEMPLATE, - STABILITY_CHAIN_TEMPLATE, - SHIBARIUM_CHAIN_TEMPLATE, - ].filter(Boolean); - - const CHAIN_SPECIFIC_TEMPLATE = CHAIN_SPECIFIC_DATA.length > 0 ? ` +function chainSpecificSection(): string { + const sections = [ + beaconChainSection(), + arbitrumChainSection(), + optimismChainSection(), + celoChainSection(), + zksyncChainSection(), + tacChainSection(), + scrollChainSection(), + zilliqaChainSection(), + stabilityChainSection(), + shibariumChainSection(), + ].filter(Boolean); + + return sections.length > 0 ? ` ## Chain-Specific Data - ${ CHAIN_SPECIFIC_DATA.join('\n') } + ${ sections.join('\n') } ` : '{blank}'; +} - const MAIN_TEMPLATE = dedent` - # Blockscout - ${chainName} +export function generateStandard(): string { + return dedent` + # Blockscout - ${ chainName } Blockscout is a human-friendly blockchain explorer for EVM-compatible networks. It lets users browse blocks, transactions, addresses, tokens (ERC-20/721/1155), logs, contract ABIs, and decoded contract interactions. While the site is primarily designed for people, all rendered information is backed by API endpoints that machines can consume. Large Language Models should prefer the LLM-ready endpoints listed below to retrieve precise, structured data. - Chain name: ${chainName} - Chain ID: ${chainId} - ${parentChainUrl ? `Settlement layer Blockscout URL: ${parentChainUrl}` : '{blank}'} + Chain name: ${ chainName } + Chain ID: ${ chainId } + ${ parentChainUrl ? `Settlement layer Blockscout URL: ${ parentChainUrl }` : '{blank}' } ## General LLM-ready Data @@ -315,153 +347,151 @@ export function generateStandard(): string { ### Specific Block Info \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/get_block_info?chain_id=${chainId}&number_or_hash={block_number_or_hash}&include_transactions=false' + curl --request GET --url '${ MCP_SERVER_URL }/v1/get_block_info?chain_id=${ chainId }&number_or_hash={block_number_or_hash}&include_transactions=false' \`\`\` ### Specific Transaction Info \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/get_transaction_info?chain_id=${chainId}&transaction_hash={transaction_hash}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/get_transaction_info?chain_id=${ chainId }&transaction_hash={transaction_hash}' \`\`\` ### Get Transaction Logs \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/get_transaction_logs?chain_id=${chainId}&transaction_hash={transaction_hash}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/get_transaction_logs?chain_id=${ chainId }&transaction_hash={transaction_hash}' \`\`\` ### Transaction Summary \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/transaction_summary?chain_id=${chainId}&transaction_hash={transaction_hash}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/transaction_summary?chain_id=${ chainId }&transaction_hash={transaction_hash}' \`\`\` ### Specific Account info \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/get_address_info?chain_id=${chainId}&address={account_address}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/get_address_info?chain_id=${ chainId }&address={account_address}' \`\`\` ### Get Address by ENS name \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/get_address_by_ens_name?name={ens_name}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/get_address_by_ens_name?name={ens_name}' \`\`\` ### Get Transactions By Address \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/get_transactions_by_address?chain_id=${chainId}&address={account_address}&age_from={YYYY-MM-DDTHH:MM:SS.00Z}&age_to={YYYY-MM-DDTHH:MM:SS.00Z}&methods={4_bytes_method_signature_optional}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/get_transactions_by_address?chain_id=${ chainId }&address={account_address}&age_from={YYYY-MM-DDTHH:MM:SS.00Z}&age_to={YYYY-MM-DDTHH:MM:SS.00Z}&methods={4_bytes_method_signature_optional}' \`\`\` ### Get Token Transfers by Address \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/get_token_transfers_by_address?chain_id=${chainId}&address={account_address}&age_from={YYYY-MM-DDTHH:MM:SS.00Z}&age_to={YYYY-MM-DDTHH:MM:SS.00Z}&token={token_contract_address_optional}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/get_token_transfers_by_address?chain_id=${ chainId }&address={account_address}&age_from={YYYY-MM-DDTHH:MM:SS.00Z}&age_to={YYYY-MM-DDTHH:MM:SS.00Z}&token={token_contract_address_optional}' \`\`\` ### Get ERC20 Tokens By Address \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/get_tokens_by_address?chain_id=${chainId}&address={account_address}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/get_tokens_by_address?chain_id=${ chainId }&address={account_address}' \`\`\` ### Get NFT Tokens By Address \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/nft_tokens_by_address?chain_id=${chainId}&address={account_address}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/nft_tokens_by_address?chain_id=${ chainId }&address={account_address}' \`\`\` ### Lookup Token By Symbol \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/lookup_token_by_symbol?chain_id=${chainId}&symbol={token_symbol}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/lookup_token_by_symbol?chain_id=${ chainId }&symbol={token_symbol}' \`\`\` ### Get Contract ABI \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/get_contract_abi?chain_id=${chainId}&address={contract_address}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/get_contract_abi?chain_id=${ chainId }&address={contract_address}' \`\`\` ### Read Contract Data \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/read_contract?chain_id=${chainId}&address={contract_address}&abi={string_encoded_function_abi}&function_name={function_name}&args={string_encoded_arguments_list}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/read_contract?chain_id=${ chainId }&address={contract_address}&abi={string_encoded_function_abi}&function_name={function_name}&args={string_encoded_arguments_list}' \`\`\` ### Get Source Files Tree of Verified Contract \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/inspect_contract_code?chain_id=${chainId}&address={contract_address}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/inspect_contract_code?chain_id=${ chainId }&address={contract_address}' \`\`\` ### Inspect Specific Source File of Verified Contract \`\`\`bash - curl --request GET --url '${MCP_SERVER_URL}/v1/inspect_contract_code?chain_id=${chainId}&address={contract_address}&file_name={file_name}' + curl --request GET --url '${ MCP_SERVER_URL }/v1/inspect_contract_code?chain_id=${ chainId }&address={contract_address}&file_name={file_name}' \`\`\` ## Miscellaneous Blockchain Data - ${GENERAL_COUNTERS_TEMPLATE} + ${ generalCountersSection() } ### Gas Tracker \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/stats' + curl --request GET --url '${ coreApiUrl }/api/v2/stats' \`\`\` ### Coin Balance History by Address \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/addresses/{account_address}/coin-balance-history-by-day' - curl --request GET --url '${coreApiUrl}/api/v2/addresses/{account_address}/coin-balance-history' + curl --request GET --url '${ coreApiUrl }/api/v2/addresses/{account_address}/coin-balance-history-by-day' + curl --request GET --url '${ coreApiUrl }/api/v2/addresses/{account_address}/coin-balance-history' \`\`\` ### Logs Emitted by Address \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/addresses/{account_address}/logs' + curl --request GET --url '${ coreApiUrl }/api/v2/addresses/{account_address}/logs' \`\`\` ### Blocks Validated by Address \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/addresses/{account_address}/blocks-validated' + curl --request GET --url '${ coreApiUrl }/api/v2/addresses/{account_address}/blocks-validated' \`\`\` - ${USER_OPS_TEMPLATE} + ${ userOpsSection() } ### Holders By Token Address \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/tokens/{token_contract_address}/holders' + curl --request GET --url '${ coreApiUrl }/api/v2/tokens/{token_contract_address}/holders' \`\`\` ### NFT Inventory By Token Address \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/tokens/{token_contract_address}/instances' + curl --request GET --url '${ coreApiUrl }/api/v2/tokens/{token_contract_address}/instances' \`\`\` ### NFT Instance Info \`\`\`bash - curl --request GET --url '${coreApiUrl}/api/v2/tokens/{token_contract_address}/instances/{instance_id}' - curl --request GET --url '${coreApiUrl}/api/v2/tokens/{token_contract_address}/instances/{instance_id}/transfers' + curl --request GET --url '${ coreApiUrl }/api/v2/tokens/{token_contract_address}/instances/{instance_id}' + curl --request GET --url '${ coreApiUrl }/api/v2/tokens/{token_contract_address}/instances/{instance_id}/transfers' \`\`\` - ${CHAIN_SPECIFIC_TEMPLATE} + ${ chainSpecificSection() } ## Additional Info **Recommendation**: For programmatic access and LLM workflows, prefer the MCP Server endpoints (HTTP, not SSE). - - MCP landing: [${MCP_SERVER_URL}](${MCP_SERVER_URL}) - - MCP server root: [${MCP_SERVER_URL}/mcp/](${MCP_SERVER_URL}/mcp/) + - MCP landing: [${ MCP_SERVER_URL }](${ MCP_SERVER_URL }) + - MCP server root: [${ MCP_SERVER_URL }/mcp/](${ MCP_SERVER_URL }/mcp/) ### Other Blockscout instances (lookup by chain id or name): \`\`\`bash curl --request GET --url 'https://chains.blockscout.com/api/chains' \`\`\` - `; - - return MAIN_TEMPLATE.replace('{blank}\n', ''); + `.replaceAll('{blank}\n', ''); } diff --git a/deploy/tools/llms-txt-generator/index.ts b/deploy/tools/llms-txt-generator/index.ts index a7c7008e7f8..45ac76a9733 100644 --- a/deploy/tools/llms-txt-generator/index.ts +++ b/deploy/tools/llms-txt-generator/index.ts @@ -1,8 +1,11 @@ -import config from 'src/config'; +// SPDX-License-Identifier: LicenseRef-Blockscout + import { writeFileSync } from 'node:fs'; import { dirname, resolve as resolvePath } from 'node:path'; import { fileURLToPath } from 'node:url'; +import config from 'src/config'; + import { generateProApi } from './generate-pro-api'; import { generateStandard } from './generate-standard'; @@ -12,26 +15,26 @@ const outputDir = resolvePath(currentDir, '../../../../public'); const outputFile = resolvePath(outputDir, 'llms.txt'); function run(): void { - try { - if (config.features.multichain.isEnabled) { - console.log('⏭️ Skipping llms.txt generation for multichain explorer'); - return; - } + try { + if (config.features.multichain.isEnabled) { + console.log('⏭️ Skipping llms.txt generation for multichain explorer'); + return; + } - const isInProApi = config.chain.isProApiSupported; - const mode = isInProApi ? 'PRO API' : 'standard'; + const isInProApi = config.chain.isProApiSupported; + const mode = isInProApi ? 'Blockscout API' : 'standard'; - console.log(`🌀 Generating llms.txt (${ mode } mode)...`); + console.log(`🌀 Generating llms.txt (${ mode } mode)...`); - const content = isInProApi ? generateProApi() : generateStandard(); - writeFileSync(outputFile, content); + const content = isInProApi ? generateProApi() : generateStandard(); + writeFileSync(outputFile, content); - console.log('👍 Done!\n'); - } catch (error) { - console.error('🚨 Error generating llms.txt:', error); - console.log('\n'); - process.exit(1); - } + console.log('👍 Done!\n'); + } catch (error) { + console.error('🚨 Error generating llms.txt:', error); + console.log('\n'); + process.exit(1); + } } run(); diff --git a/deploy/tools/llms-txt-generator/package.json b/deploy/tools/llms-txt-generator/package.json index a10364f51a7..09be910dc3d 100644 --- a/deploy/tools/llms-txt-generator/package.json +++ b/deploy/tools/llms-txt-generator/package.json @@ -14,9 +14,8 @@ }, "devDependencies": { "@types/dedent": "0.7.2", - "@types/node": "22.12.0", + "@types/node": "24.13.4", "dotenv-cli": "10.0.0", - "typescript": "7.0.2", - "vite": "6.4.3" + "vite": "8.3.5" } } diff --git a/deploy/tools/llms-txt-generator/tsconfig.json b/deploy/tools/llms-txt-generator/tsconfig.json deleted file mode 100644 index 04d6a092c4d..00000000000 --- a/deploy/tools/llms-txt-generator/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "ESNext", - "moduleResolution": "bundler", - "esModuleInterop": true, - "strict": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "outDir": "./dist", - "rootDir": "../../../", - "paths": { - "src/*": ["../../../src/*"] - }, - "types": ["node"], - "allowImportingTsExtensions": true, - "noEmit": true - }, - "include": [ - "index.ts", - "../app/**/*" - ], - "exclude": [ - "node_modules", - "dist" - ] -} \ No newline at end of file diff --git a/deploy/tools/llms-txt-generator/vite.config.ts b/deploy/tools/llms-txt-generator/vite.config.ts index b92cdb9ab8e..373b5222bff 100644 --- a/deploy/tools/llms-txt-generator/vite.config.ts +++ b/deploy/tools/llms-txt-generator/vite.config.ts @@ -10,7 +10,7 @@ export default defineConfig({ formats: [ 'es' ], fileName: (format, entryName) => `${ entryName }.js`, }, - rollupOptions: { + rolldownOptions: { external: [ 'node:worker_threads', 'node:url', 'node:path', 'node:fs' ], output: { dir: 'dist', diff --git a/deploy/tools/multichain-config-generator/index.ts b/deploy/tools/multichain-config-generator/index.ts index 9110d4cf0d3..f81e5db7df9 100644 --- a/deploy/tools/multichain-config-generator/index.ts +++ b/deploy/tools/multichain-config-generator/index.ts @@ -1,26 +1,18 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { delay } from 'es-toolkit'; import { mkdirSync, writeFileSync } from 'node:fs'; import { dirname, resolve as resolvePath } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Worker } from 'node:worker_threads'; -import { delay } from 'es-toolkit'; -import { ClusterChainConfig } from 'src/features/multichain/types/client'; -import appConfig from 'src/config'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +import type appConfig from 'src/config'; const currentFilePath = fileURLToPath(import.meta.url); const currentDir = dirname(currentFilePath); -// const EXPLORER_URLS = [ -// 'https://optimism.blockscout.com', -// 'https://base.blockscout.com', -// 'https://arbitrum.blockscout.com', -// 'https://unichain.blockscout.com', -// 'https://explorer.redstone.xyz', -// 'https://matchscan.io' -// // 'https://optimism-interop-alpha-0.blockscout.com', -// // 'https://optimism-interop-alpha-1.blockscout.com', -// ]; - function getSlug(chainName: string) { return chainName.toLowerCase().replace(/ /g, '-').replace(/[^a-z0-9-]/g, ''); } @@ -36,14 +28,12 @@ async function getChainscoutInfo(chainIds: Array<string>) { if (!response.ok) { throw new Error(`Failed to fetch chains info from Chainscout API`); } - const chainsInfo = await response.json() as Record<string, { explorers: [ { url: string } ], logo: string }>; - + const chainsInfo = await response.json() as Record<string, { explorers: [ { url: string } ]; logo: string }>; + return chainIds.map((chainId) => ({ id: chainId, logoUrl: chainsInfo[chainId]?.logo, - })) - } catch (error) { - throw error; + })); } finally { clearTimeout(timeout); } @@ -54,7 +44,7 @@ async function computeChainConfig(url: string): Promise<unknown> { const worker = new Worker(workerPath, { workerData: { url }, - env: {} // Start with empty environment + env: {}, // Start with empty environment }); const controller = new AbortController(); @@ -77,24 +67,23 @@ async function computeChainConfig(url: string): Promise<unknown> { return Promise.race([ configPromise, - delay(30_000, { signal: controller.signal }) + delay(30_000, { signal: controller.signal }), ]).finally(() => { worker.terminate(); - }) + }); } async function getExplorerUrls() { - // return EXPLORER_URLS; try { const basePath = `/api/v1/clusters/${ process.env.NEXT_PUBLIC_MULTICHAIN_CLUSTER }/chains`; const url = new URL(basePath, process.env.NEXT_PUBLIC_MULTICHAIN_AGGREGATOR_API_HOST); const response = await fetch(url.toString()); - const data = await response.json(); + const data = await response.json() as { items: Array<{ explorer_url: string }> }; console.log(`💡 Found ${ data.items.length } chains in cluster.`); - return data.items.map((item: { explorer_url: string }) => item.explorer_url); + return data.items.map((item) => item.explorer_url); } catch (error) { return []; } @@ -126,8 +115,8 @@ async function run() { const chainscoutInfo = await getChainscoutInfo( configs - .map((config) => config.chain.id) - .filter((chainId) => chainId !== undefined) + .map((config) => config.chain.id) + .filter((chainId) => chainId !== undefined), ); const config = { diff --git a/deploy/tools/multichain-config-generator/package.json b/deploy/tools/multichain-config-generator/package.json index 8957e0c2186..3d5fac602de 100644 --- a/deploy/tools/multichain-config-generator/package.json +++ b/deploy/tools/multichain-config-generator/package.json @@ -9,8 +9,7 @@ }, "dependencies": {}, "devDependencies": { - "typescript": "7.0.2", - "vite": "6.4.3", - "@types/node": "22.12.0" + "vite": "8.3.5", + "@types/node": "24.13.4" } } diff --git a/deploy/tools/multichain-config-generator/tsconfig.json b/deploy/tools/multichain-config-generator/tsconfig.json deleted file mode 100644 index b29b26e17b3..00000000000 --- a/deploy/tools/multichain-config-generator/tsconfig.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "ESNext", - "moduleResolution": "bundler", - "esModuleInterop": true, - "strict": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "outDir": "./dist", - "rootDir": "../../../", - "paths": { - "src/*": ["../../../src/*"], - }, - "types": ["node"], - "allowImportingTsExtensions": true, - "noEmit": true - }, - "include": [ - "index.ts", - "worker.ts", - "../app/**/*" - ], - "exclude": [ - "node_modules", - "dist" - ] -} \ No newline at end of file diff --git a/deploy/tools/multichain-config-generator/vite.config.ts b/deploy/tools/multichain-config-generator/vite.config.ts index bdca496c4f9..41ae5d2924c 100644 --- a/deploy/tools/multichain-config-generator/vite.config.ts +++ b/deploy/tools/multichain-config-generator/vite.config.ts @@ -11,7 +11,7 @@ export default defineConfig({ formats: [ 'es' ], fileName: (format, entryName) => `${ entryName }.js`, }, - rollupOptions: { + rolldownOptions: { external: [ 'node:worker_threads', 'node:url', 'node:path', 'node:fs' ], output: { dir: 'dist', diff --git a/deploy/tools/multichain-config-generator/worker.ts b/deploy/tools/multichain-config-generator/worker.ts index 6d461d1032c..39de98324ac 100644 --- a/deploy/tools/multichain-config-generator/worker.ts +++ b/deploy/tools/multichain-config-generator/worker.ts @@ -1,4 +1,5 @@ -/* eslint-disable no-console */ +// SPDX-License-Identifier: LicenseRef-Blockscout + import { parentPort, workerData } from 'node:worker_threads'; interface WorkerData { @@ -22,8 +23,6 @@ async function fetchChainConfig(url: string): Promise<ChainConfig> { } const config = await response.json(); return config as ChainConfig; - } catch (error) { - throw error; } finally { clearTimeout(timeout); } @@ -39,7 +38,7 @@ async function computeConfig() { // 2. Set environment variables Object.entries(chainConfig.envs).forEach(([ key, value ]) => { - // eslint-disable-next-line no-restricted-properties + process.env[key] = value; }); diff --git a/deploy/tools/og-image-generator/.gitignore b/deploy/tools/og-image-generator/.gitignore new file mode 100644 index 00000000000..07e6e472cc7 --- /dev/null +++ b/deploy/tools/og-image-generator/.gitignore @@ -0,0 +1 @@ +/node_modules diff --git a/deploy/tools/og-image-generator/dev.sh b/deploy/tools/og-image-generator/dev.sh new file mode 100755 index 00000000000..5f4665fd02c --- /dev/null +++ b/deploy/tools/og-image-generator/dev.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# Generates the OG image into the repo's public/static/ from a representative instance config (eth), +# fetched into ./.env.tmp (in this tool's dir). + +../../../tools/dev-server/fetch.sh eth || exit 1 + +# index.js resolves public/ against the cwd, so run it from the repo root +dotenv \ + -e ./.env.tmp \ + -- bash -c 'cd ../../.. && node --no-warnings ./deploy/tools/og-image-generator/index.js' diff --git a/deploy/tools/og-image-generator/index.js b/deploy/tools/og-image-generator/index.js new file mode 100755 index 00000000000..b0532c6c4de --- /dev/null +++ b/deploy/tools/og-image-generator/index.js @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import fs from 'fs'; +import path from 'path'; + +console.log('🎨 Generating OG image...'); + +const targetFile = path.resolve(process.cwd(), 'public/static/og_image.png'); + +function copyPlaceholderImage() { + const sourceFile = path.resolve(process.cwd(), 'public/static/og_placeholder.png'); + fs.copyFileSync(sourceFile, targetFile); +} + +if (process.env.NEXT_PUBLIC_OG_IMAGE_URL) { + console.log('⏩ NEXT_PUBLIC_OG_IMAGE_URL is set. Skipping OG image generation...'); +} else if (!process.env.NEXT_PUBLIC_NETWORK_NAME) { + console.log('⏩ NEXT_PUBLIC_NETWORK_NAME is not set. Copying placeholder image...'); + copyPlaceholderImage(); +} else if (!process.env.NEXT_PUBLIC_NETWORK_LOGO && !process.env.NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG) { + console.log('⏩ Neither NEXT_PUBLIC_NETWORK_LOGO nor NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG is set. Copying placeholder image...'); + copyPlaceholderImage(); +} else { + try { + const bannerConfig = JSON.parse(process.env.NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG?.replaceAll('\'', '"') || '{}'); + const data = { + title: bannerConfig.text || `${ process.env.NEXT_PUBLIC_NETWORK_NAME } explorer`, + logo_url: process.env.NEXT_PUBLIC_NETWORK_LOGO_DARK ?? process.env.NEXT_PUBLIC_NETWORK_LOGO, + background: bannerConfig.background?.[0], + title_color: bannerConfig.text_color?.[0], + invert_logo: !process.env.NEXT_PUBLIC_NETWORK_LOGO_DARK, + app_url: process.env.NEXT_PUBLIC_APP_HOST, + }; + + console.log('⏳ Making request to OG image generator service...'); + + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 30_000); + + const response = await fetch('https://bigs.services.blockscout.com/generate/og', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(data), + signal: controller.signal, + }); + + clearTimeout(timeoutId); + + if (response.ok) { + console.log('⬇️ Downloading the image...'); + const buffer = await response.arrayBuffer(); + const imageBuffer = Buffer.from(buffer); + fs.writeFileSync(targetFile, imageBuffer); + } else { + const payload = response.headers.get('Content-type')?.includes('application/json') ? await response.json() : await response.text(); + console.error('🛑 Failed to generate OG image. Response:', payload); + console.log('Copying placeholder image...'); + copyPlaceholderImage(); + } + } catch (error) { + console.error('🛑 Failed to generate OG image. Error:', error?.message); + console.log('Copying placeholder image...'); + copyPlaceholderImage(); + } +} + +console.log('✅ Done.'); diff --git a/deploy/tools/og-image-generator/package.json b/deploy/tools/og-image-generator/package.json new file mode 100644 index 00000000000..b51b65611f5 --- /dev/null +++ b/deploy/tools/og-image-generator/package.json @@ -0,0 +1,12 @@ +{ + "name": "@blockscout/og-image-generator", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "./dev.sh" + }, + "devDependencies": { + "dotenv-cli": "10.0.0" + } +} diff --git a/deploy/tools/sitemap-generator/dev.sh b/deploy/tools/sitemap-generator/dev.sh new file mode 100755 index 00000000000..f00a8562033 --- /dev/null +++ b/deploy/tools/sitemap-generator/dev.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# Generates sitemap.xml / robots.txt into the repo's public/ from a representative instance config +# (eth), fetched into ./.env.tmp (in this tool's dir). Reads the repo-root .next build output, so run +# a production build first (e.g. `pnpm prod:preset eth`). + +../../../tools/dev-server/fetch.sh eth || exit 1 + +dotenv \ + -e ./.env.tmp \ + -- bash -c 'pnpm next-sitemap' diff --git a/deploy/tools/sitemap-generator/next-sitemap.config.js b/deploy/tools/sitemap-generator/next-sitemap.config.js index d1cc38b6eea..1b02138def8 100644 --- a/deploy/tools/sitemap-generator/next-sitemap.config.js +++ b/deploy/tools/sitemap-generator/next-sitemap.config.js @@ -1,8 +1,46 @@ -/* eslint-disable no-console */ const path = require('path'); const stripTrailingSlash = (str) => str[str.length - 1] === '/' ? str.slice(0, -1) : str; +const isEnvTrue = (name) => process.env[name] === 'true'; +const isEnvFalse = (name) => process.env[name] === 'false'; +const isEnvSet = (name) => Boolean(process.env[name]); + +const isRollup = () => isEnvSet('NEXT_PUBLIC_ROLLUP_TYPE'); +const isMultichain = () => isEnvTrue('NEXT_PUBLIC_MULTICHAIN_ENABLED'); +const hasBeaconDeposits = () => isEnvTrue('NEXT_PUBLIC_HAS_BEACON_CHAIN') && !isEnvTrue('NEXT_PUBLIC_BEACON_CHAIN_WITHDRAWALS_ONLY'); + +// A route is left out of the sitemap when its predicate holds for the instance's env. +const HIDDEN_ROUTES = new Map(Object.entries({ + '/batches': () => !isRollup() && !hasBeaconDeposits(), + '/deposits': () => !isRollup() && !hasBeaconDeposits(), + '/withdrawals': () => !isRollup() && !isEnvTrue('NEXT_PUBLIC_HAS_BEACON_CHAIN'), + '/dispute-games': () => process.env.NEXT_PUBLIC_ROLLUP_TYPE !== 'optimistic', + '/blobs': () => !isEnvTrue('NEXT_PUBLIC_DATA_AVAILABILITY_ENABLED'), + '/name-services': () => !isEnvSet('NEXT_PUBLIC_NAME_SERVICE_API_HOST') || !isEnvSet('NEXT_PUBLIC_CLUSTERS_API_HOST'), + '/ops': () => !isEnvTrue('NEXT_PUBLIC_HAS_USER_OPS'), + '/output-roots': () => !isEnvTrue('NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED'), + '/interop-messages': () => !isEnvTrue('NEXT_PUBLIC_INTEROP_ENABLED'), + '/pools': () => !isEnvTrue('NEXT_PUBLIC_DEX_POOLS_ENABLED'), + '/advanced-filter': () => isEnvFalse('NEXT_PUBLIC_ADVANCED_FILTER_ENABLED'), + '/apps': () => !isEnvTrue('NEXT_PUBLIC_MARKETPLACE_ENABLED'), + // on chains served by the Blockscout API the page only exists when tabs are configured explicitly + '/api-docs': () => process.env.NEXT_PUBLIC_API_DOCS_TABS === '[]' || + (isEnvTrue('NEXT_PUBLIC_PRO_API_SUPPORTED') && !isEnvSet('NEXT_PUBLIC_API_DOCS_TABS')), + '/gas-tracker': () => isEnvFalse('NEXT_PUBLIC_GAS_TRACKER_ENABLED'), + '/stats': () => !isEnvSet('NEXT_PUBLIC_STATS_API_HOST'), + '/uptime': () => !isEnvSet('NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_METRICS'), + '/validators': () => !isEnvSet('NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE'), + '/epochs': () => !isEnvTrue('NEXT_PUBLIC_CELO_ENABLED'), + '/operations': () => !isEnvSet('NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST'), + '/public-tags/submit': () => !isEnvSet('NEXT_PUBLIC_ADMIN_SERVICE_API_HOST') || !isEnvSet('NEXT_PUBLIC_METADATA_SERVICE_API_HOST'), + '/txn-withdrawals': () => process.env.NEXT_PUBLIC_ROLLUP_TYPE !== 'arbitrum', + '/hot-contracts': () => !isEnvTrue('NEXT_PUBLIC_HOT_CONTRACTS_ENABLED'), + '/block/countdown': isMultichain, + '/contract-verification': isMultichain, + '/visualize/sol2uml': isMultichain, +})); + const fetchResource = async(url, formatter) => { console.log('🌀 [next-sitemap] Fetching resource:', url); try { @@ -30,12 +68,12 @@ const fetchResource = async(url, formatter) => { }; const fetchDapps = async() => { - if(process.env.NEXT_PUBLIC_MARKETPLACE_ENABLED !== 'true'){ + if (process.env.NEXT_PUBLIC_MARKETPLACE_ENABLED !== 'true') { return; } const formatter = (data) => { - if(!Array.isArray(data)){ + if (!Array.isArray(data)) { return []; } @@ -55,20 +93,20 @@ const fetchDapps = async() => { return 0; }) .slice(0, 50) - .map(({ id }) => ({ path: `/apps/${ id }/info` })) + .map(({ id }) => ({ path: `/apps/${ id }/info` })); }; const configUrl = process.env.NEXT_PUBLIC_MARKETPLACE_CONFIG_URL; - if(configUrl){ + if (configUrl) { return fetchResource(configUrl, formatter); } const api = process.env.NEXT_PUBLIC_ADMIN_SERVICE_API_HOST; const instanceId = process.env.NEXT_PUBLIC_ADMIN_RS_INSTANCE_ID || process.env.NEXT_PUBLIC_NETWORK_ID; - if(api && instanceId){ + if (api && instanceId) { return fetchResource(`${ stripTrailingSlash(api) }/api/v1/chains/${ instanceId }/marketplace/dapps`, formatter); } -} +}; const siteUrl = [ process.env.NEXT_PUBLIC_APP_PROTOCOL || 'https', @@ -112,7 +150,7 @@ const fetchStatsCharts = async() => { (section) => (section.charts || []).map(({ id }) => ({ path: `/stats/${ id }` })), ), ); -} +}; /** @type {import('next-sitemap').IConfig} */ module.exports = { @@ -124,7 +162,7 @@ module.exports = { { userAgent: '*', allow: '/', - disallow: ['/auth/*', '/login', '/chakra', '/sprite', '/account/*'], + disallow: [ '/auth/*', '/login', '/chakra', '/sprite', '/account/*' ], }, ], }, @@ -138,125 +176,8 @@ module.exports = { '/chakra', ], transform: async({ lastmod, ...config }, path) => { - switch (path) { - case '/batches': - case '/deposits': - if (!process.env.NEXT_PUBLIC_ROLLUP_TYPE && (process.env.NEXT_PUBLIC_HAS_BEACON_CHAIN !== 'true' || process.env.NEXT_PUBLIC_BEACON_CHAIN_WITHDRAWALS_ONLY === 'true')) { - return null; - } - break; - case '/withdrawals': - if (!process.env.NEXT_PUBLIC_ROLLUP_TYPE && process.env.NEXT_PUBLIC_HAS_BEACON_CHAIN !== 'true') { - return null; - } - break; - case '/dispute-games': - if (process.env.NEXT_PUBLIC_ROLLUP_TYPE !== 'optimistic') { - return null; - } - break; - case '/blobs': - if (process.env.NEXT_PUBLIC_DATA_AVAILABILITY_ENABLED !== 'true') { - return null; - } - break; - case '/name-services': - if (!process.env.NEXT_PUBLIC_NAME_SERVICE_API_HOST || !process.env.NEXT_PUBLIC_CLUSTERS_API_HOST) { - return null; - } - break; - case '/ops': - if (process.env.NEXT_PUBLIC_HAS_USER_OPS !== 'true') { - return null; - } - break; - case '/output-roots': - if (process.env.NEXT_PUBLIC_ROLLUP_OUTPUT_ROOTS_ENABLED !== 'true') { - return null; - } - break; - case '/interop-messages': - if (process.env.NEXT_PUBLIC_INTEROP_ENABLED !== 'true') { - return null; - } - break; - case '/pools': - if (process.env.NEXT_PUBLIC_DEX_POOLS_ENABLED !== 'true') { - return null; - } - break; - case '/advanced-filter': - if (process.env.NEXT_PUBLIC_ADVANCED_FILTER_ENABLED === 'false') { - return null; - } - break; - case '/apps': - if (process.env.NEXT_PUBLIC_MARKETPLACE_ENABLED !== 'true') { - return null; - } - break; - case '/api-docs': - // on chains served by the Pro API the page only exists when tabs are configured explicitly - if ( - process.env.NEXT_PUBLIC_API_DOCS_TABS === '[]' || - (process.env.NEXT_PUBLIC_PRO_API_SUPPORTED === 'true' && !process.env.NEXT_PUBLIC_API_DOCS_TABS) - ) { - return null; - } - break; - case '/gas-tracker': - if (process.env.NEXT_PUBLIC_GAS_TRACKER_ENABLED === 'false') { - return null; - } - break; - case '/stats': - if (!process.env.NEXT_PUBLIC_STATS_API_HOST) { - return null; - } - break; - case '/uptime': - if (!process.env.NEXT_PUBLIC_MEGA_ETH_SOCKET_URL_METRICS) { - return null; - } - break; - case '/validators': - if (!process.env.NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE) { - return null; - } - break; - case '/epochs': - if (process.env.NEXT_PUBLIC_CELO_ENABLED !== 'true') { - return null; - } - break; - case '/operations': - if (!process.env.NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST) { - return null; - } - break; - case '/public-tags/submit': - if (!process.env.NEXT_PUBLIC_ADMIN_SERVICE_API_HOST || !process.env.NEXT_PUBLIC_METADATA_SERVICE_API_HOST) { - return null; - } - break; - case '/txn-withdrawals': - if (!process.env.NEXT_PUBLIC_ROLLUP_TYPE || process.env.NEXT_PUBLIC_ROLLUP_TYPE !== 'arbitrum') { - return null; - } - break; - case '/hot-contracts': - if (process.env.NEXT_PUBLIC_HOT_CONTRACTS_ENABLED !== 'true') { - return null; - } - break; - // disabled routes for multichain - case '/block/countdown': - case '/contract-verification': - case '/visualize/sol2uml': - if (process.env.NEXT_PUBLIC_MULTICHAIN_ENABLED === 'true') { - return null; - } - break; + if (HIDDEN_ROUTES.get(path)?.()) { + return null; } return { @@ -268,14 +189,14 @@ module.exports = { }; }, additionalPaths: async(config) => { - if(process.env.NEXT_PUBLIC_MULTICHAIN_ENABLED === 'true'){ + if (isMultichain()) { return; } const addresses = fetchResource( `${ apiUrl }/addresses`, (data) => data.items.map(({ hash }) => ({ - path: `/address/${ hash }` + path: `/address/${ hash }`, })), ); const txs = fetchResource( @@ -294,34 +215,29 @@ module.exports = { ); const tokens = fetchResource( `${ apiUrl }/tokens`, - (data) => data.items.map(({ address_hash }) => ({ - path: `/token/${ address_hash }` + (data) => data.items.map(({ address_hash: addressHash }) => ({ + path: `/token/${ addressHash }`, })), ); - const contracts = process.env.NEXT_PUBLIC_HOT_CONTRACTS_ENABLED === 'true' ? + const contracts = isEnvTrue('NEXT_PUBLIC_HOT_CONTRACTS_ENABLED') ? fetchResource( `${ apiUrl }/stats/hot-smart-contracts?scale=30d`, - (data) => data.items.map(({ contract_address }) => ({ - path: `/address/${ contract_address.hash }?tab=contract` + (data) => data.items.map(({ contract_address: contractAddress }) => ({ + path: `/address/${ contractAddress.hash }?tab=contract`, })), - ) : + ) : fetchResource( `${ apiUrl }/smart-contracts`, (data) => data.items.map(({ address }) => ({ - path: `/address/${ address.hash }?tab=contract` + path: `/address/${ address.hash }?tab=contract`, })), ); const dapps = fetchDapps(); const statsCharts = fetchStatsCharts(); - return Promise.all([ - ...(await addresses || []), - ...(await txs || []), - ...(await blocks || []), - ...(await tokens || []), - ...(await contracts || []), - ...(await dapps || []), - ...(await statsCharts || []), - ].map(({ path, lastmod }) => config.transform({ ...config, lastmod }, path))); + const paths = (await Promise.all([ addresses, txs, blocks, tokens, contracts, dapps, statsCharts ])) + .flatMap((items) => items || []); + + return Promise.all(paths.map(({ path, lastmod }) => config.transform({ ...config, lastmod }, path))); }, }; diff --git a/deploy/tools/sitemap-generator/package.json b/deploy/tools/sitemap-generator/package.json index 86150ba0980..b58cd40a4a7 100644 --- a/deploy/tools/sitemap-generator/package.json +++ b/deploy/tools/sitemap-generator/package.json @@ -5,7 +5,13 @@ "keywords": [], "author": "", "description": "", + "scripts": { + "dev": "./dev.sh" + }, "dependencies": { "next-sitemap": "4.2.3" + }, + "devDependencies": { + "dotenv-cli": "10.0.0" } } diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index fe7a838f9b3..1f575c61fda 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -26,7 +26,7 @@ Please note that we accept contributions for newly submitted issues or those lab cd <fork_name> ``` -3. Make sure you're running Node.js 20+ and NPM 10+; if not, upgrade it accordingly, for example using [nvm](https://github.com/nvm-sh/nvm). +3. Make sure you're running Node.js 24+ and NPM 10+; if not, upgrade it accordingly, for example using [nvm](https://github.com/nvm-sh/nvm). ```sh node -v npm -v @@ -58,18 +58,18 @@ And of course our premier language is [Typescript](https://www.typescriptlang.or To develop locally, follow one of the two paths outlined below: -A. Custom configuration: +A. Pre-defined configuration (fetched from a live instance): -1. Create `.env.local` file in the root folder and include all required environment variables from the [list](./ENVS.md) -2. Optionally, clone `.env.example` and name it `.env.secrets`. Fill it with necessary secrets for integrating with [external services](./ENVS.md#external-services-configuration). Include only secrets you need. -3. Use `pnpm dev` command to start the Dev Server. +1. Optionally, clone `.env.example` file into `.env.secrets` (repo root). Fill it with necessary secrets for integrating with [external services](./ENVS.md#external-services-configuration). Include only secrets you need. (Most public keys already come from the fetched instance config.) +2. Choose an instance alias from `tools/dev-server/registry.json` (for example, `eth` or `base`). +3. Start your local Dev Server using the `pnpm dev:preset <alias>` command — it fetches that instance's config from `<url>/node-api/config` at startup and writes it to `.env.tmp`. 4. Open your browser and navigate to the URL provided in the command line output (by default, it is `http://localhost:3000`). -B. Pre-defined configuration (fetched from a live instance): +B. Local backend or custom configuration: -1. Optionally, clone `.env.example` file into `.env.secrets` (repo root). Fill it with necessary secrets for integrating with [external services](./ENVS.md#external-services-configuration). Include only secrets you need. (Most public keys already come from the fetched instance config.) -2. Choose an instance alias from `tools/dev-server/registry.json` (for example, `eth` or `base`). -3. Start your local Dev Server using the `pnpm dev:preset <alias>` command — it fetches that instance's config from `<url>/node-api/config` at startup and writes it to `.env.tmp`. To run against a local backend instead, use `pnpm dev:local`. +1. Optionally, clone `.env.example` and name it `.env.secrets`, as above. +2. To run against a locally running Blockscout backend, nothing else is needed — the committed `tools/dev-server/.env.localhost` is the base config. For a custom configuration, create `.env.local` in the root folder with the environment variables from the [list](./ENVS.md); it overrides `.env.localhost`. +3. Start your local Dev Server using the `pnpm dev:local` command. 4. Open your browser and navigate to the URL provided in the command line output (by default, it is `http://localhost:3000`). To add or override an ENV for your branch (e.g. a new variable not yet on the instance), put it in the committed `.env.extra` file — it is layered over the fetched config for both the dev server and the review deploy. Personal, local-only overrides go in `.env.local` (git-ignored). @@ -105,16 +105,9 @@ These are the steps that you have to follow to make everything work: 5. Add the variable to CI configs where it is needed - `deploy/values/review/values.yaml.gotmpl` - review development environment - `deploy/values/review-2/values.yaml.gotmpl` - review development environment (second instance) -6. If your variable is meant to receive a link to some external resource (image or JSON-config file), extend the array `ASSETS_ENVS` in `deploy/scripts/download_assets.sh` with your variable name -7. Add validation schema for the new variable into the file `deploy/tools/envs-validator/schema.ts` -8. Check if modified validation schema is valid by doing the following steps: - - change your current directory to `deploy/tools/envs-validator` - - install deps with `pnpm` command - - add your variable into `./test/.env.base` test preset or create a new test preset if needed - - if your variable contains a link to the external JSON config file: - - add example of file content into `./test/assets` directory; the file name should be constructed by stripping away prefix `NEXT_PUBLIC_` and postfix `_URL` if any, and converting the remaining string to lowercase (for example, `NEXT_PUBLIC_MARKETPLACE_CONFIG_URL` will become `marketplace_config.json`) - - in the main script `index.ts` extend array `envsWithJsonConfig` with your variable name - - run `pnpm test` command to see the validation result +6. If your variable is meant to receive a link to some external resource (image, JSON-config file or HTML snippet), register it in `ASSET_ENVS` in `deploy/tools/assets-downloader/assets.ts`; Step 5 of `.agents/skills/add-env-var/SKILL.md` describes the registration +7. Add a validation rule for the new variable to the schemas in `deploy/tools/envs-validator` and cover it in the sibling `*.spec.ts` file; `deploy/tools/envs-validator/CONTEXT.md` describes where the rule goes and how the specs are written +8. Run `pnpm test:vitest deploy/tools/envs-validator` to see the validation result 9. Don't forget to mention in the PR notes that new ENV variable was added   @@ -142,7 +135,9 @@ We have 3 pre-configured projects. You can run your test with the desired projec - `mobile` - project for testing on mobile devices, uses Safari mobile browser; add tag `+@mobile` to run test with this project - `dark-color-mode` - project for testing app in the dark color mode, uses desktop Chrome desktop device with forced dark color mode; add tag `+@dark-mode` to run test with this project. -*Note* that, since we are developing not on the same operating system as our CI system, we have to use Docker to generate or update the screenshots. In order to do that use `pnpm test:pw:docker <path-to-file> --update-snapshots` command. Please **do not commit** any screenshots generated via `pnpm test:pw:local` command, their associated tests will fail in the CI run. +Run the tests with `pnpm test:pw` (the whole suite) or `pnpm test:pw --changed` (only the tests affected by your branch's diff against `origin/main`, which is what CI runs on a pull request). + +*Note* that, since we are developing not on the same operating system as our CI system, we have to use Docker to generate or update the screenshots. In order to do that use `pnpm test:pw --docker <path-to-file> --update-snapshots` command (after a one-off `pnpm test:pw --docker-deps`). Please **do not commit** any screenshots generated via a plain local `pnpm test:pw` run, their associated tests will fail in the CI run.   @@ -177,37 +172,43 @@ We have 3 pre-configured projects. You can run your test with the desired projec 1. Push your changes and create a Pull Request. If you are still working on the task, please use "Draft Pull Request" option, so we know that it is not ready yet. In addition, you can add label "skip checks" to your PR, so all CI checks will not be triggered. 2. Once you finish your work, remove label "skip checks" from PR, if it was added before, and publish PR if it was in the draft state 3. Make sure that all code checks and tests are successfully passed -4. Add description to your Pull Request and link an existing issue(s) that it is fixing +4. Fill in every section of the Pull Request template, link the issue(s) it fixes, and add a category label; the PR check enforces both, see the [label rules](./RELEASING.md#labels) 5. Request review from one or all core team members: @tom2drum, @isstuev. Our core team is committed to reviewing patches in a timely manner. 6. After code review is done, we merge pull requests by squashing all commits and editing the commit message if necessary using the GitHub user interface. -*Note*, if you Pull Request contains any changes that are not backwards compatible with the previous versions of the app, please specify them in PR description and add label ["breaking changes"](https://github.com/blockscout/frontend/labels/breaking%20changes) to it. +*Note*, if you Pull Request contains any changes that are not backwards compatible with the previous versions of the app, please specify them in PR description and add the `breaking changes` label to it (all labels are described in [ISSUE_LABELS.md](./ISSUE_LABELS.md)). *Note*, if your Pull Request adds a feature that is not privacy-compliant (e.g. tracking, analytics, or a third-party service), make sure it is disabled in private mode, so a privacy-focused deployment can turn it off.   +## Releasing + +How a release is cut, put on staging and published, and how a merged PR gets into one, is in [RELEASING.md](./RELEASING.md). + +  + ## Commands list | Command | Description | | --- | --- | | **Running and building** | -| `pnpm dev` | run local Dev Server with user's configuration | | `pnpm dev:preset <config_preset_name>` | run local Dev Server with predefined configuration | +| `pnpm dev:local` | run local Dev Server against a local backend / user's configuration | +| `pnpm prod:preset <config_preset_name>` | production build + start with predefined configuration | | `pnpm build:docker` | build a docker image locally | -| `pnpm start:docker:local` | start an application from previously built local docker image with user's configuration | +| `pnpm start:docker:local` | start an application from previously built local docker image against a local backend / user's configuration | | `pnpm start:docker:preset <config_preset_name>` | start an application from previously built local docker image with predefined configuration | | **Linting and formatting** | -| `pnpm lint:eslint` | lint project files with ESLint | -| `pnpm lint:eslint:fix` | lint project files with ESLint and automatically fix problems | +| `pnpm lint:eslint [--changed[=<ref>]] [--fix] [<path>...]` | lint project files with ESLint: the whole repo, the given paths, or the files changed vs `<ref>` (default `origin/main`); `--fix` and other eslint flags pass through | | `pnpm lint:tsc` | compile project typescript files using TypeScript Compiler | | `pnpm svg:format` | format and optimize SVG icons in the `/icons` folder using SVGO tool | | `pnpm svg:build-sprite` | build SVG icons sprite | | **Testing** | | `pnpm test:vitest` | run all Vitest unit tests | -| `pnpm test:pw:local` | run Playwright component tests locally | -| `pnpm test:pw:docker` | run Playwright component tests in docker container | -| `pnpm test:pw:ci` | run Playwright component tests in CI | +| `pnpm test:pw` | run Playwright component tests locally; `--changed` runs only the tests affected by the branch's diff, `--help` lists the tool's flags | +| `pnpm test:pw:docker` | alias of `pnpm test:pw --docker`: run Playwright component tests in a docker container (required to generate screenshots) | +| `pnpm test:pw:docker:deps` | alias of `pnpm test:pw --docker-deps`: install the Linux dependencies the docker run mounts (once) |   diff --git a/docs/ENVS.md b/docs/ENVS.md index 0b45338dee7..61763752b9c 100644 --- a/docs/ENVS.md +++ b/docs/ENVS.md @@ -21,6 +21,11 @@ Please be aware that all environment variables prefixed with `NEXT_PUBLIC_` will ### Note about escaping variables values All json-like values should be single-quoted. If it contains a hash (`#`) or a dollar-sign (`$`) the whole value should be wrapped in single quotes as well (see `dotenv` [readme](https://github.com/bkeepers/dotenv#variable-substitution) for the reference) +### HTML values +A variable whose description says it accepts HTML code is rendered as HTML on the app's own origin, so its markup is limited to text formatting, links and images. `<script>`, `<iframe>`, `<form>`, `<svg>`, `<object>`, inline `style` attributes, `on*` event handlers and `javascript:` links are rejected at startup, with a message naming what was found, and stripped from the rendered markup. + +The value is used as set: apostrophes and single-quoted attribute values stay as they are (unlike json-like values, no quote rewriting happens). A variable typed `Array<string>` takes a JSON list of such strings. Double-quote its items and put HTML attribute values in single quotes or escape their double quotes, for example `["Hello", "<a href='https://example.com'>Link!</a>"]`; the single-quoted form `['Hello', '<b>World</b>']` also works as long as no item itself contains a single quote. +   ## Table of contents @@ -69,6 +74,7 @@ All json-like values should be single-quoted. If it contains a hash (`#`) or a d - [API documentation](#api-documentation) - [Blockchain statistics](#blockchain-statistics) - [Bridged tokens](#bridged-tokens) + - [Bubblemaps](#bubblemaps) - [Chain variants](#chain-variants) - [Connect wallet](#connect-wallet) - [Cross-chain transactions](#cross-chain-transactions) @@ -102,12 +108,13 @@ All json-like values should be single-quoted. If it contains a hash (`#`) or a d - [Google ReCaptcha](#google-recaptcha) - [GrowthBook](#growthbook) - [Mixpanel](#mixpanel) + - [PostHog](#posthog) - [OpenTelemetry](#opentelemetry) - [Rollbar](#rollbar) - [Usercentrics CMP](#usercentrics-cmp) - [Misc](#misc) - [Design system](#design-system) - - [Pro API support](#pro-api-support) + - [Blockscout API support](#blockscout-api-support)   @@ -323,7 +330,7 @@ The repository targets and link type can be overwritten at run-time with the var | Variable | Type | Description | Compulsoriness | Default value | Example value | Version | | --- | --- | --- | --- | --- | --- | --- | -| NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE | `string \| Array<string>` | Used to display custom announcements or alerts in the site's header, this feature can handle a single instance or an array of regular strings or HTML code. If an array of instances is provided, the banners will rotate randomly each time the user reloads the page. In this case, please ensure that you properly escape the values of HTML attributes or other special symbols (for example, `<a href=\\"https://example.com\\">Link!</a>`). | - | - | `Hello world! 🤪` | v1.13.0+ | +| NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE | `string \| Array<string>` | Used to display custom announcements or alerts in the site's header, this feature can handle a single instance or an array of regular strings or HTML code (see [HTML values](#html-values)). If an array of instances is provided, the banners will rotate randomly each time the user reloads the page. | - | - | `Hello world! 🤪` | v1.13.0+ |   @@ -386,8 +393,13 @@ Meta tags, Open Graph, and SEO. | NEXT_PUBLIC_FEATURED_NETWORKS | `string` | URL of configuration file (`.json` format only) or file content string representation. It contains list of featured networks that will be shown in the network menu. See [below](#featured-network-configuration-properties) list of available properties for particular network | - | - | `https://example.com/featured_networks_config.json` \| `[{'title':'Astar(EVM)','url':'https://astar.blockscout.com/','group':'Mainnets','icon':'https://example.com/astar.svg'}]` | v1.0.x+ | | NEXT_PUBLIC_FEATURED_NETWORKS_ALL_LINK | `string` | Link to the all chains resource. Will be displayed at the bottom of featured networks list. | Works only if NEXT_PUBLIC_FEATURED_NETWORKS is set | - | `https://example.com` | v2.3.0+ | | NEXT_PUBLIC_FEATURED_NETWORKS_MODE | `tabs \| list` | Indicates how the networks are presented: in one list or in separate tabs. | Works only if NEXT_PUBLIC_FEATURED_NETWORKS is set | `list` | `tabs` | v2.5.0+ | +<<<<<<< HEAD | NEXT_PUBLIC_COLOR_THEMES | `Array<'light' \| 'dim' \| 'midnight' \| 'dark'>` | Color themes the app offers in the settings menu. | - | all themes | `['light', 'dark']` | upcoming | | NEXT_PUBLIC_COLOR_THEME_DEFAULT | `'light' \| 'dim' \| 'midnight' \| 'dark'` | Preferred color theme of the app. Must be one of the themes listed in NEXT_PUBLIC_COLOR_THEMES, if that variable is set. | - | none, unless the themes offered by NEXT_PUBLIC_COLOR_THEMES cannot cover both light and dark `prefers-color-scheme`, in which case the last (darkest) one of them | `midnight` | v1.30.0+ | +======= +| NEXT_PUBLIC_COLOR_THEMES | `Array<'light' \| 'dim' \| 'midnight' \| 'dark' \| 'system'>` | Color themes the app offers in the settings menu. The `system` theme ("Auto (System)") follows the OS `prefers-color-scheme` and is offered only when the list also covers both a light and a dark theme. | - | all themes | `['light', 'dark', 'system']` | v2.11.2+ | +| NEXT_PUBLIC_COLOR_THEME_DEFAULT | `'light' \| 'dim' \| 'midnight' \| 'dark' \| 'system'` | Preferred color theme of the app. Must be one of the themes listed in NEXT_PUBLIC_COLOR_THEMES, if that variable is set. | - | `system`, unless the themes offered by NEXT_PUBLIC_COLOR_THEMES cannot cover both light and dark `prefers-color-scheme`, in which case the last (darkest) one of them | `midnight` | v1.30.0+ | +>>>>>>> v2.13.0 | NEXT_PUBLIC_COLOR_THEME_OVERRIDES | `string` | Color overrides for the default theme; pass a JSON-like string that represents a subset of the `DEFAULT_THEME_COLORS` object (see `toolkit/theme/foundations/colors.ts`) to customize the app's main colors. See [here](https://www.figma.com/design/4In0X8UADoZaTfZ34HaZ3K/Blockscout-design-system?node-id=29124-23813&t=XOv4ahHUSsTDlNkN-4) the Figma worksheet with description of available color tokens. | - | - | `{'text':{'primary':{'_light':{'value':'rgba(16,17,18,0.80)'},'_dark':{'value':'rgba(222,217,217)'}}}}` | v2.3.0+ | #### Featured network configuration properties @@ -427,6 +439,7 @@ Meta tags, Open Graph, and SEO. | Variable | Type | Description | Compulsoriness | Default value | Example value | Version | | --- | --- | --- | --- | --- | --- | --- | | NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_FIELDS | `Array<BlockFieldId>` | Array of the block fields ids that should be hidden. See below the list of the possible id values. | - | - | `'["burnt_fees","total_reward"]'` | v1.10.0+ | +| NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_VIEWS | `Array<BlockViewId>` | Block views that should be hidden. See below the list of the possible id values. | - | - | `'["reorgs","uncles"]'` | v2.13.0+ | | NEXT_PUBLIC_VIEWS_BLOCK_PENDING_UPDATE_ALERT_ENABLED | `boolean` | The flag enables indication of the incomplete data for the block in the list and detailed views of the re-indexing block and its transactions. *Feature is enabled by default; pass `false` to disable it.* | - | `true` | `false` | v2.4.0+ | #### Block fields list @@ -440,6 +453,12 @@ Meta tags, Open Graph, and SEO. | `L1_status` | Short interpretation of the batch lifecycle (applicable for Rollup chains) | | `batch` | Batch index (applicable for Rollup chains) | +#### Block views list +| Id | Description | +| --- | --- | +| `reorgs` | Forked blocks tab on the blocks page | +| `uncles` | Uncle blocks tab on the blocks page | +   ### Chain @@ -610,8 +629,8 @@ _Note_ Some properties can hold an array of up to two strings. The first string | NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED | `boolean` | Set to true if network has account feature | Required | - | `true` | v1.0.x+ | | NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER | `auth0 \| dynamic` | Auth provider that enables basic user authentication. | - | `auth0` | `dynamic` | v2.7.0+ | | NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID | `string` | Environment ID of the Dynamic project. | Required, if provider is `dynamic` | - | `<your-secret>` | v2.7.0+ | -| NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE | `string` | Used for displaying custom alerts on the API keys page. Could be a regular string or HTML code. On chains supported by the Blockscout Pro API the page shows a built-in deprecation notice by default; this variable overrides it, and an empty value hides it. | - | - | `Hello world! 🤪` | v2.7.0+ | -| NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML | `string` | Payment instructions shown in the "Need a faster review?" block of the token info application form, as a regular string or HTML code. Setting it enables the block; leaving it empty hides it. Only applies when the address verification workflow is enabled. | - | - | `Send <b>99 USDC</b> to <code>0x123…</code>` | v2.11.0+ | +| NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE | `string` | Used for displaying custom alerts on the API keys page. Could be a regular string or HTML code (see [HTML values](#html-values)). On chains supported by the Blockscout API the page shows a built-in deprecation notice by default; this variable overrides it, and an empty value hides it. | - | - | `Hello world! 🤪` | v2.7.0+ | +| NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML | `string` | Payment instructions shown in the "Need a faster review?" block of the token info application form, as a regular string or HTML code (see [HTML values](#html-values)). Setting it enables the block; leaving it empty hides it. Only applies when the address verification workflow is enabled. | - | - | `Send <b>99 USDC</b> to <code>0x123…</code>` | v2.11.0+ | **Dependencies** @@ -745,7 +764,7 @@ This feature is **enabled by default**. To switch it off pass `NEXT_PUBLIC_ADVAN | Variable | Type | Description | Compulsoriness | Default value | Example value | Version | | --- | --- | --- | --- | --- | --- | --- | -| NEXT_PUBLIC_API_DOCS_TABS | `Array<TabId>` | Controls which tabs appear on the API documentation page. Possible values for `TabId` are `rest_api`, `eth_rpc_api`, `rpc_api`, and `graphql_api`. **Note** that this variable has a default value, so the feature is enabled by default. Pass an empty array to disable it. On chains supported by the Blockscout Pro API the page is not rendered unless this variable is set, and the "API" navigation item links to the Blockscout developer portal instead. | - | `['rest_api','eth_rpc_api','rpc_api','graphql_api']` | `[]` | v2.3.x+ | +| NEXT_PUBLIC_API_DOCS_TABS | `Array<TabId>` | Controls which tabs appear on the API documentation page. Possible values for `TabId` are `rest_api`, `eth_rpc_api`, `rpc_api`, and `graphql_api`. **Note** that this variable has a default value, so the feature is enabled by default. Pass an empty array to disable it. On chains supported by the Blockscout API the page is not rendered unless this variable is set, and the "API" navigation item links to the Blockscout developer portal instead. | - | `['rest_api','eth_rpc_api','rpc_api','graphql_api']` | `[]` | v2.3.x+ | | NEXT_PUBLIC_API_DOCS_ALERT_MESSAGE | `string` | Used for displaying custom alerts on the API documentation page. Could be a regular string or HTML code. Deprecated — no longer has any effect and will be removed in the next release. | - | - | `Hello world! 🤪` | v2.7.0+ | **Dependencies** @@ -798,6 +817,18 @@ This feature allows users to view tokens that have been bridged from other EVM c | short_title | `string` | Bridge short title for displaying in the tags | Required | - | `OMNI` |   + +### Bubblemaps + +Embeds the [Bubblemaps](https://bubblemaps.io) holder map as a "Bubblemaps" sub-tab of the "Holders" tab on the ERC-20 token page. + +| Variable | Type | Description | Compulsoriness | Default value | Example value | Version | +| --- | --- | --- | --- | --- | --- | --- | +| NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG | `string` | Bubblemaps chain identifier of the network, see the [supported chains](https://docs.bubblemaps.io/iframe/quickstart) | Required | - | `eth` | v2.13.0+ | +| NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID | `string` | Bubblemaps partner ID issued for the explorer's domains | Required | - | `demo` | v2.13.0+ | + +  + ### Chain variants #### Beacon chain @@ -890,6 +921,8 @@ This feature enables cross-chain transaction tracking and visualization, allowin | Variable | Type | Description | Compulsoriness | Default value | Example value | Version | | --- | --- | --- | --- | --- | --- | --- | | NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED | `boolean` | The flag that enables the feature | Required | - | `true` | v2.7.0+ | +| NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS | `Array<number>` | Ids of the interchain indexer bridges whose messages and transfers this instance is allowed to show. The indexer is shared between deployments and indexes every bridge it knows about, so the ids define this instance's slice of it. | Required | - | `'[1,2]'` | v2.12.0+ | +| NEXT_PUBLIC_CROSS_CHAIN_TXS_INCLUDE_UNINDEXED_CHAINS | `boolean` | Set to `true` to also show messages and transfers whose counterparty chain is not indexed by any of the configured bridges. Such rows have an incomplete counterparty side. | - | `false` | `true` | v2.12.0+ | **Dependencies** @@ -928,7 +961,11 @@ If the feature is enabled, a single button or a dropdown (if more than 1 item is | Variable | Type | Description | Compulsoriness | Default value | Example value | Version | | --- | --- | --- | --- | --- | --- | --- | | NEXT_PUBLIC_DEFI_DROPDOWN_ITEMS | `[{ text: string; icon?: string; dappId?: string, url?: string, isEssentialDapp?: boolean }]` | An array of dropdown items containing the button text, icon name and dappId in Dappscout or an external url | - | - | `[{'text':'Swap','icon':'swap','dappId':'swap','isEssentialDapp':true},{'text':'Payment link','icon':'payment_link','dappId':'peanut-protocol'}]` | v1.31.0+ | +<<<<<<< HEAD | NEXT_PUBLIC_DEFI_DROPDOWN_BUTTON_TEXT | `{ desktop: string; mobile?: string }` | Text on the button that opens the dropdown. `mobile` is the shorter form shown on narrow screens. Keep `desktop` within ~24 characters and `mobile` within ~10. | - | `{'desktop':'Blockscout DeFi','mobile':'DeFi'}` | `{'desktop':'MyChain DeFi','mobile':'DeFi'}` | upcoming | +======= +| NEXT_PUBLIC_DEFI_DROPDOWN_BUTTON_TEXT | `{ desktop: string; mobile?: string }` | Text on the button that opens the dropdown. `mobile` is the shorter form shown on narrow screens. Keep `desktop` within ~24 characters and `mobile` within ~10. | - | `{'desktop':'Blockscout DeFi','mobile':'DeFi'}` | `{'desktop':'MyChain DeFi','mobile':'DeFi'}` | v2.11.2+ | +>>>>>>> v2.13.0   @@ -1065,7 +1102,7 @@ Essential dapps are built-in dapps that are displayed on the Marketplace page in | Property | Type | Description | Compulsoriness | Example value | | --- | --- | --- | --- | --- | -| swap | `{ url: string, chains: Array<string>, fee: string, integrator: string }` | Swap config | - | `{'url': 'https://example.com', 'chains': ['1'], 'fee': '0.004', 'integrator': 'blockscout'}` | +| swap | `{ chains: Array<string>, fee: string, integrator: string }` | Swap config | - | `{'chains': ['1'], 'fee': '0.004', 'integrator': 'blockscout'}` | | revoke | `{ chains: Array<string> }` | Revoke config | - | `{'chains': ['100']}` | | multisend | `{ chains: Array<string> }` | Multisend config | - | `{'chains': ['1', '10']}` | @@ -1087,7 +1124,7 @@ If the feature is enabled, a Multichain balance button will be displayed on the | Variable | Type | Description | Compulsoriness | Default value | Example value | Version | | --- | --- | --- | --- | --- | --- | --- | -| NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG | `[{ name: string; url_template: string; dapp_id?: string; logo: string }]` | Multichain portfolio application config. See [below](#multichain-button-configuration-properties) | - | - | `[{ name: 'zerion', url_template: 'https://app.zerion.io/{address}/overview', logo: 'https://example.com/icon.svg'}]` | v1.31.0+ | +| NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG | `[{ name: string; url_template: string; dapp_id?: string; logo: string; view?: 'full' \| 'icon' }]` | Multichain portfolio application config. See [below](#multichain-button-configuration-properties) | - | - | `[{ name: 'zerion', url_template: 'https://app.zerion.io/{address}/overview', logo: 'https://example.com/icon.svg'}]` | v1.31.0+ | #### Multichain button configuration properties @@ -1097,7 +1134,7 @@ If the feature is enabled, a Multichain balance button will be displayed on the | url_template | `string` | Url template to the portfolio. Should be a template with `{address}` variable | Required | - | `https://app.zerion.io/{address}/overview` | | dapp_id | `string` | Set for open a Blockscout dapp page with the portfolio instead of opening external app page | - | - | `zerion` | | logo | `string` | Multichain portfolio application logo (.svg) url | - | - | `https://example.com/icon.svg` | -| promo | `boolean` | Make the provider stand out by placing their logo prominently at the first place in the section and in the page subheader. | - | - | `true` | +| view | `'full' \| 'icon'` | Button view: `full` shows the logo with the name, `icon` shows the logo only | - | `full` | `icon` |   ### Multichain explorer @@ -1201,11 +1238,19 @@ Solidity-to-UML smart contract visualizer. ### Token action button +<<<<<<< HEAD An action button on the ERC-20 token page, leading to an external site. On desktop it is right-aligned in the token title row; on mobile it takes a dedicated row below the token tags. In a multichain cluster the variable is cluster-level: one button, shown on the token pages of every chain in the cluster. | Variable | Type | Description | Compulsoriness | Default value | Example value | Version | | --- | --- | --- | --- | --- | --- | --- | | NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG | `TokenActionButtonConfig`, see details [below](#token-action-button-configuration-properties) | Configuration of the button. The button is shown only when this variable is set. | - | - | `{'text':'Buy on Example Portal','url':'https://portal.example.com/swap?chainId=1&token={hash}','logo':['https://example.com/logo.svg'],'colors':{'_default':{'bg':['rgb(134, 86, 239)'],'text':['white']}}}` | upcoming | +======= +An action button on the ERC-20 token page, leading to an external site. The button is hidden on tokens whose address carries the `token-action-button-hidden` tag of the `service` type in the metadata service. + +| Variable | Type | Description | Compulsoriness | Default value | Example value | Version | +| --- | --- | --- | --- | --- | --- | --- | +| NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG | `TokenActionButtonConfig`, see details [below](#token-action-button-configuration-properties) | Configuration of the button. The button is shown only when this variable is set. | - | - | `{'text':'Buy on Example Portal','url':'https://portal.example.com/swap?chainId=1&token={hash}','logo':['https://example.com/logo.svg'],'colors':{'_default':{'bg':['rgb(134, 86, 239)'],'text':['white']}}}` | v2.13.0+ | +>>>>>>> v2.13.0 #### Token action button configuration properties @@ -1322,6 +1367,15 @@ To obtain the variable values, please refer to the [reCAPTCHA documentation](htt   +### PostHog + +| Variable | Type | Description | Compulsoriness | Default value | Example value | Version | +| --- | --- | --- | --- | --- | --- | --- | +| NEXT_PUBLIC_POSTHOG_API_KEY | `string` | Project API key for [PostHog](https://posthog.com/) product analytics | Required | - | `<your-secret>` | v2.12.0+ | +| NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES | `string` | JSON-like string with a subset of the [posthog-js config](https://posthog.com/docs/libraries/js/config) merged over the app defaults | - | - | `{"disable_session_recording": false}` | v2.12.0+ | + +  + ### OpenTelemetry OpenTelemetry SDK for the Node.js server-side process. Configure the OpenTelemetry Protocol Exporter using the generic environment variables described in the [OT docs](https://opentelemetry.io/docs/specs/otel/protocol/exporter/#configuration-options). Note that this Next.js feature is currently experimental. The Docker image must be built with `NEXT_OPEN_TELEMETRY_ENABLED=true` to enable it. @@ -1367,8 +1421,8 @@ Integrates [Usercentrics](https://usercentrics.com/) as the Consent Management P   -### Pro API support +### Blockscout API support | Variable | Type | Description | Compulsoriness | Default value | Example value | Version | | --- | --- | --- | --- | --- | --- | --- | -| NEXT_PUBLIC_PRO_API_SUPPORTED | `boolean` | Indicates whether the current chain is supported by Blockscout Pro API. **This variable is automatically set during container startup**; manual configuration is typically not needed. | - | - | `true` | v2.9.0+ | +| NEXT_PUBLIC_PRO_API_SUPPORTED | `boolean` | Indicates whether the current chain is supported by Blockscout API. **This variable is automatically set during container startup**; manual configuration is typically not needed. | - | - | `true` | v2.9.0+ | diff --git a/docs/ISSUE_LABELS.md b/docs/ISSUE_LABELS.md new file mode 100644 index 00000000000..e22382afedc --- /dev/null +++ b/docs/ISSUE_LABELS.md @@ -0,0 +1,66 @@ +# Issue and PR labels + +Every label in use on `blockscout/frontend`, by what it is for. GitHub shares one label set between +issues and PRs; the "On" column says where a label is meant to go. A label not listed here is unused: +delete it rather than pick it up. + +## Category + +The rules the PR check enforces are in [RELEASING.md](./RELEASING.md#labels); which release-notes section +each label maps to is in [RELEASING.md](./RELEASING.md#release-notes-sections), with +`tools/release/categories.ts` as its code source of truth. + +| Label | On | Meaning | +| --- | --- | --- | +| `feature` | both | New substantial feature. | +| `enhancement` | both | Improvement of an existing feature, or a small new one. | +| `client feature` | both | Feature requested by, and specific to, a client chain. | +| `bug` | both | Something isn't working. | +| `performance` | both | Performance improvement. | +| `design` | both | UI and UX changes. | +| `refactoring` | both | Code restructuring without a behaviour change. | +| `tech` | both | Building, testing, and other project tooling. | +| `devops` | both | CI, deployment, infrastructure. | +| `dependencies` | PR | A PR whose sole purpose is a package bump. | +| `chore` | both | Catch-all when nothing above fits. | + +## Release mechanics + +Read or written by the release workflow, see [RELEASING.md](./RELEASING.md). + +| Label | On | Meaning | +| --- | --- | --- | +| `backport` | PR | Set by hand on a merged PR: ship it in the release being prepared. The next `prepare` or `alpha` picks it. Replaced by the version label when the PR is released; a PR that was never picked keeps it. With two lines open, both pick it until one publishes and stamps its version label. | +| `pre-release` | both | Set by `pre-release.yml` on the PRs an alpha shipped and the issues they close; removed by `release.yml` at the final release. | +| `vX.Y.Z` | both | Set by `release.yml` on every PR the final tag shipped and the issues they close. A PR carrying a version label is never relabeled, never picked onto another release branch, and never listed in another release's notes. | +| `release` | PR | A PR of the release mechanics rather than a change to ship; the PR check skips it. | + +## Workflow state + +| Label | On | Meaning | +| --- | --- | --- | +| `triage` | issue | Needs triage. | +| `available for contribution` | issue | Open to external contributors, as newly submitted issues are; who may take the rest is in [CONTRIBUTING.md](./CONTRIBUTING.md). | +| `task for agent` | issue | Scoped for an AI agent to implement through the task workflow. | +| `epic` | issue | Umbrella issue tracking a set of sub-issues. | +| `need info` | issue | Waiting for more information from the author; `stale-issues.yml` marks it `stale` and then closes it when nothing happens. | +| `stale` | issue | Set by `stale-issues.yml`; do not set by hand. | +| `need design` | issue | Blocked on a design. | +| `need API` | issue | Blocked on a backend change. | +| `PM review` | issue | Needs a decision from the PM. | +| `research` | issue | Research task, no code expected. | +| `duplicate` | issue | Closed as a duplicate. | +| `wontfix` | issue | Closed, will not be worked on. | +| `don't merge` | PR | Not to be merged even if approved. | +| `skip checks` | PR | The Checks and CodeQL workflows do not run while it is set. For long-running drafts; remove it before review. | + +## Scope + +Orthogonal to the category; add alongside one. + +| Label | On | Meaning | +| --- | --- | --- | +| `multichain explorer` | issue | Multichain explorer work. | +| `WaaS Pilot` | issue | Wallet-as-a-Service pilot work. | +| `ENVs` | PR | Adds, changes or deprecates an environment variable (`docs/ENVS.md` changed). | +| `breaking changes` | PR | Not backwards compatible with the previous version; the PR description must say what breaks. | diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 00000000000..706fd79beae --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,95 @@ +# Releasing + +`main` is trunk. Every release `vX.Y.Z`, minor or patch, lives on its own branch `release/vX.Y.Z` and goes +through the same three phases, each one `pnpm release` subcommand: `prepare`, `alpha`, `publish`. What +each subcommand does is in `pnpm release --help`; this page is for choosing one, and for the label rules +the notes and the backports depend on. + +## I need to… + +| I need to… | Run… | +| --- | --- | +| cut the next minor | `pnpm release prepare vX.Y.0` | +| start a patch on a released line | `pnpm release prepare vX.Y.Z` (`Z > 0`; `vX.Y.(Z-1)` must be the line's latest release) | +| ship a merged PR in the release being prepared | label the PR `backport`; the next `prepare` or `alpha` picks it | +| put the release on staging | `pnpm release alpha vX.Y.Z-alpha.N` | +| fix something found on staging | PR to `main` as usual, label it `backport`, cut the next alpha | +| finalise the release | `pnpm release publish vX.Y.Z` | +| resume after a pick stopped on a conflict | resolve, `git cherry-pick --continue`, re-run the same command | +| see what a phase would do | the same command with `--dry-run` | +| preview the notes of a tag | `pnpm release notes <tag>` | +| know what a release shipped, or which release shipped a PR | the `vX.Y.Z` label on the PR: `is:pr label:vX.Y.Z` | +| check my PR before CI does | `pnpm release check-pr <number>` | + +Both `prepare` and `alpha` work on your checkout: they need a clean tree and switch to the release branch. + +## A release + +```mermaid +stateDiagram-v2 + direction LR + [*] --> Prepared: prepare vX.Y.Z + Prepared --> OnStaging: alpha vX.Y.Z-alpha.1 + OnStaging --> OnStaging: alpha vX.Y.Z-alpha.N + OnStaging --> Released: publish vX.Y.Z + Released --> [*] + note right of Prepared + release/vX.Y.Z cut from main (Z = 0) + or from vX.Y.(Z-1) (a patch); + draft pre-release created + end note + note right of OnStaging + each prepare and alpha picks the + merged backport PRs, then releases + "upcoming" in the ENV docs; + the first alpha publishes the pre-release + end note + note right of Released + final tag, release marked latest, + docs commits cherry-picked to main + end note +``` + +A release branch is never merged back to `main`. Every commit on it is a `git cherry-pick -x` of a `main` +squash commit, except the docs commits `prepare` and `alpha` make, which `publish` returns to `main` the +same way. This is what lets the notes and the labels tell a backport from new work: a branch commit is +resolved to its PR through its `(cherry picked from commit …)` trailer, then the `(#N)` in its subject. + +Each release keeps one GitHub pre-release from `prepare` to `publish`, re-pointed to every alpha: a draft +until the first alpha publishes it, so that the staging roll-up request can link to it. A line cannot have +two open at once: publish the current one before preparing the next patch. Its notes are regenerated from +the PRs at every phase; a wrong line is fixed on the PR (title, labels, body), not on the release page. + +A tag is refused, by the CLI before pushing and by CI before the image is built, when `docs/ENVS.md` or +`docs/DEPRECATED_ENVS.md` still says `upcoming`, or when its notes list a PR another release already shipped. + +## Labels + +Rules for PR authors, enforced by the PR check on every non-draft PR: + +- The body keeps every heading of `docs/PULL_REQUEST_TEMPLATE.md` and none of its placeholder text. The + "Environment variables" and "Minimum API version" sections are copied into the release notes as written. +- The PR carries labels of exactly one category from the table below. Several labels of one category are + fine; labels of two categories are not. +- A PR labeled `release` is exempt from both rules. + +What `backport`, `pre-release`, `vX.Y.Z` and `release` mean, and who sets them, is in +[ISSUE_LABELS.md](./ISSUE_LABELS.md#release-mechanics). + +## Release-notes sections + +The section a PR lands in comes from its category label. The source of truth is +`tools/release/categories.ts`; this table is checked against it by the module's spec. + +| Section | Labels | +| --- | --- | +| New Features | `feature`, `enhancement`, `client feature` | +| Bug Fixes | `bug` | +| Performance Improvements | `performance` | +| Dependencies Updates | `dependencies` | +| Design Updates | `design` | +| DX & Tooling | `refactoring`, `tech`, `devops` | +| Other Changes | `chore` | + +A PR with no category label, merged before the PR check existed, lands in "Other Changes". Empty sections +are left out of the notes. diff --git a/docs/research/eslint-alternatives-2026-10-update.md b/docs/research/eslint-alternatives-2026-10-update.md new file mode 100644 index 00000000000..034ece14390 --- /dev/null +++ b/docs/research/eslint-alternatives-2026-10-update.md @@ -0,0 +1,304 @@ +# ESLint alternatives — October 2026 update (Oxlint + Oxfmt) + +Follow-up to [`eslint-alternatives.md`](./eslint-alternatives.md) (2026-07-10). Scope: what changed for **Oxlint** in the three months since, and whether adopting **Oxfmt** as the formatter (dropping our `@stylistic` / React JSX-spacing / `max-len` rules) makes sense. Biome is out of scope per the July verdict. + +Measurements were taken 2026-10-15 on this repo (`main` @ `1c86bfc68`, clean tree, Apple M2 8 cores, Node 24.21, pnpm 12.4.1). Tool versions: oxlint **1.88.0** (released 2026-10-13), oxfmt **0.72.0/0.73.0**, oxlint-tsgolint **7.0.2004**, `@oxlint/migrate` **1.88.0**. All temporary configs lived outside the repo; the tree was restored with `git checkout` after each formatting run. + +## TL;DR / Recommendation + +1. **Oxlint: the "wait for JS plugins to stabilise" blocker is gone in practice, not on paper.** JS plugins are *still labelled alpha* in the docs, but running our **entire** ESLint config through `@oxlint/migrate` (235 rules, 11 overrides, `@stylistic` + regexp + import-helpers + playwright + boundaries + consistent-default-export-name loaded as JS plugins) produced **zero plugin runtime errors** and **zero false `@stylistic` diagnostics** on our lint-clean tree, in **~10s** wall (vs. ESLint **67s**) — **~11.6s with type-aware rules on**. Only four things did not carry over: `@typescript-eslint/naming-convention`, `no-restricted-syntax`, `react/jsx-no-bind` (not implemented natively; the latter two could be JS-plugin'd via their original plugins), and our type-aware `@eslint-react/no-leaked-conditional-rendering` (type-aware *custom* rules are explicitly unsupported in JS plugins). Our two inline/local rules (SPDX header, stryker) need to be moved to plugin files and listed under `jsPlugins` by hand. + → **A full migration is now a 1–2 week engineering task, not a wait.** The remaining risk is the alpha label itself (API churn, bugs), which the hybrid `oxlint && eslint` path from July still mitigates. Recommended sequence: hybrid first (cheap, reversible), full switch once a release or two have run clean. +2. **Oxfmt: yes, if we accept Prettier's style — and the honest cost is a repo-wide reformat.** Oxfmt (beta since Feb 2026, 100% of Prettier's JS/TS conformance suite per oxc) formats this repo in **0.45s**. With the closest config to our house style (single quotes, 2-space, semicolons, trailing commas, `printWidth: 160`) it still rewrites **2,605 of 3,099 `.ts`/`.tsx` files (84%)**, ~**47k insertions / 55k deletions** across **224k** TS lines. The unavoidable part is what the July notes predicted: Prettier has **no options** for spaces inside `[ ]`, `${ }` or JSX `{ }` — those alone account for ~12% of changed lines; the other ~80% is Prettier re-flowing JSX props and call arguments to fill the print width. + - It supersedes **all 34 `@stylistic` rules**, the four `react/jsx-*-spacing`/`wrap-multilines` rules and `max-len` (soft cap). Everything else (import order, boundaries, SPDX header, naming-convention, restricted imports, playwright/regexp/vitest/next rules) stays in oxlint/ESLint. `@oxlint/migrate` itself now tells you to "use Oxfmt for stylistic rules". + - The one real design choice is **`printWidth`**. At 160 Oxfmt collapses multi-prop JSX into very long single lines (see §3.4); **120 or 100** reads much closer to what we write today at the price of ~20% more churn. Recommend **120**. + - Import sorting: Oxfmt has a built-in `sortImports` with glob `customGroups` that *can* approximate our architecture-layer groups, but its type-import handling differs from `import-helpers`; a trial on two directories reordered imports in 128 files. **Keep `import-helpers/order-imports` (as an oxlint JS plugin or in ESLint) for the first step** and revisit `sortImports` separately. +3. **Suggested order:** (a) add oxlint hybrid (`oxlint && eslint`) — one day; (b) adopt Oxfmt in one dedicated PR with a `.git-blame-ignore-revs` entry, dropping `@stylistic` and the JSX-spacing rules in the same PR — one to two days plus coordinating the 2 open PRs; (c) later, full oxlint migration and drop ESLint. + +--- + +## 1. Oxlint — what changed since July + +### 1.1 Versions and cadence + +Weekly releases continued: oxlint 1.72 (July) → **1.88.0 (2026-10-13)**, oxfmt 0.5x → **0.73.0** ([GitHub releases](https://github.com/oxc-project/oxc/releases)). Rule count on the docs page is now **871 total, 111 on by default, 334 with fixes** ([rules list](https://oxc.rs/docs/guide/usage/linter/rules)) vs. "840+" in July. `.oxlintrc.json` is now joined by a TypeScript config file, `oxlint.config.ts` ([JS plugins docs](https://oxc.rs/docs/guide/usage/linter/js-plugins)). Nothing in the Jul–Oct release notes about a persistent cache; LSP now surfaces config errors (1.88) and JS-plugin rule timings include selector execution (1.86). + +### 1.2 JS plugins — still "alpha", but complete enough for our config + +- Docs status: **"JS plugins are currently in alpha, and remain under active development."** No beta/stable announcement exists as of 2026-10-15 (the latest blog milestone is still the [March alpha post](https://oxc.rs/blog/2026-03-11-oxlint-js-plugins-alpha); the only oxc blog post in Jul–Oct is [React Compiler support](https://oxc.rs/blog/2026-08-18-react-compiler-support)). +- Supported: AST traversal, auto-fixes/suggestions/options/selectors, SourceCode text and token APIs, scope + code-path analysis, inline disable comments, **LSP diagnostics and quick-fixes**. Unsupported: custom parsers (Vue/Svelte/Angular) and **"rules that depend on TypeScript type information"** ([JS plugins docs](https://oxc.rs/docs/guide/usage/linter/js-plugins)). +- Officially tested plugins now include **Playwright, RegExp, Stylistic, React Hooks, Testing Library, Storybook, SonarJS, Mocha, Cypress, @e18e** — i.e. three of our "exotic" plugins are on the vendor's own conformance list. +- **Measured here** (migrated config, §1.5): `@stylistic` (32 rules), `eslint-plugin-regexp` (60 rules), `eslint-plugin-import-helpers`, `eslint-plugin-playwright` (25 rules), `eslint-plugin-boundaries` (2 rules), `eslint-plugin-consistent-default-export-name` all loaded and ran with **no "Error running JS plugin"** output. The only failure was `@eslint-react/no-leaked-conditional-rendering` — a *type-aware* JS rule, which fails with typescript-eslint's "requires type information" error, exactly as documented. + +### 1.3 Type-aware linting (tsgolint) + +- `tsgolint` README now says **"tsgolint is stable and powers Oxlint's type-aware linting mode"**; coverage is "59/61" (README highlights) / "60 of 62" (README rules section) typescript-eslint type-aware rules; claims 10–20× over ESLint+typescript-eslint ([tsgolint README](https://github.com/oxc-project/tsgolint)). The oxlint docs page no longer calls it a preview; it lists "Stability notes" (coverage "very close", memory on huge repos, `baseUrl` unsupported, broad `include` slows it) and documents `--type-check` as a possible replacement for `tsc --noEmit` in CI ([type-aware docs](https://oxc.rs/docs/guide/usage/linter/type-aware)). +- Docs say it requires **TypeScript 7.0+**; we are on `@typescript/typescript6@6.0.2` and it **ran fine** (tsgolint ships its own typescript-go; the requirement is about project/tsconfig compatibility, not the installed package). Worth re-checking if we lean on it. +- **Measured:** `oxlint --type-aware .` with default rules: **7.65s** wall (vs. ~6.1s in July on 1.72 — within noise of a different machine load; output includes real `no-floating-promises` hits in `deploy/tools/`). + +### 1.4 Our listed native gaps — status now + +Verified against `crates/oxc_linter/src/rules/*` on `main` and the rules page: + +| Gap in July | Oct 2026 | Note | +|---|---|---| +| `max-len` | **still none** | `@oxlint/migrate`: "Deprecated stylistic rule … use the stylistic plugin as a JS plugin if necessary". Moot once Oxfmt owns width. | +| `no-restricted-syntax` | **still none** | migrate: "Not Implemented". Our two esquery selectors (`localeCompare`, inline `Intl.Collator`) → keep in ESLint, or 20-line local JS plugin rule. | +| `id-match` | **exists** (since 1.66) | carried over by migrate. | +| `typescript/naming-convention` | **still none** | migrate: "Not Implemented". Keep in ESLint. | +| `react/jsx-no-bind` | **still none** | migrate: "Not Implemented". | +| `react/require-optimization`, `no-access-state-in-setstate`, `no-unused-state` | **won't implement** | migrate: "only applies to legacy class components". | +| `react/no-deprecated` | **won't implement** | migrate: "already implemented by `typescript/no-deprecated` via tsgolint" (type-aware). | +| `react/no-redundant-should-component-update` | **now native** | present in source tree. | +| JSX spacing rules (`jsx-curly-spacing`, `jsx-equals-spacing`, `jsx-tag-spacing`, `jsx-wrap-multilines`) | **won't implement** | migrate: "Stylistic rule from eslint-plugin-react. **Should use Oxfmt for stylistic rules**, or use JS Plugins". | +| `@stylistic/*` | no native rules (by design) | runs as JS plugin — measured clean. | +| `import/order` / import-helpers | **still none native** | `import-helpers/order-imports` runs as JS plugin — measured clean. | +| boundaries | none native | JS plugin — measured clean (uses `import/resolver` settings → migrate warns the setting is dropped; still produced no errors). | +| playwright, regexp | none native | both now on the vendor's tested-plugin list; measured clean. | +| header/SPDX | none native | our inline rule must become a file (`./tools/eslint/spdx-plugin.mjs`) and be listed in `jsPlugins` — migrate does not move local plugins. | +| React Compiler rules | **new** (Aug 2026) | `react/*` compiler-derived rules (`immutability`, `purity`, `set-state-in-effect`, `refs`, …) added to `correctness`; replaces/extends `react-hooks` v6/v7 presets ([blog](https://oxc.rs/blog/2026-08-18-react-compiler-support)). Bonus, not a gap. | + +### 1.5 `@oxlint/migrate` run on our `eslint.config.mjs` + +Command: `pnpm dlx @oxlint/migrate@latest --details --type-aware eslint.config.mjs` (output moved out of the repo). Result: + +- **235 rules migrated**, 11 overrides preserved (per-glob `*.pw.tsx`, `*.spec.*`, `src/**/*.tsx`, toolkit/no-restricted-imports overrides, …), `options.typeAware: true`, `jsPlugins: ["eslint-plugin-regexp", "eslint-plugin-import-helpers", "@stylistic/eslint-plugin"]` at root plus `eslint-plugin-playwright`, `eslint-plugin-boundaries`, `eslint-plugin-consistent-default-export-name`, `@eslint-react/eslint-plugin` and the two local plugins in overrides. +- **Skipped 16**: 1 nursery (`no-undef`), 3 not implemented (`naming-convention`, `jsx-no-bind`, `no-restricted-syntax`), 12 "unsupported" (listed in §1.4 plus `no-dupe-args`/`no-octal` "superseded by strict mode" and `no-spaced-func`). +- **Warnings**: `react.version: "detect"` unsupported (set explicit); `import/resolver` setting dropped; `settings` under a `files` override (our vitest settings) dropped; `ignores` inside overrides unsupported; 1,054 globals inlined (globals package version skew). +- Config size: 73 KB JSON (mostly the inlined globals). + +**Running it** (with the two local plugins and the type-aware `@eslint-react` rule removed, `react.version` pinned): + +| Invocation | Wall | Diagnostics | +|---|---|---| +| `oxlint .` (default rules, 96 rules, 3,122 files) | **0.24–0.31s** warm, 1.6s first run incl. dlx | 216 | +| `oxlint --type-aware .` (default + tsgolint) | **7.65s** | adds real `no-floating-promises` etc. | +| `oxlint -c <migrated> .` (235 rules incl. 6 JS plugins) | **10.0–10.8s** | 106 | +| `oxlint -c <migrated> --type-aware .` | **11.6s** | 106 + typed | +| ESLint today (`eslint .`, July measurement) | **67s** | 0 | + +The 106 diagnostics: **102** `consistent-default-export-name/default-export-match-filename` (we pass `[ 'error', null ]` and rely on ESLint-side ignores that did not carry over — config issue, not a runtime one), 2 `react/jsx-curly-brace-presence` and 2 `no-restricted-imports` (option-mapping differences to triage). **Zero diagnostics from the 32 `@stylistic` rules** — i.e. the JS-plugin runtime reproduced ESLint's verdict on a tree ESLint considers clean. (JS-plugin cost is visible: 0.3s → 10s. Still 6× faster than ESLint, and single-run; `eslint --cache` warm is 2.2s but with the typed-lint caveat from July.) + +### 1.6 Hybrid tooling + +`eslint-plugin-oxlint` tracks oxlint's version (1.88.0). README documents `buildFromConfigFile('./.oxlintrc.json')` / `buildFromOxlintConfig(obj)` to disable in ESLint whatever oxlint owns; it says nothing about `jsPlugins` or formatter overlap ([README](https://github.com/oxc-project/eslint-plugin-oxlint)). Migration guide order is unchanged: migrate → enable oxlint → add `eslint-plugin-oxlint` → `oxlint && eslint` → drop ESLint when the remaining rules exist ([migrate guide](https://oxc.rs/docs/guide/usage/linter/migrate-from-eslint)). + +--- + +## 2. Oxfmt — capability check + +### 2.1 Status + +- **Beta** since 2026-02-24: "passes 100% of Prettier's JavaScript and TypeScript conformance tests"; >30× Prettier, ~3× Biome on an uncached run (vendor benchmarks); import sorting, Tailwind sorting, `package.json` sorting, embedded-language formatting, Node API, `overrides`, `.editorconfig`, `--migrate prettier|biome` ([beta post](https://oxc.rs/blog/2026-02-24-oxfmt-beta)). Still 0.x (0.73.0); no 1.0 announcement found. Roadmap before stable: Prettier plugin support, embedded-template formatting, stability/perf ([same post](https://oxc.rs/blog/2026-02-24-oxfmt-beta)). +- Docs position it as "the recommended choice when you want a dedicated formatter with a Prettier-compatible workflow", and say to stay on Prettier only if you depend on plugins Oxfmt lacks ([overview](https://oxc.rs/docs/guide/usage/formatter)). Unsupported vs Prettier: `prettier` key in `package.json`, nested `.editorconfig`, `experimentalTernaries`, Prettier plugins in general ([unsupported features](https://oxc.rs/docs/guide/usage/formatter/unsupported-features)). Bundled Prettier reference is 3.9.9 (oxfmt 0.71 notes). + +### 2.2 Options vs. our house style + +Full option list: [config](https://oxc.rs/docs/guide/usage/formatter/config), [config file reference](https://oxc.rs/docs/guide/usage/formatter/config-file-reference). + +| Our rule (value) | Oxfmt option | Reproducible? | +|---|---|---| +| `@stylistic/indent` 2 | `tabWidth: 2`, `useTabs: false` (defaults) | ✅ | +| `@stylistic/quotes` single | `singleQuote: true` | ✅ (template literals untouched either way) | +| `@stylistic/jsx-quotes` prefer-double | `jsxSingleQuote: false` (default) | ✅ | +| `@stylistic/semi` always | `semi: true` (default) | ✅ | +| `@stylistic/comma-dangle` always-multiline | `trailingComma: "all"` (default) | ✅ (Prettier only emits trailing commas when multi-line) | +| `@stylistic/object-curly-spacing` always | `bracketSpacing: true` (default) | ✅ | +| `@stylistic/brace-style` 1tbs | fixed Prettier behaviour | ✅ | +| `@stylistic/operator-linebreak` after | `experimentalOperatorPosition: "end"` (default) | ✅ | +| `@stylistic/quote-props` as-needed (+keywords, numbers) | `quoteProps: "as-needed"` | ≈ (Prettier's as-needed has no keyword/number sub-options) | +| `max-len` 160 | `printWidth` | ≈ soft limit (Prettier never breaks strings/comments) — see §3.4 on the value | +| `@stylistic/array-bracket-spacing` **always** (`[ a, b ]`) | **no option** | ❌ → `[a, b]` | +| `@stylistic/template-curly-spacing` **always** (`${ x }`) | **no option** | ❌ → `${x}` | +| `react/jsx-curly-spacing` **always** (`{ x }`, children too) | **no option** | ❌ → `{x}` | +| `react/jsx-tag-spacing` beforeSelfClosing **never** (`<X/>`) | fixed Prettier behaviour | ❌ → `<X />` | +| `react/jsx-wrap-multilines` parens-new-line | fixed Prettier behaviour | ✅ (Prettier does the same) | +| `@stylistic/space-before-function-paren` never (named/anon) | fixed Prettier behaviour | ✅ (`function foo()`, `async () =>`) | +| `arrowParens` (we don't enforce) | `"always"` default | n/a — pick `always` | +| `eol-last`, `no-trailing-spaces`, `no-multiple-empty-lines`, `no-multi-spaces`, `key-spacing`, `comma-spacing`, `space-infix-ops`, `type-annotation-spacing`, `member-delimiter-style`, … | formatter inherently | ✅ | + +Verdict: **four spacing conventions are not expressible** and are the mandatory churn. Everything else maps. + +### 2.3 Import sorting (`sortImports`) + +Built in, **off by default**, modelled on `eslint-plugin-perfectionist/sort-imports`: `groups` (selectors like `value-external`, `type-internal`, arrays to merge groups, `{ newlinesBetween }` markers), `customGroups` with glob `elementNamePattern`, `internalPattern`, `order`, `ignoreCase`, `partitionByComment/Newline`, `sortSideEffects` ([sorting docs](https://oxc.rs/docs/guide/usage/formatter/sorting), [config reference](https://oxc.rs/docs/guide/usage/formatter/config-file-reference)). Our `import-helpers` groups (`module`, `/types/`, `src/server`, `src/api`, `src/shell`, `src/slices`, `src/features`, `src/{config,services,shared,sprite}`, `src/toolkit`, `deploy|playwright|vitest`, relative) are expressible as glob custom groups; **but** Oxfmt classifies `import type` separately (`type-*` selectors) whereas `import-helpers` sorts type imports with their path group, and our `/types/` path-regex group has no direct analogue. Trial on `src/features/account` + `src/shared/pagination` with a best-effort mapping (type-import group first) reordered **282 import lines in 128 files**; dropping the `type-import` group pushed all type imports to the trailing `unknown` block. A faithful mapping needs `["value-external","type-external"]`-style paired groups per layer and a `**/types/**` custom group — doable, but a separate change. Recommendation: **keep `import-helpers/order-imports`** (runs clean as an oxlint JS plugin) and leave `sortImports: false` for now. + +### 2.4 Tooling + +- CLI: `oxfmt` (write, default), `--check`, `--list-different`, `-c/--config`, `--ignore-path`, `--threads`, `--stdin-filepath`, `--lsp`, `--migrate prettier|biome`, `--no-error-on-unmatched-pattern` for lint-staged ([CI docs](https://oxc.rs/docs/guide/usage/formatter/ci)). lint-staged recipe: `"*": "oxfmt --no-error-on-unmatched-pattern"`. +- Ignores: respects `.gitignore` (+ `.git/info/exclude`), `.prettierignore`, and `ignorePatterns` in config (recommended); `node_modules` and lockfiles always skipped ([ignore files](https://oxc.rs/docs/guide/usage/formatter/ignore-files)). Inline: `// oxfmt-ignore` (JS/TS, next statement), `prettier-ignore` honoured too ([ignore comments](https://oxc.rs/docs/guide/usage/formatter/ignore-comments)). +- Editors: same official **`oxc.oxc-vscode`** extension as oxlint (format-on-save via `editor.defaultFormatter`), JetBrains "Oxc" plugin, Zed extension, Neovim via `oxfmt --lsp` ([editors](https://oxc.rs/docs/guide/usage/formatter/editors)). +- Interplay with ESLint: the Prettier-migration guide says keep **`eslint-config-prettier`** to switch off conflicting style rules; it covers `@stylistic/eslint-plugin` ([migrate from Prettier](https://oxc.rs/docs/guide/usage/formatter/migrate-from-prettier), [eslint-config-prettier README](https://github.com/prettier/eslint-config-prettier)). `eslint-plugin-oxlint` does **not** handle formatter overlap. For us the simplest is to delete the `@stylistic` block and the four `react/jsx-*` spacing rules outright rather than add another config layer. +- Oxfmt also formats JSON/YAML/Markdown/CSS/HTML by default — 212 non-TS files changed in our run (mostly `.md` reflow and JSON/YAML). Either accept, or scope `ignorePatterns`/CLI globs to `**/*.{ts,tsx,js,mjs,cjs}` initially. + +--- + +## 3. Measurements — Oxfmt on this repo + +### 3.1 Defaults (`oxfmt --check .`, no config) + +- **1.34s** wall (incl. pnpm dlx startup). **3,311 files** would change (1,636 tsx, 1,426 ts, 149 md, 50 json, 20 yml, 17 js, …) — essentially everything, because defaults are double quotes + `printWidth 100`. +- **One hard error**: `src/shared/router/nextjs-routes.d.ts:190` — `TS(1038) 'declare' modifier cannot be used in an already ambient context` (generated by `nextjs-routes`, has `/* eslint-disable */` + `// prettier-ignore`; oxc's parser rejects what Prettier tolerates). Must go in `ignorePatterns`. + +### 3.2 Tuned config (our style where possible) + +```jsonc +// .oxfmtrc.json used for the measurement +{ + "printWidth": 160, // also measured with 120 and 100 + "tabWidth": 2, "useTabs": false, "semi": true, + "singleQuote": true, "jsxSingleQuote": false, "quoteProps": "as-needed", + "trailingComma": "all", "bracketSpacing": true, "bracketSameLine": false, + "arrowParens": "always", "sortPackageJson": false, + "ignorePatterns": ["src/shared/router/nextjs-routes.d.ts"] +} +``` + +Write run: **0.45s** wall for the whole repo. + +| `printWidth` | All files changed | `.ts`/`.tsx` files changed (of 3,099) | TS/JS lines `+` / `−` | md/json/yml | +|---|---|---|---|---| +| 160 | 2,840 | **2,605 (84%)** | **+47,200 / −54,715** | 212 files, ±4.2k | +| 120 | 2,867 | 2,632 (85%) | +56,943 / −49,829 | ~same | +| 100 (Oxfmt default) | 2,934 | 2,700 (87%) | +75,930 / −52,666 | ~same | + +Reference: tracked TS/TSX is **224,220 lines**; at `printWidth: 160` about **60.8k changed line-pairs ≈ 27%** of lines are touched. + +### 3.3 What the churn is (printWidth 160, TS/TSX diff, heuristic classification of 60,786 changed line-pairs) + +| Share | Kind | +|---|---| +| 69.5% | structural re-flow (hunks with different line counts): JSX props collapsed onto one line or expanded, call arguments / destructuring re-wrapped to fill the width | +| 9.1% | same line count, content differs beyond spacing (operators/parens moved, `<X/>` → `<X />`) | +| 8.8% | other spacing-only edits (`{ ...rest }` → `{...rest}`, object/arrow spacing) | +| 6.3% | `[ a, b ]` → `[a, b]` | +| 4.2% | JSX `{ x }` → `{x}` | +| 1.7% | `` `${ x }` `` → `` `${x}` `` | + +### 3.4 What it looks like (the `printWidth` decision) + +`src/shared/pagination/Pagination.tsx` at **160**: + +```diff +- <Flex +- as="nav" +- alignItems="center" +- { ...rest } +- > +- <Skeleton loading={ showSkeleton } mr={ 3 }> +- <Button +- variant="pagination" +- size="sm" +- onClick={ resetPage } +- disabled={ page === 1 || isLoading } +- > ++ <Flex as="nav" alignItems="center" {...rest}> ++ <Skeleton loading={showSkeleton} mr={3}> ++ <Button variant="pagination" size="sm" onClick={resetPage} disabled={page === 1 || isLoading}> +... +- <Button +- variant="pagination" +- size="sm" +- selected={ !showSkeleton } +- pointerEvents="none" +- loadingSkeleton={ showSkeleton } +- mx={ 2 } +- minW={ 8 } +- px={ 2 } +- > +- { page } ++ <Button variant="pagination" size="sm" selected={!showSkeleton} pointerEvents="none" loadingSkeleton={showSkeleton} mx={2} minW={8} px={2}> ++ {page} +``` + +Prettier fills to the print width and does **not** preserve a hand-chosen one-prop-per-line layout; at 160 that yields 150-char JSX tags. At **120** the same file also *expands* the 10-key props destructuring to one-per-line and keeps the shorter tags on one line — closer to today's visual density. `objectWrap: "preserve"` (default) keeps multi-line *objects* multi-line if the first key is on its own line, but there is no JSX equivalent. A `.ts` hook at 160 shows the other direction: three nested `parseFloat(formatUnits(BigInt(...), ...))` lines collapse into one 140-char line. + +**Recommendation: `printWidth: 120`** (or 100 to match Oxfmt/Prettier-ecosystem defaults). 160 was chosen for a *hard* max-len; as a *target* width it produces lines nobody would write. + +--- + +## 4. Recommendation (expanded) + +### 4.1 Oxlint + +- **Hybrid now** (unchanged from July, still the right first step): `@oxlint/migrate` → prune (drop inlined globals, pin `react.version`, fix `consistent-default-export-name` options) → `eslint-plugin-oxlint` → `oxlint && eslint . --cache` in CI/lint-staged. ~1 day. +- **Full migration is technically available today** (§1.5): everything runs under oxlint except `naming-convention`, `no-restricted-syntax` (two selectors — trivial local JS rule, or keep ESLint for just this), `jsx-no-bind`, and the type-aware `@eslint-react/no-leaked-conditional-rendering` (would be lost; nearest native is tsgolint's `no-unnecessary-condition`/`strict-boolean-expressions` family). Our inline SPDX rule and the stryker rule move to plugin files. Expected CI lint: **~10–12s** full-repo, no cache needed, typed rules included. Decision point is tolerance for the **alpha** label on JS plugins; vendor has shipped it in weekly releases since October 2025 and lists `@stylistic`/playwright/regexp as conformance-tested. Suggest: run the hybrid for a release cycle, then switch. + +### 4.2 Oxfmt — **adopt**, with eyes open + +Why yes: a formatter removes ~38 rules from the linter config, gives sub-second format-on-save in every editor via the same oxc extension, makes `max-len` and all whitespace arguments disappear, and is what both `@oxlint/migrate` and the oxc docs steer towards. Why it hurts: one-off **~84% of TS files / ~27% of TS lines** reformatted and four house-style conventions (`[ ]`, `${ }`, JSX `{ }`, `<X/>`) gone for good. + +**Supersedes** (delete from `eslint.config.mjs`): the whole `@stylistic` block (34 rules), `react/jsx-curly-spacing`, `react/jsx-equals-spacing`, `react/jsx-tag-spacing`, `react/jsx-wrap-multilines`, `max-len`. Keep `react/jsx-curly-brace-presence`, `react/jsx-fragments`, `one-var`, `no-nested-ternary`, `id-match` etc. — those are lint, not layout. + +**Still lint-side** (oxlint native / JS plugin / ESLint): `import-helpers/order-imports`, `boundaries`, SPDX header, `naming-convention`, `no-restricted-imports/-properties/-syntax`, `consistent-default-export-name`, playwright, regexp, vitest, react-hooks + React Compiler rules, nextjs. + +**Proposed `.oxfmtrc.json`:** + +```jsonc +{ + "$schema": "./node_modules/oxfmt/configuration_schema.json", + "printWidth": 120, + "tabWidth": 2, + "useTabs": false, + "semi": true, + "singleQuote": true, + "jsxSingleQuote": false, + "quoteProps": "as-needed", + "trailingComma": "all", + "bracketSpacing": true, + "bracketSameLine": false, + "arrowParens": "always", + "experimentalOperatorPosition": "end", + "sortImports": false, // keep import-helpers for now; revisit (§2.3) + "sortPackageJson": false, // avoid an unrelated package.json diff; enable later if wanted + "ignorePatterns": [ + "src/shared/router/nextjs-routes.d.ts", // generated; oxc parser rejects TS1038 + "public/**", + "deploy/tools/**/dist/**" + ] +} +``` + +(Consider starting with `"ignorePatterns"` or CLI globs limited to `**/*.{ts,tsx,js,mjs,cjs}` and bringing `.md`/`.json`/`.yml` under Oxfmt in a second PR — 212 files of unrelated reflow otherwise land in the same commit.) + +**Migration sequence:** + +1. Land the oxlint hybrid first (independent; reduces ESLint's job before we touch style). +2. PR "adopt Oxfmt": add `oxfmt` dev dep + `.oxfmtrc.json`; scripts `fmt` / `fmt:check`; CI `code_quality` job gets `pnpm fmt:check`; lint-staged `"*.{ts,tsx,js,mjs,cjs}": ["oxfmt --no-error-on-unmatched-pattern", "eslint --cache --fix"]`; `.vscode/settings.json` (`editor.defaultFormatter: oxc.oxc-vscode`, `formatOnSave`); delete `@stylistic` block + 4 react spacing rules + `max-len` and `@stylistic/eslint-plugin` dep; update `.agents/rules/code-quality.md` / `design-system.md` wherever `[ a ]`-style is documented. +3. In the **same PR, as a separate final commit**: `pnpm fmt` over the repo (the ~2.6k-file commit), then add that commit's SHA to a new **`.git-blame-ignore-revs`** (the repo has none today) and mention `git config blame.ignoreRevsFile .git-blame-ignore-revs` in `docs/CONTRIBUTING.md`. GitHub's blame view honours the file automatically. +4. Merge when the **2 currently open PRs** (and any agent worktrees — four exist now) are either merged or their authors are told to run `pnpm fmt` after rebasing; conflicts from a formatting rebase are mechanical (`git rebase`, run `pnpm fmt`, `git add`, continue) but every open branch will hit them. +5. Follow-up candidates: `sortImports` replacing `import-helpers` (§2.3); `sortPackageJson: true`; extend Oxfmt to md/json/yml; `--type-check` replacing `lint:tsc` once we trust tsgolint. + +**Risks / caveats:** + +- Oxfmt is **beta / 0.x**; formatting output may still shift between minor versions (release notes Jul–Oct show mostly markdown/CSS/JSDoc fixes and one `quoteProps: consistent` fix for JS). Pin the version; bump deliberately and reformat in the bump PR. +- `src/toolkit` (the `@blockscout/ui-toolkit` workspace) has no package.json of its own and is linted by the root config, so one root `.oxfmtrc.json` covers it; nested configs are supported if that changes. +- Playwright visual tests (`*.pw.tsx`) are unaffected by formatting but will all appear in the diff; snapshot images do not change. +- Pending `@oxlint/migrate` option gaps (`consistent-default-export-name` options, two `no-restricted-imports` hits, `react/jsx-curly-brace-presence` ×2) must be triaged before oxlint can gate CI — a few hours. +- `eslint-plugin-react` `jsx-no-bind` and `@typescript-eslint/naming-convention` remain ESLint-only for as long as we care about them. + +--- + +## 5. Sources + +Measured numbers are ours (see header for versions/machine). External claims: + +- Oxlint JS plugins status, supported/unsupported APIs, tested plugin list: <https://oxc.rs/docs/guide/usage/linter/js-plugins> +- JS plugins alpha announcement (March 2026): <https://oxc.rs/blog/2026-03-11-oxlint-js-plugins-alpha> +- Oxlint type-aware docs (59/61, TS 7 requirement, `--type-check`, stability notes): <https://oxc.rs/docs/guide/usage/linter/type-aware> +- tsgolint README ("stable", rule counts, benchmarks): <https://github.com/oxc-project/tsgolint> +- Oxlint rules list (871 rules): <https://oxc.rs/docs/guide/usage/linter/rules>; rule presence verified against `crates/oxc_linter/src/rules/{eslint,react,import,typescript}` on <https://github.com/oxc-project/oxc> +- React Compiler support in oxlint (Aug 2026): <https://oxc.rs/blog/2026-08-18-react-compiler-support> +- Migration guide (`@oxlint/migrate`, `eslint-plugin-oxlint`, order of steps): <https://oxc.rs/docs/guide/usage/linter/migrate-from-eslint> +- `eslint-plugin-oxlint` README: <https://github.com/oxc-project/eslint-plugin-oxlint> +- oxc GitHub releases (oxlint 1.85–1.88, oxfmt 0.70–0.73 notes): <https://github.com/oxc-project/oxc/releases> +- Oxfmt beta announcement (100% Prettier JS/TS conformance, features, roadmap): <https://oxc.rs/blog/2026-02-24-oxfmt-beta> +- Oxfmt overview / recommendation wording: <https://oxc.rs/docs/guide/usage/formatter> +- Oxfmt configuration and file reference (all options, `sortImports` schema): <https://oxc.rs/docs/guide/usage/formatter/config>, <https://oxc.rs/docs/guide/usage/formatter/config-file-reference> +- Oxfmt sorting (imports, Tailwind, package.json): <https://oxc.rs/docs/guide/usage/formatter/sorting> +- Oxfmt unsupported features: <https://oxc.rs/docs/guide/usage/formatter/unsupported-features> +- Oxfmt ignore files / inline ignore comments: <https://oxc.rs/docs/guide/usage/formatter/ignore-files>, <https://oxc.rs/docs/guide/usage/formatter/ignore-comments> +- Oxfmt CI / lint-staged / pre-commit: <https://oxc.rs/docs/guide/usage/formatter/ci> +- Oxfmt editor setup (`oxc.oxc-vscode`, JetBrains, Zed, Neovim): <https://oxc.rs/docs/guide/usage/formatter/editors> +- Oxfmt migrate-from-Prettier guide (keep `eslint-config-prettier`, `.git-blame-ignore-revs`): <https://oxc.rs/docs/guide/usage/formatter/migrate-from-prettier> +- `eslint-config-prettier` covers `@stylistic/eslint-plugin`: <https://github.com/prettier/eslint-config-prettier> +- npm registry: `oxlint@1.88.0`, `oxfmt@0.73.0`, `oxlint-tsgolint@7.0.2004`, `@oxlint/migrate@1.88.0`, `eslint-plugin-oxlint@1.88.0` (queried 2026-10-15) diff --git a/docs/research/tanstack-start-migration.md b/docs/research/tanstack-start-migration.md new file mode 100644 index 00000000000..58b46102a0b --- /dev/null +++ b/docs/research/tanstack-start-migration.md @@ -0,0 +1,193 @@ +# Migrating from Next.js (Pages Router) to TanStack Start + +Research notes, 2026-11-02. Repo state: `main` @ `42f58c665`, Next.js 16.4.3, React 19.1.4, Vite 8.3.5 (already a devDependency for Vitest / Playwright CT), TanStack Query 5.55.4, no TanStack Router. Counts below were taken with `grep`/`find` over `src/`, `deploy/`, `tools/`, `playwright/`, `vitest/` (excluding `node_modules`, `.next`, `.claude/worktrees`). TanStack facts are from the official docs / GitHub as of this date; where a doc page did not state something, the row says so rather than guessing. + +## TL;DR / Recommendation + +**Defer. Do not open the migration PR now.** Three findings drive this: + +1. **Start 1.0 went stable three weeks ago** ([blog, 2026-10-13](https://tanstack.com/blog/tanstack-start-1-0): "TanStack Start 1.0 is finally stable"; current `@tanstack/react-start` is 1.169.4). The APIs are committed, but the RC→1.0 guide still lists removed APIs and changed error semantics ([migrate-from-release-candidate](https://tanstack.com/start/latest/docs/framework/react/migrate-from-release-candidate)), the official "Migrate from Next.js" guide covers the **App Router only** ([link](https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js)), and several surfaces this repo depends on (CSP nonce plumbing, request-body limits, React Compiler, runtime-added static files) are documented only in PRs or third-party guides. +2. **The coupling is wide, not deep: 273 source files import `next/*`, 130 more import `nextjs-routes`, 89 files export `getServerSideProps`, 63 Playwright tests stub `next/router`, and the Docker image, entrypoint, dev-server tooling, ESLint, tsconfig, Rollbar filters and the agent skills all assume Next.** Estimate for a single PR: **~90–125 agent-hours plus ~35–45 human review hours**, with at least four decisions that only a human can take (§5). +3. **The runtime-env contract collides with Vite's static-asset model.** The container writes `envs.js`, favicons, the OG image, sitemap, multichain config and downloaded JSON configs into `public/` *at startup* (`deploy/scripts/CONTEXT.md`); Vite copies `public/` into the build output *at build time* ([Vite assets guide](https://vite.dev/guide/assets)). How Nitro's node server serves files that appear after the build must be proven before anything else is written — it is the one item that could sink the plan. + +What *is* worth doing now, framework-agnostically, is the prep in Phase 2 (a router facade and a `route()` shim); it shrinks the eventual diff from ~400 files to ~50 and pays off even if the migration never happens. + +--- + +## 1. Inventory of Next.js coupling in this repo + +### 1.1 Import surface + +| Surface | Count | Where | +|---|---|---| +| Files importing anything from `next`/`next/*` | **273** | `src/`, `playwright/` | +| `next/router` (`useRouter`) | 152 imports / 147 files; **142 files call `useRouter`** | app-wide; `src/shared/router/useQueryParams.ts` is the shared write path | +| `router.query` / `.pathname` / `.replace` / `.push` / `.asPath` / `.events` | 208 / 42 / 35 / 26 / 5 / 3 member reads | no `isReady`, `prefetch`, `back`, `beforePopState` | +| `next` (types: `NextPage`, `GetServerSideProps`, `NextApiRequest`…) | 99 imports | `src/pages/**`, `src/server/**` | +| `next/dynamic` | 70 imports; **77 `ssr: false`** call sites | every page file + `_app.tsx` wallet/rewards providers | +| `next/server` (`NextRequest`/`NextResponse`) | 13 imports / 11 files | `src/proxy.ts`, `src/server/middlewares/*`, `src/server/csp/index.ts` | +| `next/script` | 5 files | Sevio/Adbutler ads, GA, CapybaraRunner | +| `next/navigation` | 3 files | `useNotifyOnNavigation`, `useLogPageView`, `AdbutlerBanner` | +| `next/link` | 3 files, incl. **`src/toolkit/chakra/link.tsx`** (the published `@blockscout/ui-toolkit`) | ESLint bans `next/link` elsewhere (`eslint.config.mjs`) | +| `next/head`, `next/document`, `next/app`, `next/error` | 1 each | `PageMetadata.tsx`, `_document.tsx`, `_app.tsx`, `_error.tsx` | +| `nextjs-routes` (`route()`, `Route` type) | **130 files**; 102 `route` imports | typed URL building; `src/shared/router/nextjs-routes.d.ts` (255 lines) is generated by `pnpm routes:generate` from the `pages/` tree | +| `next/image`, `next/font`, `next/headers`, `next/cookies` | 0 | fonts are `<link>` tags in `_document.tsx`; images are Chakra/`<img>` (55 files) | +| `process.env.NEXT_*` outside config modules | 5 files | server-only, allowed by `src/config/CONTEXT.md` rule 3 | + +### 1.2 Routing + +| Item | Count / fact | +|---|---| +| Router | **Pages Router only** (`src/pages/`, `.agents/rules/architecture.md`); no `app/` | +| Page files (excl. `api/`) | **84**, incl. `_app`, `_document`, `_error`, `404`, `chakra`, `sprite` | +| Files with a dynamic segment | 25; **0 catch-all** (`[...x]`) | +| Multichain duplicates | 10 under `src/pages/chain/[chain_slug_or_id]/**`, served by `factoryMultichain` (`src/server/getServerSideProps/utils.ts`) | +| `getServerSideProps` | 200 occurrences in **89 files**; every page re-exports a guard chain from `src/server/getServerSideProps/main.ts` (46 named factories, 1 guard per feature flag → `notFound`) | +| `getInitialProps` | 5 (`_document`, `_error`) | +| Server-side page data | `handlers.base` builds `Props` (query, cookies, referrer, adBannerProvider, uuid cookie, cspNonce, onionDomain) and fires the pageview ping; `PageNextJs` renders children only after mount (`useIsMounted`) — **the app does not SSR its UI**, only the shell | +| Client-side metadata | `src/shell/metadata/update.ts` mutates `document.title` / JSON-LD after data loads; `PageMetadata.tsx` renders `<Head>` from `metadata.generate` | + +### 1.3 Server plumbing + +| Item | Detail | +|---|---| +| `src/proxy.ts` (Next 16 "proxy", ex-middleware) | runs on every HTML request: account redirect, app-profile/colour-theme/address-format/scam-token cookies, **CSP header** (+ optional per-request nonce when the Sevio ad provider is on), `Server-Timing`, `Docker-ID` | +| `src/server/csp/` | policies built **once at startup**; primer-script sha256 hashes baked in (`src/server/primedRequests/CONTEXT.md`); dev allows `ws://localhost:3000/_next/webpack-hmr` | +| `src/server/primedRequests/` | inline `<script>` in `_document` keyed by `__NEXT_DATA__.page`; deterministic per config so its hash is static — **the CSP determinism constraint** | +| `_document.tsx` | colour-mode inline script, primer script, sprite preload, Google Fonts links, **sync `<script src="/assets/envs.js">`** (+ multichain / essential-dapps config scripts), favicons, Usercentrics loader, `Server-Timing` of `renderPage`, bot logging | +| API routes (`src/pages/api/`) | **8**: `config`, `proxy` (100 MB body limit, SSRF allow-list), `csrf`, `log`, `healthz`, `metrics` (prom-client), `monitoring/invalid-api-schema`, `tokens/[hash]/instances/[id]/media-type` | +| `next.config.js` | rewrites `/node-api/:slug*` → `/api/:slug*` and `/node-api/proxy/:slug*` → `/api/proxy`; **75 redirects** (55 old-UI, 17 Etherscan-style incl. `has: query` matchers, 3 permanent); 6 security headers; Turbopack `*.svg` → `@svgr/webpack` rule + browser-only `fs`/`net`/`tls` stubs; webpack mirror (bundle analyzer, `--profile`); `output: 'standalone'`; `outputFileTracingIncludes` for `@swc/helpers`; `serverExternalPackages` (OTel, pino-pretty); `experimental.staleTimes`; `typescript.ignoreBuildErrors` (ADR 0004); `outDir` hack for `nextjs-routes` | +| `instrumentation.ts` | OpenTelemetry SDK (`instrumentation.node.ts`, ignores `/_next/static`) + `startup.node.ts` (loads multichain / essential-dapps configs at boot) | +| `next-env.d.ts` / `next-types.d.ts` | gitignored + hand-kept references; `next/image-types/global` supplies the `*.svg` module declaration that `pnpm lint:tsc` depends on | + +### 1.4 Env delivery, build, deploy + +| Item | Detail | +|---|---| +| Env contract | `NEXT_PUBLIC_*` validated at container start (`deploy/tools/envs-validator/CONTEXT.md`), written to `public/assets/envs.js` as `window.__envs` (`make_envs_script.sh`), read only via `getEnvValue` (`src/config/utils/envs.ts`, browser → `window.__envs`, Node → `process.env`). **One image serves every instance**; only 4 build-time envs (`docs/BUILD-TIME_ENVS.md`) | +| `/node-api/config` | serves `{ envs }` for `tools/dev-server/fetch.ts`, the demo deploy (`ENVS_PRESET`), the `resolve-api-url` skill and the review tooling | +| Runtime-generated files in `public/` | `assets/envs.js`, `assets/configs/*` (downloaded), favicons, `static/og_image.png`, `sitemap.xml`, `robots.txt`, `llms.txt`, multichain + essential-dapps config JS — all written by `entrypoint.sh` **after** the build | +| Dockerfile | 3 stages; `pnpm routes:generate && pnpm run build`; copies `.next/standalone` + `.next/static` + `public`; runs as user `nextjs`; `CMD node server.js`; `PORT 3000` | +| CI | `checks.yml` runs lint/tsc/Vitest/complexity/react-doctor/mutation/Playwright — **no app build**; `publish-image.yml` builds the image; deploy is triggered in the external `blockscout/deployment-values` repo (`e2e-tests.yml`) | +| Dev tooling | `tools/dev-server/*` wraps `next dev -p`, `next build`, `next start`; `--profile` → `next build --webpack --profile`; `build:analyze` → `@next/bundle-analyzer` (webpack); `tools/scripts/dev.sh` runs `pnpm routes:generate` | +| ADRs | `0003-turbopack-for-production-builds.md` (Turbopack build 87 s vs webpack 186 s; FCP/TBT numbers) and `0004-typescript-7-side-by-side.md` (TS 7 `tsc`, TS 6 for tooling) both reason about Next's pipeline | + +### 1.5 Tests and quality tooling + +| Item | Detail | +|---|---| +| Vitest (275 spec files) | `vitest.config.ts` stubs `.svg` "to mirror `@svgr/webpack`"; `vitest/setup.ts` defines `globalThis.__envs`; `*.primed.spec.tsx` drift tests mount real pages | +| Playwright CT (229 `*.pw.tsx`) | already **Vite 8 + Rolldown** (`ctViteConfig.build.rolldownOptions`); aliases `next/router` → `playwright/mocks/modules/next/router.ts`; **63 tests pass `hooksConfig.router`**; `define: { 'process.env': '__envs' }` | +| ESLint | `@next/eslint-plugin-next` `recommended` + `core-web-vitals` (`eslint.config.mjs:392-396`), `eslint-config-next` dep, `no-restricted-imports` on `next/link`, `next.config.js` in ignores | +| Rollbar | `src/services/rollbar/queue.ts` `APP_BUNDLE_PATH = '/_next/'` and `utils.ts` `url.includes('/_next/')` gate which traces are "ours" | +| react-doctor / profiling | `tools/profiling/CONTEXT.md` depends on `next build --webpack --profile` for the `react-dom/profiling` alias; react-doctor itself is framework-agnostic | +| Agent instruction set | 20 files under `.agents/` mention Next; `add-new-page` skill templates emit `NextPage` + `next/dynamic` + `PageNextJs`; `architecture.md` states "Pages Router only" | +| Other | no i18n library (`src/shared/i18n/set-locale.ts` is a `toLocaleString` shim); PostHog/Mixpanel/GA/GrowthBook are plain client SDKs; OG image + sitemap are generated by entrypoint scripts, not Next | + +### 1.6 In-flight work that conflicts + +None at the time of writing. Any PR touching `src/pages/**` during a migration window would conflict with Phase 3 (see §4, item 15). + +--- + +## 2. TanStack Start — current state (Nov 2026) + +| Topic | Fact | Source | +|---|---|---| +| Status | 1.0 stable 2026-10-13: "TanStack Start 1.0 is finally stable … ready for production". RC was 2025-09-23. Overview: "TanStack Start is stable"; RSC "available as an experimental feature". `@tanstack/react-start` latest **1.169.4**; peers `react >=18`, `vite >=8` (optional), `@rsbuild/core ^2` (optional); `engines.node >=22.12` | [1.0 post](https://tanstack.com/blog/tanstack-start-1-0), [RC post](https://tanstack.com/blog/announcing-tanstack-start-v1), [overview](https://tanstack.com/start/latest/docs/framework/react/overview), [package.json](https://github.com/TanStack/router/blob/main/packages/react-start/package.json) | +| Build layer | Vite plugin `tanstackStart()` from `@tanstack/react-start/plugin/vite`, `viteReact()` after it; Rsbuild also supported. "Start requires Vite 8 when you build with Vite" | [build-from-scratch](https://tanstack.com/start/latest/docs/framework/react/build-from-scratch), [migrate-from-RC](https://tanstack.com/start/latest/docs/framework/react/migrate-from-release-candidate) | +| Server / hosting | Node & Docker go through **Nitro**: `plugins: [tanstackStart(), nitro(), viteReact()]` (`nitro/vite`; the old `@tanstack/nitro-v2-vite-plugin` was removed), `vite build` → `node .output/server/index.mjs`. Nitro node server reads `NITRO_PORT`/`PORT`, `NITRO_HOST`/`HOST`, has graceful-shutdown envs. Rsbuild path uses `srvx` instead. The docs never say Nitro is *required*; it is the only documented Node path | [hosting](https://tanstack.com/start/latest/docs/framework/react/guide/hosting), [Nitro node](https://nitro.build/deploy/runtimes/node) | +| Server entry | optional `src/server.ts`: `createServerEntry({ fetch(request, opts) { return createStartHandler(defaultStreamHandler)(request, opts) } })` — the place to mutate the final `Response` (headers after `await` are not applied by helpers) | [server-entry-point](https://tanstack.com/start/latest/docs/framework/react/guide/server-entry-point) | +| Middleware | `createMiddleware()` (request middleware, runs for SSR, server routes and server functions) vs `createMiddleware({ type: 'function' })`; global registration in `src/start.ts` via `createStart(() => ({ requestMiddleware, functionMiddleware }))`; defining `start.ts` means adding `createCsrfMiddleware()` yourself; `defaultSsr` also lives here | [middleware](https://tanstack.com/start/latest/docs/framework/react/guide/middleware), [selective-ssr](https://tanstack.com/start/latest/docs/framework/react/guide/selective-ssr) | +| Server functions | `createServerFn({ method }).validator(...).handler(...)`; `getRequest`, `getRequestHeader`, `setResponseHeader(s)`, `setResponseStatus` from `@tanstack/react-start/server`; `throw redirect()` / `throw notFound()`; called from loaders directly, from components via `useServerFn` | [server-functions](https://tanstack.com/start/latest/docs/framework/react/guide/server-functions) | +| Server routes (API) | same `createFileRoute` with `server: { handlers: { GET, POST… }, middleware }`; co-located with page routes, even the same file; `$` splat → `params._splat`; handlers return a web `Response`. **No body-size limit or body-streaming guidance documented** | [server-routes](https://tanstack.com/start/latest/docs/framework/react/guide/server-routes) | +| File routing | `__root.tsx`; `.` nesting; `$param`; trailing `$` splat; `_layout` pathless; `_` suffix breaks nesting; `-` prefix ignored; `(group)`; `[.]` escaping; `index`, `route` tokens | [file-naming-conventions](https://tanstack.com/router/latest/docs/framework/react/routing/file-naming-conventions) | +| Selective SSR | `ssr: true \| false \| 'data-only'` per route, children can only tighten; `defaultSsr` in `createStart`; with `ssr: false` "neither `beforeLoad` nor `loader` will run on the server"; the root `shellComponent` "is always SSRed" | [selective-ssr](https://tanstack.com/start/latest/docs/framework/react/guide/selective-ssr) | +| Head / metadata | route `head: () => ({ title, meta, links, styles, scripts })`; `<HeadContent/>` required in `<head>`, `<Scripts/>` required in `<body>`; last nested occurrence of a `title`/`meta` wins. Inline **head** scripts are not shown in the docs (only `src`); inline body scripts via `scripts[].children` | [document-head-management](https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management) | +| CSP nonce | `router.options.ssr.nonce` is stamped on router-rendered head tags, scripts and styles, and emitted as `<meta property="csp-nonce">` for the client to read back — merged in [PR #5522](https://github.com/TanStack/router/pull/5522) (2025-10-17, fixes #5511). **Not in the RouterOptions docs page**; third-party guides only. Hash-based allow-listing of a custom inline script (the primer) is unaffected — it is just a `<script>` you render yourself | +| Navigation | `<Link to params search hash preload replace resetScroll activeProps from href>`, `useNavigate`, `<Navigate>`, `router.navigate`; `useParams`, `useSearch({ from })`; `validateSearch` (valibot works natively via Standard Schema — the repo already uses valibot) | [navigation](https://tanstack.com/router/latest/docs/framework/react/guide/navigation), [search-params](https://tanstack.com/router/latest/docs/framework/react/guide/search-params) | +| Search-param serialisation | default parser: "First level values that are not strings are accurately preserved as actual numbers and booleans"; nested → URL-encoded JSON; plain strings stay plain. `trailingSlash: 'always' \| 'never' \| 'preserve'` (default `never`); `caseSensitive` default `false` | [search-params](https://tanstack.com/router/latest/docs/framework/react/guide/search-params), [RouterOptions](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType) | +| Not found / redirects | `throw notFound()` in `beforeLoad`/`loader`; `notFoundComponent` per route, `defaultNotFoundComponent`; `notFoundMode: 'fuzzy' \| 'root'`. `redirect({ to \| href, throw })` from `beforeLoad`/`loader`/server fns. The HTTP status code behaviour during SSR is on the `Redirect` type page, not the guides | [not-found-errors](https://tanstack.com/router/latest/docs/framework/react/guide/not-found-errors), [redirect](https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction) | +| Env vars | client: `import.meta.env.VITE_*`, replaced at bundle time ("public client variables are replaced at bundle time only"); server: `process.env`; runtime values reach the client via a server function called from a loader; "Read env per-request, not at module scope" | [environment-variables](https://tanstack.com/start/latest/docs/framework/react/guide/environment-variables) | +| Static files | Vite `public/` is "served at root path `/` during dev, and copied to the root of the dist directory as-is" — **a build-time copy**; nothing in Vite or the Start hosting docs covers files added to the output after build | [Vite assets](https://vite.dev/guide/assets) | +| TanStack Query SSR | `@tanstack/react-router-ssr-query`: `setupRouterSsrQueryIntegration({ router, queryClient })`, `wrapQueryClient: false` when you own the provider, `handleRedirects` default on; "Create the client inside `getRouter`, not at module scope"; loader `queryClient.query(...)` + `useSuspenseQuery` for SSR-visible data; `router.invalidate()` ≠ `queryClient.invalidateQueries()` | [tanstack-query](https://tanstack.com/start/latest/docs/framework/react/guide/tanstack-query), [integrations/query](https://tanstack.com/router/latest/docs/framework/react/integrations/query) | +| Code splitting | `autoCodeSplitting: true` splits `component`/`errorComponent`/`pendingComponent`/`notFoundComponent`; loaders stay in the critical chunk; `__root.tsx` cannot be split | [code-splitting](https://tanstack.com/router/latest/docs/framework/react/guide/code-splitting) | +| `next/dynamic` equivalent | none needed: `next/dynamic` "is a composite of `React.lazy()` and Suspense"; `ssr:false` maps to route-level `ssr: false` or a mount gate | [Next lazy-loading](https://nextjs.org/docs/pages/guides/lazy-loading) | +| `next/image`, `next/font` | "Start does not automatically provide the Next.js image optimizer"; fonts are self-hosted/`<link>` — both already true here | [migrate-from-next-js](https://tanstack.com/start/latest/docs/framework/react/migrate-from-next-js) | +| React 19 / Compiler | React `>=19` is a supported peer. No official Start doc for the React Compiler was found; the Vite-plugin option `customViteReactPlugin` (pass your own `viteReact({ babel })`) appears only in a docs mirror of v1.131 — **unverified**. The repo does not use the compiler, so this is moot today | +| Testing | official pattern: `createRouter` + `createMemoryHistory({ initialEntries })` + `<RouterProvider>`; "Use the custom render function with router" — no sanctioned hook mocking | [setup-testing](https://tanstack.com/router/latest/docs/framework/react/how-to/setup-testing) | +| Vite 8 | stable 2026-03-12, Rolldown replaces esbuild+Rollup, "10-30x faster builds", Node 20.19+/22.12+; `rollupOptions` auto-converted | [Vite 8 post](https://vite.dev/blog/announcing-vite8) | +| Known gaps / issues | Vite's ecosystem-CI table in [vitejs/vite#22484](https://github.com/vitejs/vite/pull/22484) shows a failing `tanstack-start` row for 8.0.14 (cause not stated); [#5289](https://github.com/TanStack/router/issues/5289) memory growth per SSR-streamed request (Bun, 1.132); [#5823](https://github.com/TanStack/router/issues/5823) render cost of many `<Link>`s (1.135); route-tree type-checking was tuned on a 400-route stress test ([TS perf post](https://tanstack.com/blog/tanstack-router-typescript-performance)) — at 84 routes this repo is well inside that | + +--- + +## 3. Phased plan for a single PR + +Assumptions: one agent works the PR as a stack of commits, one phase per commit group; "agent-hours" are wall-clock hours of an autonomous session *including* running the gates and fixing their fallout; "review-hours" are human time reading the diff and doing the manual QA named in the row. The estimates assume the §4 decisions are taken **before** Phase 1 and that the runtime-static-files question (§4.1) has a proven answer. If it does not, stop after Phase 0. + +| # | Phase | Scope (files / areas) | Depends on | Agent h | Review h | Who acts | +|---|---|---|---|---|---|---| +| 0 | Decide & spike | §5 decisions; a throwaway Start app in `/tmp` proving (a) Nitro serves a file written into the output `public/` after build, (b) a hash-allow-listed inline `<script>` and a nonce coexist, (c) `vite build` of this repo's dependency graph (wagmi/reown/dynamic-labs/helia/monaco) succeeds on Rolldown — the Playwright CT config already lists the modules that need aliases | — | 6–8 | 3 | **human** decides; agent spikes | +| 1 | Framework-neutral facade (land-able on its own, even without Start) | `src/shared/router/`: a `useAppRouter()` exposing `{ query, pathname, push, replace }` over the current `next/router`, and `route()`/`Route` re-exported from one module; codemod the 142 `useRouter` files and 130 `nextjs-routes` importers to it (`ast-grep --rewrite`); `src/toolkit/chakra/link.tsx` takes an injectable link component so `@blockscout/ui-toolkit` stops depending on `next/link` | 0 | 14–20 | 6–8 | agent; human signs off the toolkit API change (published package) | +| 2 | Scaffold | `vite.config.ts` (`tanstackStart()`, `nitro()`, `viteReact()`, `vite-plugin-svgr` already in use by CT, `fs`/`net`/`tls` browser stubs, `@metamask`/helia aliases), `src/router.tsx` (`getRouter`, request-scoped `QueryClient`, `setupRouterSsrQueryIntegration({ wrapQueryClient: false })`), `src/start.ts` (`defaultSsr: false` or `'data-only'`, `requestMiddleware`), `src/server.ts`, `src/routes/__root.tsx` carrying `_document.tsx` + `_app.tsx` (shellComponent: colour-mode script, `envs.js` sync script, primer script, fonts, favicons, Usercentrics; component: provider tree), `tsconfig` (`vite/client` types replace `next/image-types/global`), remove `next-types.d.ts`/`next-env.d.ts` | 0 | 8–12 | 3 | agent | +| 3 | Pages → routes | 84 page files → `src/routes/**` (dots or directories; `chain/$chain_slug_or_id/...` for the 10 multichain pages); each `gSSP` guard chain → `beforeLoad` throwing `notFound()`; `handlers.base` (uuid cookie, ad provider pick, pageview ping, onion header, cookies/referrer) → a request middleware + router context; `PageNextJs` → route-component wrapper; `404.tsx`/`_error.tsx` → `defaultNotFoundComponent`/`defaultErrorComponent`; regenerate the typed route surface and delete `nextjs-routes` | 1, 2 | 14–20 | 5–7 | agent; human spot-checks guard parity (every feature flag × route) | +| 4 | Server | `src/proxy.ts` → request middleware (cookies, account redirect, CSP header, nonce via `router.options.ssr.nonce`, `Server-Timing`, `Docker-ID`); 8 API routes → server routes mounted at **`/node-api/*`** directly (drops the rewrite); `proxy.ts` body-limit behaviour re-verified (undocumented in Start); 75 redirects → either a request middleware table (keeps `has: query` matching, 301 vs 302) or `beforeLoad` redirects; 6 security headers in `server.ts`; OTel + `startup.node.ts` → server entry bootstrap; `instrumentation.node.ts` ignore list loses `/_next/` | 2 | 10–14 | 4 | agent | +| 5 | Head & primer | `PageMetadata.tsx` → root `head()` fed by the same `metadata.generate`; `primedRequests` keyed by route id instead of `__NEXT_DATA__.page`; CSP hash list unchanged (still startup-computed); `metadata/update.ts` unchanged; OG/sitemap remain entrypoint-generated | 3, 4 | 6–10 | 3 | agent; human checks link unfurls on a demo deploy | +| 6 | Client API swaps | 77 `dynamic(..., { ssr:false })` → `React.lazy` + existing mount gates (`useIsMounted`) or route `ssr: false`; 5 `next/script` → `<script>`/effects (keep CSP hashes for Sevio/Adbutler/GA); 3 `next/navigation` → `useLocation`/router subscribe; `router.events` (3) → `router.subscribe`; `useQueryParams` → `navigate({ search })` with a **custom `parseSearch`/`stringifySearch` that keeps every value a string** (§4.2) | 1, 3 | 6–8 | 2 | agent | +| 7 | Env & image | keep `window.__envs` + `/assets/envs.js` + `/node-api/config` byte-compatible; Dockerfile: `vite build` → copy `.output/`, `public` stays writable by the `nextjs` user, `CMD node .output/server/index.mjs`, `PORT` unchanged; `entrypoint.sh` writes into the directory Phase 0(a) proved is served; `make_envs_script.sh`/`collect_envs.sh` untouched; `docs/BUILD-TIME_ENVS.md` entries become `define`s or server-read; `NEXT_PUBLIC_` prefix **kept** (renaming 200+ documented envs is a separate product decision) | 0, 2 | 8–12 | 4 + infra | agent; **human** for Helm/`deployment-values`, registry, CDN cache rules | +| 8 | Tooling & docs | ESLint: drop `@next/eslint-plugin-next`/`eslint-config-next`, add `@tanstack/eslint-plugin-router`, retarget `no-restricted-imports`; Vitest: svg stub comment, router test utils (`createMemoryHistory`), `vitest/setup.ts`; Playwright CT: replace the `next/router` alias with a `RouterProvider` in `TestApp` and migrate 63 `hooksConfig.router` call sites to `initialLocation`; `tools/dev-server/*` → `vite dev`/`vite build`/`node .output/...`, `--profile` → Vite `resolve.alias` `react-dom` → `react-dom/profiling`, `build:analyze` → `rolldown-plugin-visualizer` or Vite's analyzer; Rollbar `/_next/` → the new asset prefix; `cspell`, `.agents/` (20 files), `add-new-page` templates, `architecture.md`, a new ADR superseding 0003 | 2–7 | 12–16 | 5 | agent; human reviews the ADR | +| 9 | Verification | see below | all | 8–12 | 4 + QA | agent runs; **human** does visual QA and the production rollout | +| | **Total** | | | **~92–132** | **~39–47** (+ infra) | | + +### Verification strategy + +Automated, agent-runnable: + +- `pnpm lint:tsc`, `pnpm lint:eslint`, `pnpm lint:cspell`, `pnpm lint:doc-links`, `pnpm presets:lint` — must be clean; tsc is the primary regression net for the 400-file codemod. +- `pnpm test:vitest` (275 specs) incl. the `*.primed.spec.tsx` drift suite — it mounts real pages, so it is the strongest proof that the primer still matches first-render requests; `pnpm test:code-complexity --changed`; `pnpm test:mutation-testing --changed`; `pnpm lint:react-doctor --scope changed`. +- `pnpm test:pw` full run (229 files, 3 projects) — force-full because `playwright-ct.config.ts` changes; screenshot diffs should be zero for everything that is not a route shell. +- `pnpm dev:preset eth` smoke + `pnpm prod:preset eth`: curl every one of the 84 routes with a representative param (there is no e2e suite in this repo; `e2e-tests.yml` runs against a k8s deploy), assert 200/404 parity against `eth.blockscout.com`, assert the CSP header, `Set-Cookie` for uuid/colour-theme, and the redirect table (75 URLs, status code + `Location`). +- `pnpm build:docker` + `start:docker:preset`: container boots through `entrypoint.sh`, `/node-api/config`, `/node-api/healthz`, `/node-api/metrics`, `/assets/envs.js` serve, favicon/OG/sitemap files are reachable (this is the Phase 0(a) proof, again, on the real image). +- Playwright (ordinary `@playwright/test`, not CT) visual diff of ~15 key pages, new build vs `https://eth.blockscout.com`, same viewport and `MockDate` — screenshots are the only automated signal for the shell/metadata/font changes. +- Loading-performance comparison with the harness already in `.agents/tasks/3566-main-page-loading-perf/tools/` (M1 FCP, M2 first API request, M5 blocking time, M6 JS before FCP), Turbopack build vs Vite build, so the primer/CSP work is measured, not assumed; also record `vite build` wall-clock against the 87 s Turbopack baseline in ADR 0003. + +Not verifiable by an agent: production infra (Helm values, ingress/CDN caching of `envs.js` and `.output/public`), real traffic (memory under SSR streaming, cf. #5289), SEO/crawler behaviour and link unfurls on real hosts, Rollbar/PostHog/Mixpanel event volume and the Rollbar own-bundle filter after the asset prefix changes, GrowthBook flag evaluation, multi-instance regressions (each instance is a different env set — the demo deploy covers one preset per run). + +--- + +## 4. Pitfalls requiring a decision before starting + +1. **Runtime-written static files vs build-time `public/`.** Everything the entrypoint generates lands in `public/` after the build (§1.4). Vite copies `public/` at build time ([Vite](https://vite.dev/guide/assets)); whether Nitro's node preset serves a file that appears in `.output/public` later is not documented on the pages read here. Options: (a) prove Nitro serves from disk and write there; (b) serve `/assets/*`, `/sitemap.xml`, `/robots.txt`, favicons from a splat server route reading the filesystem; (c) move `envs.js` to a server route that renders `window.__envs` from `process.env` on request (keeps the URL, drops the file). (c) also keeps the primer and `getEnvValue` untouched. **Must be decided first; it shapes Phases 2, 4 and 7.** +2. **URL compatibility — search params.** Blockscout URLs are linked from everywhere and the app round-trips `?tab=`, `?page=`, `?items_count=`, `?block_number=`, hex hashes and JSON-ish filters through `router.query` (208 reads) and `useQueryParams`. TanStack's default parser turns `page=2` into a number and `desc=true` into a boolean, and writes nested values as JSON ([search-params](https://tanstack.com/router/latest/docs/framework/react/guide/search-params)). Decision: supply `parseSearch`/`stringifySearch` that keep strings strings and arrays as repeated keys, exactly as `URLSearchParams` does today, and set `trailingSlash: 'preserve'` (the redirect table contains `/tokens/?tab=bridged`). Without this, every shared link and the primer's byte-for-byte URL match (`src/server/primedRequests/CONTEXT.md`) break. +3. **Keep `NEXT_PUBLIC_*` and `window.__envs`, or move to `VITE_*`?** Start's model inlines client envs at build time ([env docs](https://tanstack.com/start/latest/docs/framework/react/guide/environment-variables)); this repo's whole model is one image, runtime envs, validated by `envs-validator` and documented in `docs/ENVS.md` (200+ variables, external operators). Recommendation: keep the names and the `window.__envs` contract unchanged in this PR; a rename is a separate, operator-facing deprecation cycle (`deprecate-env-var` skill). +4. **Primer and CSP nonce.** The primer is allow-listed by startup-computed hashes and must stay request-independent. Start's own hydration scripts are nonce'd via `router.options.ssr.nonce` ([PR #5522](https://github.com/TanStack/router/pull/5522)); today the nonce exists only when Sevio ads are on. Decision: keep hash-based primer + optional nonce (as now), or go nonce-always (simpler CSP, but `src/server/csp/index.ts` caches policies and would template every request). Also decide whether loaders + `ssr-query` streaming *replace* the primer for home/tx/address — that changes the loading-perf baseline the ADR 0003 numbers rest on. +5. **Nitro or a hand-written Node server.** Nitro is the documented Node path and gives `.output/server/index.mjs`, `PORT`/`HOST`, graceful shutdown ([Nitro](https://nitro.build/deploy/runtimes/node)). The repo also needs pino-http logging, prom-client `/metrics`, OTel auto-instrumentation of the HTTP server, the 100 MB proxy body, and `Server-Timing`. Those are all doable as server routes / middleware, but OTel's `instrumentation-http` hooks assume Node's `http` server, which Nitro's node preset does use. Decide Nitro (default) vs Rsbuild+`srvx` (not Vite — rules out reusing the CT config). +6. **The toolkit's `Link`.** `src/toolkit/chakra/link.tsx` imports `next/link` and is published as `@blockscout/ui-toolkit`. Making it router-agnostic (inject the anchor component, or `asChild`) is an API change for external consumers and should ship (Phase 1) before any Start code. +7. **`/node-api/*` and the config endpoint.** The dev-server registry, the demo deploy, the `resolve-api-url` skill and external tooling fetch `/node-api/config`. Mount server routes at `/node-api/...` directly rather than re-creating the rewrite; keep the JSON shape. +8. **Redirects (75) and 404/500 pages.** Next's redirect table runs before any route (including `has: query` matchers and `permanent`). In Start the equivalent is a request middleware or `beforeLoad` redirects; `redirect()`'s HTTP status handling is on the `Redirect` type page, not covered by the guides fetched — verify 301 vs 302 parity in Phase 0. `_error.tsx` reports to Rollbar server-side; map to `defaultErrorComponent` + a request-middleware catch. +9. **ESLint and the eslint-alternatives research.** `@next/eslint-plugin-next` goes; `docs/research/eslint-alternatives*.md` assumed it in the oxlint migration plan — the swap simplifies that plan (one plugin fewer to JS-plugin). Add `@tanstack/eslint-plugin-router` (`create-route-property-order`). +10. **Playwright CT.** Already Vite 8 + Rolldown with the aliases a Start build will need — reuse them in `vite.config.ts`. The `next/router` alias and `hooksConfig.router` in 63 tests become a `RouterProvider` with `createMemoryHistory` ([setup-testing](https://tanstack.com/router/latest/docs/framework/react/how-to/setup-testing)); `define: { 'process.env': '__envs' }` stays. +11. **TypeScript 7 side-by-side (ADR 0004).** Start's Vite plugin generates `routeTree.gen.ts` and does not need the TS compiler API; `typescript-eslint` still pins TS 6. No change needed, but Next's `typescript.ignoreBuildErrors` reasoning in the ADR becomes moot — update the ADR. +12. **Profiling / bundle analysis.** `tools/profiling` relies on `next build --webpack --profile`; in Vite it is a `resolve.alias` of `react-dom` → `react-dom/profiling` behind a flag; `@next/bundle-analyzer` → a Rolldown visualizer. ADR 0003's two "stays on webpack" rows disappear — write ADR 0005 superseding it. +13. **Rollbar own-bundle filter.** `/_next/` is hard-coded in `src/services/rollbar/queue.ts` and `utils.ts`; the Vite asset prefix (default `/assets/` — which collides with this repo's `public/assets/` convention) must be chosen (`build.assetsDir`) and the filter plus its specs updated. +14. **Body size for the proxy route.** `pages/api/proxy.ts` sets a 100 MB limit (contract verification uploads). Start's server-routes docs say nothing about limits; Nitro/h3 defaults must be measured in Phase 0. +15. **Concurrent page work.** Any PR touching `src/pages/**` during the migration window will conflict with Phase 3 — freeze or rebase policy needed. +16. **Scope of SSR.** Today nothing below the shell is server-rendered (`PageNextJs` + `useIsMounted`). Keeping `defaultSsr: false`/`'data-only'` preserves behaviour and the visual baseline; turning SSR on is a separate performance project with its own CSP/hydration risks and should not ride on this PR. + +--- + +## 5. Recommendation + +**Defer the framework switch; land the decoupling now.** + +- *No-go for a single PR this quarter*: 1.0 is three weeks old, the Next.js migration guide targets the App Router, two of the contracts this repo lives on (runtime-written `public/`, hash-allow-listed primer + optional nonce) are only provable by spike, and the diff is ~400 source files plus Docker/entrypoint/dev-server/tests/tooling/agent docs — too much for one review even in phases. The upside is unquantified: ADR 0003 already got the build to 87 s and halved FCP on Turbopack, and the repo does not use App Router, RSC, `next/image` or `next/font`, so the Pages Router is not holding anything back today. +- *Do now*: Phase 1 (router facade, `route()` shim, toolkit `Link` injection). It is framework-neutral, shrinks the future migration to ~50 touched files outside `src/pages`/`src/server`, and unblocks the oxlint plan regardless. +- *Re-evaluate* when: Start has ≥2 months of 1.x patch history, the hosting docs cover runtime static files — or when Next.js forces a move (Pages Router deprecation). + +Top 5 decisions a human must make first: + +1. **How runtime-generated files (`envs.js`, configs, favicons, OG, sitemap) are served** under Vite/Nitro — disk-served `.output/public`, splat server route, or `envs.js` as a server route (§4.1). +2. **URL contract**: custom string-preserving `parseSearch`/`stringifySearch`, `trailingSlash: 'preserve'`, and where the 75 redirects live (middleware vs `beforeLoad`) — every current URL must keep working (§4.2, §4.8). +3. **Server runtime**: Nitro node preset (documented path) vs anything else, given OTel, pino, prom-client, the 100 MB proxy body and `Server-Timing` (§4.5, §4.14). +4. **Env model**: keep `NEXT_PUBLIC_*` + `window.__envs` + `/node-api/config` byte-compatible in this PR (recommended) vs start a `VITE_`/rename deprecation cycle (§4.3). +5. **SSR scope and the primer**: keep `ssr: false`/`'data-only'` everywhere and the hash-allow-listed primer (behaviour-preserving) vs adopt loaders + `ssr-query` streaming and a nonce-always CSP (a performance project with its own ADR) (§4.4, §4.16) — plus the toolkit `Link` API change that must ship first (§4.6). diff --git a/doctor.config.json b/doctor.config.json new file mode 100644 index 00000000000..5c019acb3dc --- /dev/null +++ b/doctor.config.json @@ -0,0 +1,44 @@ +{ + "$schema": "https://react.doctor/schema/config.json", + "categories": { + "Security": "off", + "Bugs": "off", + "Performance": "off", + "Accessibility": "off", + "Maintainability": "off" + }, + "rules": { + "react-doctor/jsx-key": "error", + "react-doctor/no-impure-state-updater": "error", + "react-doctor/no-side-effect-in-state-updater-function": "error", + "react-doctor/no-direct-state-mutation": "error", + "react-doctor/no-mutating-array-method-on-prop-or-hook-result": "error", + "react-doctor/no-adjust-state-on-prop-change": "error", + "react-doctor/no-derived-state": "error", + "react-doctor/no-derived-state-effect": "error", + "react-doctor/no-initialize-state": "error", + "react-doctor/no-effect-chain": "error", + "react-doctor/no-set-state-after-await-in-effect": "error", + "react-doctor/no-create-object-url-without-revoke": "error", + "react-doctor/query-no-query-in-effect": "error" + }, + "ignore": { + "files": [ + "public/**", + "playwright/**", + "vitest/**", + "deploy/**", + "tools/**", + "**/*.pw.tsx", + "**/*.spec.ts", + "**/*.spec.tsx" + ] + }, + "projects": [ "." ], + "warnings": false, + "blocking": "error", + "adoptExistingLintConfig": false, + "noScore": true, + "share": false, + "supplyChain": { "enabled": false } +} diff --git a/eslint.config.mjs b/eslint.config.mjs index 576fc17cd24..5fcabbb925b 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,3 +1,4 @@ +import eslintReactPlugin from '@eslint-react/eslint-plugin'; import { includeIgnoreFile } from '@eslint/compat'; import jsPlugin from '@eslint/js'; import nextJsPlugin from '@next/eslint-plugin-next'; @@ -19,6 +20,8 @@ import { fileURLToPath } from 'node:url'; import tseslint from 'typescript-eslint'; +import { strykerDisableRule } from './tools/mutation-testing/eslint/well-formed-disable.mjs'; + const SPDX_HEADER = '// SPDX-License-Identifier: LicenseRef-Blockscout'; const spdxLicenseRule = { @@ -45,6 +48,29 @@ const spdxLicenseRule = { }, }; +/* + * The router facade (src/shared/router) is the only consumer of the framework's routing primitives; everything + * else goes through it so a router change touches the adapter, not the app. + */ +const ROUTER_FRAMEWORK_MODULES = [ + { name: 'next/router', message: 'Please use useRouter() from "src/shared/router/useRouter" instead' }, + { name: 'next/navigation', message: 'Please use usePathname() from "src/shared/router/usePathname" instead' }, + { name: 'next/link', message: 'Please use the Link component from "src/toolkit/chakra/link" instead' }, + { + name: 'nextjs-routes', + message: 'Please import route() and the Route / Query / DynamicRoute types from "src/shared/router/routes" instead', + }, +]; +const ROUTER_FRAMEWORK_MODULE_NAMES = ROUTER_FRAMEWORK_MODULES.map((module) => module.name); + +const ROUTER_FRAMEWORK_ALLOWED_FILES = [ + 'src/shared/router/NextRouterProvider.tsx', + 'src/shared/router/routes.ts', + 'src/toolkit/router/**', + 'vitest/**', + 'playwright/**', +]; + const RESTRICTED_MODULES = { paths: [ { name: 'dayjs', message: 'Please use src/shared/date-and-time/dayjs.ts instead of directly importing dayjs' }, @@ -73,14 +99,44 @@ const RESTRICTED_MODULES = { ], message: 'Please use corresponding component or hook from "src/toolkit" instead', }, - { - name: 'next/link', - importNames: [ 'default' ], - message: 'Please use toolkit/chakra/link component instead', - }, + ...ROUTER_FRAMEWORK_MODULES, ], patterns: [ - 'src/sprite/icons/*', + { group: [ 'src/sprite/icons/*' ] }, + ], +}; + +const ANALYTICS_VENDOR_MESSAGE = + 'Analytics vendors are reached only through the provider-neutral facade. Please import from "src/shared/analytics" instead.'; + +const ANALYTICS_VENDOR_ALLOWED_FILES = [ + 'src/shared/analytics/**', + 'src/services/mixpanel/**', + 'src/services/posthog/**', + 'src/config/**', + 'src/server/csp/**', + '**/*.spec.{ts,tsx}', +]; + +const RESTRICTED_MODULES_WITH_ANALYTICS_VENDORS = { + paths: [ + ...RESTRICTED_MODULES.paths, + { name: 'mixpanel-browser', message: ANALYTICS_VENDOR_MESSAGE }, + { name: 'posthog-js', message: ANALYTICS_VENDOR_MESSAGE }, + ], + patterns: [ + ...RESTRICTED_MODULES.patterns, + { + group: [ + 'mixpanel-browser/**', + 'posthog-js/**', + 'src/services/mixpanel', + 'src/services/mixpanel/**', + 'src/services/posthog', + 'src/services/posthog/**', + ], + message: ANALYTICS_VENDOR_MESSAGE, + }, ], }; @@ -95,19 +151,75 @@ const ARCH_BOUNDARY_ELEMENTS = [ { type: 'src-features', pattern: 'src/features/**', mode: 'full' }, ]; +/* + * App config convention (src/config/CONTEXT.md) — the modules the root aggregator assembles. + * `types/config.ts` and `mocks/config.ts` are companions, not config modules, and stay out. + */ +const APP_CONFIG_MODULE_GLOBS = [ + 'src/api/config.ts', + 'src/features/**/config.ts', + 'src/services/*/config.ts', + 'src/shell/*/config.ts', + 'src/slices/*/config.ts', +]; +const APP_CONFIG_COMPANION_GLOBS = [ '**/types/config.ts', '**/mocks/config.ts' ]; + +const APP_CONFIG_ELEMENTS = [ + { type: 'app-config-envs', pattern: 'src/config/utils/envs.ts', mode: 'full' }, + { type: 'app-config-root', pattern: 'src/config/**', mode: 'full' }, + { type: 'app-config-module', pattern: APP_CONFIG_MODULE_GLOBS.map((glob) => glob.replace('**/config.ts', '**/!(types|mocks)/config.ts')), mode: 'full' }, + { type: 'app-config-spec', pattern: 'src/**/config.spec.ts', mode: 'full' }, +]; + +const APP_CONFIG_IMPORT_MESSAGE = + 'Read app config through the root aggregator: `import config from \'src/config\'`. ' + + 'Only another config.ts, src/config/** or a config.spec.ts may import a config module directly.'; + +const APP_CONFIG_ENVS_MESSAGE = + 'Env values are read only in config modules. Move the getEnvValue / parseEnvJson / getExternalAssetFilePath call into the owning config.ts ' + + 'and read the structured result via src/config.'; + +const APP_CONFIG_NAMED_EXPORT_MESSAGE = + 'A config module exposes only its default export. Put the value inside the config object (widen the Feature payload) ' + + 'so it is unreachable while the feature is disabled; types and constants go to a sibling role file (types/config.ts, types.ts, consts.ts).'; + +// app config convention (src/config/CONTEXT.md): the raw runtime env map is read by getEnvValue only +const WINDOW_ENVS_RESTRICTION = { + object: 'window', + property: '__envs', + message: APP_CONFIG_ENVS_MESSAGE, +}; + +const RESTRICTED_SYNTAX = [ + { + selector: 'CallExpression[callee.property.name=\'localeCompare\']', + message: 'Use the shared collator from src/shared/texts/collator.ts (collator.compare) instead of String.prototype.localeCompare.', + }, + { + selector: 'NewExpression[callee.object.name=\'Intl\'][callee.property.name=\'Collator\']', + message: 'Use the shared collator from src/shared/texts/collator.ts instead of constructing Intl.Collator inline.', + }, +]; + /** @type {import('eslint').Linter.Config[]} */ export default tseslint.config( includeIgnoreFile(gitignorePath), - { files: [ '**/*.{js,mjs,cjs,ts,jsx,tsx}', '**/*.pw.tsx' ] }, + { files: [ '**/*.{js,mjs,cjs,ts,mts,jsx,tsx}', '**/*.pw.tsx' ] }, { ignores: [ - 'deploy/tools/', + 'deploy/tools/*/dist/', + 'deploy/tools/envs-validator/public/', + // generated files that only a nested .gitignore covers; includeIgnoreFile reads the root one alone + 'deploy/tools/envs-validator/index.js', + '.design-sync/.cache/', 'public/', '.git/', // agent worktrees are full checkouts of the repo; linting them doubles the work and can exhaust the heap '.claude/worktrees/', 'next.config.js', + 'tools/code-complexity/dist/', + 'tools/review-screen/dist/', ] }, { languageOptions: { globals: { ...globals.browser, ...globals.node } } }, @@ -115,7 +227,18 @@ export default tseslint.config( { settings: { react: { version: 'detect' }, - 'boundaries/elements': ARCH_BOUNDARY_ELEMENTS, + // first matching descriptor wins, so the file-level config elements go before the layer-level ones; + // the trailing catch-all makes every src file a known element — policies never run from unknown files + 'boundaries/elements': [ ...APP_CONFIG_ELEMENTS, ...ARCH_BOUNDARY_ELEMENTS, { type: 'src-other', pattern: 'src/**', mode: 'full' } ], + 'boundaries/dependency-nodes': [ 'import', 'dynamic-import', 'export' ], + // without a resolver every import target is "unknown" and no boundaries policy ever matches; + // `paths` makes the tsconfig-style root-relative specifiers (src/…, playwright/…) resolvable + 'import/resolver': { + node: { + extensions: [ '.ts', '.tsx', '.js', '.mjs' ], + paths: [ __dirname ], + }, + }, }, }, @@ -239,6 +362,7 @@ export default tseslint.config( }, } ], 'react/jsx-equals-spacing': [ 'error', 'never' ], + 'react/jsx-filename-extension': [ 'error', { allow: 'as-needed', extensions: [ '.tsx' ] } ], 'react/jsx-fragments': [ 'error', 'syntax' ], 'react/jsx-no-duplicate-props': 'error', 'react/jsx-no-target-blank': 'off', @@ -271,6 +395,17 @@ export default tseslint.config( }, }, + { + // type-aware, so TS files only + files: [ '**/*.{ts,tsx}' ], + plugins: { + '@eslint-react': eslintReactPlugin, + }, + rules: { + '@eslint-react/no-leaked-conditional-rendering': 'error', + }, + }, + { plugins: { '@next/next': nextJsPlugin, @@ -364,9 +499,46 @@ export default tseslint.config( 'default': 'allow', rules: [ { - from: 'src-api', - disallow: [ 'src-slices', 'src-features' ], - importKind: 'value', + // by path, not by element type: `src/api/config.ts` is an `app-config-module` element (a file + // is one element only), and the layer policy still applies to it + from: { path: 'src/api/**' }, + disallow: { to: { type: [ 'src-slices', 'src-features' ] }, dependency: { kind: 'value' } }, + }, + ], + } ], + }, + }, + + /* + * App config convention (src/config/CONTEXT.md): the root aggregator is the only import surface for + * config modules, and env values are read only inside them. Later policies override earlier ones. + */ + { + files: [ + 'src/**/*.{ts,tsx}', + ], + plugins: { + boundaries: boundariesPlugin, + }, + rules: { + 'boundaries/dependencies': [ 'error', { + 'default': 'allow', + rules: [ + { + disallow: { to: { type: 'app-config-module' }, dependency: { kind: 'value' } }, + message: APP_CONFIG_IMPORT_MESSAGE, + }, + { + from: { type: [ 'app-config-module', 'app-config-root', 'app-config-spec' ] }, + allow: { to: { type: 'app-config-module' } }, + }, + { + disallow: { to: { type: 'app-config-envs' } }, + message: APP_CONFIG_ENVS_MESSAGE, + }, + { + from: { type: [ 'app-config-module', 'app-config-root' ] }, + allow: { to: { type: 'app-config-envs' } }, }, ], } ], @@ -526,23 +698,17 @@ export default tseslint.config( 'prefer-const': 'error', // restricted imports, properties and syntax - 'no-restricted-syntax': [ 'error', - { - selector: 'CallExpression[callee.property.name=\'localeCompare\']', - message: 'Use the shared collator from src/shared/texts/collator.ts (collator.compare) instead of String.prototype.localeCompare.', - }, + 'no-restricted-syntax': [ 'error', ...RESTRICTED_SYNTAX ], + 'no-restricted-imports': [ 'error', RESTRICTED_MODULES_WITH_ANALYTICS_VENDORS ], + 'no-restricted-properties': [ 2, { - selector: 'NewExpression[callee.object.name=\'Intl\'][callee.property.name=\'Collator\']', - message: 'Use the shared collator from src/shared/texts/collator.ts instead of constructing Intl.Collator inline.', + object: 'process', + property: 'env', + // FIXME: restrict the rule only NEXT_PUBLIC variables + message: 'Please use src/config/index.ts to import any NEXT_PUBLIC environment variables. For other properties please disable this rule for a while.', }, + WINDOW_ENVS_RESTRICTION, ], - 'no-restricted-imports': [ 'error', RESTRICTED_MODULES ], - 'no-restricted-properties': [ 2, { - object: 'process', - property: 'env', - // FIXME: restrict the rule only NEXT_PUBLIC variables - message: 'Please use src/config/index.ts to import any NEXT_PUBLIC environment variables. For other properties please disable this rule for a while.', - } ], }, }, { @@ -558,8 +724,33 @@ export default tseslint.config( '*.config.js', ], rules: { - // for configs allow to consume env variables from process.env directly - 'no-restricted-properties': 'off', + // for configs allow to consume env variables from process.env directly; the raw browser env map stays off-limits + 'no-restricted-properties': [ 2, WINDOW_ENVS_RESTRICTION ], + }, + }, + { + // the deploy tools are CLIs that run at container startup; console is their output channel + files: [ 'deploy/tools/**' ], + rules: { + 'no-console': 'off', + }, + }, + { + // app config convention (src/config/CONTEXT.md): a config module has no export besides the default + files: APP_CONFIG_MODULE_GLOBS, + ignores: APP_CONFIG_COMPANION_GLOBS, + rules: { + 'no-restricted-syntax': [ 'error', + ...RESTRICTED_SYNTAX, + { selector: 'ExportNamedDeclaration', message: APP_CONFIG_NAMED_EXPORT_MESSAGE }, + { selector: 'ExportAllDeclaration', message: APP_CONFIG_NAMED_EXPORT_MESSAGE }, + ], + }, + }, + { + files: ANALYTICS_VENDOR_ALLOWED_FILES, + rules: { + 'no-restricted-imports': [ 'error', RESTRICTED_MODULES ], }, }, { @@ -569,8 +760,17 @@ export default tseslint.config( 'src/toolkit/package/**', ], rules: { - // for toolkit components allow to import @chakra-ui/react directly - 'no-restricted-imports': 'off', + // toolkit components import @chakra-ui/react directly; the package stays framework-neutral, so only the router ban applies + 'no-restricted-imports': [ 'error', { paths: ROUTER_FRAMEWORK_MODULES } ], + }, + }, + { + files: ROUTER_FRAMEWORK_ALLOWED_FILES, + rules: { + 'no-restricted-imports': [ 'error', { + paths: RESTRICTED_MODULES_WITH_ANALYTICS_VENDORS.paths.filter((path) => !ROUTER_FRAMEWORK_MODULE_NAMES.includes(path.name)), + patterns: RESTRICTED_MODULES_WITH_ANALYTICS_VENDORS.patterns, + } ], }, }, @@ -596,4 +796,12 @@ export default tseslint.config( 'spdx-license/header': 'error', }, }, + + { + plugins: { stryker: { rules: { 'well-formed-disable': strykerDisableRule } } }, + files: [ '**/*.{ts,tsx,mjs,js,cjs}' ], + rules: { + 'stryker/well-formed-disable': 'error', + }, + }, ); diff --git a/global.d.ts b/global.d.ts index 47e85e4f776..f069af101f8 100644 --- a/global.d.ts +++ b/global.d.ts @@ -3,6 +3,8 @@ import type { MultichainConfig } from 'src/features/multichain/types/client'; import type { WalletProvider } from 'src/features/web3-wallet/types/wallet-provider'; import 'vitest-fetch-mock'; +import type { MockUrlBuilder } from 'playwright/utils/mock-url-builder'; + declare global { export interface Window { ethereum?: WalletProvider | undefined; @@ -16,6 +18,7 @@ declare global { }; abkw: string; __envs: Record<string, string>; + __mockUrlBuilder: MockUrlBuilder; __primedFetches?: Map<string, { promise: Promise<Response>; headers: Record<string, string> }>; __multichainConfig?: MultichainConfig; __essentialDappsChains?: { chains: Array<EssentialDappsChainConfig> }; diff --git a/next.config.js b/next.config.js index f9b4d3b6bba..eaec3755047 100644 --- a/next.config.js +++ b/next.config.js @@ -93,18 +93,25 @@ const moduleExports = { dynamic: 30, 'static': 180, }, - // Next 16.3 defaults build-time type-checking to the `tsc` CLI, which requires a - // `typescript/bin/tsc` binary. This repo runs the native TypeScript compiler via the - // `@typescript/typescript6` alias, which ships `bin/tsc6` only — so the CLI path reports - // `typescript` as missing and aborts the build. The compiler-API path checks against - // `lib/typescript.js`, which the alias does provide, so type-checking runs normally. - useTypeScriptCli: false, + // Next 16.4 turned the Turbopack shared runtime on by default. In production it replaces the per-route + // runtime chunk with an inline bootstrap <script> that carries neither a nonce nor a hash, so the strict + // script-src in src/server/csp blocks it and the page never hydrates. Keep the per-route chunk instead. + // Upstream: https://github.com/vercel/next.js/pull/100102 (app router only), https://github.com/vercel/next.js/pull/97574 + turbopackSharedRuntime: false, + }, + + // Type-checking is done by `pnpm lint:tsc` (TypeScript 7), not by Next: Next resolves the + // `typescript` package, which here is the TS 6 alias — see .agents/adr/0004-typescript-7-side-by-side.md. + typescript: { + ignoreBuildErrors: true, }, // workaround for passing outDir to nextjs-routes CLI, see ROUTES_OUT_DIR above. // Next.js warns about this unrecognized key on startup; the warning is harmless. outDir: ROUTES_OUT_DIR, + + agentRules: false }; module.exports = withBundleAnalyzer(withRoutes(moduleExports)); diff --git a/package.json b/package.json index 7bcaac4a2a2..e7d23b28d86 100644 --- a/package.json +++ b/package.json @@ -4,66 +4,71 @@ "private": false, "homepage": "https://github.com/blockscout/frontend#readme", "engines": { - "node": ">=22.14.0", + "node": ">=24.21.0", "pnpm": ">=9.0.0" }, "license": "SEE LICENSE IN ./LICENSE", "scripts": { - "dev": "./tools/scripts/dev.sh", "dev:preset": "./tools/dev-server/dev.preset.sh", "dev:local": "./tools/dev-server/dev.local.sh", "prod:preset": "./tools/dev-server/prod.preset.sh", - "profile:analyze": "node ./tools/profiling/aggregate-react-profile.mjs", - "presets:sync": "node ./tools/dev-server/sync-preset-lists.mjs --write", - "presets:lint": "node ./tools/dev-server/sync-preset-lists.mjs", - "build": "next build", - "build:next": "./deploy/scripts/download_assets.sh ./public/assets/configs && pnpm svg:build-sprite && ./deploy/scripts/make_envs_script.sh && next build", - "build:docker": "./tools/scripts/build.docker.sh", - "build:analyze": "BUNDLE_ANALYZER=true next build --webpack", + "profile:analyze": "./tools/profiling/run.sh", + "presets:sync": "./tools/dev-server/sync-presets/run.sh --write", + "presets:lint": "./tools/dev-server/sync-presets/run.sh", + "build": "pnpm lint:tsc && next build", + "build:next": "./deploy/scripts/download_assets.sh ./public/assets/configs && pnpm svg:build-sprite && ./deploy/scripts/make_envs_script.sh && pnpm build", + "build:docker": "./tools/dev-server/docker.build.sh", + "build:analyze": "pnpm lint:tsc && BUNDLE_ANALYZER=true next build --webpack", "start": "next start", - "start:docker:local": "docker run -p 3000:3000 --env-file .env.local blockscout-frontend:local", - "start:docker:preset": "./tools/scripts/docker.preset.sh", + "start:docker:local": "./tools/dev-server/docker.local.sh", + "start:docker:preset": "./tools/dev-server/docker.preset.sh", "chakra:snippets:add": "chakra snippet add --outdir ./src/toolkit/chakra", "chakra:typegen": "chakra typegen ./src/toolkit/theme/theme.ts", "routes:generate": "nextjs-routes", - "lint:eslint": "eslint .", - "lint:eslint:fix": "eslint . --fix", + "lint:eslint": "./tools/eslint/run.sh", "lint:tsc": "tsc -p ./tsconfig.json", "lint:cspell": "cspell . --no-must-find-files", - "lint:doc-links": "node ./tools/scripts/check-doc-links.mjs", + "lint:doc-links": "./tools/doc-links/run.sh", + "lint:react-doctor": "./tools/react-doctor/run.sh", + "react-doctor": "./tools/react-doctor/run.sh", "lint:license:check": "license-report > ./license.json && license-report-check --source=./license.json --output=table --forbidden=n/a", - "lint:envs-validator:test": "cd ./deploy/tools/envs-validator && ./test.sh", "prepare": "husky install", "svg:format": "svgo -r --config svgo-format.config.js ./src/sprite/icons ./src/toolkit/chakra/assets", "svg:build-sprite": "./deploy/scripts/build_sprite.sh", - "test:pw": "./tools/scripts/pw.sh", - "test:pw:local": "export NODE_PATH=$(pwd)/node_modules && pnpm test:pw", - "test:pw:docker": "docker run --rm --ipc=host -v $(pwd):/work/ -v $(pwd)/node_modules_linux:/work/node_modules -w /work/ -it mcr.microsoft.com/playwright:v1.57.0-noble ./tools/scripts/pw.docker.sh", - "test:pw:docker:deps": "docker run --rm --ipc=host -v $(pwd):/work/ -v blockscout-pnpm-linux:/pnpm-store -w /work/ -it mcr.microsoft.com/playwright:v1.57.0-noble ./tools/scripts/pw.docker.deps.sh", - "test:pw:ci": "pnpm test:pw --project=$PW_PROJECT", - "test:pw:detect-affected": "node ./deploy/tools/affected-tests/index.js", + "test:pw": "./tools/playwright/run.sh", + "test:pw:docker": "pnpm test:pw --docker", + "test:pw:docker:deps": "pnpm test:pw --docker-deps", "test:vitest": "vitest run", "test:vitest:watch": "vitest", - "favicon:generate:dev": "./tools/scripts/favicon-generator.dev.sh", - "og-image:generate:dev": "./tools/scripts/og-image-generator.dev.sh", - "sitemap:generate:dev": "./tools/scripts/sitemap-generator.dev.sh", + "test:code-complexity": "./tools/code-complexity/run.sh", + "test:mutation-testing": "./tools/mutation-testing/run.sh", + "review:screen": "./tools/review-screen/run.sh", + "design:readout": "./tools/design-readout/run.sh", + "release": "./tools/release/run.sh", "monitoring:prometheus:local": "docker run --name blockscout_prometheus -d -p 127.0.0.1:9090:9090 -v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus", "monitoring:grafana:local": "docker run -d -p 4000:3000 --name=blockscout_grafana --user $(id -u) --volume $(pwd)/grafana:/var/lib/grafana grafana/grafana-enterprise", "postinstall": "chakra typegen ./src/toolkit/theme/theme.ts" }, "dependencies": { "@blockscout/admin-rs-types": "1.5.1", +<<<<<<< HEAD "@blockscout/api-types": "0.0.1-beta.d261ddc", +======= + "@blockscout/api-types": "0.0.1-beta.e1f332f", +>>>>>>> v2.13.0 "@blockscout/bens-types": "1.7.1", "@blockscout/contracts-info-types": "1.5.3", - "@blockscout/interchain-indexer-types": "1.6.0", - "@blockscout/multichain-aggregator-types": "2.1.6", + "@blockscout/interchain-indexer-types": "1.11.0", + "@blockscout/multichain-aggregator-types": "2.1.8", "@blockscout/points-types": "1.4.1", - "@blockscout/stats-types": "2.11.1", + "@blockscout/stats-types": "2.19.1", "@blockscout/tac-operation-lifecycle-types": "0.0.1-beta.71a05d5", "@blockscout/visualizer-types": "0.2.0", "@blockscout/zetachain-cctx-types": "1.0.0-rc.10", "@chakra-ui/react": "3.36.1", + "@dnd-kit/core": "6.3.1", + "@dnd-kit/sortable": "10.0.0", + "@dnd-kit/utilities": "3.2.2", "@dynamic-labs/ethereum": "4.91.4", "@dynamic-labs/ethereum-aa": "4.91.4", "@dynamic-labs/sdk-react-core": "4.91.4", @@ -71,8 +76,10 @@ "@emotion/react": "11.14.0", "@graphiql/toolkit": "0.11.3", "@growthbook/growthbook-react": "0.21.0", - "@helia/verified-fetch": "2.6.12", + "@helia/http": "4.0.8", + "@helia/verified-fetch": "8.1.2", "@internationalized/date": "3.12.2", + "@lifi/widget-light": "4.3.2", "@metamask/post-message-stream": "^7.0.0", "@metamask/providers": "^10.2.1", "@monaco-editor/react": "4.7.0", @@ -95,7 +102,7 @@ "@reown/appkit-adapter-wagmi": "1.7.20", "@scure/base": "1.1.9", "@slise/embed-react": "^2.2.0", - "@specify-sh/sdk": "0.4.2", + "@specify-sh/publisher-sdk": "1.2.0", "@tanstack/react-query": "5.55.4", "@tanstack/react-query-devtools": "5.55.4", "@types/d3-selection": "3.0.11", @@ -119,17 +126,18 @@ "dom-to-image": "^2.6.0", "dotenv": "17.3.1", "es-toolkit": "1.39.10", - "esbuild": "0.25.12", "focus-visible": "^5.2.1", "gradient-avatar": "git+https://github.com/blockscout/gradient-avatar.git", "graphiql": "^4.1.2", "graphql": "^16.14.0", "graphql-ws": "^5.16.2", + "helia": "7.1.16", "js-cookie": "^3.0.7", "magic-bytes.js": "1.8.0", "mixpanel-browser": "2.67.0", "monaco-editor": "0.52.2", - "next": "16.3.1", + "multiformats": "14.0.5", + "next": "16.4.3", "next-themes": "0.4.4", "nextjs-routes": "2.2.5", "node-fetch": "^3.3.2", @@ -138,6 +146,7 @@ "phoenix": "^1.8.7", "pino-http": "^8.6.1", "pino-pretty": "^9.4.1", + "posthog-js": "1.434.15", "prom-client": "15.1.1", "qrcode": "^1.5.4", "react": "19.1.4", @@ -160,11 +169,15 @@ }, "devDependencies": { "@chakra-ui/cli": "3.36.1", + "@eslint-react/eslint-plugin": "5.19.0", "@eslint/compat": "1.2.2", "@eslint/js": "9.14.0", "@next/eslint-plugin-next": "16.2.6", - "@playwright/experimental-ct-react": "1.57.0", - "@playwright/test": "1.57.0", + "@playwright/experimental-ct-react": "1.62.1", + "@playwright/test": "1.62.1", + "@stryker-mutator/api": "10.1.1", + "@stryker-mutator/core": "10.1.1", + "@stryker-mutator/vitest-runner": "10.1.1", "@stylistic/eslint-plugin": "5.2.3", "@svgr/webpack": "^6.5.1", "@tanstack/eslint-plugin-query": "5.100.5", @@ -177,7 +190,7 @@ "@types/dom-to-image": "^2.6.7", "@types/js-cookie": "^3.0.6", "@types/mixpanel-browser": "^2.66.0", - "@types/node": "20.16.7", + "@types/node": "24.13.4", "@types/phoenix": "^1.6.7", "@types/qrcode": "^1.5.6", "@types/react": "19.1.7", @@ -185,13 +198,15 @@ "@types/react-google-recaptcha": "^2.1.9", "@types/swagger-ui-react": "5.18.0", "@types/ws": "^8.18.1", + "@typesafe-ai/sdk": "0.6.0", "@typescript-eslint/eslint-plugin": "^5.62.0", "@typescript/native": "npm:typescript@7.0.2", - "@vitejs/plugin-react": "^4.3.4", + "@vitejs/plugin-react": "6.1.2", + "@vitest/coverage-v8": "5.0.0", "css-loader": "^6.11.0", "dotenv-cli": "10.0.0", "eslint": "9.39.2", - "eslint-config-next": "16.2.6", + "eslint-import-resolver-node": "0.3.10", "eslint-plugin-boundaries": "6.0.2", "eslint-plugin-consistent-default-export-name": "^0.0.15", "eslint-plugin-import": "2.31.0", @@ -213,17 +228,16 @@ "style-loader": "^3.3.4", "svg-icons-cli": "0.0.8", "svgo": "^2.8.2", - "ts-node": "^10.9.2", "typescript": "npm:@typescript/typescript6@6.0.2", "typescript-eslint": "8.59.2", + "vite": "8.3.5", "vite-plugin-svgr": "5.2.0", - "vite-tsconfig-paths": "5.1.4", - "vitest": "4.1.7", + "vitest": "5.0.0", "vitest-fetch-mock": "0.4.5", "ws": "8.21.0" }, "lint-staged": { "*.{js,jsx,ts,tsx}": "eslint --cache --fix" }, - "packageManager": "pnpm@11.5.1" + "packageManager": "pnpm@12.4.1" } diff --git a/patches/@lifi__widget-light@4.3.2.patch b/patches/@lifi__widget-light@4.3.2.patch new file mode 100644 index 00000000000..ee25f694532 --- /dev/null +++ b/patches/@lifi__widget-light@4.3.2.patch @@ -0,0 +1,187 @@ +diff --git a/dist/esm/handlers/ethereum/useEthereumIframeHandler.js b/dist/esm/handlers/ethereum/useEthereumIframeHandler.js +index 4759c2e65418e8739dc020bf3ada1901b5c16b63..63e98fb081e053faf9573d7bcf144ac60a238f45 100644 +--- a/dist/esm/handlers/ethereum/useEthereumIframeHandler.js ++++ b/dist/esm/handlers/ethereum/useEthereumIframeHandler.js +@@ -1,7 +1,19 @@ + import { handleRpcRequest } from "./rpcHandler.js"; + import { useCallback, useEffect, useMemo, useRef } from "react"; +-import { useConnection, usePublicClient, useSwitchChain, useWalletClient } from "wagmi"; ++import { useAccount, useConfig, useSwitchChain } from "wagmi"; ++import { getAccount, getPublicClient, getWalletClient } from "wagmi/actions"; + //#region src/handlers/ethereum/useEthereumIframeHandler.ts ++const WALLET_METHODS = new Set([ ++ "eth_sendTransaction", ++ "personal_sign", ++ "eth_sign", ++ "eth_signTypedData_v4", ++ "wallet_addEthereumChain", ++ "wallet_sendCalls", ++ "wallet_getCallsStatus", ++ "wallet_showCallsStatus", ++ "wallet_getCapabilities" ++]); + /** + * Host-side hook that creates an `IframeEcosystemHandler` for EVM. + * +@@ -9,25 +21,20 @@ import { useConnection, usePublicClient, useSwitchChain, useWalletClient } from + * forwards EIP-1193 RPC requests from the guest iframe. + */ + function useEthereumIframeHandler() { +- const { address, chainId, connector } = useConnection(); +- const { data: walletClient } = useWalletClient(); +- const publicClient = usePublicClient(); +- const { mutateAsync: switchChainAsync } = useSwitchChain(); ++ const { address, chainId, connector } = useAccount(); ++ const config = useConfig(); ++ const { switchChainAsync } = useSwitchChain(); + const connectorName = connector?.name; + const connectorIcon = connector?.icon; + const stateRef = useRef({ + address, + chainId, +- walletClient, +- publicClient, + connectorName, + connectorIcon + }); + stateRef.current = { + address, + chainId, +- walletClient, +- publicClient, + connectorName, + connectorIcon + }; +@@ -66,7 +73,11 @@ function useEthereumIframeHandler() { + }; + }, []); + const handleRequest = useCallback(async (_id, method, params) => { +- const { address, chainId, walletClient, publicClient } = stateRef.current; ++ const { address, chainId, connector } = getAccount(config); ++ const walletClient = address && WALLET_METHODS.has(method) ++ ? await getWalletClient(config, { account: address, chainId, connector }) ++ : undefined; ++ const publicClient = getPublicClient(config, { chainId }); + return handleRpcRequest(method, params, { + address, + chainId, +@@ -76,7 +87,7 @@ function useEthereumIframeHandler() { + await switchChainAsync({ chainId: targetChainId }); + } + }); +- }, [switchChainAsync]); ++ }, [config, switchChainAsync]); + const subscribe = useCallback((emit) => { + emitRef.current = emit; + return () => { +diff --git a/dist/esm/host/useWidgetLightHost.js b/dist/esm/host/useWidgetLightHost.js +index 93e96184f3a00879d496554d34bdcfaedf94c95e..74bd0f0f7aeadcd007a8140f0debe6274d6d1e75 100644 +--- a/dist/esm/host/useWidgetLightHost.js ++++ b/dist/esm/host/useWidgetLightHost.js +@@ -65,7 +65,7 @@ function useWidgetLightHost({ config, handlers = EMPTY_HANDLERS, iframeOrigin, a + return; + } + if (msg.type === "RESIZE" && autoResize) { +- iframeRef.current.style.height = `${msg.height}px`; ++ iframeRef.current.style.height = `calc(${msg.height}px + var(--lifi-iframe-height-offset, 0px))`; + return; + } + if (msg.type === "WIDGET_EVENT") { +diff --git a/src/handlers/ethereum/useEthereumIframeHandler.ts b/src/handlers/ethereum/useEthereumIframeHandler.ts +index 30f119089950c81dd66b6937f710e6657a0a0164..10a97557ad0c825f4efdf8d77cbb0d2af4399748 100644 +--- a/src/handlers/ethereum/useEthereumIframeHandler.ts ++++ b/src/handlers/ethereum/useEthereumIframeHandler.ts +@@ -1,13 +1,21 @@ + import { useCallback, useEffect, useMemo, useRef } from 'react' +-import { +- useConnection, +- usePublicClient, +- useSwitchChain, +- useWalletClient, +-} from 'wagmi' ++import { useAccount, useConfig, useSwitchChain } from 'wagmi' ++import { getAccount, getPublicClient, getWalletClient } from 'wagmi/actions' + import type { IframeEcosystemHandler } from '../../shared/protocol.js' + import { handleRpcRequest } from './rpcHandler.js' + ++const WALLET_METHODS = new Set([ ++ 'eth_sendTransaction', ++ 'personal_sign', ++ 'eth_sign', ++ 'eth_signTypedData_v4', ++ 'wallet_addEthereumChain', ++ 'wallet_sendCalls', ++ 'wallet_getCallsStatus', ++ 'wallet_showCallsStatus', ++ 'wallet_getCapabilities', ++]) ++ + /** + * Host-side hook that creates an `IframeEcosystemHandler` for EVM. + * +@@ -15,10 +23,9 @@ import { handleRpcRequest } from './rpcHandler.js' + * forwards EIP-1193 RPC requests from the guest iframe. + */ + export function useEthereumIframeHandler(): IframeEcosystemHandler { +- const { address, chainId, connector } = useConnection() +- const { data: walletClient } = useWalletClient() +- const publicClient = usePublicClient() +- const { mutateAsync: switchChainAsync } = useSwitchChain() ++ const { address, chainId, connector } = useAccount() ++ const config = useConfig() ++ const { switchChainAsync } = useSwitchChain() + + const connectorName = connector?.name + const connectorIcon = connector?.icon +@@ -26,16 +33,12 @@ export function useEthereumIframeHandler(): IframeEcosystemHandler { + const stateRef = useRef({ + address, + chainId, +- walletClient, +- publicClient, + connectorName, + connectorIcon, + }) + stateRef.current = { + address, + chainId, +- walletClient, +- publicClient, + connectorName, + connectorIcon, + } +@@ -76,7 +79,11 @@ export function useEthereumIframeHandler(): IframeEcosystemHandler { + + const handleRequest = useCallback( + async (_id: string, method: string, params?: unknown) => { +- const { address, chainId, walletClient, publicClient } = stateRef.current ++ const { address, chainId, connector } = getAccount(config) ++ const walletClient = address && WALLET_METHODS.has(method) ++ ? await getWalletClient(config, { account: address, chainId, connector }) ++ : undefined ++ const publicClient = getPublicClient(config, { chainId }) + return handleRpcRequest(method, params as unknown[] | undefined, { + address, + chainId, +@@ -87,7 +94,7 @@ export function useEthereumIframeHandler(): IframeEcosystemHandler { + }, + }) + }, +- [switchChainAsync] ++ [config, switchChainAsync] + ) + + const subscribe = useCallback( +diff --git a/src/host/useWidgetLightHost.ts b/src/host/useWidgetLightHost.ts +index 96dd214321f91aa0d1198c2b04d54e96e70415eb..8984d5db7c82ee47c502c4a4da488221da6393b7 100644 +--- a/src/host/useWidgetLightHost.ts ++++ b/src/host/useWidgetLightHost.ts +@@ -140,7 +140,7 @@ export function useWidgetLightHost({ + + // ── RESIZE ───────────────────────────────────────────────────────────── + if (msg.type === 'RESIZE' && autoResize) { +- iframeRef.current.style.height = `${msg.height}px` ++ iframeRef.current.style.height = `calc(${msg.height}px + var(--lifi-iframe-height-offset, 0px))` + return + } + diff --git a/playwright-ct.config.ts b/playwright-ct.config.ts index 378eb852d09..848df17c2f3 100644 --- a/playwright-ct.config.ts +++ b/playwright-ct.config.ts @@ -1,12 +1,14 @@ import type { PlaywrightTestConfig } from '@playwright/experimental-ct-react'; import { devices, defineConfig } from '@playwright/experimental-ct-react'; import react from '@vitejs/plugin-react'; -import type { Plugin } from 'esbuild'; import svgr from 'vite-plugin-svgr'; -import tsconfigPaths from 'vite-tsconfig-paths'; import appConfig from 'src/config'; +import { ctPort } from './playwright/utils/ports'; + +const isInsideWorktree = __dirname.includes('/.claude/worktrees/'); + /** * See https://playwright.dev/docs/test-configuration. */ @@ -15,8 +17,7 @@ const config: PlaywrightTestConfig = defineConfig({ testMatch: /.*\.pw\.tsx/, - // agent worktrees are full checkouts of the repo; their tests would run a second time - testIgnore: '.claude/worktrees/**', + testIgnore: isInsideWorktree ? undefined : '.claude/worktrees/**', snapshotPathTemplate: '{testDir}/{testFileDir}/__screenshots__/{testFileName}_{projectName}_{arg}{ext}', @@ -37,8 +38,15 @@ const config: PlaywrightTestConfig = defineConfig({ // so we opt out of parallel tests in any environment workers: 1, + outputDir: 'playwright-results', + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ - reporter: process.env.CI ? 'blob' : 'html', + // The json report sits under outputDir rather than next to the html one: the html reporter wipes + // playwright-report/ when the run ends, whereas outputDir is cleared at run start. + reporter: [ + process.env.CI ? [ 'blob' ] : [ 'html' ], + [ 'json', { outputFile: 'playwright-results/report.json' } ], + ], expect: { toHaveScreenshot: { @@ -55,13 +63,12 @@ const config: PlaywrightTestConfig = defineConfig({ trace: 'on-first-retry', /* Port to use for Playwright component endpoint. */ - ctPort: 3100, + ctPort, headless: true, ctViteConfig: { plugins: [ - tsconfigPaths({ loose: true, ignoreConfigErrors: true }), react(), svgr({ include: '**/*.svg', @@ -85,15 +92,15 @@ const config: PlaywrightTestConfig = defineConfig({ }, }, }), - ] as unknown as Array<Plugin>, + ], build: { // it actually frees some memory that vite needs a lot // https://github.com/storybookjs/builder-vite/issues/409#issuecomment-1152848986 sourcemap: false, minify: false, - rollupOptions: { + rolldownOptions: { output: { - // Ensure __envs exists in every chunk so code (e.g. next/router, configs/app) that + // Ensure __envs exists in every chunk so code (e.g. configs/app) that // runs before index.ts/envs.js doesn't throw. Real envs are set when envs.js runs. // // Explanation: @@ -108,6 +115,7 @@ const config: PlaywrightTestConfig = defineConfig({ }, }, resolve: { + tsconfigPaths: true, alias: [ // There is an issue with building these package using vite that I cannot resolve // The solution described here - https://github.com/vitejs/vite/issues/9703#issuecomment-1216662109 @@ -121,6 +129,8 @@ const config: PlaywrightTestConfig = defineConfig({ // Mock for reCaptcha hook { find: 'src/services/re-captcha/useReCaptcha', replacement: './playwright/mocks/client/services/re-captcha/useReCaptcha.js' }, + // Mock for reCaptcha widget, so Google's script never loads and never fires the init error + { find: /^react-google-recaptcha$/, replacement: './playwright/mocks/modules/react-google-recaptcha.js' }, // The createWeb3Modal() function from web3modal/wagmi/react somehow pollutes the global styles which causes the tests to fail // We don't call this function in TestApp and since we use useWeb3Modal() and useWeb3ModalState() hooks in the code, we have to mock the module @@ -133,11 +143,13 @@ const config: PlaywrightTestConfig = defineConfig({ // Fix for @libp2p/utils missing merge-options export { find: '@libp2p/utils/merge-options', replacement: 'merge-options' }, - // Mock for @helia/verified-fetch to avoid build issues in tests + // Mocks for the Helia packages to avoid build issues in tests { find: '@helia/verified-fetch', replacement: './playwright/mocks/modules/@helia/verified-fetch.js' }, + { find: /^@helia\/http$/, replacement: './playwright/mocks/modules/@helia/http.js' }, + { find: /^helia$/, replacement: './playwright/mocks/modules/helia.js' }, - // Mock for @specify-sh/sdk to avoid build issues in tests - { find: '@specify-sh/sdk', replacement: './playwright/mocks/modules/@specify-sh/sdk.js' }, + // Mock for @specify-sh/publisher-sdk to avoid build issues in tests + { find: '@specify-sh/publisher-sdk', replacement: './playwright/mocks/modules/@specify-sh/publisher-sdk.js' }, ], }, define: { @@ -147,8 +159,9 @@ const config: PlaywrightTestConfig = defineConfig({ }, // configured projects - // these projects are also used for sharding tests in CI - // when adding or deleting a project, make sure to update github workflow accordingly + // these projects are also used for sharding tests in CI: the `pw_tests` matrix in + // .github/workflows/checks.yml runs one job per project, with `default` split into three shards + // when adding or deleting a project, or changing the shard count, make sure to update github workflow accordingly projects: [ { name: 'default', diff --git a/playwright/.env.pw b/playwright/.env.pw index b3c2d1cf83a..7dfb1529a69 100644 --- a/playwright/.env.pw +++ b/playwright/.env.pw @@ -48,13 +48,13 @@ NEXT_PUBLIC_CONTRACT_INFO_API_HOST=http://localhost:3005 NEXT_PUBLIC_ADMIN_SERVICE_API_HOST=http://localhost:3006 NEXT_PUBLIC_METADATA_SERVICE_API_HOST=http://localhost:3007 NEXT_PUBLIC_NAME_SERVICE_API_HOST=http://localhost:3008 -NEXT_PUBLIC_REWARDS_SERVICE_API_HOST=http://localhost:3009 -NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST=http://localhost:3100 +NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST=http://localhost:3010 NEXT_PUBLIC_USER_OPS_INDEXER_API_HOST=http://localhost:3110 NEXT_PUBLIC_ZETACHAIN_SERVICE_API_HOST=http://localhost:3111 NEXT_PUBLIC_MULTICHAIN_AGGREGATOR_API_HOST=http://localhost:3012 NEXT_PUBLIC_MULTICHAIN_STATS_API_HOST=http://localhost:3013 NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST=http://localhost:3014 +NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS=[1,2] NEXT_PUBLIC_MULTICHAIN_CLUSTER=test NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY=xxx NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID=xxx diff --git a/playwright/TestApp.tsx b/playwright/TestApp.tsx index cb5e0c53d54..dee94194ed6 100644 --- a/playwright/TestApp.tsx +++ b/playwright/TestApp.tsx @@ -1,3 +1,4 @@ +import { Box } from '@chakra-ui/react'; import { GrowthBookProvider } from '@growthbook/growthbook-react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import React from 'react'; @@ -5,12 +6,15 @@ import { http } from 'viem'; import { WagmiProvider, createConfig, mock } from 'wagmi'; import { mainnet } from 'wagmi/chains'; +import type { Router, RouterContextValue } from 'src/toolkit/router/types'; + import type { Props as PageProps } from 'src/server/getServerSideProps/handlers'; import { SocketProvider } from 'src/api/socket/context'; import { AppContextProvider } from 'src/shell/app/context'; import { SettingsContextProvider } from 'src/shell/top-bar/settings/context'; +import { SettingsModalContextProvider } from 'src/shell/top-bar/settings/modal/context'; import { currentChain } from 'src/features/connect-wallet/utils/chains'; import { CsvExportContextProvider } from 'src/features/csv-export/utils/context'; @@ -18,10 +22,13 @@ import { MarketplaceContext } from 'src/features/marketplace/context'; import { RewardsContextProvider } from 'src/features/rewards/context'; import config from 'src/config'; +import { NextLink } from 'src/shared/router/NextRouterProvider'; import SpriteInjector from 'src/sprite/SpriteInjector'; import { Provider as ChakraProvider } from 'src/toolkit/chakra/provider'; +import { RouterProvider } from 'src/toolkit/router/context'; +import { getRouterOverrides } from './utils/router'; import { port as socketPort } from './utils/socket'; export type Props = { @@ -55,6 +62,14 @@ const defaultMarketplaceContext = { setIsAutoConnectDisabled: () => {}, }; +const DEFAULT_ROUTER: Router = { + query: {}, + pathname: '', + asPath: '', + push: () => Promise.resolve(true), + replace: () => Promise.resolve(true), +}; + const wagmiConfig = createConfig({ chains: [ currentChain ?? mainnet ], connectors: [ @@ -81,29 +96,45 @@ const TestApp = ({ children, withSocket, appContext, marketplaceContext = defaul const pageProps = { ...defaultAppContext.pageProps, ...appContext?.pageProps }; + const [ routerContext ] = React.useState((): RouterContextValue => { + const router = { ...DEFAULT_ROUTER, ...getRouterOverrides() }; + return { Link: NextLink, router, pathname: new URL(router.asPath, 'http://localhost').pathname }; + }); + return ( - <ChakraProvider> - <SpriteInjector/> - <QueryClientProvider client={ queryClient }> - <SocketProvider url={ withSocket ? `ws://${ config.app.host }:${ socketPort }` : undefined }> - <AppContextProvider pageProps={ pageProps }> - <MarketplaceContext.Provider value={ marketplaceContext }> - <SettingsContextProvider> - <GrowthBookProvider> - <WagmiProvider config={ wagmiConfig! }> - <RewardsContextProvider> - <CsvExportContextProvider> - { children } - </CsvExportContextProvider> - </RewardsContextProvider> - </WagmiProvider> - </GrowthBookProvider> - </SettingsContextProvider> - </MarketplaceContext.Provider> - </AppContextProvider> - </SocketProvider> - </QueryClientProvider> - </ChakraProvider> + <RouterProvider value={ routerContext }> + <ChakraProvider> + <SpriteInjector/> + <QueryClientProvider client={ queryClient }> + <SocketProvider url={ withSocket ? `ws://${ config.app.host }:${ socketPort }` : undefined }> + <AppContextProvider pageProps={ pageProps }> + <MarketplaceContext.Provider value={ marketplaceContext }> + <SettingsContextProvider> + <SettingsModalContextProvider> + <GrowthBookProvider> + <WagmiProvider config={ wagmiConfig! }> + <RewardsContextProvider> + <CsvExportContextProvider> + { /* + The mount locator resolves to the only child of #root, or to #root when there are several. + Without the wrapper, a component whose first render is null leaves the color mode script + as the only child, and the screenshot waits for that hidden script to become visible. + */ } + <Box display="contents"> + { children } + </Box> + </CsvExportContextProvider> + </RewardsContextProvider> + </WagmiProvider> + </GrowthBookProvider> + </SettingsModalContextProvider> + </SettingsContextProvider> + </MarketplaceContext.Provider> + </AppContextProvider> + </SocketProvider> + </QueryClientProvider> + </ChakraProvider> + </RouterProvider> ); }; diff --git a/playwright/fixtures/mockApiResponse.ts b/playwright/fixtures/mockApiResponse.ts index d65c083bdfa..118938ef1a1 100644 --- a/playwright/fixtures/mockApiResponse.ts +++ b/playwright/fixtures/mockApiResponse.ts @@ -1,21 +1,35 @@ import type { TestFixture, Page } from '@playwright/test'; -import type { ResourceName, ResourcePayload } from 'src/api/resources'; -import buildUrl from 'src/api/utils/build-url'; +import type { ExternalChainExtended } from 'src/shared/external-chains/types'; + +import type { ResourceName, ResourcePathParams, ResourcePayload } from 'src/api/resources'; + +import type { MockApiUrlArgs, MockUrlQueryParams } from '../utils/mock-url-builder'; +import type { MockRegistryFixture } from './mockRegistry'; interface Options<R extends ResourceName> { - pathParams?: Parameters<typeof buildUrl<R>>[1]; - queryParams?: Parameters<typeof buildUrl<R>>[2]; - chainConfig?: Parameters<typeof buildUrl<R>>[4]; + pathParams?: ResourcePathParams<R>; + queryParams?: MockUrlQueryParams; + chainConfig?: ExternalChainExtended; times?: number; status?: number; } export type MockApiResponseFixture = <R extends ResourceName>(resourceName: R, responseMock: ResourcePayload<R>, options?: Options<R>) => Promise<string>; -const fixture: TestFixture<MockApiResponseFixture, { page: Page }> = async({ page }, use) => { +const fixture: TestFixture<MockApiResponseFixture, { page: Page; mockRegistry: MockRegistryFixture }> = async({ page, mockRegistry }, use) => { await use(async(resourceName, responseMock, options) => { - const apiUrl = buildUrl(resourceName, options?.pathParams, options?.queryParams, undefined, options?.chainConfig); + // Resolved in the page, not in Node: the browser config honours the localStorage overrides + // written by mockEnvs, so the matcher equals the URL the component will request. + const args: MockApiUrlArgs = { + resourceName, + pathParams: options?.pathParams, + queryParams: options?.queryParams, + chainConfig: options?.chainConfig, + }; + const apiUrl = await page.evaluate((args) => window.__mockUrlBuilder.api(args), args); + + mockRegistry.registrations.push({ fixture: 'mockApiResponse', url: apiUrl }); await page.route(apiUrl, (route) => route.fulfill({ status: options?.status ?? 200, diff --git a/playwright/fixtures/mockConfigResponse.ts b/playwright/fixtures/mockConfigResponse.ts index 3dd302bfa65..2b85a652908 100644 --- a/playwright/fixtures/mockConfigResponse.ts +++ b/playwright/fixtures/mockConfigResponse.ts @@ -1,13 +1,18 @@ import type { TestFixture, Page } from '@playwright/test'; -import config from 'src/config'; -import { buildExternalAssetFilePath } from 'src/config/utils/envs'; +import type { MockRegistryFixture } from './mockRegistry'; export type MockConfigResponseFixture = (envName: string, envValue: string, content: unknown, isImage?: boolean) => Promise<string>; -const fixture: TestFixture<MockConfigResponseFixture, { page: Page }> = async({ page }, use) => { +const fixture: TestFixture<MockConfigResponseFixture, { page: Page; mockRegistry: MockRegistryFixture }> = async({ page, mockRegistry }, use) => { await use(async(envName, envValue, content, isImage) => { - const url = config.app.baseUrl + buildExternalAssetFilePath(envName, envValue); + // Resolved in the page so the base URL reflects the envs mocked for this test. + const url = await page.evaluate( + ({ envName, envValue }) => window.__mockUrlBuilder.configAsset(envName, envValue), + { envName, envValue }, + ); + + mockRegistry.registrations.push({ fixture: 'mockConfigResponse', url }); if (isImage && typeof content === 'string') { await page.route(url, (route) => route.fulfill({ diff --git a/playwright/fixtures/mockContractReadResponse.ts b/playwright/fixtures/mockContractReadResponse.ts index 2fc4c104f36..9a8615a36eb 100644 --- a/playwright/fixtures/mockContractReadResponse.ts +++ b/playwright/fixtures/mockContractReadResponse.ts @@ -24,12 +24,15 @@ const fixture: TestFixture<MockContractReadResponseFixture, { page: Page }> = as return; } + // Playwright's own `times` counts every invocation, a miss included, so a handler consulted for an + // unrelated RPC call would expire before its matching request arrives; count fulfilled matches here. + let fulfilledCount = 0; + await page.route(rpcUrl, (route) => { const method = route.request().method(); - if (method !== 'POST') { - route.continue(); - return; + if (method !== 'POST' || fulfilledCount >= times) { + return route.fallback(); } const dataJson = route.request().postDataJSON(); @@ -47,24 +50,27 @@ const fixture: TestFixture<MockContractReadResponseFixture, { page: Page }> = as value: params?.value, }; - if (isEqual(params, callParams) && id !== undefined && json?.method === rpcMethod) { + if (!isEqual(params, callParams) || id === undefined || json?.method !== rpcMethod) { + return route.fallback(); + } - const json = { - id, - jsonrpc: '2.0', - result: noResultEncoding ? result : encodeFunctionResult({ - abi: [ abiItem ], - functionName: abiItem.name, - result: result as never, - }), - }; + fulfilledCount++; - return route.fulfill({ - status: 200, - json: Array.isArray(dataJson) ? [ json ] : json, - }); - } - }, { times }); + const response = { + id, + jsonrpc: '2.0', + result: noResultEncoding ? result : encodeFunctionResult({ + abi: [ abiItem ], + functionName: abiItem.name, + result: result as never, + }), + }; + + return route.fulfill({ + status: 200, + json: Array.isArray(dataJson) ? [ response ] : response, + }); + }); }); }; diff --git a/playwright/fixtures/mockEnvs.ts b/playwright/fixtures/mockEnvs.ts index 918c44c3f67..f6e41186d28 100644 --- a/playwright/fixtures/mockEnvs.ts +++ b/playwright/fixtures/mockEnvs.ts @@ -1,9 +1,21 @@ import type { TestFixture, Page } from '@playwright/test'; +import type { MockRegistryFixture } from './mockRegistry'; + export type MockEnvsFixture = (envs: Array<[string, string]>) => Promise<void>; -const fixture: TestFixture<MockEnvsFixture, { page: Page }> = async({ page }, use) => { +const fixture: TestFixture<MockEnvsFixture, { page: Page; mockRegistry: MockRegistryFixture }> = async({ page, mockRegistry }, use) => { await use(async(envs) => { + const [ firstRegistration ] = mockRegistry.registrations; + + if (firstRegistration) { + throw new Error( + `mockEnvs() was called after ${ firstRegistration.fixture }() in the same test. ` + + 'Env overrides must come first: the first mock registration resolves its URL against the app config ' + + 'in the browser, which snapshots the envs, so call mockEnvs() before any mockApiResponse() or mockConfigResponse().', + ); + } + for (const [ name, value ] of envs) { await page.evaluate(({ name, value }) => { window.localStorage.setItem(name, value); diff --git a/playwright/fixtures/mockRegistry.ts b/playwright/fixtures/mockRegistry.ts new file mode 100644 index 00000000000..b3ad2d49254 --- /dev/null +++ b/playwright/fixtures/mockRegistry.ts @@ -0,0 +1,22 @@ +import type { TestFixture } from '@playwright/test'; + +export interface MockRegistration { + fixture: 'mockApiResponse' | 'mockConfigResponse'; + url: string; +} + +export interface MockRegistryFixture { + registrations: Array<MockRegistration>; + unmockedUrls: Array<string>; +} + +// Test-scoped state shared by the mock fixtures, mockEnvs and the catch-all route in lib.ts. The first +// mock registration resolves its URL in the page, which evaluates the browser config singleton with +// whatever envs are in localStorage at that moment, so mockEnvs uses the list to refuse to run after +// one; the afterEach check reads both lists to name a request no matcher handled. +// eslint-disable-next-line no-empty-pattern -- Playwright fixtures must destructure their (here empty) dependencies +const fixture: TestFixture<MockRegistryFixture, object> = async({}, use) => { + await use({ registrations: [], unmockedUrls: [] }); +}; + +export default fixture; diff --git a/playwright/fixtures/mockRpcResponse.ts b/playwright/fixtures/mockRpcResponse.ts index e0bb42ceb7c..fa6ab6e7d48 100644 --- a/playwright/fixtures/mockRpcResponse.ts +++ b/playwright/fixtures/mockRpcResponse.ts @@ -20,16 +20,14 @@ const fixture: TestFixture<MockRpcResponseFixture, { page: Page }> = async({ pag const method = route.request().method(); if (method !== 'POST') { - route.continue(); - return; + return route.fallback(); } const json = route.request().postDataJSON(); const id = json?.id; if (id === undefined) { - route.continue(); - return; + return route.fallback(); } const rpcMock = rpcMocks.find((mock) => { @@ -43,30 +41,32 @@ const fixture: TestFixture<MockRpcResponseFixture, { page: Page }> = async({ pag return isEqual(json, payload); }); - if (rpcMock) { - if (rpcMock.status && rpcMock.status !== 200) { - return route.fulfill({ - status: rpcMock.status, - json: { - id, - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Internal error', - }, - }, - }); - } + if (!rpcMock) { + return route.fallback(); + } + if (rpcMock.status && rpcMock.status !== 200) { return route.fulfill({ - status: 200, + status: rpcMock.status, json: { id, jsonrpc: '2.0', - result: rpcMock.ReturnType, + error: { + code: -32000, + message: 'Internal error', + }, }, }); } + + return route.fulfill({ + status: 200, + json: { + id, + jsonrpc: '2.0', + result: rpcMock.ReturnType, + }, + }); }); }); }; diff --git a/playwright/fixtures/mockUrlResolution.pw.tsx b/playwright/fixtures/mockUrlResolution.pw.tsx new file mode 100644 index 00000000000..1b55c77401e --- /dev/null +++ b/playwright/fixtures/mockUrlResolution.pw.tsx @@ -0,0 +1,33 @@ +/* eslint-disable react/jsx-filename-extension -- the runner only picks up *.pw.tsx; this test exercises the fixtures and mounts nothing */ +import * as statsMock from 'src/slices/chain/stats/mocks'; + +import * as crossChainTxMock from 'src/features/cross-chain-txs/mocks/txs'; + +import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; +import { test, expect } from 'playwright/lib'; + +const HOME_CHAIN_ID = '43114'; +const API_HOST_OVERRIDE = 'localhost:4242'; + +test('mockApiResponse resolves the URL against the envs mocked for the test', async({ mockEnvs, mockApiResponse }) => { + await mockEnvs([ + ...ENVS_MAP.crossChainTxs, + [ 'NEXT_PUBLIC_NETWORK_ID', HOME_CHAIN_ID ], + [ 'NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST', `http://${ API_HOST_OVERRIDE }` ], + ]); + + const url = new URL(await mockApiResponse('interchainIndexer:messages', crossChainTxMock.listResponse)); + + expect(url.host).toBe(API_HOST_OVERRIDE); + expect(url.searchParams.get('home_chain_id')).toBe(HOME_CHAIN_ID); + expect(url.searchParams.has('bridge_ids')).toBe(false); + expect(url.searchParams.get('include_unindexed_chains')).toBe('false'); +}); + +test('mockEnvs after a registered mock fails the test', async({ mockEnvs, mockApiResponse }) => { + await mockApiResponse('core:stats', statsMock.base); + + await expect(mockEnvs([ [ 'NEXT_PUBLIC_NETWORK_ID', HOME_CHAIN_ID ] ])).rejects.toThrow( + /mockEnvs\(\) was called after mockApiResponse\(\).*Env overrides must come first/, + ); +}); diff --git a/playwright/fixtures/render.tsx b/playwright/fixtures/render.tsx index d46af27a481..7089d30c0b3 100644 --- a/playwright/fixtures/render.tsx +++ b/playwright/fixtures/render.tsx @@ -1,9 +1,10 @@ /* eslint-disable no-restricted-imports */ import type { MountOptions } from '@playwright/experimental-ct-react'; import type { Locator, TestFixture } from '@playwright/test'; -import type router from 'next/router'; import React from 'react'; +import type { Router } from 'src/toolkit/router/types'; + import type { Props as TestAppProps } from 'playwright/TestApp'; import TestApp from 'playwright/TestApp'; @@ -13,7 +14,7 @@ interface MountResult extends Locator { } interface AppHooksConfig { - router: Partial<Pick<typeof router, 'query' | 'isReady' | 'asPath' | 'pathname'>>; + router: Partial<Pick<Router, 'query' | 'asPath' | 'pathname'>>; } type Mount = <HooksConfig extends AppHooksConfig>(component: React.JSX.Element, options?: MountOptions<HooksConfig>) => Promise<MountResult>; diff --git a/playwright/fixtures/socketServer.ts b/playwright/fixtures/socketServer.ts index 6ee7dd0407f..34d2294c6a7 100644 --- a/playwright/fixtures/socketServer.ts +++ b/playwright/fixtures/socketServer.ts @@ -4,7 +4,7 @@ import { WebSocketServer } from 'ws'; import type { schemas } from '@blockscout/api-types'; import type { AddressCoinBalanceSocketMessage, AddressTransactionsSocketMessage, AddressTokensBalancesSocketMessage } from 'src/slices/address/types/api'; -import type { NewBlockSocketResponse } from 'src/slices/block/types/api'; +import type { NewBlockCountSocketResponse, NewBlockSocketResponse } from 'src/slices/block/types/api'; import type { SmartContractVerificationResponse } from 'src/slices/contract/types/api'; import type { TokenInstanceMetadataSocketMessage } from 'src/slices/token/types/api'; @@ -65,6 +65,7 @@ export function sendMessage(socket: WebSocket, channel: Channel, msg: 'transacti export function sendMessage(socket: WebSocket, channel: Channel, msg: 'pending_transaction', payload: { pending_transaction: number }): void; export function sendMessage(socket: WebSocket, channel: Channel, msg: 'pending_transaction', payload: AddressTransactionsSocketMessage): void; export function sendMessage(socket: WebSocket, channel: Channel, msg: 'new_block', payload: NewBlockSocketResponse): void; +export function sendMessage(socket: WebSocket, channel: Channel, msg: 'new_blocks_count', payload: NewBlockCountSocketResponse): void; export function sendMessage(socket: WebSocket, channel: Channel, msg: 'verification_result', payload: SmartContractVerificationResponse): void; export function sendMessage(socket: WebSocket, channel: Channel, msg: 'total_supply', payload: { total_supply: number }): void; export function sendMessage(socket: WebSocket, channel: Channel, msg: 'changed_bytecode', payload: Record<string, never>): void; diff --git a/playwright/index.ts b/playwright/index.ts index 85b8084a087..170cfa81c64 100644 --- a/playwright/index.ts +++ b/playwright/index.ts @@ -3,27 +3,37 @@ import './index.css'; import '../src/server/global.css'; import { beforeMount } from '@playwright/experimental-ct-react/hooks'; import MockDate from 'mockdate'; -import * as router from 'next/router'; -const NEXT_ROUTER_MOCK = { - query: {}, - pathname: '', - push: () => Promise.resolve(), - replace: () => Promise.resolve(), -}; +import type { Router } from 'src/toolkit/router/types'; -beforeMount(async({ hooksConfig }: { hooksConfig?: { router: typeof router } }) => { - // Before mount, redefine useRouter to return mock value from test. +import type { MockUrlBuilder } from './utils/mock-url-builder'; +import { setRouterOverrides } from './utils/router'; - // @ts-ignore: I really want to redefine this property :) - // eslint-disable-next-line no-import-assign - router.useRouter = () => ({ - ...NEXT_ROUTER_MOCK, - ...hooksConfig?.router, - }); +beforeMount(async({ hooksConfig }: { hooksConfig?: { router?: Partial<Router> } }) => { + setRouterOverrides(hooksConfig?.router); // set current date MockDate.set('2022-11-11T12:00:00Z'); }); +// The mock fixtures resolve their route matchers here, in the page, so that the URL reflects the +// localStorage env overrides the component itself will see. The production modules are imported +// lazily: evaluating src/config pins the env snapshot, which must not happen before mockEnvs has run. +const mockUrlBuilder: MockUrlBuilder = { + api: async({ resourceName, pathParams, queryParams, chainConfig }) => { + const { 'default': buildUrl } = await import('../src/api/utils/build-url'); + // pathParams arrive as plain data from page.evaluate; the fixture already typed them against the resource. + return buildUrl(resourceName, pathParams as never, queryParams, undefined, chainConfig); + }, + configAsset: async(envName, envValue) => { + const [ { 'default': config }, { buildExternalAssetFilePath } ] = await Promise.all([ + import('../src/config'), + import('../src/config/utils/envs'), + ]); + return config.app.baseUrl + buildExternalAssetFilePath(envName, envValue); + }, +}; + +window.__mockUrlBuilder = mockUrlBuilder; + export {}; diff --git a/playwright/lib.ts b/playwright/lib.ts new file mode 100644 index 00000000000..e29c15258f2 --- /dev/null +++ b/playwright/lib.ts @@ -0,0 +1,107 @@ +/* eslint-disable no-console */ +import { test as base } from '@playwright/experimental-ct-react'; +import type { Page } from '@playwright/test'; + +import * as injectMetaMaskProvider from './fixtures/injectMetaMaskProvider'; +import * as mockApiResponse from './fixtures/mockApiResponse'; +import * as mockAssetResponse from './fixtures/mockAssetResponse'; +import * as mockConfigResponse from './fixtures/mockConfigResponse'; +import * as mockContractReadResponse from './fixtures/mockContractReadResponse'; +import * as mockEnvs from './fixtures/mockEnvs'; +import * as mockEssentialDappsChainsConfig from './fixtures/mockEssentialDappsChainsConfig'; +import * as mockFeatures from './fixtures/mockFeatures'; +import * as mockMultichainConfig from './fixtures/mockMultichainConfig'; +import * as mockRegistry from './fixtures/mockRegistry'; +import * as mockRpcResponse from './fixtures/mockRpcResponse'; +import * as mockTextAd from './fixtures/mockTextAd'; +import * as render from './fixtures/render'; +import * as socketServer from './fixtures/socketServer'; +import { ctPort } from './utils/ports'; +import { port as socketPort } from './utils/socket'; +import { formatUnmockedRequests } from './utils/unmocked-requests'; + +export interface Fixtures { + render: render.RenderFixture; + mockApiResponse: mockApiResponse.MockApiResponseFixture; + mockAssetResponse: mockAssetResponse.MockAssetResponseFixture; + mockConfigResponse: mockConfigResponse.MockConfigResponseFixture; + mockContractReadResponse: mockContractReadResponse.MockContractReadResponseFixture; + mockEnvs: mockEnvs.MockEnvsFixture; + mockFeatures: mockFeatures.MockFeaturesFixture; + mockMultichainConfig: mockMultichainConfig.MockMultichainConfigFixture; + mockEssentialDappsChainsConfig: mockEssentialDappsChainsConfig.MockEssentialDappsChainsConfigFixture; + mockRegistry: mockRegistry.MockRegistryFixture; + mockRpcResponse: mockRpcResponse.MockRpcResponseFixture; + createSocket: socketServer.CreateSocketFixture; + injectMetaMaskProvider: injectMetaMaskProvider.InjectMetaMaskProvider; + mockTextAd: mockTextAd.MockTextAdFixture; +} + +export type TestFnArgs = Fixtures & { page: Page }; + +const OWN_PORTS: ReadonlySet<string> = new Set([ String(ctPort), String(socketPort) ]); + +const test = base.extend<Fixtures>({ + render: render.default, + mockApiResponse: mockApiResponse.default, + mockAssetResponse: mockAssetResponse.default, + mockConfigResponse: mockConfigResponse.default, + mockContractReadResponse: mockContractReadResponse.default, + mockEnvs: mockEnvs.default, + mockFeatures: mockFeatures.default, + mockMultichainConfig: mockMultichainConfig.default, + mockEssentialDappsChainsConfig: mockEssentialDappsChainsConfig.default, + mockRegistry: mockRegistry.default, + mockRpcResponse: mockRpcResponse.default, + // FIXME: for some reason Playwright does not intercept requests to text ad provider when running multiple tests in parallel + // even if we have a global request interceptor (maybe it is related to service worker issue, maybe not) + // so we have to inject mockTextAd fixture in each test and mock the response where it is needed + mockTextAd: mockTextAd.default, + createSocket: socketServer.createSocket, + injectMetaMaskProvider: injectMetaMaskProvider.default, +}); + +test.beforeEach(async({ page, mockTextAd, mockRegistry }) => { + // The worker reuses the browser context, and Playwright only resets storage for origins it seeded + // itself, so envs and feature flags a previous test wrote to localStorage would leak into this one. + await page.evaluate(() => window.localStorage.clear()); + + // debug + const isDebug = process.env.PWDEBUG === '1'; + + if (isDebug) { + page.on('console', msg => console.log(msg.text())); + page.on('request', request => console.info('\x1b[34m%s\x1b[0m', '>>', request.method(), request.url())); + page.on('response', response => console.info('\x1b[35m%s\x1b[0m', '<<', String(response.status()), response.url())); + } + + // Abort all other requests to external resources. Registered first, so this handler is consulted + // last: a localhost request reaching it on a port other than the CT or socket server is unmocked. + await page.route('**', (route) => { + const url = route.request().url(); + const { hostname, port } = new URL(url); + if (hostname !== 'localhost') { + isDebug && console.info('Aborting request to', url); + route.abort(); + return; + } + if (!OWN_PORTS.has(port)) { + mockRegistry.unmockedUrls.push(url); + } + route.continue(); + }); + + // with few exceptions: + // 1. mock text AD requests + await mockTextAd(); +}); + +test.afterEach(async({ mockRegistry }) => { + if (mockRegistry.unmockedUrls.length === 0) { + return; + } + throw new Error(formatUnmockedRequests(mockRegistry.unmockedUrls, mockRegistry.registrations)); +}); + +export * from '@playwright/experimental-ct-react'; +export { test }; diff --git a/playwright/lib.tsx b/playwright/lib.tsx deleted file mode 100644 index 9380e9d24c7..00000000000 --- a/playwright/lib.tsx +++ /dev/null @@ -1,82 +0,0 @@ -/* eslint-disable no-console */ -import { test as base } from '@playwright/experimental-ct-react'; -import type { Page } from '@playwright/test'; - -import * as injectMetaMaskProvider from './fixtures/injectMetaMaskProvider'; -import * as mockApiResponse from './fixtures/mockApiResponse'; -import * as mockAssetResponse from './fixtures/mockAssetResponse'; -import * as mockConfigResponse from './fixtures/mockConfigResponse'; -import * as mockContractReadResponse from './fixtures/mockContractReadResponse'; -import * as mockEnvs from './fixtures/mockEnvs'; -import * as mockEssentialDappsChainsConfig from './fixtures/mockEssentialDappsChainsConfig'; -import * as mockFeatures from './fixtures/mockFeatures'; -import * as mockMultichainConfig from './fixtures/mockMultichainConfig'; -import * as mockRpcResponse from './fixtures/mockRpcResponse'; -import * as mockTextAd from './fixtures/mockTextAd'; -import * as render from './fixtures/render'; -import * as socketServer from './fixtures/socketServer'; - -export interface Fixtures { - render: render.RenderFixture; - mockApiResponse: mockApiResponse.MockApiResponseFixture; - mockAssetResponse: mockAssetResponse.MockAssetResponseFixture; - mockConfigResponse: mockConfigResponse.MockConfigResponseFixture; - mockContractReadResponse: mockContractReadResponse.MockContractReadResponseFixture; - mockEnvs: mockEnvs.MockEnvsFixture; - mockFeatures: mockFeatures.MockFeaturesFixture; - mockMultichainConfig: mockMultichainConfig.MockMultichainConfigFixture; - mockEssentialDappsChainsConfig: mockEssentialDappsChainsConfig.MockEssentialDappsChainsConfigFixture; - mockRpcResponse: mockRpcResponse.MockRpcResponseFixture; - createSocket: socketServer.CreateSocketFixture; - injectMetaMaskProvider: injectMetaMaskProvider.InjectMetaMaskProvider; - mockTextAd: mockTextAd.MockTextAdFixture; -} - -export type TestFnArgs = Fixtures & { page: Page }; - -const test = base.extend<Fixtures>({ - render: render.default, - mockApiResponse: mockApiResponse.default, - mockAssetResponse: mockAssetResponse.default, - mockConfigResponse: mockConfigResponse.default, - mockContractReadResponse: mockContractReadResponse.default, - mockEnvs: mockEnvs.default, - mockFeatures: mockFeatures.default, - mockMultichainConfig: mockMultichainConfig.default, - mockEssentialDappsChainsConfig: mockEssentialDappsChainsConfig.default, - mockRpcResponse: mockRpcResponse.default, - // FIXME: for some reason Playwright does not intercept requests to text ad provider when running multiple tests in parallel - // even if we have a global request interceptor (maybe it is related to service worker issue, maybe not) - // so we have to inject mockTextAd fixture in each test and mock the response where it is needed - mockTextAd: mockTextAd.default, - createSocket: socketServer.createSocket, - injectMetaMaskProvider: injectMetaMaskProvider.default, -}); - -test.beforeEach(async({ page, mockTextAd }) => { - // debug - const isDebug = process.env.PWDEBUG === '1'; - - if (isDebug) { - page.on('console', msg => console.log(msg.text())); - page.on('request', request => console.info('\x1b[34m%s\x1b[0m', '>>', request.method(), request.url())); - page.on('response', response => console.info('\x1b[35m%s\x1b[0m', '<<', String(response.status()), response.url())); - } - - // Abort all other requests to external resources - await page.route('**', (route) => { - if (!route.request().url().startsWith('http://localhost')) { - isDebug && console.info('Aborting request to', route.request().url()); - route.abort(); - } else { - route.continue(); - } - }); - - // with few exceptions: - // 1. mock text AD requests - await mockTextAd(); -}); - -export * from '@playwright/experimental-ct-react'; -export { test }; diff --git a/playwright/mocks/modules/@helia/http.js b/playwright/mocks/modules/@helia/http.js new file mode 100644 index 00000000000..9ccd6410829 --- /dev/null +++ b/playwright/mocks/modules/@helia/http.js @@ -0,0 +1 @@ +export const withHTTP = (helia) => helia; diff --git a/playwright/mocks/modules/@helia/verified-fetch.js b/playwright/mocks/modules/@helia/verified-fetch.js index b48b48999e4..64771d0d327 100644 --- a/playwright/mocks/modules/@helia/verified-fetch.js +++ b/playwright/mocks/modules/@helia/verified-fetch.js @@ -1 +1 @@ -export const verifiedFetch = () => Promise.resolve(new Response()); +export const createVerifiedFetchWithHelia = () => Promise.resolve(() => Promise.resolve(new Response())); diff --git a/playwright/mocks/modules/@specify-sh/publisher-sdk.js b/playwright/mocks/modules/@specify-sh/publisher-sdk.js new file mode 100644 index 00000000000..fe9ecf9befc --- /dev/null +++ b/playwright/mocks/modules/@specify-sh/publisher-sdk.js @@ -0,0 +1,31 @@ +// Mock for @specify-sh/publisher-sdk to avoid build issues in Playwright component tests + +export const ImageFormat = { + LANDSCAPE: 'LANDSCAPE', + LONG_BANNER: 'LONG_BANNER', + NO_IMAGE: 'NO_IMAGE', + SHORT_BANNER: 'SHORT_BANNER', +}; + +export default class Specify { + constructor(options) { + this.publisherKey = options.publisherKey; + } + + setCookieConsent() {} + + hasCookieConsent() { + return false; + } + + identify() {} + + onIdentityChange() { + return () => {}; + } + + async serve() { + // Mock implementation that returns null to simulate no ad + return null; + } +} diff --git a/playwright/mocks/modules/@specify-sh/sdk.js b/playwright/mocks/modules/@specify-sh/sdk.js deleted file mode 100644 index ef0fd2d280b..00000000000 --- a/playwright/mocks/modules/@specify-sh/sdk.js +++ /dev/null @@ -1,23 +0,0 @@ -// Mock for @specify-sh/sdk to avoid build issues in Playwright component tests - -export const ImageFormat = { - SHORT_BANNER: 'short_banner', - LONG_BANNER: 'long_banner', -}; - -export default class Specify { - constructor(options) { - this.publisherKey = options.publisherKey; - } - - async serve() { - // Mock implementation that returns null to simulate no ad - return null; - } -} - -export const SpecifyAd = { - imageUrl: '', - headline: '', - ctaUrl: '', -}; diff --git a/playwright/mocks/modules/helia.js b/playwright/mocks/modules/helia.js new file mode 100644 index 00000000000..1b6807969a6 --- /dev/null +++ b/playwright/mocks/modules/helia.js @@ -0,0 +1 @@ +export const createHeliaLight = () => ({ start: () => Promise.resolve() }); diff --git a/playwright/mocks/modules/react-google-recaptcha.js b/playwright/mocks/modules/react-google-recaptcha.js new file mode 100644 index 00000000000..951a2bc04ff --- /dev/null +++ b/playwright/mocks/modules/react-google-recaptcha.js @@ -0,0 +1,19 @@ +// Mock for react-google-recaptcha to keep Playwright component tests off the network +// When Google's script slips past the global request interceptor, it renders with the fake site key and fires onErrored, +// so the reCAPTCHA initialization warning shows up in screenshots at random + +import React from 'react'; + +const ReCAPTCHA = React.forwardRef((props, ref) => { + React.useImperativeHandle(ref, () => ({ + execute: () => {}, + executeAsync: () => Promise.resolve('recaptcha_token'), + reset: () => {}, + getValue: () => null, + getWidgetId: () => null, + }), []); + + return null; +}); + +export default ReCAPTCHA; diff --git a/playwright/utils/mock-url-builder.ts b/playwright/utils/mock-url-builder.ts new file mode 100644 index 00000000000..fb4cbe2be3b --- /dev/null +++ b/playwright/utils/mock-url-builder.ts @@ -0,0 +1,19 @@ +import type { ExternalChainExtended } from 'src/shared/external-chains/types'; + +import type { ResourceName } from 'src/api/resources'; +import type buildUrl from 'src/api/utils/build-url'; + +export type MockUrlQueryParams = NonNullable<Parameters<typeof buildUrl>[2]>; + +// Plain data: these cross the page.evaluate boundary, so they carry no generic resource typing. +export interface MockApiUrlArgs { + resourceName: ResourceName; + pathParams?: Record<string, string | undefined>; + queryParams?: MockUrlQueryParams; + chainConfig?: ExternalChainExtended; +} + +export interface MockUrlBuilder { + api: (args: MockApiUrlArgs) => Promise<string>; + configAsset: (envName: string, envValue: string) => Promise<string>; +} diff --git a/playwright/utils/ports.ts b/playwright/utils/ports.ts new file mode 100644 index 00000000000..47bb638611f --- /dev/null +++ b/playwright/utils/ports.ts @@ -0,0 +1,3 @@ +// The component-test server port, shared by playwright-ct.config.ts and the unmocked-request check in +// playwright/lib.ts, which must not import the config module. +export const ctPort = 3100; diff --git a/playwright/utils/router.ts b/playwright/utils/router.ts new file mode 100644 index 00000000000..0c43b212652 --- /dev/null +++ b/playwright/utils/router.ts @@ -0,0 +1,14 @@ +import type { Router } from 'src/toolkit/router/types'; + +// `hooksConfig.router` crosses from the test to the page in `beforeMount` (playwright/index.ts), which +// never sees the component tree; TestApp reads the overrides back from here when it mounts the provider. + +let routerOverrides: Partial<Router> | undefined; + +export function setRouterOverrides(overrides: Partial<Router> | undefined): void { + routerOverrides = overrides; +} + +export function getRouterOverrides(): Partial<Router> | undefined { + return routerOverrides; +} diff --git a/playwright/utils/unmocked-requests.spec.ts b/playwright/utils/unmocked-requests.spec.ts new file mode 100644 index 00000000000..81a09f882de --- /dev/null +++ b/playwright/utils/unmocked-requests.spec.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest'; + +import type { MockRegistration } from '../fixtures/mockRegistry'; +import { formatUnmockedRequests } from './unmocked-requests'; + +const HEADING = 'Unmocked localhost requests. Mock each one, or answer it with an error status when the test expects a failure:'; +const TOKENS_MATCHER: MockRegistration = { fixture: 'mockApiResponse', url: 'http://localhost:3003/api/v2/tokens?q=usdt&type=ERC-20' }; +const CONFIG_MATCHER: MockRegistration = { fixture: 'mockConfigResponse', url: 'http://localhost:3000/assets/configs/marketplace.json' }; + +describe('formatUnmockedRequests', () => { + it('says when no matcher shares the pathname and counts every matcher as other', () => { + expect(formatUnmockedRequests([ 'http://localhost:3003/api/v2/stats' ], [ TOKENS_MATCHER, CONFIG_MATCHER ])).toBe([ + HEADING, + ' http://localhost:3003/api/v2/stats', + ' no registered matcher shares this pathname', + ' 2 other matchers registered', + ].join('\n')); + }); + + // The case the check exists for: the component sent a query param the test did not restate. + it('puts a query-param drift side by side with the matcher of the same pathname', () => { + const unmocked = 'http://localhost:3003/api/v2/tokens?q=usdt&type=ERC-20&chain_id=1'; + + expect(formatUnmockedRequests([ unmocked ], [ TOKENS_MATCHER, CONFIG_MATCHER ])).toBe([ + HEADING, + ` ${ unmocked }`, + ` mockApiResponse: ${ TOKENS_MATCHER.url }`, + ' 1 other matchers registered', + ].join('\n')); + }); + + it('lists several unmocked urls once each, with their own matchers under each', () => { + const stats = 'http://localhost:3003/api/v2/stats'; + const config = 'http://localhost:3000/assets/configs/marketplace.json?v=2'; + + expect(formatUnmockedRequests([ stats, config, stats ], [ TOKENS_MATCHER, CONFIG_MATCHER ])).toBe([ + HEADING, + ` ${ stats }`, + ' no registered matcher shares this pathname', + ` ${ config }`, + ` mockConfigResponse: ${ CONFIG_MATCHER.url }`, + ' 1 other matchers registered', + ].join('\n')); + }); +}); diff --git a/playwright/utils/unmocked-requests.ts b/playwright/utils/unmocked-requests.ts new file mode 100644 index 00000000000..c98dc3787bb --- /dev/null +++ b/playwright/utils/unmocked-requests.ts @@ -0,0 +1,29 @@ +import { uniq } from 'es-toolkit'; + +import type { MockRegistration } from '../fixtures/mockRegistry'; + +function pathnameOf(url: string): string { + return new URL(url).pathname; +} + +export function formatUnmockedRequests(unmockedUrls: ReadonlyArray<string>, registrations: ReadonlyArray<MockRegistration>): string { + const urls = uniq(unmockedUrls); + const pathnames = new Set(urls.map(pathnameOf)); + const lines = [ 'Unmocked localhost requests. Mock each one, or answer it with an error status when the test expects a failure:' ]; + + for (const url of urls) { + lines.push(` ${ url }`); + const samePathname = registrations.filter((registration) => pathnameOf(registration.url) === pathnameOf(url)); + if (samePathname.length === 0) { + lines.push(' no registered matcher shares this pathname'); + } + for (const registration of samePathname) { + lines.push(` ${ registration.fixture }: ${ registration.url }`); + } + } + + const others = registrations.filter((registration) => !pathnames.has(pathnameOf(registration.url))).length; + lines.push(` ${ others } other matchers registered`); + + return lines.join('\n'); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 22fa57f877d..70dd69f3a2f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,3 +1,161 @@ +--- +lockfileVersion: '9.0' + +importers: + + .: + configDependencies: {} + packageManagerDependencies: + pnpm: + specifier: 12.4.1 + version: 12.4.1 + +packages: + + '@pnpm/exe.android-arm64@12.4.1': + resolution: {integrity: sha512-/HwsqXMSmlOfgtV9+O0ratzjV6Vd/8n1hh4rGHpCGmDURvt52MwZxdbhyxP4K03ZfvgSDvotFPr8O+RzE5Eu8A==} + cpu: [arm64] + os: [android] + + '@pnpm/exe.android-x64@12.4.1': + resolution: {integrity: sha512-+l74Qb4c2YjOzNKHXJLg+1wr8xHM1ckkUhnU5KRUK9TJqiiczt6yeTZqqzHIlJ8i6pAoj5V0OJevDRwnQKLgrQ==} + cpu: [x64] + os: [android] + + '@pnpm/exe.darwin-arm64@12.4.1': + resolution: {integrity: sha512-6rkZkT3iGfaxknUdGHraqSWFvTa6N0ajAHluv9Ax0GRWs0sIcGNiFhDopv6xSZCsJZmG483aNS/b6UEDy3blfw==} + cpu: [arm64] + os: [darwin] + + '@pnpm/exe.darwin-x64@12.4.1': + resolution: {integrity: sha512-Vb1CHlR88HghC1qUxjxjs82zQSXnXacPD+btG2CmG8Q/hBU7Q0/b2YWJKSQqZXicunV5khFtfTlAwJddV9RkYA==} + cpu: [x64] + os: [darwin] + + '@pnpm/exe.freebsd-x64@12.4.1': + resolution: {integrity: sha512-iT3iHz3Nl0Sxxj7UPOtZ/aQ81AFsQhjoeWMAlPkSRO04gsgDGAXv3UYxOFaesMWsfNxaGn0A+CITbuCHFF66FA==} + cpu: [x64] + os: [freebsd] + + '@pnpm/exe.linux-arm64-musl@12.4.1': + resolution: {integrity: sha512-aBooZfNXM5f+OGUgCAMFWpE/kAhsWfvmqIyMtHy6zl3aNxyInWrcY/Saln/UElzo7lZWMC0Yktroxd/2J26lNQ==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-arm64@12.4.1': + resolution: {integrity: sha512-TlOdacTTP09BgcMvwWBFRsu8VAjfwqwnslBj+XSq1JFM3ck4f3k+1O/747EuctxZxs3/o785b6Q3s7Pd92Ptsg==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-ppc64@12.4.1': + resolution: {integrity: sha512-r/ab/MlIBo75oizUP5ITiziCCrnXz4SJwfErLQ+603AshB+Yq7xTMCoMtzTSCAMu6aaymIKkAFtZvd2J75Wq0w==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-riscv64@12.4.1': + resolution: {integrity: sha512-C/D1QWdKMiB8+wv/spl1rGITFUuqC+aI/fb6h8NB5sqxsOaGXeYc/g891oCuzggHn6SODk9p+I09hI76x/cMNw==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-s390x@12.4.1': + resolution: {integrity: sha512-nxz5zD4yXt94uzbStDk0QTPKW+aE92hH1b5tFXK9ctB1HE9Xcq1vjTiA2LsZMFC6p4gdu5OwQeFqYNAVGa6QlA==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-x64-musl@12.4.1': + resolution: {integrity: sha512-5AwgFdGhVUg2kIweYGfxzSLEHiIG77PQhZAkXC3TwofQHsu1Wr+TrV5/rNX2PopFnHRzuE581zoB8F6Wle32yg==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-x64@12.4.1': + resolution: {integrity: sha512-FJOZuuuQMhp0oLzBtcKkLXknBI92hfkmSnlKc47vfin4HrmfID5khY2lGekL9tCzk1cpR+HShEw/meFl+nHtzQ==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.win32-arm64@12.4.1': + resolution: {integrity: sha512-OO7eKBL9S+xk5hRy+JUUZSNJknGuGe3GEUffsrlC2LbqKF02g+VX1anGIzSbJDvkkdnpJhSlxF5AUz2JzJu2Jw==} + cpu: [arm64] + os: [win32] + + '@pnpm/exe.win32-x64@12.4.1': + resolution: {integrity: sha512-x7gJHZgHo6hp354xCYA2NvoFzYJkHwovt2kVsUBK5EmXULLcP51JGMq09CX+5FRFJUZFKoXjLu3mZWmfP7o6PQ==} + cpu: [x64] + os: [win32] + + pnpm@12.4.1: + resolution: {integrity: sha512-LoHjmdc/6DkNqyXgaqeIq3pZCCSNL1o3D4K0gRR6ano2e/gEj5pv22Rg8hpm8FQt7bi5TKLIcjWWdBkgsWVtTA==} + engines: {node: '>=18.*'} + hasBin: true + +snapshots: + + '@pnpm/exe.android-arm64@12.4.1': + optional: true + + '@pnpm/exe.android-x64@12.4.1': + optional: true + + '@pnpm/exe.darwin-arm64@12.4.1': + optional: true + + '@pnpm/exe.darwin-x64@12.4.1': + optional: true + + '@pnpm/exe.freebsd-x64@12.4.1': + optional: true + + '@pnpm/exe.linux-arm64-musl@12.4.1': + optional: true + + '@pnpm/exe.linux-arm64@12.4.1': + optional: true + + '@pnpm/exe.linux-ppc64@12.4.1': + optional: true + + '@pnpm/exe.linux-riscv64@12.4.1': + optional: true + + '@pnpm/exe.linux-s390x@12.4.1': + optional: true + + '@pnpm/exe.linux-x64-musl@12.4.1': + optional: true + + '@pnpm/exe.linux-x64@12.4.1': + optional: true + + '@pnpm/exe.win32-arm64@12.4.1': + optional: true + + '@pnpm/exe.win32-x64@12.4.1': + optional: true + + pnpm@12.4.1: + optionalDependencies: + '@pnpm/exe.android-arm64': 12.4.1 + '@pnpm/exe.android-x64': 12.4.1 + '@pnpm/exe.darwin-arm64': 12.4.1 + '@pnpm/exe.darwin-x64': 12.4.1 + '@pnpm/exe.freebsd-x64': 12.4.1 + '@pnpm/exe.linux-arm64': 12.4.1 + '@pnpm/exe.linux-arm64-musl': 12.4.1 + '@pnpm/exe.linux-ppc64': 12.4.1 + '@pnpm/exe.linux-riscv64': 12.4.1 + '@pnpm/exe.linux-s390x': 12.4.1 + '@pnpm/exe.linux-x64': 12.4.1 + '@pnpm/exe.linux-x64-musl': 12.4.1 + '@pnpm/exe.win32-arm64': 12.4.1 + '@pnpm/exe.win32-x64': 12.4.1 + +--- lockfileVersion: '9.0' settings: @@ -13,10 +171,14 @@ overrides: node-forge: 1.3.2 brace-expansion: 1.1.12 js-yaml: 4.1.1 - '@noble/hashes': 1.8.0 + '@noble/hashes@1': 1.8.0 vite-plugin-dts>brace-expansion: 2.0.2 + minimatch@10>brace-expansion: 5.0.9 protobufjs: 7.5.5 +patchedDependencies: + '@lifi/widget-light@4.3.2': 8ee9f6665560f5ce16422afed5a38522d274ad98ca518fe83619f682b53ed378 + importers: .: @@ -25,8 +187,13 @@ importers: specifier: 1.5.1 version: 1.5.1 '@blockscout/api-types': +<<<<<<< HEAD specifier: 0.0.1-beta.d261ddc version: 0.0.1-beta.d261ddc +======= + specifier: 0.0.1-beta.e1f332f + version: 0.0.1-beta.e1f332f +>>>>>>> v2.13.0 '@blockscout/bens-types': specifier: 1.7.1 version: 1.7.1 @@ -34,17 +201,17 @@ importers: specifier: 1.5.3 version: 1.5.3 '@blockscout/interchain-indexer-types': - specifier: 1.6.0 - version: 1.6.0 + specifier: 1.11.0 + version: 1.11.0 '@blockscout/multichain-aggregator-types': - specifier: 2.1.6 - version: 2.1.6 + specifier: 2.1.8 + version: 2.1.8 '@blockscout/points-types': specifier: 1.4.1 version: 1.4.1 '@blockscout/stats-types': - specifier: 2.11.1 - version: 2.11.1 + specifier: 2.19.1 + version: 2.19.1 '@blockscout/tac-operation-lifecycle-types': specifier: 0.0.1-beta.71a05d5 version: 0.0.1-beta.71a05d5 @@ -56,37 +223,52 @@ importers: version: 1.0.0-rc.10 '@chakra-ui/react': specifier: 3.36.1 - version: 3.36.1(@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4))(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + version: 3.36.1(@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4)(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + '@dnd-kit/core': + specifier: 6.3.1 + version: 6.3.1(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + '@dnd-kit/sortable': + specifier: 10.0.0 + version: 10.0.0(@dnd-kit/core@6.3.1(react-dom@19.1.4(react@19.1.4))(react@19.1.4))(react@19.1.4) + '@dnd-kit/utilities': + specifier: 3.2.2 + version: 3.2.2(react@19.1.4) '@dynamic-labs/ethereum': specifier: 4.91.4 - version: 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) + version: 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) '@dynamic-labs/ethereum-aa': specifier: 4.91.4 - version: 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@zerodev/webauthn-key@5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + version: 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@zerodev/webauthn-key@5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) '@dynamic-labs/sdk-react-core': specifier: 4.91.4 - version: 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + version: 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) '@dynamic-labs/wagmi-connector': specifier: 4.91.4 - version: 4.91.4(cd9ebb1a64f614b48e624e4e0701fe2e) + version: 4.91.4(86bf20e8ca9767cde8328256d5f07007) '@emotion/react': specifier: 11.14.0 - version: 11.14.0(@types/react@19.1.7)(react@19.1.4) + version: 11.14.0(@types/react@19.1.7)(react@19.1.4)(supports-color@10.2.2) '@graphiql/toolkit': specifier: 0.11.3 - version: 0.11.3(@types/node@20.16.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0) + version: 0.11.3(@types/node@24.13.4)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0) '@growthbook/growthbook-react': specifier: 0.21.0 version: 0.21.0(react@19.1.4) + '@helia/http': + specifier: 4.0.8 + version: 4.0.8 '@helia/verified-fetch': - specifier: 2.6.12 - version: 2.6.12(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(utf-8-validate@6.0.6) + specifier: 8.1.2 + version: 8.1.2(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6) '@internationalized/date': specifier: 3.12.2 version: 3.12.2 + '@lifi/widget-light': + specifier: 4.3.2 + version: 4.3.2(patch_hash=8ee9f6665560f5ce16422afed5a38522d274ad98ca518fe83619f682b53ed378)(@wagmi/core@2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(@wallet-standard/base@1.1.0)(react@19.1.4)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(wagmi@2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3)) '@metamask/post-message-stream': specifier: ^7.0.0 - version: 7.0.0 + version: 7.0.0(supports-color@10.2.2) '@metamask/providers': specifier: ^10.2.1 version: 10.2.1 @@ -95,7 +277,7 @@ importers: version: 4.7.0(monaco-editor@0.52.2)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) '@multisender.app/multisender-react-widget': specifier: 0.2.3 - version: 0.2.3(b9d9ab1f9c537c8f45225bdc5044ccc9) + version: 0.2.3(4c18776c2376832d04d8e6a63f20812b) '@next/bundle-analyzer': specifier: 16.2.4 version: 16.2.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) @@ -104,13 +286,13 @@ importers: version: 0.10.0 '@nouns/sdk': specifier: ^1.2.0 - version: 1.2.0(@tanstack/react-query@5.55.4(react@19.1.4))(@wagmi/core@2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(wagmi@2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76)) + version: 1.2.0(@tanstack/react-query@5.55.4(react@19.1.4))(@wagmi/core@2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(wagmi@2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3)) '@opentelemetry/api': specifier: ^1.9.1 version: 1.9.1 '@opentelemetry/auto-instrumentations-node': specifier: 0.75.0 - version: 0.75.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.8.0(@opentelemetry/api@1.9.1)) + version: 0.75.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.8.0(@opentelemetry/api@1.9.1))(supports-color@10.2.2) '@opentelemetry/exporter-jaeger': specifier: 2.8.0 version: 2.8.0(@opentelemetry/api@1.9.1) @@ -128,7 +310,7 @@ importers: version: 2.8.0(@opentelemetry/api@1.9.1) '@opentelemetry/sdk-node': specifier: 0.218.0 - version: 0.218.0(@opentelemetry/api@1.9.1) + version: 0.218.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/sdk-trace-node': specifier: 2.8.0 version: 2.8.0(@opentelemetry/api@1.9.1) @@ -140,19 +322,19 @@ importers: version: 5.4.0 '@reown/appkit': specifier: 1.7.20 - version: 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + version: 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-adapter-wagmi': specifier: 1.7.20 - version: 1.7.20(09e58c13ebbf9932f0a56e13a5b340ff) + version: 1.7.20(df3f0d3afef4414b7f4264d6db7d6a30) '@scure/base': specifier: 1.1.9 version: 1.1.9 '@slise/embed-react': specifier: ^2.2.0 version: 2.2.0(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@specify-sh/sdk': - specifier: 0.4.2 - version: 0.4.2 + '@specify-sh/publisher-sdk': + specifier: 1.2.0 + version: 1.2.0(react@19.1.4) '@tanstack/react-query': specifier: 5.55.4 version: 5.55.4(react@19.1.4) @@ -176,7 +358,7 @@ importers: version: 2.4.1(react-dom@19.1.4(react@19.1.4))(react@19.1.4) abitype: specifier: 1.2.3 - version: 1.2.3(@typescript/typescript6@6.0.2)(zod@3.25.76) + version: 1.2.3(@typescript/typescript6@6.0.2)(zod@4.4.3) airtable: specifier: ^0.12.2 version: 0.12.2 @@ -209,7 +391,7 @@ importers: version: 3.0.1(d3-selection@3.0.0) dappscout-iframe: specifier: 0.4.0 - version: 0.4.0(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + version: 0.4.0(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) dayjs: specifier: ^1.11.21 version: 1.11.21 @@ -222,9 +404,6 @@ importers: es-toolkit: specifier: 1.39.10 version: 1.39.10 - esbuild: - specifier: 0.25.12 - version: 0.25.12 focus-visible: specifier: ^5.2.1 version: 5.2.1 @@ -233,13 +412,16 @@ importers: version: https://codeload.github.com/blockscout/gradient-avatar/tar.gz/86810368c2581d2dc3aca089dc648336c8e17045 graphiql: specifier: ^4.1.2 - version: 4.1.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@20.16.7)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) + version: 4.1.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@24.13.4)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) graphql: specifier: ^16.14.0 version: 16.14.0 graphql-ws: specifier: ^5.16.2 version: 5.16.2(graphql@16.14.0) + helia: + specifier: 7.1.16 + version: 7.1.16(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6) js-cookie: specifier: ^3.0.7 version: 3.0.7 @@ -252,15 +434,18 @@ importers: monaco-editor: specifier: 0.52.2 version: 0.52.2 + multiformats: + specifier: 14.0.5 + version: 14.0.5 next: - specifier: 16.3.1 - version: 16.3.1(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.57.0)(@types/node@20.16.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + specifier: 16.4.3 + version: 16.4.3(@babel/core@7.29.7(supports-color@10.2.2))(@opentelemetry/api@1.9.1)(@playwright/test@1.62.1)(@types/node@24.13.4)(babel-plugin-macros@3.1.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) next-themes: specifier: 0.4.4 version: 0.4.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) nextjs-routes: specifier: 2.2.5 - version: 2.2.5(next@16.3.1(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.57.0)(@types/node@20.16.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)) + version: 2.2.5(next@16.4.3(@babel/core@7.29.7(supports-color@10.2.2))(@opentelemetry/api@1.9.1)(@playwright/test@1.62.1)(@types/node@24.13.4)(babel-plugin-macros@3.1.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)) node-fetch: specifier: ^3.3.2 version: 3.3.2 @@ -279,6 +464,9 @@ importers: pino-pretty: specifier: ^9.4.1 version: 9.4.1 + posthog-js: + specifier: 1.434.15 + version: 1.434.15(@types/react@19.1.7)(react@19.1.4) prom-client: specifier: 15.1.1 version: 15.1.1 @@ -320,7 +508,7 @@ importers: version: 2.26.5 swagger-ui-react: specifier: 5.32.6 - version: 5.32.6(@types/react@19.1.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + version: 5.32.6(@types/react@19.1.7)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react@19.1.4) use-font-face-observer: specifier: ^1.3.0 version: 1.3.0(react@19.1.4) @@ -329,20 +517,23 @@ importers: version: 1.2.0(@typescript/typescript6@6.0.2) viem: specifier: 2.41.2 - version: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + version: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) wagmi: specifier: 2.19.5 - version: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) + version: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) xss: specifier: ^1.0.15 version: 1.0.15 devDependencies: '@chakra-ui/cli': specifier: 3.36.1 - version: 3.36.1(@chakra-ui/react@3.36.1(@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4))(react-dom@19.1.4(react@19.1.4))(react@19.1.4)) + version: 3.36.1(@chakra-ui/react@3.36.1(@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4)(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react@19.1.4))(supports-color@10.2.2) + '@eslint-react/eslint-plugin': + specifier: 5.19.0 + version: 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) '@eslint/compat': specifier: 1.2.2 - version: 1.2.2(eslint@9.39.2) + version: 1.2.2(eslint@9.39.2(supports-color@10.2.2)) '@eslint/js': specifier: 9.14.0 version: 9.14.0 @@ -350,20 +541,29 @@ importers: specifier: 16.2.6 version: 16.2.6 '@playwright/experimental-ct-react': - specifier: 1.57.0 - version: 1.57.0(@types/node@20.16.7)(terser@5.48.0)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0))(yaml@2.9.0) + specifier: 1.62.1 + version: 1.62.1(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0))(yaml@2.9.0) '@playwright/test': - specifier: 1.57.0 - version: 1.57.0 + specifier: 1.62.1 + version: 1.62.1 + '@stryker-mutator/api': + specifier: 10.1.1 + version: 10.1.1 + '@stryker-mutator/core': + specifier: 10.1.1 + version: 10.1.1(@types/node@24.13.4) + '@stryker-mutator/vitest-runner': + specifier: 10.1.1 + version: 10.1.1(@stryker-mutator/core@10.1.1(@types/node@24.13.4))(vitest@5.0.0) '@stylistic/eslint-plugin': specifier: 5.2.3 - version: 5.2.3(eslint@9.39.2) + version: 5.2.3(eslint@9.39.2(supports-color@10.2.2)) '@svgr/webpack': specifier: ^6.5.1 - version: 6.5.1 + version: 6.5.1(supports-color@10.2.2) '@tanstack/eslint-plugin-query': specifier: 5.100.5 - version: 5.100.5(@typescript/typescript6@6.0.2)(eslint@9.39.2) + version: 5.100.5(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) '@testing-library/react': specifier: ^14.3.1 version: 14.3.1(react-dom@19.1.4(react@19.1.4))(react@19.1.4) @@ -392,8 +592,8 @@ importers: specifier: ^2.66.0 version: 2.66.0 '@types/node': - specifier: 20.16.7 - version: 20.16.7 + specifier: 24.13.4 + version: 24.13.4 '@types/phoenix': specifier: ^1.6.7 version: 1.6.7 @@ -415,57 +615,63 @@ importers: '@types/ws': specifier: ^8.18.1 version: 8.18.1 + '@typesafe-ai/sdk': + specifier: 0.6.0 + version: 0.6.0 '@typescript-eslint/eslint-plugin': specifier: ^5.62.0 - version: 5.62.0(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2) + version: 5.62.0(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) '@typescript/native': specifier: npm:typescript@7.0.2 version: typescript@7.0.2 '@vitejs/plugin-react': - specifier: ^4.3.4 - version: 4.3.4(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) + specifier: 6.1.2 + version: 6.1.2(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) + '@vitest/coverage-v8': + specifier: 5.0.0 + version: 5.0.0(vitest@5.0.0) css-loader: specifier: ^6.11.0 - version: 6.11.0(webpack@5.107.2(esbuild@0.25.12)(postcss@8.5.15)) + version: 6.11.0(webpack@5.107.2(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3)) dotenv-cli: specifier: 10.0.0 version: 10.0.0 eslint: specifier: 9.39.2 - version: 9.39.2 - eslint-config-next: - specifier: 16.2.6 - version: 16.2.6(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2) + version: 9.39.2(supports-color@10.2.2) + eslint-import-resolver-node: + specifier: 0.3.10 + version: 0.3.10(supports-color@10.2.2) eslint-plugin-boundaries: specifier: 6.0.2 - version: 6.0.2(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint@9.39.2) + version: 6.0.2(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) eslint-plugin-consistent-default-export-name: specifier: ^0.0.15 version: 0.0.15 eslint-plugin-import: specifier: 2.31.0 - version: 2.31.0(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint@9.39.2) + version: 2.31.0(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) eslint-plugin-import-helpers: specifier: 2.0.1 - version: 2.0.1(eslint@9.39.2) + version: 2.0.1(eslint@9.39.2(supports-color@10.2.2)) eslint-plugin-jsx-a11y: specifier: 6.10.2 - version: 6.10.2(eslint@9.39.2) + version: 6.10.2(eslint@9.39.2(supports-color@10.2.2)) eslint-plugin-playwright: specifier: 2.0.1 - version: 2.0.1(eslint@9.39.2) + version: 2.0.1(eslint@9.39.2(supports-color@10.2.2)) eslint-plugin-react: specifier: 7.37.5 - version: 7.37.5(eslint@9.39.2) + version: 7.37.5(eslint@9.39.2(supports-color@10.2.2)) eslint-plugin-react-hooks: specifier: 5.0.0 - version: 5.0.0(eslint@9.39.2) + version: 5.0.0(eslint@9.39.2(supports-color@10.2.2)) eslint-plugin-regexp: specifier: 2.6.0 - version: 2.6.0(eslint@9.39.2) + version: 2.6.0(eslint@9.39.2(supports-color@10.2.2)) eslint-plugin-vitest: specifier: 0.5.4 - version: 0.5.4(@typescript-eslint/eslint-plugin@5.62.0(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2)(vitest@4.1.7(@opentelemetry/api@1.9.1)(@types/node@20.16.7)(jsdom@27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6))(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0))) + version: 0.5.4(@typescript-eslint/eslint-plugin@5.62.0(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(vitest@5.0.0) globals: specifier: 15.12.0 version: 15.12.0 @@ -474,10 +680,10 @@ importers: version: 8.0.3 jsdom: specifier: 27.3.0 - version: 27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) + version: 27.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) license-report: specifier: 6.8.1 - version: 6.8.1 + version: 6.8.1(supports-color@10.2.2) license-report-check: specifier: 0.1.2 version: 0.1.2 @@ -492,58 +698,52 @@ importers: version: 2.0.0(@typescript/typescript6@6.0.2) style-loader: specifier: ^3.3.4 - version: 3.3.4(webpack@5.107.2(esbuild@0.25.12)(postcss@8.5.15)) + version: 3.3.4(webpack@5.107.2(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3)) svg-icons-cli: specifier: 0.0.8 version: 0.0.8 svgo: specifier: ^2.8.2 version: 2.8.2 - ts-node: - specifier: ^10.9.2 - version: 10.9.2(@types/node@20.16.7)(@typescript/typescript6@6.0.2) typescript: specifier: npm:@typescript/typescript6@6.0.2 version: '@typescript/typescript6@6.0.2' typescript-eslint: specifier: 8.59.2 - version: 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) + version: 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + vite: + specifier: 8.3.5 + version: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) vite-plugin-svgr: specifier: 5.2.0 - version: 5.2.0(@typescript/typescript6@6.0.2)(rollup@4.60.4)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) - vite-tsconfig-paths: - specifier: 5.1.4 - version: 5.1.4(@typescript/typescript6@6.0.2)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) + version: 5.2.0(@typescript/typescript6@6.0.2)(rollup@4.60.4)(supports-color@10.2.2)(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) vitest: - specifier: 4.1.7 - version: 4.1.7(@opentelemetry/api@1.9.1)(@types/node@20.16.7)(jsdom@27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6))(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) + specifier: 5.0.0 + version: 5.0.0(@opentelemetry/api@1.9.1)(@types/node@24.13.4)(@vitest/coverage-v8@5.0.0)(jsdom@27.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6))(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) vitest-fetch-mock: specifier: 0.4.5 - version: 0.4.5(vitest@4.1.7(@opentelemetry/api@1.9.1)(@types/node@20.16.7)(jsdom@27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6))(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0))) + version: 0.4.5(vitest@5.0.0) ws: specifier: 8.21.0 version: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) - deploy/tools/affected-tests: - dependencies: - dependency-tree: - specifier: 10.0.9 - version: 10.0.9 + deploy/tools/assets-downloader: + devDependencies: + '@types/node': + specifier: 24.13.4 + version: 24.13.4 + vite: + specifier: 8.3.5 + version: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) deploy/tools/envs-validator: devDependencies: - dotenv-cli: - specifier: ^7.4.4 - version: 7.4.4 - typescript: - specifier: 7.0.2 - version: 7.0.2 + valibot: + specifier: 1.2.0 + version: 1.2.0(@typescript/typescript6@6.0.2) vite: - specifier: 6.4.3 - version: 6.4.3(@types/node@25.9.2)(terser@5.48.0)(yaml@2.9.0) - yup: - specifier: ^1.7.1 - version: 1.7.1 + specifier: 8.3.5 + version: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) deploy/tools/essential-dapps-chains-config-generator: dependencies: @@ -552,20 +752,17 @@ importers: version: 1.39.10 viem: specifier: 2.38.6 - version: 2.38.6(bufferutil@4.1.0)(typescript@7.0.2)(utf-8-validate@6.0.6)(zod@4.4.3) + version: 2.38.6(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) devDependencies: '@types/node': - specifier: 22.12.0 - version: 22.12.0 + specifier: 24.13.4 + version: 24.13.4 dotenv-cli: specifier: 10.0.0 version: 10.0.0 - typescript: - specifier: 7.0.2 - version: 7.0.2 vite: - specifier: 6.4.3 - version: 6.4.3(@types/node@22.12.0)(terser@5.48.0)(yaml@2.9.0) + specifier: 8.3.5 + version: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) deploy/tools/favicon-generator: dependencies: @@ -576,17 +773,14 @@ importers: deploy/tools/feature-reporter: devDependencies: '@types/node': - specifier: 22.12.0 - version: 22.12.0 + specifier: 24.13.4 + version: 24.13.4 dotenv-cli: specifier: ^7.4.4 version: 7.4.4 - typescript: - specifier: 7.0.2 - version: 7.0.2 vite: - specifier: 6.4.3 - version: 6.4.3(@types/node@22.12.0)(terser@5.48.0)(yaml@2.9.0) + specifier: 8.3.5 + version: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) deploy/tools/llms-txt-generator: dependencies: @@ -598,44 +792,48 @@ importers: specifier: 0.7.2 version: 0.7.2 '@types/node': - specifier: 22.12.0 - version: 22.12.0 + specifier: 24.13.4 + version: 24.13.4 dotenv-cli: specifier: 10.0.0 version: 10.0.0 - typescript: - specifier: 7.0.2 - version: 7.0.2 vite: - specifier: 6.4.3 - version: 6.4.3(@types/node@22.12.0)(terser@5.48.0)(yaml@2.9.0) + specifier: 8.3.5 + version: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) deploy/tools/multichain-config-generator: devDependencies: '@types/node': - specifier: 22.12.0 - version: 22.12.0 - typescript: - specifier: 7.0.2 - version: 7.0.2 + specifier: 24.13.4 + version: 24.13.4 vite: - specifier: 6.4.3 - version: 6.4.3(@types/node@22.12.0)(terser@5.48.0)(yaml@2.9.0) + specifier: 8.3.5 + version: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) + + deploy/tools/og-image-generator: + devDependencies: + dotenv-cli: + specifier: 10.0.0 + version: 10.0.0 deploy/tools/sitemap-generator: dependencies: next-sitemap: specifier: 4.2.3 - version: 4.2.3(next@16.3.1(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.57.0)(@types/node@20.16.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)) + version: 4.2.3(next@16.4.3(@babel/core@8.0.1)(@opentelemetry/api@1.9.1)(@playwright/test@1.62.1)(@types/node@24.13.4)(babel-plugin-macros@3.1.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)) + devDependencies: + dotenv-cli: + specifier: 10.0.0 + version: 10.0.0 src/toolkit/package: dependencies: '@chakra-ui/react': specifier: '>=3.36.1' - version: 3.36.1(@emotion/react@11.14.0(@types/react@18.3.12)(react@19.1.4))(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + version: 3.36.1(@emotion/react@11.14.0(@types/react@18.3.12)(react@19.1.4)(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react@19.1.4) '@emotion/react': specifier: '>=11.14.0' - version: 11.14.0(@types/react@18.3.12)(react@19.1.4) + version: 11.14.0(@types/react@18.3.12)(react@19.1.4)(supports-color@10.2.2) '@internationalized/date': specifier: '>=3.12.2' version: 3.12.2 @@ -654,9 +852,6 @@ importers: es-toolkit: specifier: '>=1.39.10' version: 1.39.10 - next: - specifier: '>=16.2.6' - version: 16.2.6(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.57.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) next-themes: specifier: '>=0.4.4' version: 0.4.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) @@ -672,10 +867,10 @@ importers: devDependencies: '@svgr/plugin-jsx': specifier: 8.1.0 - version: 8.1.0(@svgr/core@8.1.0(@typescript/typescript6@6.0.2)) + version: 8.1.0(@svgr/core@8.1.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2))(supports-color@10.2.2) '@types/node': - specifier: 20.16.7 - version: 20.16.7 + specifier: 24.13.4 + version: 24.13.4 '@types/react': specifier: 18.3.12 version: 18.3.12 @@ -686,23 +881,20 @@ importers: specifier: npm:typescript@7.0.2 version: typescript@7.0.2 '@vitejs/plugin-react': - specifier: 4.3.4 - version: 4.3.4(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) + specifier: 6.1.2 + version: 6.1.2(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) typescript: specifier: npm:@typescript/typescript6@6.0.2 version: '@typescript/typescript6@6.0.2' vite: - specifier: 6.4.3 - version: 6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0) + specifier: 8.3.5 + version: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) vite-plugin-dts: specifier: 4.5.4 - version: 4.5.4(@types/node@20.16.7)(@typescript/typescript6@6.0.2)(rollup@4.60.4)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) + version: 4.5.4(@types/node@24.13.4)(@typescript/typescript6@6.0.2)(rollup@4.60.4)(supports-color@10.2.2)(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) vite-plugin-svgr: - specifier: 4.5.0 - version: 4.5.0(@typescript/typescript6@6.0.2)(rollup@4.60.4)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) - vite-tsconfig-paths: - specifier: 5.1.4 - version: 5.1.4(@typescript/typescript6@6.0.2)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) + specifier: 5.2.0 + version: 5.2.0(@typescript/typescript6@6.0.2)(rollup@4.60.4)(supports-color@10.2.2)(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) packages: @@ -760,32 +952,62 @@ packages: resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} engines: {node: '>=6.9.0'} + '@babel/code-frame@8.0.0': + resolution: {integrity: sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/compat-data@7.29.7': resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==} engines: {node: '>=6.9.0'} + '@babel/compat-data@8.0.0': + resolution: {integrity: sha512-DOjnob/cXOUgDOozCDeq/aK2p5y8dUIVdf6tNhEV1HQRd6I8aQ4f4fbtHRVEvb6lP3BGomrKHiS8ICAASSVQSw==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/core@7.29.7': resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==} engines: {node: '>=6.9.0'} + '@babel/core@8.0.1': + resolution: {integrity: sha512-5FgxM4dLQpMJHSiVATk8foW263dVHQHBVpXYiimNECVWG01f4nFyEbQixeT6Mwvg7TayREJ2gpKl3o2RoMdnqw==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/generator@7.29.7': resolution: {integrity: sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==} engines: {node: '>=6.9.0'} + '@babel/generator@8.0.0': + resolution: {integrity: sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-annotate-as-pure@7.29.7': resolution: {integrity: sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==} engines: {node: '>=6.9.0'} + '@babel/helper-annotate-as-pure@8.0.0': + resolution: {integrity: sha512-NSpMkMsvvZqzThJ0p1B02cbtA2ObEyfBvq950bmNkyxsxvcxwhvvCB036rKhlEnuBBo30bOrk13u3FzlKSoRrw==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-compilation-targets@7.29.7': resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==} engines: {node: '>=6.9.0'} + '@babel/helper-compilation-targets@8.0.0': + resolution: {integrity: sha512-JwculLABZvyPvyLBpwU/E/IbH2uM3mnxNtIJpxnIfb24y1PrdVxK5Dqjle4DpgqpGRnwgC7G8IkzPdSXZrO1Ew==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-create-class-features-plugin@7.29.7': resolution: {integrity: sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0 + '@babel/helper-create-class-features-plugin@8.0.1': + resolution: {integrity: sha512-++t3ZktzlLmASAxIlxeXQK9Z2YwUafYGYcvGBFevqOqt16HozVHStUoQvWD09fzAZOb/uJGpUTBuGK41AJAuOA==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/helper-create-regexp-features-plugin@7.29.7': resolution: {integrity: sha512-907Uymvqgg1dwUA+7IGwFAOSYzQOuzPXKNJ1yxzwPffzkYFg2q2eHi1fIOs6sXkG9NbIUMunnUlkYsfRFNvomg==} engines: {node: '>=6.9.0'} @@ -801,28 +1023,56 @@ packages: resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==} engines: {node: '>=6.9.0'} + '@babel/helper-globals@8.0.0': + resolution: {integrity: sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-member-expression-to-functions@7.29.7': resolution: {integrity: sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg==} engines: {node: '>=6.9.0'} + '@babel/helper-member-expression-to-functions@8.0.0': + resolution: {integrity: sha512-xkXrMbtk87Gk7+oKBVmBc6EORg/Qwx++AHESldmHkpvG8wgccdhJJFwrzqlF382Fk8wfXhJHWE/g/43QvEGNPQ==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-module-imports@7.29.7': resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==} engines: {node: '>=6.9.0'} + '@babel/helper-module-imports@8.0.0': + resolution: {integrity: sha512-NZ7mSS93o4ndX4KrbD7W8Sf3QT8Qe24PrnFyUcuOPDzK6faqDFKjY9RG7he7+I7FdiQ4llpnosFqzrXa+Vy3Ew==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-module-transforms@7.29.7': resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0 + '@babel/helper-module-transforms@8.0.1': + resolution: {integrity: sha512-UgAhl1kqiW5ciE0yCXqqvnb4H2n3IELJ7lIIQRezwDPilPEZX5i+Rvbja9MFTkwUn2biEiSMeV31aUzR4Lwakw==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/helper-optimise-call-expression@7.29.7': resolution: {integrity: sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong==} engines: {node: '>=6.9.0'} + '@babel/helper-optimise-call-expression@8.0.0': + resolution: {integrity: sha512-3W6satvtPuCUkUx63S2jMoW9EQNYkADgs1HTfufmL7gCmAulHMKupA/12WNz4A0GMMFn/YnWWwqOT9IZrJHQjg==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-plugin-utils@7.29.7': resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==} engines: {node: '>=6.9.0'} + '@babel/helper-plugin-utils@8.0.1': + resolution: {integrity: sha512-3PKFgjTyPlhFhorfP+SjKQxLViIL++zWjFOO4hGriYU+Bsm983DxEM1JmDRJVWXV0O9npu+xXRqz7Pbd3mh70g==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/helper-remap-async-to-generator@7.29.7': resolution: {integrity: sha512-16AMiW26DbXWBbr3B8wNozKM0ydMLB892vaOaJW/fPJdnT8vJk5sdkQcU/isqUxyCE0cEoa8wZOcbgDuC4b6Og==} engines: {node: '>=6.9.0'} @@ -835,22 +1085,44 @@ packages: peerDependencies: '@babel/core': ^7.0.0 + '@babel/helper-replace-supers@8.0.1': + resolution: {integrity: sha512-B1SZADIcy3tmH8CmWvj4SHi/oAPom4UL3uknTc2QRNsPVLFk/sPnZvQL/8kj7Y5omvjMqie0vklvs6XM4OLW5Q==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/helper-skip-transparent-expression-wrappers@7.29.7': resolution: {integrity: sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ==} engines: {node: '>=6.9.0'} + '@babel/helper-skip-transparent-expression-wrappers@8.0.0': + resolution: {integrity: sha512-xmCA9kP3IhySsqhzwIdWGlDN/1A4cCKNBO/uwZx/3YzmDoMePwno2Q5/Bq0q+tYaKbeF940YiKV/kaW8Mzvpjw==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-string-parser@7.29.7': resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} engines: {node: '>=6.9.0'} + '@babel/helper-string-parser@8.0.0': + resolution: {integrity: sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-validator-identifier@7.29.7': resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} engines: {node: '>=6.9.0'} + '@babel/helper-validator-identifier@8.0.4': + resolution: {integrity: sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-validator-option@7.29.7': resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==} engines: {node: '>=6.9.0'} + '@babel/helper-validator-option@8.0.0': + resolution: {integrity: sha512-U4Dybxh4WESWHt5XhBeExi4DrY0/DNK1aHpQbsrQXCUbFHuMweT0TpLEWKvaraV2Y6fS+ZXunsZ8zIuZIgvF2Q==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-wrap-function@7.29.7': resolution: {integrity: sha512-iES0Skag9ERIF68aXadpO6dbXa03mNWK3sEqJaMnLNs/eC3l0lkImdfoy6Y09/SfkpawdAB4RjQ7PVA7TcVGdw==} engines: {node: '>=6.9.0'} @@ -859,11 +1131,20 @@ packages: resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==} engines: {node: '>=6.9.0'} + '@babel/helpers@8.0.0': + resolution: {integrity: sha512-wfbi91pM3py96oIiJEz7qIpyXDytgr9zQC1HEWwlGNVRAEmItuU/0a41ZUKu1sJGyhhOIpc4t5vk4PYzt8wpsg==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/parser@7.29.7': resolution: {integrity: sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==} engines: {node: '>=6.0.0'} hasBin: true + '@babel/parser@8.0.4': + resolution: {integrity: sha512-srpptsAkEbbNIC/q8nT7o+m6CQe8CJUTV/t7MYc9NnWlgYVtHOb7JH6SorxMhN0kuRJjVqXbKClG6xSbPtzz+g==} + engines: {node: ^22.18.0 || >=24.11.0} + hasBin: true + '@babel/plugin-bugfix-firefox-class-in-computed-class-key@7.29.7': resolution: {integrity: sha512-j8SrR0zLZrRsC09DlszEx8FpMiwukKffYXMK0d5LmOglO7vGG6sz/BR/20yHqWH+Lnn31JTt2PE3hIWNgM2J6w==} engines: {node: '>=6.9.0'} @@ -900,12 +1181,24 @@ packages: peerDependencies: '@babel/core': ^7.0.0 + '@babel/plugin-proposal-decorators@8.0.2': + resolution: {integrity: sha512-+C6O6KKXU7BBq1GNaIkFJxrALUVGRcr+WeWm4OcuRl3h+l/CmNfcTLMrT2Lm3uvGBimBH/8pEBRrXJFLoO67Gg==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2': resolution: {integrity: sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-syntax-decorators@8.0.1': + resolution: {integrity: sha512-NI+0S/6MvR6GlcQFwjDZ+WIc2qvG6TXN534lYs9llNldwW4b7Dh6KTtk030FA0xWdYGs4t1lWo+OEWN8wGB+Nw==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/plugin-syntax-import-assertions@7.29.7': resolution: {integrity: sha512-/An1OCBN93thpBAGyfsK2pcf0jvju1SAtKkL2Ny++B5Sy6sqgzXDQH1cZxWbF96Wuk+bn41MDA9bLd4VVAw6rw==} engines: {node: '>=6.9.0'} @@ -924,12 +1217,24 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-syntax-jsx@8.0.1': + resolution: {integrity: sha512-n0jtCOxEovhU7METqSQjcZO9pX53nu9uNIjMS+hEt+Nt9jA7oOZoBIgbCxhhASmF6T6rPDGge5UAvh6Z4eFz/g==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/plugin-syntax-typescript@7.29.7': resolution: {integrity: sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-syntax-typescript@8.0.3': + resolution: {integrity: sha512-jmTPwps7oSQSZaV1SxkQ3C12UWyufGysGc5OzDpZzvPAIX4mO7dJT3hoqkWVrSImvkcMiknir1iLN1SNV/CZzg==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/plugin-syntax-unicode-sets-regex@7.18.6': resolution: {integrity: sha512-727YkEAPwSIQTv5im8QHz3upqp92JTWhidIC81Tdx4VJYIte/VndKf1qKrfnnhPLiPghStWfvC/iFaMCQu7Nqg==} engines: {node: '>=6.9.0'} @@ -996,6 +1301,12 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-transform-destructuring@8.0.1': + resolution: {integrity: sha512-RtR8uLDl0QcCmqMNIkM8gmDeYZ3rS0ZH+sa+I6sfc09yFoqfp9AEPgBstq9KyfVb0lFCVSRFfJXCI70FIl5ccw==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/plugin-transform-dotall-regex@7.29.7': resolution: {integrity: sha512-3qc18hsD2RdZiyJNDNc7HQpv6xbncwh8FYtxNFFzclSyh/trPD9KkVR9BDECUjDLvb7yJVF15GfYUuC+LMkkiQ==} engines: {node: '>=6.9.0'} @@ -1026,6 +1337,12 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-transform-explicit-resource-management@8.0.1': + resolution: {integrity: sha512-VzDIYwBlLCpV6mJfloRdJm8HmYnMqs7O+bGha8yfg2kP7jAdxeCw6yZBVBeaKKQUThtSU52iy+3lB7DhYsbOBA==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/plugin-transform-exponentiation-operator@7.29.7': resolution: {integrity: sha512-zFpMOTLZBdW5LfObqcSbL6kefg4R4eLdmvS0wbN9M6D5Mym/sKm9toOoWyVOa+xDjvCnuWcHls2YonXwHvH3CQ==} engines: {node: '>=6.9.0'} @@ -1086,6 +1403,12 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-transform-modules-commonjs@8.0.1': + resolution: {integrity: sha512-PMuzulWrrzFNmY3lXSk/tV9NRb7y0eZZLJY4UEo2TKszroxvUZHAPPi+T9FDyrQhod+TQA+t+8/QYaaMpiEuhA==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/plugin-transform-modules-systemjs@7.29.7': resolution: {integrity: sha512-TM2ZcQLoG2/y4HODiStCo10DibYhWhGWAwVv+EQKmG/7GFl0N+AAmUiXOMKM+aiJ9XBJ9AHVZBvTzMnJ2sM3cQ==} engines: {node: '>=6.9.0'} @@ -1182,23 +1505,23 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 - '@babel/plugin-transform-react-jsx-development@7.29.7': - resolution: {integrity: sha512-Xfy3UVMF04+ypnFbkhvfqtmvwfe92qwQdbGZVonhE+6v35GzlofmOnA1szaZqzb9xYWr0nl1e5EMmzi0DNON1g==} - engines: {node: '>=6.9.0'} + '@babel/plugin-transform-react-display-name@8.0.1': + resolution: {integrity: sha512-soLishXlkyu6jcICPyO3HEP7A3GCzKEnn7XfvYrImuWEOwFAz93qShmWSYPf5ww0ZkO4By0zsN2bVIDF54fSdA==} + engines: {node: ^22.18.0 || >=24.11.0} peerDependencies: - '@babel/core': ^7.0.0-0 + '@babel/core': ^8.0.0 - '@babel/plugin-transform-react-jsx-self@7.29.7': - resolution: {integrity: sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==} + '@babel/plugin-transform-react-jsx-development@7.29.7': + resolution: {integrity: sha512-Xfy3UVMF04+ypnFbkhvfqtmvwfe92qwQdbGZVonhE+6v35GzlofmOnA1szaZqzb9xYWr0nl1e5EMmzi0DNON1g==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0-0 - '@babel/plugin-transform-react-jsx-source@7.29.7': - resolution: {integrity: sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==} - engines: {node: '>=6.9.0'} + '@babel/plugin-transform-react-jsx-development@8.0.1': + resolution: {integrity: sha512-Hb+HUZpV9KFHjm+F+P3aLDMi8QXU9l3ROCQv20z18Me2sGyW5nNNR5YTevNlgHvCpFek3BnAwhDGq/BRndXViw==} + engines: {node: ^22.18.0 || >=24.11.0} peerDependencies: - '@babel/core': ^7.0.0-0 + '@babel/core': ^8.0.0 '@babel/plugin-transform-react-jsx@7.29.7': resolution: {integrity: sha512-WsZulLVBUHXVj2cUcPVx6UE21TpalB6bHbSFErKT0Ib++ax24jjXe73FqlWvdylFOjiuPHYi6VCcgRad1ItN+A==} @@ -1206,12 +1529,24 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-transform-react-jsx@8.0.1': + resolution: {integrity: sha512-NgkoF7Uq+30TmOPDdNUimT0Nta02uVjqJRFNlVWKrbOCu/CkzfHa4aMnIs0lMpkMmZmWA1e42Va+F04i/pY1zw==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/plugin-transform-react-pure-annotations@7.29.7': resolution: {integrity: sha512-H5E+HBgDpr6Q5t+Aj11tL7XkIui1jhbIoArVQnqjgXo5/3YxkN7ZEBcWF4RQlB0T4rrxJQbXS6kiFV6B7XTqUA==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-transform-react-pure-annotations@8.0.1': + resolution: {integrity: sha512-7/8UwU8hoPBurXa9tUiTTC8aACTRy5tCqLUtqikHp2eGiWoEB57AduOdbQ71OOMTEvawKrGhv3WfzkDpI+/oSg==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/plugin-transform-regenerator@7.29.7': resolution: {integrity: sha512-rNNFV0DBAJp988xW2DOntfDoYn1eR8GGF5AT5vYc+rjyfaQkM242c9tZUHHPe7KYaiJizXPWhQTzzdbXySyhBw==} engines: {node: '>=6.9.0'} @@ -1266,6 +1601,12 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/plugin-transform-typescript@8.0.1': + resolution: {integrity: sha512-0Svqp3413Eg0GElldykF/T7SNsxQO5YVGD70fZyAdZTnX8WRgcopmbiU7GTa5xY5ZnJcEpNbfns8/GjX+/1yeA==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/plugin-transform-unicode-escapes@7.29.7': resolution: {integrity: sha512-jCfXxSjf94lf4E0hKE0AByxF6F3/pVFqRdUUNkDJhsY0m1ZKjnN6ZYyMeHNpzflxb/0q5b7t3p+BE+SLF1WOtA==} engines: {node: '>=6.9.0'} @@ -1307,12 +1648,24 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/preset-react@8.0.1': + resolution: {integrity: sha512-jrFuPp/pTddFZbtmWhdLNAYc6UMcpboeUPnw0BBrm4nOmcAko/1TRcFi1PzWCeOFRU+VaSiKmat87W1HvR7mIg==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/preset-typescript@7.29.7': resolution: {integrity: sha512-/Foi8vKY2EVbed/1eZx0gJEEwHAIxogrySI7rULcRIvhZzbvoE/b5qG5Ghc0WKAFKOHA9SD1x7RsFlOYdutIiQ==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/preset-typescript@8.0.1': + resolution: {integrity: sha512-qrPhQIN1NLrPmzgazF9XKQqXrOcp/WJly+K+6ReFonn24FZqRJO7clxOJo6Ni75L+2vAqI3cHVU2OJLBxoPp5A==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/runtime-corejs3@7.29.7': resolution: {integrity: sha512-ppj9ouYku+RX0ljtgZd+KMO5mkM2bCqg8H2PYAFWnLsHEIKIdRojqbJ2i3eVHrisuxy7nOFCmngTDdWtUCdXUQ==} engines: {node: '>=6.9.0'} @@ -1325,25 +1678,46 @@ packages: resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==} engines: {node: '>=6.9.0'} + '@babel/template@8.0.0': + resolution: {integrity: sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/traverse@7.29.7': resolution: {integrity: sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==} engines: {node: '>=6.9.0'} + '@babel/traverse@8.0.4': + resolution: {integrity: sha512-bZnmqzGG8UZneG1lLxBoWIH0G6Gr1D846Yu4/3XnY6FhCndMR49u26nTY08u/dAxWmLWF9vGQOuC+84FfIUoeg==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/types@7.29.7': resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==} engines: {node: '>=6.9.0'} + '@babel/types@8.0.4': + resolution: {integrity: sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g==} + engines: {node: ^22.18.0 || >=24.11.0} + '@base-org/account@1.1.1': resolution: {integrity: sha512-IfVJPrDPhHfqXRDb89472hXkpvJuQQR7FDI9isLPHEqSYt/45whIoBxSPgZ0ssTt379VhQo4+87PWI1DoLSfAQ==} '@base-org/account@2.4.0': resolution: {integrity: sha512-A4Umpi8B9/pqR78D1Yoze4xHyQaujioVRqqO3d6xuDFw9VRtjg6tK3bPlwE0aW+nVH/ntllCpPa2PbI8Rnjcug==} + '@bcoe/v8-coverage@1.0.2': + resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==} + engines: {node: '>=18'} + '@blockscout/admin-rs-types@1.5.1': resolution: {integrity: sha512-+wGwULmzzfwkASJKwPB1X09iqmNUeIPu7Pc5INQxL2XunllTs32bhyvji1XqyA+VmF5yOxxYhQuLhNqCeN4SfQ==} +<<<<<<< HEAD '@blockscout/api-types@0.0.1-beta.d261ddc': resolution: {integrity: sha512-9xB/r+C+MrtGhkielJojMPPfEQXQu+wpU09pctQoRfyfkdGVfWz5HCz8fqRY8D6CrBbR8P8+TKXYyF/NhwUJBA==} +======= + '@blockscout/api-types@0.0.1-beta.e1f332f': + resolution: {integrity: sha512-PXmfc3JpAtHJ9eq7Leu7eo3MvEWHnMs7PFCSjbnwnN5NjO5du89gmSpqIcCeYA6QsKxrQmhzRsFfX81K7xmpig==} +>>>>>>> v2.13.0 '@blockscout/bens-types@1.7.1': resolution: {integrity: sha512-MNIvYbj1I2vcU2rb6otlRnVMIpFG2B1WDqC7HicNrt10DbM5yPZNfBcsNM+Mhk/965Aeg529Fd+BkV9zhINqjA==} @@ -1351,17 +1725,17 @@ packages: '@blockscout/contracts-info-types@1.5.3': resolution: {integrity: sha512-J+n4C+H9418r2xcIJLPEpK6WJnhJVRGZVaRzpUpXmcxBkIqzsKqfxBMddaDt5uQX8OnQJyZY3fSkfoGAAfBQaw==} - '@blockscout/interchain-indexer-types@1.6.0': - resolution: {integrity: sha512-zWrL3tWqXqvQre9SURlheD6jxp447Ujv7tP35a94K0Ovs3bYCT/ydsUmLoZY3CrqKyRr6cTu8V/1qUql5l9Cpw==} + '@blockscout/interchain-indexer-types@1.11.0': + resolution: {integrity: sha512-vQvnAiqQJVJXmBGtRYeuz64Qlu+IgexSjkI+54VHldic0wIuxbgsgT3HWxYx4p2mZ3Yn/HpCKhcX9ijl2dWJQQ==} - '@blockscout/multichain-aggregator-types@2.1.6': - resolution: {integrity: sha512-qpotHqUXhp8NFZ9JioCn2B/gewWQ5stTV9QoHKnUbO/0HzXkLvJXdsOjqhkBlaVcOKEMFY08+T3t9O0oI0wQEA==} + '@blockscout/multichain-aggregator-types@2.1.8': + resolution: {integrity: sha512-j8dqb4h22FYQv3JdYa2pJp30P8YmLW556z/6u/JaT8rQyPylUY1oIZJ5944yhOtJsDUAgwzLsafFiPShTLgRog==} '@blockscout/points-types@1.4.1': resolution: {integrity: sha512-8aIE1od1zzXeVfQCIO8LU1aWT/CRx82t+1ZK4RbgFFrxWH8RX0Yo+I6haeraVj3qKjxiMkBda1xMbGohiKgXSg==} - '@blockscout/stats-types@2.11.1': - resolution: {integrity: sha512-Ti9RbekRfLR7dUnOp2dWU0VBu7uRkutnkFqKphvfxvbrY9fiXUJ/tT6Qg+OTNewK3RbuQ0O1ZPxbqMX5eRr0OQ==} + '@blockscout/stats-types@2.19.1': + resolution: {integrity: sha512-94PhDtR+WbylCuV01JhxW3f1jm4LfAIsY+yMgLEGam/iYcleZ4oMdCW9TtJj0X4HokyWWYTkUS2JGENn0WLE9Q==} '@blockscout/tac-operation-lifecycle-types@0.0.1-beta.71a05d5': resolution: {integrity: sha512-SFHCKG+Q1c+zn91HGcPdfVoLlxmk2uD55IiILJ6VIgfg5IhHLKLeu4+eoTwByq6fMirmyy1F/ywIdRhhQBFjUw==} @@ -1388,12 +1762,6 @@ packages: '@chainsafe/is-ip@2.1.0': resolution: {integrity: sha512-KIjt+6IfysQ4GCv66xihEitBjvhU/bixbbbFxdJ1sqCp4uJ0wuZiYBPhksZoy4lfaF0k9cwNzY5upEW/VWdw3w==} - '@chainsafe/libp2p-noise@16.1.5': - resolution: {integrity: sha512-yac0bknwfuYdXXOAFGVL4fYR0de0p1Uk7W0gIkuxlj8JSqhkHr+kEt3958PfnfmX880QJAIogsh/ZupFjg0uJA==} - - '@chainsafe/libp2p-yamux@7.0.4': - resolution: {integrity: sha512-Qw+EB9ew/9hRCq9V702gkm5xXThFHQ3Bdvh01M+enI1RScriSDWFGod02dwNHUxsYRc743i49sLlHp0edC7hSQ==} - '@chainsafe/netmask@2.0.0': resolution: {integrity: sha512-I3Z+6SWUoaljh3TBzCnCxjlUyN8tA+NAk5L6m9IxvCf1BENQTePzPMis97CoN/iMW1St3WN+AWCCRp+TTBRiDg==} @@ -1702,10 +2070,6 @@ packages: resolution: {integrity: sha512-LY1lFiZLTQF/ma1ilfKmRmFmEOw0RfYhyl0UMhY7/d93b+kiDMhxP/9Qir4+5LyiRncaE3++ZcWno9Hya+ssRg==} engines: {node: '>=20'} - '@cspotcode/source-map-support@0.8.1': - resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} - engines: {node: '>=12'} - '@csstools/color-helpers@6.0.2': resolution: {integrity: sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==} engines: {node: '>=20.19.0'} @@ -1745,14 +2109,32 @@ packages: '@csstools/normalize.css@12.1.1': resolution: {integrity: sha512-YAYeJ+Xqh7fUou1d1j9XHl44BmsuThiTr4iNrgCQ3J27IbhXsxXDGZ1cXv8Qvs99d4rBbLiSKy3+WZiet32PcQ==} - '@dependents/detective-less@4.1.0': - resolution: {integrity: sha512-KrkT6qO5NxqNfy68sBl6CTSoJ4SNDIS5iQArkibhlbGU4LaDukZ3q2HIkh8aUKDio6o4itU4xDR7t82Y2eP1Bg==} - engines: {node: '>=14'} - '@discoveryjs/json-ext@0.5.7': resolution: {integrity: sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==} engines: {node: '>=10.0.0'} + '@dnd-kit/accessibility@3.1.1': + resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==} + peerDependencies: + react: '>=16.8.0' + + '@dnd-kit/core@6.3.1': + resolution: {integrity: sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==} + peerDependencies: + react: '>=16.8.0' + react-dom: '>=16.8.0' + + '@dnd-kit/sortable@10.0.0': + resolution: {integrity: sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==} + peerDependencies: + '@dnd-kit/core': ^6.3.0 + react: '>=16.8.0' + + '@dnd-kit/utilities@3.2.2': + resolution: {integrity: sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==} + peerDependencies: + react: '>=16.8.0' + '@dnsquery/dns-packet@6.1.1': resolution: {integrity: sha512-WXTuFvL3G+74SchFAtz3FgIYVOe196ycvGsMgvSH/8Goptb1qpIQtIuM4SOK9G9lhMWYpHxnXyy544ZhluFOew==} engines: {node: '>=6'} @@ -2016,312 +2398,156 @@ packages: '@emotion/weak-memoize@0.4.0': resolution: {integrity: sha512-snKqtPW01tN0ui7yu9rGv69aJXr/a/Ywvl11sUjNtEcRc+ng/mQriFL0wLXMef74iHa/EkftbDzU9F8iFbH+zg==} - '@esbuild/aix-ppc64@0.25.12': - resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [aix] - '@esbuild/aix-ppc64@0.28.1': resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==} engines: {node: '>=18'} cpu: [ppc64] os: [aix] - '@esbuild/android-arm64@0.25.12': - resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [android] - '@esbuild/android-arm64@0.28.1': resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==} engines: {node: '>=18'} cpu: [arm64] os: [android] - '@esbuild/android-arm@0.25.12': - resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==} - engines: {node: '>=18'} - cpu: [arm] - os: [android] - '@esbuild/android-arm@0.28.1': resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==} engines: {node: '>=18'} cpu: [arm] os: [android] - '@esbuild/android-x64@0.25.12': - resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==} - engines: {node: '>=18'} - cpu: [x64] - os: [android] - '@esbuild/android-x64@0.28.1': resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==} engines: {node: '>=18'} cpu: [x64] os: [android] - '@esbuild/darwin-arm64@0.25.12': - resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [darwin] - '@esbuild/darwin-arm64@0.28.1': resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==} engines: {node: '>=18'} cpu: [arm64] os: [darwin] - '@esbuild/darwin-x64@0.25.12': - resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==} - engines: {node: '>=18'} - cpu: [x64] - os: [darwin] - '@esbuild/darwin-x64@0.28.1': resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==} engines: {node: '>=18'} cpu: [x64] os: [darwin] - '@esbuild/freebsd-arm64@0.25.12': - resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [freebsd] - '@esbuild/freebsd-arm64@0.28.1': resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==} engines: {node: '>=18'} cpu: [arm64] os: [freebsd] - '@esbuild/freebsd-x64@0.25.12': - resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [freebsd] - '@esbuild/freebsd-x64@0.28.1': resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==} engines: {node: '>=18'} cpu: [x64] os: [freebsd] - '@esbuild/linux-arm64@0.25.12': - resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==} - engines: {node: '>=18'} - cpu: [arm64] - os: [linux] - '@esbuild/linux-arm64@0.28.1': resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==} engines: {node: '>=18'} cpu: [arm64] os: [linux] - '@esbuild/linux-arm@0.25.12': - resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==} - engines: {node: '>=18'} - cpu: [arm] - os: [linux] - '@esbuild/linux-arm@0.28.1': resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==} engines: {node: '>=18'} cpu: [arm] os: [linux] - '@esbuild/linux-ia32@0.25.12': - resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==} - engines: {node: '>=18'} - cpu: [ia32] - os: [linux] - '@esbuild/linux-ia32@0.28.1': resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==} engines: {node: '>=18'} cpu: [ia32] os: [linux] - '@esbuild/linux-loong64@0.25.12': - resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==} - engines: {node: '>=18'} - cpu: [loong64] - os: [linux] - '@esbuild/linux-loong64@0.28.1': resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==} engines: {node: '>=18'} cpu: [loong64] os: [linux] - '@esbuild/linux-mips64el@0.25.12': - resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==} - engines: {node: '>=18'} - cpu: [mips64el] - os: [linux] - '@esbuild/linux-mips64el@0.28.1': resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==} engines: {node: '>=18'} cpu: [mips64el] os: [linux] - '@esbuild/linux-ppc64@0.25.12': - resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [linux] - '@esbuild/linux-ppc64@0.28.1': resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==} engines: {node: '>=18'} cpu: [ppc64] os: [linux] - '@esbuild/linux-riscv64@0.25.12': - resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==} - engines: {node: '>=18'} - cpu: [riscv64] - os: [linux] - '@esbuild/linux-riscv64@0.28.1': resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==} engines: {node: '>=18'} cpu: [riscv64] os: [linux] - '@esbuild/linux-s390x@0.25.12': - resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==} - engines: {node: '>=18'} - cpu: [s390x] - os: [linux] - '@esbuild/linux-s390x@0.28.1': resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==} engines: {node: '>=18'} cpu: [s390x] os: [linux] - '@esbuild/linux-x64@0.25.12': - resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==} - engines: {node: '>=18'} - cpu: [x64] - os: [linux] - '@esbuild/linux-x64@0.28.1': resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==} engines: {node: '>=18'} cpu: [x64] os: [linux] - '@esbuild/netbsd-arm64@0.25.12': - resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [netbsd] - '@esbuild/netbsd-arm64@0.28.1': resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==} engines: {node: '>=18'} cpu: [arm64] os: [netbsd] - '@esbuild/netbsd-x64@0.25.12': - resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [netbsd] - '@esbuild/netbsd-x64@0.28.1': resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==} engines: {node: '>=18'} cpu: [x64] os: [netbsd] - '@esbuild/openbsd-arm64@0.25.12': - resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openbsd] - '@esbuild/openbsd-arm64@0.28.1': resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==} engines: {node: '>=18'} cpu: [arm64] os: [openbsd] - '@esbuild/openbsd-x64@0.25.12': - resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==} - engines: {node: '>=18'} - cpu: [x64] - os: [openbsd] - '@esbuild/openbsd-x64@0.28.1': resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==} engines: {node: '>=18'} cpu: [x64] os: [openbsd] - '@esbuild/openharmony-arm64@0.25.12': - resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openharmony] - '@esbuild/openharmony-arm64@0.28.1': resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==} engines: {node: '>=18'} cpu: [arm64] os: [openharmony] - '@esbuild/sunos-x64@0.25.12': - resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==} - engines: {node: '>=18'} - cpu: [x64] - os: [sunos] - '@esbuild/sunos-x64@0.28.1': resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==} engines: {node: '>=18'} cpu: [x64] os: [sunos] - '@esbuild/win32-arm64@0.25.12': - resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [win32] - '@esbuild/win32-arm64@0.28.1': resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==} engines: {node: '>=18'} cpu: [arm64] os: [win32] - '@esbuild/win32-ia32@0.25.12': - resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==} - engines: {node: '>=18'} - cpu: [ia32] - os: [win32] - '@esbuild/win32-ia32@0.28.1': resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==} engines: {node: '>=18'} cpu: [ia32] os: [win32] - '@esbuild/win32-x64@0.25.12': - resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==} - engines: {node: '>=18'} - cpu: [x64] - os: [win32] - '@esbuild/win32-x64@0.28.1': resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==} engines: {node: '>=18'} @@ -2338,6 +2564,55 @@ packages: resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + '@eslint-react/ast@5.19.0': + resolution: {integrity: sha512-6d9UY/CVz+zGMi6+aext7HSOVAj2Fa9eL7okBRnjBeMrRhmRAqtbm1oK7J+VlWrmUNLsiNXpyklhq36BsmYddg==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + + '@eslint-react/core@5.19.0': + resolution: {integrity: sha512-PFhetWfvG6ZhLiJomkzjKKCLu6DVbKdyeYZ7HE7/rvAvmfsNi9iCGBqxkgXWfWpWEf24KrRUVpS3wLGJpPL8+g==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + + '@eslint-react/eslint-plugin@5.19.0': + resolution: {integrity: sha512-SA3+Iz87sH3pq8hFHb+QhYrOpOyzut+k9YCx2WCJsapK3fu7odk73GRXB6J/W5f8tz0J0ARj1r+DsaSdGtF/zw==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + + '@eslint-react/eslint@5.19.0': + resolution: {integrity: sha512-wod1Yd/atJbUD36naGirzztZ9w4BAWSxwIxF8/6qT7PaN/Q9r/vTB/T5rmmgvMa3C/hp0yI3uqr4zbO2mRPBOQ==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + + '@eslint-react/jsx@5.19.0': + resolution: {integrity: sha512-iqauNb+qeNaEbG7VfDj+8taRLJFbEkptzdPx+YnIbyxhCVAnMaB3s/yeVyi4nszja7YwE/FccFInPZ4Qv8fVZw==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + + '@eslint-react/shared@5.19.0': + resolution: {integrity: sha512-4x56YzT3Gph725Z8x1vMbOYUkOpbqp2v9NuFb9F7GqVmyZq9OxAQPEj5b7o+Fd2C1VIC3mHNCfL3FHVZ1YH8mA==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + + '@eslint-react/var@5.19.0': + resolution: {integrity: sha512-dRRM/AYqQli1VNijY7n0+q4zUlNCGiOY1wGr1r+c5ajvlv/XwGibhTJjY6zGZWIjL9TUMIbIEH8aOdRaw2iNQg==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + '@eslint/compat@1.2.2': resolution: {integrity: sha512-jhgiIrsw+tRfcBQ4BFl2C3vCrIUw2trCY0cnDvGZpwTtKCEDmZhAtMfrEUP/KpnwM6PrO0T+Ltm+ccW74olG3Q==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2543,35 +2818,47 @@ packages: react: ^18 || ^19 || ^19.0.0-rc react-dom: ^18 || ^19 || ^19.0.0-rc - '@helia/bitswap@2.2.0': - resolution: {integrity: sha512-fYHjXM8SZpgRkGRM7qq8VVpBsrSLHlRGTLUEesfKZ+wYBYHZaqpn0mT9KbdLZowLrooz0qaUUiF6OIZBNmArcw==} + '@helia/bitswap@4.0.20': + resolution: {integrity: sha512-spJhbrfpgeBzkweULgimtdQv3xPMkKiZmShmtQ36lFYh0NbuegBkb1Dv7zFyQOtUdK0LJJKEBeBDLcb5StJZag==} + + '@helia/car@6.0.9': + resolution: {integrity: sha512-DkVCq/XO3keQTAsxoLk8uaKdjqzh2HMM3vqaNCeFaFr6lMSnvKPqPEdZRy2fVHz18qP70WAhcwep1uI5P+bYJw==} - '@helia/block-brokers@4.2.4': - resolution: {integrity: sha512-Xz7JyRIprbldi5bxfvuj5xTDijkfndgLPKoK/AUVeFOBD0n04Cb6RzqYGVQN6of8a6hfL6tD0fO4RVUFh/Jl6A==} + '@helia/delegated-routing-client@1.0.7': + resolution: {integrity: sha512-AqhPwY8libDs4VLVibLGIz0J3MPmTi8Mx0ljEiWdYLhziU82T3AjW10qBQ3oGSDrMd6tA9lEOoviAbPL88y0OQ==} - '@helia/car@4.2.0': - resolution: {integrity: sha512-COX0l9mjqjl4Cybq0b5HKW/K1z77LOiiJfEZBF4MziVUUPfD/ivX6B6bqe889+YotUWO/vEv/HBY1m+BF2HeTQ==} + '@helia/delegated-routing-v1-http-api-client@9.0.2': + resolution: {integrity: sha512-NVbX/8Uf+04g5gZkpqk6J6aFMCgMxzyQ2XBxW2gpYysGEuMSEESRyiYuWUrKysy9Oo08ST4tJJ19Vh/+4wjzOA==} - '@helia/delegated-routing-v1-http-api-client@4.2.5': - resolution: {integrity: sha512-fFqVhs7a4TnpKQ1cZ4im3tj53v+8UZLFkQo85otl/GpbIVBmBoGbjkDHGPv4UdjJ2lmYM/cRdnHsYbfjuc5pwA==} + '@helia/dnslink@2.0.2': + resolution: {integrity: sha512-diDgiDEdo8GcwFOYHucxtbmYLmuMRTmGTnv0z1P+F5yX9BIuMGcMmPafknxGVPrQNP00LFBmi/Ed54BcEv3puw==} - '@helia/interface@5.4.0': - resolution: {integrity: sha512-UfY/Xa2qYJ6Bh4XUUSgwU3s2VY69cKwRznkS9Ab0C3ciU+dUeyz3IPIn5qqRGVfNVM9SD2wISXmwA7FJvhdRAQ==} + '@helia/fallback-router@1.1.2': + resolution: {integrity: sha512-BBXyfkLI+HPSKAxjQ/zIdWGNtB8o2C47Obm/48WjBsz24DSt+hA+wQYLLqa8BH1vW061gIleBWmHTWSqB2RyBA==} - '@helia/ipns@8.2.4': - resolution: {integrity: sha512-Jdx6yQvSDpV2IRQR06TlBjW5yOPxj820eoNK44P+kU/xU+dwREs8JJAj455SsDboj2XV9YnA9OQJVhu7SmtpBw==} + '@helia/http@4.0.8': + resolution: {integrity: sha512-7XVzYzcW+ODokU21KduXmTsTZKuWEdx0hVOmLadmrB3JNm5inyI7GxEXygFFDR/2wpaBfqM42iCfDV2I+dr/Wg==} - '@helia/routers@3.1.3': - resolution: {integrity: sha512-BPbzN3WCe6EF3yXjeORJbbb5hZjv0PKaJri1sSPHRZX6sKUCvRzwAc0AkQKUMHeMzTLrrAcl0yAz5x1r8z3Ynw==} + '@helia/interface@7.1.2': + resolution: {integrity: sha512-wzbtRy+HbEP4Rn78Uks42U5PwioO12H2y7qiYfTkYM73qGvmmZe4JB34cQqm60fTbWOOBUB09a4coy8o7/x9Uw==} - '@helia/unixfs@5.1.0': - resolution: {integrity: sha512-QGY6atWRAGAkx2/iPAioTKli4OduCxm6pdnII9HnsYAw0O5To+uERFpEm06J8gawxQuwD05Ux3wVfH/C0Wo87Q==} + '@helia/ipns@10.2.2': + resolution: {integrity: sha512-EDuPo/RWrS0v6x5d1T6hd8vHu15b/kdTvemN3J5MZp/f/fwIpcQ3jOaYM8v8stk62F02jKKfS4fF/PnBsaz0KQ==} - '@helia/utils@1.4.0': - resolution: {integrity: sha512-xXwhQbfSQEC5uHd6HVwdGXksZayy5xnYB5aOk0TU1fDnwbaeJz46o/GdWcxkTxnbfGyxqs9hyK5NqHw1B58yAw==} + '@helia/libp2p@2.1.5': + resolution: {integrity: sha512-DvzNxXes/WoOseUdGKH/lynpWEVr750X0+Dp6ZMr7KW4GyVtcacfnctyFCFLHXcZDSGra8OFcW375t62uXcm5Q==} - '@helia/verified-fetch@2.6.12': - resolution: {integrity: sha512-aGeRrcXffZ3s/U6bT2jpcJfQ76uWwMTEYNiV5NK3zugRul5XQVhBw8qHuuePXhdu9QLUL5yA7eULBNg+g0+Nbw==} + '@helia/trustless-gateway-client@1.0.7': + resolution: {integrity: sha512-xmPrGUCqxQ3Fhvy3lFcFsuyixbPA9WDvYJfa8MjQ0NZuQRpL5ogMfSUnr9ey9NYYQTjY36cTM4L7bqPBwxngVw==} + + '@helia/unixfs@8.0.9': + resolution: {integrity: sha512-LKKfjZMWiIuKM8XEU7rcwG9ht9fnaJe24puzcnfaREW8lR1cFVuuphyxvBm68sRMfZv/rkBXPLJdEdTTAtepPA==} + + '@helia/utils@3.0.6': + resolution: {integrity: sha512-QEMVKSVc7NnosXmcM1opdw81cLakLJinpr3FTYCylHid+7MmP3/lHs2MSlTAvW6Tff5y/QLMKG+929qDA0zfFA==} + + '@helia/verified-fetch@8.1.2': + resolution: {integrity: sha512-bnkQ9P4aarcktXyUIrf/koxCawGziARuJspN+WsicwQ7BKh02HziZz2y+WgGjbQaBeB4evxTh75Pd49o91qhhA==} '@hpke/chacha20poly1305@1.8.0': resolution: {integrity: sha512-FcBfAQ+Y99vMNJP2yrZ9wpL8V0GOwp1+zMyzvc6alasrBygfFjFm1yeUtyADJCu/27C3Lm5mJzx6u7pwg+cX5w==} @@ -2623,14 +2910,8 @@ packages: cpu: [arm64] os: [darwin] - '@img/sharp-darwin-arm64@0.34.5': - resolution: {integrity: sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [darwin] - - '@img/sharp-darwin-arm64@0.35.3': - resolution: {integrity: sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg==} + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] @@ -2641,20 +2922,14 @@ packages: cpu: [x64] os: [darwin] - '@img/sharp-darwin-x64@0.34.5': - resolution: {integrity: sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [darwin] - - '@img/sharp-darwin-x64@0.35.3': - resolution: {integrity: sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w==} + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] - '@img/sharp-freebsd-wasm32@0.35.3': - resolution: {integrity: sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg==} + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} engines: {node: '>=20.9.0'} os: [freebsd] @@ -2663,13 +2938,8 @@ packages: cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-arm64@1.2.4': - resolution: {integrity: sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==} - cpu: [arm64] - os: [darwin] - - '@img/sharp-libvips-darwin-arm64@1.3.2': - resolution: {integrity: sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg==} + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] @@ -2678,13 +2948,8 @@ packages: cpu: [x64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.2.4': - resolution: {integrity: sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==} - cpu: [x64] - os: [darwin] - - '@img/sharp-libvips-darwin-x64@1.3.2': - resolution: {integrity: sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw==} + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] @@ -2694,14 +2959,8 @@ packages: os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-arm64@1.2.4': - resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@img/sharp-libvips-linux-arm64@1.3.2': - resolution: {integrity: sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==} + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] libc: [glibc] @@ -2712,38 +2971,20 @@ packages: os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-arm@1.2.4': - resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==} - cpu: [arm] - os: [linux] - libc: [glibc] - - '@img/sharp-libvips-linux-arm@1.3.2': - resolution: {integrity: sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==} + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-ppc64@1.2.4': - resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@img/sharp-libvips-linux-ppc64@1.3.2': - resolution: {integrity: sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==} + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-riscv64@1.2.4': - resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==} - cpu: [riscv64] - os: [linux] - libc: [glibc] - - '@img/sharp-libvips-linux-riscv64@1.3.2': - resolution: {integrity: sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==} + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} cpu: [riscv64] os: [linux] libc: [glibc] @@ -2754,14 +2995,8 @@ packages: os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-s390x@1.2.4': - resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@img/sharp-libvips-linux-s390x@1.3.2': - resolution: {integrity: sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==} + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] libc: [glibc] @@ -2772,14 +3007,8 @@ packages: os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-x64@1.2.4': - resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@img/sharp-libvips-linux-x64@1.3.2': - resolution: {integrity: sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==} + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] libc: [glibc] @@ -2790,14 +3019,8 @@ packages: os: [linux] libc: [musl] - '@img/sharp-libvips-linuxmusl-arm64@1.2.4': - resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@img/sharp-libvips-linuxmusl-arm64@1.3.2': - resolution: {integrity: sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==} + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] libc: [musl] @@ -2808,14 +3031,8 @@ packages: os: [linux] libc: [musl] - '@img/sharp-libvips-linuxmusl-x64@1.2.4': - resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==} - cpu: [x64] - os: [linux] - libc: [musl] - - '@img/sharp-libvips-linuxmusl-x64@1.3.2': - resolution: {integrity: sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==} + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] libc: [musl] @@ -2827,15 +3044,8 @@ packages: os: [linux] libc: [glibc] - '@img/sharp-linux-arm64@0.34.5': - resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-arm64@0.35.3': - resolution: {integrity: sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==} + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] @@ -2848,43 +3058,22 @@ packages: os: [linux] libc: [glibc] - '@img/sharp-linux-arm@0.34.5': - resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-arm@0.35.3': - resolution: {integrity: sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==} + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-linux-ppc64@0.34.5': - resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-ppc64@0.35.3': - resolution: {integrity: sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==} + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} engines: {node: '>=20.9.0'} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-linux-riscv64@0.34.5': - resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [riscv64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-riscv64@0.35.3': - resolution: {integrity: sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==} + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} engines: {node: '>=20.9.0'} cpu: [riscv64] os: [linux] @@ -2897,15 +3086,8 @@ packages: os: [linux] libc: [glibc] - '@img/sharp-linux-s390x@0.34.5': - resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-s390x@0.35.3': - resolution: {integrity: sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==} + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] @@ -2918,15 +3100,8 @@ packages: os: [linux] libc: [glibc] - '@img/sharp-linux-x64@0.34.5': - resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-x64@0.35.3': - resolution: {integrity: sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==} + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] @@ -2939,15 +3114,8 @@ packages: os: [linux] libc: [musl] - '@img/sharp-linuxmusl-arm64@0.34.5': - resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@img/sharp-linuxmusl-arm64@0.35.3': - resolution: {integrity: sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==} + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] @@ -2960,15 +3128,8 @@ packages: os: [linux] libc: [musl] - '@img/sharp-linuxmusl-x64@0.34.5': - resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [linux] - libc: [musl] - - '@img/sharp-linuxmusl-x64@0.35.3': - resolution: {integrity: sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==} + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] @@ -2979,28 +3140,17 @@ packages: engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [wasm32] - '@img/sharp-wasm32@0.34.5': - resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [wasm32] - - '@img/sharp-wasm32@0.35.3': - resolution: {integrity: sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==} + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} engines: {node: '>=20.9.0'} - '@img/sharp-webcontainers-wasm32@0.35.3': - resolution: {integrity: sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q==} + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} engines: {node: '>=20.9.0'} cpu: [wasm32] - '@img/sharp-win32-arm64@0.34.5': - resolution: {integrity: sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [win32] - - '@img/sharp-win32-arm64@0.35.3': - resolution: {integrity: sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w==} + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [win32] @@ -3011,14 +3161,8 @@ packages: cpu: [ia32] os: [win32] - '@img/sharp-win32-ia32@0.34.5': - resolution: {integrity: sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [ia32] - os: [win32] - - '@img/sharp-win32-ia32@0.35.3': - resolution: {integrity: sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw==} + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} engines: {node: ^20.9.0} cpu: [ia32] os: [win32] @@ -3029,62 +3173,193 @@ packages: cpu: [x64] os: [win32] - '@img/sharp-win32-x64@0.34.5': - resolution: {integrity: sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [win32] - - '@img/sharp-win32-x64@0.35.3': - resolution: {integrity: sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA==} + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] - '@internationalized/date@3.12.2': - resolution: {integrity: sha512-FY1Y+H64NDs+HAF6omlnWxm3mEpfgaCSWtL5l551ZZfImA+kGjPFgrnJrGjH6lfmLL0g8Z/mBu1R3kufeCp6Jw==} + '@inquirer/ansi@2.0.7': + resolution: {integrity: sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} - '@internationalized/number@3.6.6': - resolution: {integrity: sha512-iFgmQaXHE0vytNfpLZWOC2mEJCBRzcUxt53Xf/yCXG93lRvqas237i3r7X4RKMwO3txiyZD4mQjKAByFv6UGSQ==} + '@inquirer/checkbox@5.2.2': + resolution: {integrity: sha512-Y5/bAScMy5Y+9isCx0SKbyJebMCaXXX5em0kxkj115eZNscgV9srOHrgyfS0e5xAVymIfOh9piYBKDILktsMMg==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true - '@internationalized/string@3.2.8': - resolution: {integrity: sha512-NdbMQUSfXLYIQol5VyMtinm9pZDciiMfN7RtmSuSB78io1hqwJ0naYfxyW6vgxWBkzWymQa/3uLDlbfmshtCaA==} + '@inquirer/confirm@6.2.0': + resolution: {integrity: sha512-SKXarWrYhtpqOEctf9XGCGy29QjsvJAM0Aq9ZR9z4Ns94OmpqudOly+aSEfNqUf9SwsQaUgY9+Z8hyzG0xX8fw==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true - '@ipld/car@5.4.6': - resolution: {integrity: sha512-f1Iyb9ci8B/TGCyjAuSQ6BOLiy2u8en7rB+SumbyweqXDu3gxYJwYbGzoposKjOzc4CeGlkEbwEw8REoekYAKQ==} - engines: {node: '>=16.0.0', npm: '>=7.0.0'} + '@inquirer/core@12.0.0': + resolution: {integrity: sha512-+nnvFEXIB08CZNVXpvW3B+zHW96QXvGUjNKJ8NJIPqAZi5Kd4WhYt2S3C234ReepG1qw2HOlEUbjYVHBowXObA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true - '@ipld/dag-cbor@10.0.1': - resolution: {integrity: sha512-nF07iiZPqduSXyMxc0jGANArRHFa9hjMQpQlgLOV2O/3xI1CNb5sXhvbmigbMiz5owSGi0Oq10VtauupMojuiw==} + '@inquirer/editor@5.3.0': + resolution: {integrity: sha512-nnsP/IdJ8s83q7ZuObmgn12QM+uLCkab9E0Oordojbn62WUg1c+v9Ou/F/057pgh0ppX0W+Hj5bO/Dp5hsxQtA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true - '@ipld/dag-cbor@9.2.7': - resolution: {integrity: sha512-ZmfXmElRWATr+hoUTSAOr6HUcjVhOcNHDqgczc76qte2DHHFEK0ZhNzUcdTDQhF/VSIvf2ioaRTRLWwLc83sNw==} + '@inquirer/expand@5.1.2': + resolution: {integrity: sha512-OWIH1IyyWqEKIyqC9Xy+Bnga7NkGMovFdo4atYZMUOTRqf6rO2WCv9E/1MyzvOErDBCxs+9UFliRUDc50xs/jw==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true - '@ipld/dag-json@10.2.9': - resolution: {integrity: sha512-opNPQQsTuCFZkaJCAqXrB/n9OqUD6W2Boz/Au5HjhLQyczmT8lxoOZObqQ5S5hhnV8p6sgKAimNhUB2W6y0Mzg==} + '@inquirer/external-editor@3.0.4': + resolution: {integrity: sha512-tZbbaK2ovq6vlrRBNQvjrypmrED/p5x2ncIHQ79cD55tei3dD96v5glMMA+6tiq7K104i/25DVYKWVPJuV6ptA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true - '@ipld/dag-pb@4.1.7': - resolution: {integrity: sha512-/i/13trFihjWfDyXlylRwhuYjtzYjvOFw0vlRjYGnZuv7d7MOgA2lV/vRuL5RfeUajM03aZfFLdq4S7cTbbTRg==} - engines: {node: '>=16.0.0', npm: '>=7.0.0'} + '@inquirer/figures@2.0.8': + resolution: {integrity: sha512-tApbon79GM9ry56ja/Ud3SY2CL4TQsao9fIwDQbgTeNY55025GdMzQ2+UdegV/lx51VNGUB59M0v0nMpybYY4Q==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} - '@ipshipyard/libp2p-auto-tls@1.0.0': - resolution: {integrity: sha512-wV1smnqbg3xUCHmPB8KWFuP8G9MKlx8KDuiJvhCWPi7B03xJq2FMybMDPI8tM9boa9sHD+5+NFu+Teo3Lz76fw==} + '@inquirer/input@5.1.3': + resolution: {integrity: sha512-F/BZHtyEzP+HO+IGVd4AjBRgvX/ywm42bx8S0+dENk2YclzE9tJ3X/15THwtT6ehApmKvdYDMsVTuyyDod0gOQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true - '@ipshipyard/node-datachannel@0.26.6': - resolution: {integrity: sha512-70HdhYMyAGXEMuCUq9ATO1Rx/JmiENM5LrGN94KT/q/Et2VsMjJpOWbyFzgodtkQJjDG5saNXTOiQpYZ1AnvEg==} - engines: {node: '>=18.20.0'} + '@inquirer/number@4.2.0': + resolution: {integrity: sha512-ew+fSDijsQ/WhD4TV3XLb+if400cDuzTzHfGR8sTNBXkK9CYDWoGE8fhaO8GbT312pNv1AJEOsDxy/z/HVettA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true - '@isaacs/cliui@8.0.2': - resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} - engines: {node: '>=12'} + '@inquirer/password@5.1.2': + resolution: {integrity: sha512-nSdufycW8xynEVssFkNQEYIzTySilog0UlfOVRwh3pXzPSk4frXUT2jZWjHnKae6RU9PaoF9wfy1pGwewQuqGw==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true - '@isaacs/ttlcache@1.4.1': - resolution: {integrity: sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA==} - engines: {node: '>=12'} + '@inquirer/prompts@8.6.0': + resolution: {integrity: sha512-WgBVDRy3IQ4v9XMCpQ1YDGpso2PcMUxYJzZdH4Nt4t0eoXhEPmOCh5iZbXbR4GTbdUB9VPWBbJB12rkjbaGDCw==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true - '@jest/schemas@29.6.3': - resolution: {integrity: sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==} - engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + '@inquirer/rawlist@5.3.2': + resolution: {integrity: sha512-oPSKrYK1X1bMkjXDzIKHUkJp195LFSfgbnVtXnjSKGFjrCbS6I+wyvfAZTwKE9BSt3HwWgfD7JfsXALBgCogzQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/search@4.3.0': + resolution: {integrity: sha512-HFxXE5w727ctSUcAwrDquftJGjMgu36OeV5SHEXMlr2j/ahzmRX9xSEeVolV8tzYnTf45cg6vGkdMMRdm3RPhQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/select@5.2.2': + resolution: {integrity: sha512-RkI8dRHWt+bh04oLixvF1kFzKC7e5rqJoHKkzcqSHATebBXFC6GmrT8ddbVkgSzLV0HnHs2cPFuBINr8otij8Q==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/type@4.0.7': + resolution: {integrity: sha512-t28inv14nMQ1PhKpsJPY+kEs/c00qzeCOS2gTNRyTjG5d6qsVA2fItxW4hkvGZ5lvanGLdtCzVIx5dwdRpN1+g==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@internationalized/date@3.12.2': + resolution: {integrity: sha512-FY1Y+H64NDs+HAF6omlnWxm3mEpfgaCSWtL5l551ZZfImA+kGjPFgrnJrGjH6lfmLL0g8Z/mBu1R3kufeCp6Jw==} + + '@internationalized/number@3.6.6': + resolution: {integrity: sha512-iFgmQaXHE0vytNfpLZWOC2mEJCBRzcUxt53Xf/yCXG93lRvqas237i3r7X4RKMwO3txiyZD4mQjKAByFv6UGSQ==} + + '@internationalized/string@3.2.8': + resolution: {integrity: sha512-NdbMQUSfXLYIQol5VyMtinm9pZDciiMfN7RtmSuSB78io1hqwJ0naYfxyW6vgxWBkzWymQa/3uLDlbfmshtCaA==} + + '@ipld/car@5.4.6': + resolution: {integrity: sha512-f1Iyb9ci8B/TGCyjAuSQ6BOLiy2u8en7rB+SumbyweqXDu3gxYJwYbGzoposKjOzc4CeGlkEbwEw8REoekYAKQ==} + engines: {node: '>=16.0.0', npm: '>=7.0.0'} + + '@ipld/dag-cbor@10.0.1': + resolution: {integrity: sha512-nF07iiZPqduSXyMxc0jGANArRHFa9hjMQpQlgLOV2O/3xI1CNb5sXhvbmigbMiz5owSGi0Oq10VtauupMojuiw==} + + '@ipld/dag-json@11.0.1': + resolution: {integrity: sha512-cMDD0yWkUruqhbLDwAWaV5q92hYKQDP2xP0n+yZp0oxsC68Pw+xFZNc9rj0v2n5m5m/Aa1A+Qlb2tY3NjQMsWg==} + + '@ipld/dag-pb@4.1.7': + resolution: {integrity: sha512-/i/13trFihjWfDyXlylRwhuYjtzYjvOFw0vlRjYGnZuv7d7MOgA2lV/vRuL5RfeUajM03aZfFLdq4S7cTbbTRg==} + engines: {node: '>=16.0.0', npm: '>=7.0.0'} + + '@ipld/dag-pb@4.2.0': + resolution: {integrity: sha512-T2hsy18NNAUkIiQgvtrhKJXIkTjKcGHPJzp6mYp/tx4x0X9wedUTrCNADEP4hAS7Vy4/bJtc37eX4GSDFiKLhw==} + engines: {node: '>=16.0.0', npm: '>=7.0.0'} + + '@ipshipyard/crypto@1.1.0': + resolution: {integrity: sha512-xMnzqJFuDirmjdMlmHb9r/olj++oFv3Pf5utF49+MvNQqKjYZ2YHMiO8Y8xk8nh6E+xa4g9+r/hij0FpNVZusw==} + + '@ipshipyard/keychain@1.0.2': + resolution: {integrity: sha512-otMCFOItScEX3VNy/gHF+CVd2QGPNo75uwZBoYUj2Rr8xnF5eq1nlbk6iEqH6cwqu2j/UuzFvtD2s2lmGo0mDA==} + + '@ipshipyard/libp2p-auto-tls@2.0.2': + resolution: {integrity: sha512-jnGqf/eif9GpjH03PaenekRWRvlJgoVZ1JsAawW0dJxcIW8qHiSMIbVh49xOjUGTK8vUbN26bsO+Rustg0n72A==} + + '@isaacs/cliui@8.0.2': + resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} + engines: {node: '>=12'} + + '@isaacs/ttlcache@1.4.1': + resolution: {integrity: sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA==} + engines: {node: '>=12'} + + '@jest/schemas@29.6.3': + resolution: {integrity: sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} '@jest/types@29.6.3': resolution: {integrity: sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==} @@ -3106,12 +3381,12 @@ packages: '@jridgewell/sourcemap-codec@1.5.5': resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} - '@jridgewell/trace-mapping@0.3.9': - resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} - '@js-sdsl/ordered-map@4.4.2': resolution: {integrity: sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==} @@ -3133,98 +3408,149 @@ packages: '@lezer/lr@1.4.10': resolution: {integrity: sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==} - '@libp2p/autonat@2.0.38': - resolution: {integrity: sha512-SuJUbXsF0YQg926hxb6d/f7x4NEHqWHLSXnR6Og5fJSOv2A1i1xRUe8zXaCuxQkPa+CguH2tAPZ+l1A+NZlF5A==} + '@libp2p/autonat@3.0.28': + resolution: {integrity: sha512-e4Sw+T72QHS//cqHOhPtRUI50TRF6haZtrsAg5rk1neFx8zHHlVNsjIm38uv9P/GmK1vvc8jU442S/5opi8gZA==} - '@libp2p/bootstrap@11.0.47': - resolution: {integrity: sha512-D3V8AHZvX9R0cFD0BKmDp7fKTo+GgPFFWa55z62VP14yA3f3kSAELyZ7NujrD0QXEtUdd/d7suqeJ4tKGsnZ5A==} + '@libp2p/bootstrap@12.0.32': + resolution: {integrity: sha512-MpGPeijiYP7a//EsbcrWAuWjHNoGhIqv4ONcGXkuTgSCJbJVWpZrR2uA+I/UW7wW0UB4a3PmHJWAd4klMgZqlA==} - '@libp2p/circuit-relay-v2@3.2.24': - resolution: {integrity: sha512-JXSm0dOOpPC+Yax0ngLYWqELHLFmaYPNZOhZkrr0iEtbiXwhDXuDuwT71pwmozp7h/rYd2YFoIk178AhZ4711Q==} + '@libp2p/circuit-relay-v2@4.2.13': + resolution: {integrity: sha512-AGEzj72W7Ae5eizaM+HeDzJBR28zK4yYp4BYvUOHQViT62W97FIITo/9Gc5rlkKti+gJJAurBm3cHV4A8Wcoxw==} - '@libp2p/config@1.1.31': - resolution: {integrity: sha512-4G1rGzNuTmNtqUxD/9kpC4/C+aPLSMy+q6exhm9E+cORb+AjW1Q90Oef2uKVj2eWWw14Rw7r2mK3jEa5IWVL8g==} + '@libp2p/config@1.1.37': + resolution: {integrity: sha512-aapBnhItf4Zi1BV2k8iuUan4nIiPM9QwHu8r44DC/MlBvah/Wf7Gv37w0h6vQucwMi9dieg2EXbZHxEwfWA5ag==} '@libp2p/crypto@5.1.18': resolution: {integrity: sha512-sCm+dFFZmH4LJIHTCzPy7+EBRhzkndFUcIU8bui6iaxK6SDSRVa11+/O6DzW8hn/U9LgDXe6jXnzWM8bM7OoCA==} - '@libp2p/dcutr@2.0.38': - resolution: {integrity: sha512-Ny3yA/BqtmRrPIiWjobduccZrUCP+H0HD+2x83wO723iCqBYIMN8Usa5arLTu+TUiMTbxtlWHYaZxGHqfKqn9Q==} + '@libp2p/crypto@5.1.23': + resolution: {integrity: sha512-u6XVMD1YpUJgjS5MAayrxlzi+hQcj3FHY0wS6/M/T93ntyCW13BmmRzFb2ESamk65PEuSCAChmQeSzRV2sh2rQ==} + + '@libp2p/dcutr@3.0.28': + resolution: {integrity: sha512-ULbHSdedcLpCzXUB1BGwiKPs+sshaT+TuicDullCWwsdq6nhzpfg3KkGP/BmvzIwkEkNTRGWQ7AScI6rIHBT7g==} + + '@libp2p/fetch@4.1.13': + resolution: {integrity: sha512-cILiJik5tOyJzxS3gzPVGUI8fXvu0t6FDJPJ1zhfxlhYk7BHzQwe4poV/6BdWhaK/P8RU6tVPsZeDqSLLtsKhg==} + + '@libp2p/http-fetch@4.0.4': + resolution: {integrity: sha512-MHROqwXP4KnRIZguzUIyrexRWuEF6InXKzUCFktergqgkkkkkt45ZiGx8wOa/1xbdUEZmiDoOITpHsNhU5GWBQ==} + + '@libp2p/http-peer-id-auth@2.0.3': + resolution: {integrity: sha512-lBzwbnqIJa4SnMssseEtbgdGHB+sH2CQr3HxhSwEhLRRpU1iCmkUR1L9X+FTH6A5Xo62y/JYnnhBO7CG3YTSdg==} + + '@libp2p/http-utils@2.0.6': + resolution: {integrity: sha512-WIYT1luITS4AZl0/b3tB5c7Kw9MKHAX2Lumx83oKImBPI9lPpRNafOmVVVRvwfjPq77t5nVt4ha8y1UDEtRN6g==} - '@libp2p/http-fetch@2.2.2': - resolution: {integrity: sha512-dMPo2pe2h/AHAljgwDEErdiB8JbiJM5b0LzuF/Yq4HcplfJZf33VtzUHN1n8x+3K+F8fntWUKN30SwSisSoVaw==} + '@libp2p/http-websocket@2.0.4': + resolution: {integrity: sha512-AEATJ6MERtxY/UZkFWCgNpB7bhcVTmeeBKZkVl2RJbVYTk8CSv3fO3uXLcYFQ9W4rOa0eG4Gvr/USBU+41xB8A==} - '@libp2p/identify@3.0.39': - resolution: {integrity: sha512-302y1LAGuPy8im+LUiB5+2sUOa/VZuAphOAKLsAQ/74EglWlSrw0Q7f09WUQvfNXmn7XpQnDh7GEI3NZBl54Jw==} + '@libp2p/http@2.0.6': + resolution: {integrity: sha512-z3RRdZP/+/kjYREY9MyZ5E90bKrGThQAw9sTZyv0ahxzUM+7I0/JPFLj98Wu0tgI9LStA6vtweVi0Ffwp0u9bA==} - '@libp2p/interface-internal@2.3.19': - resolution: {integrity: sha512-v335EB0i5CaNF+0SqT01CTBp0VyjJizpy46KprcshFFjX16UQ8+/QzoTZqmot9WiAmAzwR0b87oKmlAE9cpxzQ==} + '@libp2p/identify@4.1.14': + resolution: {integrity: sha512-c7oU0DSKzkMNsanruOQc4Zy6mSf3fq8/W+4E/I936HiHZc/LIbUuCWaxbgmQexdfKqECH1qH4q9IwaCUWmjPMQ==} - '@libp2p/interface@2.11.0': - resolution: {integrity: sha512-0MUFKoXWHTQW3oWIgSHApmYMUKWO/Y02+7Hpyp+n3z+geD4Xo2Rku2gYWmxcq+Pyjkz6Q9YjDWz3Yb2SoV2E8Q==} + '@libp2p/interface-internal@3.1.13': + resolution: {integrity: sha512-+vjQzpQl+0uoWCyNwV5NDnv1RAK9LDeWGeMbx/Fl2ZWrndtuFUPa9LxwqHXrTly6YOhgUatSzVqZBWnrQ1PxGg==} '@libp2p/interface@3.2.2': resolution: {integrity: sha512-IU78g6uF8Ls0//4v9VE1rL5Jvy+i6I8LI/DssojFICbaDJSkL59Sn5XRfHrY5OCxTnUnUxnWK7pHz/3+UZcRNQ==} - '@libp2p/kad-dht@15.1.11': - resolution: {integrity: sha512-a5sdnkztx8AVRDG/+llboRfTLkjQJpSPsSD6F/q6xlI2GbAyEf+JnNKJv0GAUZe9UJCl+g4htM1jA/Rjl0IuCg==} + '@libp2p/interface@3.3.0': + resolution: {integrity: sha512-SXahM/4IgpiFKTtocbXYSTA1wEUVjktmT1yBCzBbc2Vgsu1VBCg6SvsFmXo2Hbeyev3D8EU+y3uaCKDB43C/Vg==} - '@libp2p/keychain@5.2.9': - resolution: {integrity: sha512-BgZKMqQCu3Xzd7YFIdwWqG2xXtvsO6RVHJKS8VOw6Dg5tuPAWcQhs0T84TZ5PCg5r6NNBwwI8fWdZGVtu/pPfQ==} + '@libp2p/kad-dht@16.4.5': + resolution: {integrity: sha512-Pxmk3pIfe5Ih1xr+CY1uzw8AXRY+2VI6p3iebM4ljueu+dovEPIahW8tq4F2iNHIQftuc9Svncw4JikwrU7I1w==} '@libp2p/keychain@6.1.1': resolution: {integrity: sha512-szZBnnO+VX4Fjz6KZKE6Z0mFEWaQautb5sV+cK23r6nZ17gd3dv/U8hI2I2DjtPDKB3HimpQcVLnDF8Tc3EkfQ==} - '@libp2p/logger@5.2.0': - resolution: {integrity: sha512-OEFS529CnIKfbWEHmuCNESw9q0D0hL8cQ8klQfjIVPur15RcgAEgc1buQ7Y6l0B6tCYg120bp55+e9tGvn8c0g==} + '@libp2p/keychain@6.1.7': + resolution: {integrity: sha512-kemRM/37UXfkqmZsFFIsICX8iMX3TUShYGaRL7xXqNq3oIebm12e54DW1dtDuUnpNLctdF6zWPPelUHQm50Szg==} + + '@libp2p/logger@6.2.13': + resolution: {integrity: sha512-+tkZuRPoiFdh+frG//3hQ3goV1uMzRblpZ+mwtezgLXkRNqB5YKBLl+c/rtrurwAUqjCuI/yoEPJBiCizg2z6w==} '@libp2p/logger@6.2.7': resolution: {integrity: sha512-IVEz5+0kE4mRWwMzXP34AlXe2k1FLzBqKkjeASyhPVdMz0A4qH9nYmCBwonzmRzymklGjFIEDa1s7Vjhd9V4Rg==} - '@libp2p/mdns@11.0.47': - resolution: {integrity: sha512-mHIOfzyrJaXw2oVba1xZ5/6ETqsckkdQZVe66+7XNbjlr1plfO+FneEQ66N03LkqeffHDLht0BAm3WYae6XGkw==} + '@libp2p/mdns@12.0.32': + resolution: {integrity: sha512-CrTtxxqnsdIanWZMNxKAr1G0F5alsj56uTNIEyidBdNWMFP1/RJXBzBLRQ+ruttE+yaDE9s5x16gDJ+KiceQdQ==} + + '@libp2p/mplex@12.0.32': + resolution: {integrity: sha512-qY+vStdCFDrdmdMeMCmR0VLGy6m+Rq68ufzAvbZS5HjNVCD8aWci6VZzIsiQPWwPtur/een0bferUt/4Ry6NBQ==} + + '@libp2p/multistream-select@7.0.28': + resolution: {integrity: sha512-X6rmxeAlFeTDHDc4IPujz+y9TdA8cSMFfWyGJfxdIbQpDc1PwZI/Ttt3YWp0LAT9sbSYVFaWA6cGTN9EnMWtGQ==} + + '@libp2p/noise@17.0.3': + resolution: {integrity: sha512-dUmOjqkkeyUm9NCaFiSEqif1vsLsRFmlZXEfIeREerKXB7sLBvRLbpGiglsLNu7BlA6mrnsQk4BMjZ8aEDqzdA==} - '@libp2p/mplex@11.0.47': - resolution: {integrity: sha512-bZvToaf//ITkLzKx2FxpHP/J7IHvUI7lPHzSYAo2dRfB67VMnTnmAkP4IZmR9DV5oORaUrSt8ZRzQfXO7XjzlQ==} + '@libp2p/peer-collections@7.0.28': + resolution: {integrity: sha512-+evafZ5oSnGRfB7z+ycf09ehzNhCKoOZaiHgi6TpnDitpRQM5KQeN0H9Ep2uNJtzyW944HOG41BqcSaHbEHv7Q==} - '@libp2p/multistream-select@6.0.29': - resolution: {integrity: sha512-SWQbPcABOIpznEY7+vAp0Y3HNrE2PlaVY4EywN0lUZ7zvTv9VnAb7av3/gMvfaLI+YrOvhCr1mZ9qbSB93k4kA==} + '@libp2p/peer-id@6.0.15': + resolution: {integrity: sha512-aIbYJcldMNOIzmm9J57aESjZInYFdrQ9AY0ij+qn0Oam2vBxDfEIJZxJu+JzVkB2rVvT+FHDQXKWT2nAqNgB8w==} - '@libp2p/peer-collections@6.0.35': - resolution: {integrity: sha512-QiloK3T7DXW7R2cpL38dBnALCHf5pMzs/TyFzlEK33WezA2YFVoj7CtOJKqbn29bmV9uspWOxMgfmLUXf8ALvA==} + '@libp2p/peer-record@9.0.16': + resolution: {integrity: sha512-J4QoPr0F1v6xqjHjAJ9KPbg4jdDlGutDk2K3Km6+o0nWzZCgCGeSEIDOO2UvPa2bFoZTL62cD73fn8tm5K06cg==} - '@libp2p/peer-id@5.1.9': - resolution: {integrity: sha512-cVDp7lX187Epmi/zr0Qq2RsEMmueswP9eIxYSFoMcHL/qcvRFhsxOfUGB8361E26s2WJvC9sXZ0oJS9XVueJhQ==} + '@libp2p/peer-store@12.0.28': + resolution: {integrity: sha512-dj4qRhN01kml/It5/4P4DVcjfEZXJ2uZVVItCrs2YBGG2HLEYfWQZYROVbTCXDOCWwZK46aJ8eSLt4orsefq7Q==} - '@libp2p/peer-record@8.0.35': - resolution: {integrity: sha512-0818zvjKbucq5XBnusG8oSWxJ992rVry/2qlfcn/nyK/uDrZ12tjDYHNMCoOWTNeFvFUVkMg9pRkvXvTNp6Yiw==} + '@libp2p/ping@3.1.13': + resolution: {integrity: sha512-zB0TYbxWD73z3kqHrC2PDk7CAX0wQ0smz6mZ9okE4MoFgJv+XtMaIB2pB/4eT7xjWwdc2w3mYRmq+lMyXl3nXQ==} - '@libp2p/peer-store@11.2.7': - resolution: {integrity: sha512-dwTM+0i7mAgAnZvMHghgGcFoWPGaTbKx2nBueMd2Yg38mCs9WeambmR6gQdjwvYpybvNgFDAA+XesCKCotuczg==} + '@libp2p/record@4.0.15': + resolution: {integrity: sha512-EaHFtQAlZuM9vCpd+0KnZhTVgV26Uzje7DkyUseGNKTy+Wit9Q94C/+wDThpZuRHnK1FH/CvPxJ4kLj7AoQ1WA==} - '@libp2p/ping@2.0.37': - resolution: {integrity: sha512-SvCYM/tHvK3LQzCEa4eflQmrHEL5EAPWPxbIclqJ6SA0mi7jW3xO21AIsHkQDxfFVevIRWKaKoLj6MAythrNcg==} + '@libp2p/tcp@11.0.28': + resolution: {integrity: sha512-+YD59zz1V8YT47ZiInqoHAeSx45BC2bb5FVu3Bplo5zOxMMNXcH5WATIgn+IYIbusNPpMcs5wKd0QimQwzBl6Q==} - '@libp2p/record@4.0.12': - resolution: {integrity: sha512-CODkztILDzow3I76XbqshRpsP6g7EczNH0fZQdvbNXEqkwJtMOvRrpqxC9n/q65A6V7z6r9oUNSl7etvxS8WnQ==} + '@libp2p/tls@3.1.10': + resolution: {integrity: sha512-V8J0hVRjN7AFNX1yA/klNSzmdZwGrxwiu3K7UEeWpxSO4ky86V4W1TYqzIHVaS7mnP/fePU1sIqtgraYeuFCfQ==} - '@libp2p/tcp@10.1.19': - resolution: {integrity: sha512-Z+s1n7gBexc32d+DUhOGgQpA8HVukubmNJHzolzZPqly5DYkG2f6SIelitp+M5tDYOPH/43EH9pPSSZ3vUuOwQ==} + '@libp2p/upnp-nat@4.0.28': + resolution: {integrity: sha512-mPyEBT6R0L+FcDng73iIfWZC2fMdnWlw7iaDVb0nFXtGoh/BWWAWfj8bZJfrCVMt7ubJWIK5Fe4wrgB6T4QP1w==} - '@libp2p/tls@2.2.7': - resolution: {integrity: sha512-sPCzDtyR24+4fV+0lTTLIa2iIQONRx6s+Ad96P5YyHvjFTff/SrHQEPpn0f+A/d93qIoiEuovVo/tGjcho5e1A==} + '@libp2p/utils@7.4.1': + resolution: {integrity: sha512-e9cZeop+awI0rFczG4DvAwVeHqBhuCZfTyskvgONfKQrsT7L0BSlTlTTzZoFF8Dnb+QrzHsoIpnl0PrCr0h+Hg==} - '@libp2p/upnp-nat@3.1.22': - resolution: {integrity: sha512-+Hm78LtgJzEEFrQDqnL8A2tkiQVAwEEe8aAE1niyBmujNLu1KYmqmmjsH6F5F4wacBOetU0QGXmBNMx6eq42CA==} + '@libp2p/webrtc@6.0.33': + resolution: {integrity: sha512-vnjOnmUl7+0Cuy/khNjbDY0KUk/7JZ+fyf27lGmHHZas2mXJ5wzLZOS1b63/5yIq6EtIdouF0wpSdjLh1cvA7g==} - '@libp2p/utils@6.7.2': - resolution: {integrity: sha512-yglVPcYErb4al3MMTdedVLLsdUvr5KaqrrxohxTl/FXMFBvBs0o3w8lo29nfnTUpnNSHFhWZ9at0ZGNnpT/C/w==} + '@libp2p/websockets@10.1.21': + resolution: {integrity: sha512-2iItZGEfTlGFUEcFCghtlsIiQ+fBowopysBB/8ya0MvZkRic/6o9oSklWT5pWDmXtmqmbp1Dko/iLcBOhDOgFw==} - '@libp2p/webrtc@5.2.24': - resolution: {integrity: sha512-0Ne/GDR0FBnKQ/KpJDdQ0Ohii1jyhSCJvbKRxLISm8XItCuJtE1WA2awiWZddZwp2lPDPh9iQmFaYUvv8Zel2w==} + '@libp2p/yamux@8.0.3': + resolution: {integrity: sha512-iYe9YTdkPM6BRaQWpFb/tpHZcUcxdOGH0zlHUV00XBd+FvCQXrSWsy2+NMNcflT/QL7pOI6+U2i3obhQqFq/BA==} - '@libp2p/websockets@9.2.19': - resolution: {integrity: sha512-+g2qI9Lgvyofoc6GFztPoPVZV+z/lg9pIUfneHht6j88Y7tH3NrAQ7Ki+9lqS5XBX2h1O1bHULWbCaVYCj9TZg==} + '@lifi/widget-light@4.3.2': + resolution: {integrity: sha512-2TrQYZkMZjBSjbzyjy36bNSG+ZKuBclyxHNgrhYwEKCUU5xFLqUchxsJppDY/YIYJKdqjHcS5Yd0U6J3FeE7vQ==} + peerDependencies: + '@bigmi/client': ^0.10.1 + '@bigmi/react': ^0.9.1 + '@mysten/dapp-kit-react': ^2.1.3 + '@wagmi/core': ^3.5.0 + '@wallet-standard/base': ^1.1.0 + react: '>=19' + viem: '>=2.52.0' + wagmi: ^3.6.16 + peerDependenciesMeta: + '@bigmi/client': + optional: true + '@bigmi/react': + optional: true + '@mysten/dapp-kit-react': + optional: true + '@wagmi/core': + optional: true + '@wallet-standard/base': + optional: true + viem: + optional: true + wagmi: + optional: true '@lit-labs/ssr-dom-shim@1.6.0': resolution: {integrity: sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==} @@ -3415,20 +3741,14 @@ packages: '@multiformats/dns@1.0.13': resolution: {integrity: sha512-yr4bxtA3MbvJ+2461kYIYMsiiZj/FIqKI64hE4SdvWJUdWF9EtZLar38juf20Sf5tguXKFUruluswAO6JsjS2w==} - '@multiformats/mafmt@12.1.6': - resolution: {integrity: sha512-tlJRfL21X+AKn9b5i5VnaTD6bNttpSpcqwKVmDmSHLwxoz97fAHaepqFOk/l1fIu94nImIXneNbhsJx/RQNIww==} - - '@multiformats/multiaddr-matcher@1.8.0': - resolution: {integrity: sha512-tR/HFhDucXjvwCef5lfXT7kikqR2ffUjliuYlg/RKYGPySVKVlvrDufz86cIuHNc+i/fNR16FWWgD/pMJ6RW4w==} + '@multiformats/dns@1.0.15': + resolution: {integrity: sha512-W0zAMABtAn+3chgFcPGvllKND7M6GblMAAFcJQTy+iMmGiyFErZYPzAh2b50Y3SFf340iFV7+ckVgZkGfUyxzA==} - '@multiformats/multiaddr-matcher@2.0.2': - resolution: {integrity: sha512-si7EZCI93mfBJKKRkh+u2bB9W6W5APVN3XfdwuseEJ0OS7ysg0Jno9SuAi0bRzsl5OEFESoF71SjsRqgp8PXAA==} + '@multiformats/multiaddr-matcher@3.0.2': + resolution: {integrity: sha512-iphGQJliZxe2yKu57bdRDgeS+3znc5uXtMybDO1Wau3rIjas4zjrjlyxmFz3wqyUL9f3VDQwas/ZqA7N4QeSfw==} - '@multiformats/multiaddr-to-uri@11.0.2': - resolution: {integrity: sha512-SiLFD54zeOJ0qMgo9xv1Tl9O5YktDKAVDP4q4hL16mSq4O4sfFNagNADz8eAofxd6TfQUzGQ3TkRRG9IY2uHRg==} - - '@multiformats/multiaddr@12.5.1': - resolution: {integrity: sha512-+DDlr9LIRUS8KncI1TX/FfUn8F2dl6BIxJgshS/yFQCNB5IAF0OGzcwB39g5NLE22s4qqDePv0Qof6HdpJ/4aQ==} + '@multiformats/multiaddr-to-uri@12.0.0': + resolution: {integrity: sha512-3uIEBCiy8tfzxYYBl81x1tISiNBQ7mHU4pGjippbJRoQYHzy/ZdZM/7JvTldr8pc/dzpkaNJxnsuxxlhsPOJsA==} '@multiformats/multiaddr@13.0.3': resolution: {integrity: sha512-mEqqJ4r3a/uuFMTpRkU316wGNIDQNhuVWpm+ebKTQeYsfv9jXbPONWM6VVnj3KGUrwfsX7GZOyp4TFqEA2SPCw==} @@ -3437,8 +3757,8 @@ packages: resolution: {integrity: sha512-M+VwV8hEx5qB8i7b8fljMwZETJsqyLo8RAXA+JAn+QF9NnH46ZWvGErNukJVlxXSR2KQpuOtHIYIzZlbhhdFvw==} engines: {node: '>=16.0.0', npm: '>=7.0.0'} - '@multiformats/uri-to-multiaddr@9.0.2': - resolution: {integrity: sha512-2TCQR5Y2unG2s9Jm1BdBMTSFmmfgHy8D0777PRT+U2D+IXC1E9JkKF1OS0QlHtGyKUA0IRIk8T0JV4D3v5iOyQ==} + '@multiformats/uri-to-multiaddr@10.0.0': + resolution: {integrity: sha512-QsmwLmY6iB1wDU1e1wyctqF0eP/2KD1QPLQ+APISuqETbCTSpaq159S/K/ssmWlBpSEkhH0SUfBUgGi014Ttfw==} '@multisender.app/multisender-react-widget@0.2.3': resolution: {integrity: sha512-D2AhC0gKAGH0SCqhBQ/9qzciFZ8sfoHT294VekDkEalR3BsEBXJ8J0g3At8IWOoddsYMcnhHMyH9BeY3MoLiAg==} @@ -3480,115 +3800,60 @@ packages: '@next/env@13.5.11': resolution: {integrity: sha512-fbb2C7HChgM7CemdCY+y3N1n8pcTKdqtQLbC7/EQtPdLvlMUT9JX/dBYl8MMZAtYG4uVMyPFHXckb68q/NRwqg==} - '@next/env@16.2.6': - resolution: {integrity: sha512-gd8HoHN4ufj73WmR3JmVolrpJR47ILK6LouP5xElPglaVxir6e1a7VzvTvDWkOoPXT9rkkTzyCxBu4yeZfZwcw==} - - '@next/env@16.3.1': - resolution: {integrity: sha512-35G3xwkQUb2oETSDjFXGrVugknoayLFBh7vSE+yAcl9IP2zT9wyGwq7297AYHR11kJld807t5f8AJBs6WBzXsQ==} + '@next/env@16.4.3': + resolution: {integrity: sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==} '@next/eslint-plugin-next@16.2.6': resolution: {integrity: sha512-Z8l6o4JWKUl755x4R+wogD86KPeU+Ckw4K+SYG4kHeOJtRenDeK+OSbGcqZpDtbwn9DsJVdir2UxmwXuinUbUw==} - '@next/swc-darwin-arm64@16.2.6': - resolution: {integrity: sha512-ZJGkkcNfYgrrMkqOdZ7zoLa1TOy0qpcMfk/z4Mh/FKUz40gVO+HNQWqmLxf67Z5WB64DRp0dhEbyHfel+6sJUg==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [darwin] - - '@next/swc-darwin-arm64@16.3.1': - resolution: {integrity: sha512-ABMIu2zQ7cnNIHm5ivKGwZwUrm0pAai3yiJ/gK/rF1c1VP9UOnj7XECbMKFdVKp9I9eMYq9NoDs1WXOoowxzJw==} + '@next/swc-darwin-arm64@16.4.3': + resolution: {integrity: sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==} engines: {node: '>= 10'} cpu: [arm64] os: [darwin] - '@next/swc-darwin-x64@16.2.6': - resolution: {integrity: sha512-v/YLBHIY132Ced3puBJ7YJKw1lqsCrgcNo2aRJlCEyQrrCeRJlvGlnmxhPxNQI3KE3N1DN5r9TPNPvka3nq5RQ==} - engines: {node: '>= 10'} - cpu: [x64] - os: [darwin] - - '@next/swc-darwin-x64@16.3.1': - resolution: {integrity: sha512-gNG21e/UnrroeScbY/QndUEdl0mF1FRibW7BBeYUz/5ABCepjqDdEdgr592vpzMtCn/m7FTjYq3TN4TpyDnutw==} + '@next/swc-darwin-x64@16.4.3': + resolution: {integrity: sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==} engines: {node: '>= 10'} cpu: [x64] os: [darwin] - '@next/swc-linux-arm64-gnu@16.2.6': - resolution: {integrity: sha512-RPOvqlYBbcQjkz9VQQDZ2T2bARIjXZV1KFlt+V2Mr6SW/e4I9fcKsaA0hdyf2FHoTlsV2xnBd5Y912rP/1Ce6w==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@next/swc-linux-arm64-gnu@16.3.1': - resolution: {integrity: sha512-6B6Lw016iwNUQuaJoraMMTLh6TwHzFUtxipSScD1F3YyymcrRWkobodRS2ftIOkF5vrs4zNlyUrTC5YZQ9Lz5w==} + '@next/swc-linux-arm64-gnu@16.4.3': + resolution: {integrity: sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] libc: [glibc] - '@next/swc-linux-arm64-musl@16.2.6': - resolution: {integrity: sha512-URUTu1+dMkxJsPFgm+OeEvq9wf5sujw0EvgYy80TDGHTSLTnIHeqb0Eu8A3sC95IRgjejQL+kC4mw+4yPxiAXA==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@next/swc-linux-arm64-musl@16.3.1': - resolution: {integrity: sha512-JUiPXZKK9wOhjf4MgDiH29GZLxfqOesbLtHq2pDxwH/WwscTRV2ToymnOTh1egzaZf0ueUf8T2+CeYTGHjW0Iw==} + '@next/swc-linux-arm64-musl@16.4.3': + resolution: {integrity: sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] libc: [musl] - '@next/swc-linux-x64-gnu@16.2.6': - resolution: {integrity: sha512-DOj182mPV8G3UkrayLoREM5YEYI+Dk5wv7Ox9xl1fFibAELEsFD0lDPfHIeILlutMMfdyhlzYPELG3peuKaurw==} - engines: {node: '>= 10'} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@next/swc-linux-x64-gnu@16.3.1': - resolution: {integrity: sha512-Uog9jsrmIRIL/lfvIp9htmskSNC7JcQsMVucXL2V2YY1y/D9IUN3LPEafqy0zRJ2cIU1SQ0V6F6TlffQ+pLAGg==} + '@next/swc-linux-x64-gnu@16.4.3': + resolution: {integrity: sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==} engines: {node: '>= 10'} cpu: [x64] os: [linux] libc: [glibc] - '@next/swc-linux-x64-musl@16.2.6': - resolution: {integrity: sha512-HKQ5SP/V/ub73UvF7n/zeJlxk2kLmtL7Wzrg4WfmkjmNos5onJ2tKu7yZOPdL18A6Svfn3max29ym+ry7NkK4g==} - engines: {node: '>= 10'} - cpu: [x64] - os: [linux] - libc: [musl] - - '@next/swc-linux-x64-musl@16.3.1': - resolution: {integrity: sha512-6yy3FT13KgUFOj5H8bl8w/6nKiJwHIvbtwh1V+1acsu+7y4tJjnemSa6mhsh53BeoVrlozE+fMgZhXH46WmjMA==} + '@next/swc-linux-x64-musl@16.4.3': + resolution: {integrity: sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==} engines: {node: '>= 10'} cpu: [x64] os: [linux] libc: [musl] - '@next/swc-win32-arm64-msvc@16.2.6': - resolution: {integrity: sha512-LZXpTlPyS5v7HhSmnvsLGP3iIYgYOBnc8r8ArlT55sGHV89bR2HlDdBjWQ+PY6SJMmk8TuVGFuxalnP3k/0Dwg==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [win32] - - '@next/swc-win32-arm64-msvc@16.3.1': - resolution: {integrity: sha512-iOoN1QecUoGNZik536U/vtK43YwgyrCsGIkth52yIkl612n+0C9MjSnJbQAikISpb+WYRooBVhaDlUW7iZoKog==} + '@next/swc-win32-arm64-msvc@16.4.3': + resolution: {integrity: sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==} engines: {node: '>= 10'} cpu: [arm64] os: [win32] - '@next/swc-win32-x64-msvc@16.2.6': - resolution: {integrity: sha512-F0+4i0h9J6C4eE3EAPWsoCk7UW/dbzOjyzxY0qnDUOYFu6FFmdZ6l97/XdV3/Nz3VYyO7UWjyEJUXkGqcoXfMA==} - engines: {node: '>= 10'} - cpu: [x64] - os: [win32] - - '@next/swc-win32-x64-msvc@16.3.1': - resolution: {integrity: sha512-d/k+PpAriUPaeMJJOG7HUSdqfEX46FEPWU1p3/nm2ACmXhj9hFEWdFODUBIpkuijXYkfL90qZzTqVPRp4BW/hw==} + '@next/swc-win32-x64-msvc@16.4.3': + resolution: {integrity: sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==} engines: {node: '>= 10'} cpu: [x64] os: [win32] @@ -3604,6 +3869,10 @@ packages: resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==} engines: {node: ^14.21.3 || >=16} + '@noble/ciphers@2.4.0': + resolution: {integrity: sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==} + engines: {node: '>= 20.19.0'} + '@noble/curves@1.4.2': resolution: {integrity: sha512-TavHr8qycMChk8UwMld0ZDRvatedkzWfH8IiaeGCfymOP5i0hSCozz9vHOL0nkwk7HRMlFnAiKpS2jrUmSybcw==} @@ -3647,10 +3916,71 @@ packages: resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} engines: {node: ^14.21.3 || >=16} + '@noble/hashes@2.0.1': + resolution: {integrity: sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==} + engines: {node: '>= 20.19.0'} + + '@noble/hashes@2.2.0': + resolution: {integrity: sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==} + engines: {node: '>= 20.19.0'} + + '@noble/hashes@2.4.0': + resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==} + engines: {node: '>= 20.19.0'} + '@noble/post-quantum@0.5.4': resolution: {integrity: sha512-leww0zzIirrvwaYMPI9fj6aRIlA/c6Y0/lifQQ1YOOyHEr0MNH3yYpjXeiVG+tWdPps4XxGclFWX2INPO3Yo5w==} engines: {node: '>= 20.19.0'} + '@node-datachannel/android-arm64@0.33.4': + resolution: {integrity: sha512-Kd1K+drJlxdGmZYBlzh5HHX2E7les99eTWlt7WldZgvJmcGf2z9L/bnUVn4zbhNm2q/MtNZ2tPX2bd+fGlDDpQ==} + cpu: [arm64] + os: [android] + + '@node-datachannel/darwin-arm64@0.33.4': + resolution: {integrity: sha512-bkIA+IbModz/NUmbVYTSWj8dZvkiab+cU4zOa6rhfKsNcW3EkdD2/DDoJjUrRrw+LbEZ40V7NuAKUlMNFDXFsw==} + cpu: [arm64] + os: [darwin] + + '@node-datachannel/darwin-x64@0.33.4': + resolution: {integrity: sha512-+dLnwiwC3GdWqW0OQShZcSFYrx3hRx0+7U85swoiP3iiRqtDUARME6AIAmW3glpP0vmus1jv5KhPCy/Q+jAvqw==} + cpu: [x64] + os: [darwin] + + '@node-datachannel/linux-arm64-gnu@0.33.4': + resolution: {integrity: sha512-rR4yjwxpI1miLSrruLGcfR9yfw0Qebw+Twt+u+lKsL9SwmXxTm5pJhUAa9RU+c35oZ98IyAxGFjRwwq85BTbog==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@node-datachannel/linux-arm64-musl@0.33.4': + resolution: {integrity: sha512-MR4o1F0aREj/AtbNlXL20YiNx8/pDI8L/5B4Vr9ldiEDottD0IOdCd0khB8fpr5Np2CW7WwU9QG+uto00QGVdw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@node-datachannel/linux-x64-gnu@0.33.4': + resolution: {integrity: sha512-xN0x3lcQ87qwOAmf1dBLVWrYY40LQ7pM4Y9wuNjP+EtN4IwiXqrhPdgupzGAElxna+n2NgBG0gT60dZpgoYU2Q==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@node-datachannel/linux-x64-musl@0.33.4': + resolution: {integrity: sha512-FWqJEjL7TqOPmsqdfwmG/BUwOXQN7MfpEU8kzw6ePbglUbwgdc3976Ls9BCBUXyPgEJyLo8YE1LJyWAlbXWyvA==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@node-datachannel/win32-arm64-msvc@0.33.4': + resolution: {integrity: sha512-TeDV2tSPm+qAnF6MIPlLFTIlobSYLwOVe3/wQl+8hD/q3cEPTQi7vByFaQQ5lRULKKdnjKRR5iDMsxMilqbtXA==} + cpu: [arm64] + os: [win32] + + '@node-datachannel/win32-x64-msvc@0.33.4': + resolution: {integrity: sha512-eU0w/9ykrNaA5vWs5gjVs3Qxa45jbQ8mYoMyh5OWnRCE5GzXKxHCpfhFUnO+jGqi0KxkyP0hSA6fiwXXkirk6g==} + cpu: [x64] + os: [win32] + '@nodelib/fs.scandir@2.1.5': resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} engines: {node: '>= 8'} @@ -3682,10 +4012,6 @@ packages: wagmi: optional: true - '@opentelemetry/api-logs@0.208.0': - resolution: {integrity: sha512-CjruKY9V6NMssL/T1kAFgzosF1v9o6oeN+aX5JB/C/xPNtmgIJqcXHG7fA82Ou1zCpWGl4lROQUKwUNE1pMCyg==} - engines: {node: '>=8.0.0'} - '@opentelemetry/api-logs@0.217.0': resolution: {integrity: sha512-Cdq0jW2lknrNfrAm92MyEAvpe2cRsKjdnQLHUL6xRA4IVUnsWx6P65E7NcUO0Y+L4w1Aee5iV8FvjSwd+lrs9A==} engines: {node: '>=8.0.0'} @@ -3729,12 +4055,6 @@ packages: peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' - '@opentelemetry/core@2.2.0': - resolution: {integrity: sha512-FuabnnUm8LflnieVxs6eP7Z383hgQU4W1e3KJS6aOG3RxWxcHyBxH8fDMHNgu/gFx/M2jvTOW/4/PHhLz6bjWw==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' - '@opentelemetry/core@2.7.1': resolution: {integrity: sha512-QAqIj32AtK6+pEVNG7EOVxHdE06RP+FM5qpiEJ4RtDcFIqKUZHYhl7/7UY5efhwmwNAg7j8QbJVBLxMerc0+gw==} engines: {node: ^18.19.0 || >=20.6.0} @@ -3765,12 +4085,6 @@ packages: peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-logs-otlp-http@0.208.0': - resolution: {integrity: sha512-jOv40Bs9jy9bZVLo/i8FwUiuCvbjWDI+ZW13wimJm4LjnlwJxGgB+N/VWOZUTpM+ah/awXeQqKdNlpLf2EjvYg==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-logs-otlp-http@0.217.0': resolution: {integrity: sha512-KfLAdt1uilVE+3FxbgVnp2ZrzqbIawzcesnRoi+Kh9ckB5Ld5D8btUgoBvwTbdmuNx1j6b132Wsh72azq+pPNQ==} engines: {node: ^18.19.0 || >=20.6.0} @@ -4137,12 +4451,6 @@ packages: peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/otlp-exporter-base@0.208.0': - resolution: {integrity: sha512-gMd39gIfVb2OgxldxUtOwGJYSH8P1kVFFlJLuut32L6KgUC4gl1dMhn+YC2mGn0bDOiQYSk/uHOdSjuKp58vvA==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': ^1.3.0 - '@opentelemetry/otlp-exporter-base@0.217.0': resolution: {integrity: sha512-eYfqnB3UhKu/5frhd1R6+FprKygbhkomuaceMXDyzxbfXB9tKgZOVmjaJ02CkLA6Tdzumxl+e2H+vo2a8jiMPQ==} engines: {node: ^18.19.0 || >=20.6.0} @@ -4167,12 +4475,6 @@ packages: peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/otlp-transformer@0.208.0': - resolution: {integrity: sha512-DCFPY8C6lAQHUNkzcNT9R+qYExvsk6C5Bto2pbNxgicpcSWbe2WHShLxkOxIdNcBiYPdVHv/e7vH7K6TI+C+fQ==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': ^1.3.0 - '@opentelemetry/otlp-transformer@0.217.0': resolution: {integrity: sha512-MKK8UHKFUOGAvbZRWh90MhwHG+Fxm6OROBdjKPCF+HQobjuJ/Kuf8Chs8CR45X1aqotxrMj7OxTdsXe8sXuGVA==} engines: {node: ^18.19.0 || >=20.6.0} @@ -4231,12 +4533,6 @@ packages: peerDependencies: '@opentelemetry/api': ^1.0.0 - '@opentelemetry/resources@2.2.0': - resolution: {integrity: sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/resources@2.7.1': resolution: {integrity: sha512-DeT6KKolmC4e/dRQvMQ/RwlnzhaqeiFOXY5ngoOPJ07GgVVKxZOg9EcrNZb5aTzUn+iCrJldAgOfQm1O/QfPAQ==} engines: {node: ^18.19.0 || >=20.6.0} @@ -4249,12 +4545,6 @@ packages: peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/sdk-logs@0.208.0': - resolution: {integrity: sha512-QlAyL1jRpOeaqx7/leG1vJMp84g0xKP6gJmfELBpnI4O/9xPX+Hu5m1POk9Kl+veNkyth5t19hRlN6tNY1sjbA==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': '>=1.4.0 <1.10.0' - '@opentelemetry/sdk-logs@0.217.0': resolution: {integrity: sha512-BB+PcHItcZDL63dPMW+mJvwN9rk37wuIDjRxbVlg6pPDvDR/7GL7UJHbGsllgoggOoTimsKgENaWPoGch/oE1A==} engines: {node: ^18.19.0 || >=20.6.0} @@ -4267,12 +4557,6 @@ packages: peerDependencies: '@opentelemetry/api': '>=1.4.0 <1.10.0' - '@opentelemetry/sdk-metrics@2.2.0': - resolution: {integrity: sha512-G5KYP6+VJMZzpGipQw7Giif48h6SGQ2PFKEYCybeXJsOCB4fp8azqMAAzE5lnnHK3ZVwYQrgmFbsUJO/zOnwGw==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': '>=1.9.0 <1.10.0' - '@opentelemetry/sdk-metrics@2.7.1': resolution: {integrity: sha512-MpDJdkiFDs3Pm1RHO3KByuZbuBdJEXEAkiC0+yJdsZGVCdf1RpHR6n+LHDcS7ffmfrt5kVCzJSCfm4z2C7v0uQ==} engines: {node: ^18.19.0 || >=20.6.0} @@ -4297,12 +4581,6 @@ packages: peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/sdk-trace-base@2.2.0': - resolution: {integrity: sha512-xWQgL0Bmctsalg6PaXExmzdedSp3gyKV8mQBwK/j9VGdCDu2fmXIb2gAehBKbkXCpJ4HPkgv3QfoJWRT4dHWbw==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/sdk-trace-base@2.7.1': resolution: {integrity: sha512-NAYIlsF8MPUsKqJMiDQJTMPOmlbawC1Iz/omMLygZ1C9am8fTKYjTaI+OZM+WTY3t3Glo0wnOg/6/pac6RGPPw==} engines: {node: ^18.19.0 || >=20.6.0} @@ -4347,6 +4625,9 @@ packages: '@openzeppelin/contracts@5.4.0': resolution: {integrity: sha512-eCYgWnLg6WO+X52I16TZt8uEjbtdkgLC0SUX/xnAksjjrQI4Xfn4iBRoI5j55dmlOhDv1Y7BoR3cU7e3WWhC6A==} + '@oxc-project/types@0.155.0': + resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==} + '@pandacss/is-valid-prop@1.11.1': resolution: {integrity: sha512-tvfThJmSw88Lgk5qVYzVckZ2FY8T376mGvP1cWUC5SR58AYm82ZKEFciDbGOQKcyN70rF9qqJBB5JVWgJo3JmA==} @@ -4354,33 +4635,81 @@ packages: resolution: {integrity: sha512-IHnV6A+zxU7XwmKFinmYjUcwlyK9+xkG3/s9KcQhI9BjQKycrJ1JRO+FbNYPwZiPKW3je/DR0k7w8/gLa5eaxQ==} deprecated: 'Switch to "qr" (new package name) for security updates: npm install qr' + '@peculiar/asn1-asym-key@2.10.0': + resolution: {integrity: sha512-1R8xUTeqcUTSMLFTTCzJyFuKiq3y25EQKs9DezUetJ8qMqbJyxo3XkzykiwwT/Xzlt5/vRzS/sW4M1r+pq1FTg==} + engines: {node: '>=14'} + + '@peculiar/asn1-cms@2.10.0': + resolution: {integrity: sha512-CkX0H4NCIOMHOU3rh2xXZywinYZ/EnJlaOlJiGI0e5L4XjFqHf4iH30LMbXWChVppdA9ljbanjtzQFOhDNfTWg==} + engines: {node: '>=14'} + '@peculiar/asn1-cms@2.7.0': resolution: {integrity: sha512-hew63shtzzvBcSHbhm+cyAmKe6AIfinT9hzEqSPjDC6opTTMKmTkQ0gHuN2KsWlvqiKw1S/fS94fhag/FJkioQ==} + '@peculiar/asn1-csr@2.10.0': + resolution: {integrity: sha512-jTPTr/9rxKM+niQLMF3jiAMb0lWHUhUHIuSOhdGCIfpB4FAQYf9SoiXOgxP8bS/68IB+bj+1OHvVnDVCQfVUZw==} + engines: {node: '>=14'} + '@peculiar/asn1-csr@2.7.0': resolution: {integrity: sha512-VVsAyGqErT9D1SY4aEqozThXMVI+ssVRiv2DDeYuvpBKLIgZ3hYs3Ay3u/VSoKq6ESFi9cf6rf3IOOzfwh7oMA==} + '@peculiar/asn1-ecc@2.10.0': + resolution: {integrity: sha512-GFd3iOjFrWX+QWH2R2dO5QSJyyRGv9CIBKtRlGlPNCvb2RvmCbBDexe91MJgV76c69d998Xsa+CvuQ98seoiPg==} + engines: {node: '>=14'} + '@peculiar/asn1-ecc@2.7.0': resolution: {integrity: sha512-n7KEs/Q/wrB415cxy4fHOBhegp4NdJ15fkJPwcB/3/8iNBQC2L/N7SChJPKDJPZGYH0jD4Tg4/0vnHmwghnbKw==} + '@peculiar/asn1-pfx@2.10.0': + resolution: {integrity: sha512-1y3QK9ZH1IPleAMmRoJlPS10eGkAWnULETW8zDFNUK1ffqpG7zmDY+kYBMYQgwlcQZ2iitLm2z2EBP0xzRXpaA==} + engines: {node: '>=14'} + '@peculiar/asn1-pfx@2.7.0': resolution: {integrity: sha512-V/nrlQVmhg7lYAsM7E13UDL5erAwFv6kCIVFqNaMIHSVi7dngcT839JkRTkQBqznMG98l2XjxYk74ZztAohZzA==} + '@peculiar/asn1-pkcs8@2.10.0': + resolution: {integrity: sha512-Ri+BZT9bnwqlHWmhs7lvWjvJRxKev2hA2+4EbZajgeYWCbR8hyv0znF4DhsFouOhMj2nSDV/iGJ6DMQtwITnCw==} + engines: {node: '>=14'} + '@peculiar/asn1-pkcs8@2.7.0': resolution: {integrity: sha512-9GTl1nE8Mx1kTZ+7QyYatDyKsm34QcWRBFkY1iPvWC3X4Dona5s/tlLiQsx5WzVdZqiMBZNYT0buyw4/vbhnjw==} + '@peculiar/asn1-pkcs9@2.10.0': + resolution: {integrity: sha512-XIXsbDQFezYk6fudczkuvawkRD4GNpISGCqfYhdkJlvcGF/RFknU+0DDJagOaJqBf+PdPzk4J9oMqDGcvfR9HQ==} + engines: {node: '>=14'} + '@peculiar/asn1-pkcs9@2.7.0': resolution: {integrity: sha512-Bh7m+OuIaSEllPQcSd9OSp93F4ROWH7sbITWV8MI+8dwsjE5111/87VxiWVvYFKyww3vp39geLv9ENqhwWHcew==} + '@peculiar/asn1-rsa@2.10.0': + resolution: {integrity: sha512-4Jvmwlh3gZAhNZ4/u7JSyLuce9hofOFZ4o3PYKAccCImGnyaT5CMym/ATgvAvqpOYFNW531oPZvJlEBhJy9VfA==} + engines: {node: '>=14'} + '@peculiar/asn1-rsa@2.7.0': resolution: {integrity: sha512-/qvENQrXyTZURjMqSeofHul0JJt2sNSzSwk36pl2olkHbaioMQgrASDZAlHXl0xUlnVbHj0uGgOrBMTb5x2aJQ==} + '@peculiar/asn1-schema@2.10.0': + resolution: {integrity: sha512-GhokD41lV4gQrrLYm3wCkHfBOnJrnhDMgt4XeMW8gzfE1UdJqIuSwsE+ggf82XBjUXRJylcm+KIGQFa4utIVLw==} + engines: {node: '>=14'} + '@peculiar/asn1-schema@2.7.0': resolution: {integrity: sha512-W8ZfWzLmQnrcky+eh3tni4IozMdqBDiHWU0N+vve/UGjMaUs8c0L7A2oEdkBXS8rTpWDpK/aoI3DG/L/hxmxPg==} + '@peculiar/asn1-x509-attr@2.10.0': + resolution: {integrity: sha512-/85GtKOKmgvuSJNlaFfwGWNdRSZZ+hpF02NyM01XiCdzpaZONiBltDyfluFPvFx966CR+ZHNSG1jniwpy07oGg==} + engines: {node: '>=14'} + '@peculiar/asn1-x509-attr@2.7.0': resolution: {integrity: sha512-NS8e7SOgXipkzUPLF/sce7ukpMpWjhxYsH0n6Y+bHYo4TTxOb95Zv7hqwSuL212mj5YxovjdOKQOgH1As3E94w==} + '@peculiar/asn1-x509-post-quantum@2.10.0': + resolution: {integrity: sha512-cXKcZ30wKbUkRK5RK4Z3W1imewXvHAB9apEAuIqJ0OOkOQCpJrwLOuN38QlsEXqOI+3gtUv8Kf3UZohUmCbf3w==} + engines: {node: '>=14'} + + '@peculiar/asn1-x509@2.10.0': + resolution: {integrity: sha512-ucNVg8+ANveTpMN3fy9lA2alryONdXc2A4cEG2hMniWbvQt+YOZoe8BI80YYNO8FBcuDY1qbDQ4uQGQVraHxGA==} + engines: {node: '>=14'} + '@peculiar/asn1-x509@2.7.0': resolution: {integrity: sha512-mUn9RRrkGDnG4ALfunDmzyRW5dg+sWCj/pfnCCqEHYbkGxEpvUt6iVJv8Yw1cyp6SWZ26ZE5oSmI5SqEaen15g==} @@ -4399,6 +4728,10 @@ packages: resolution: {integrity: sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==} engines: {node: '>=20.0.0'} + '@peculiar/x509@2.1.0': + resolution: {integrity: sha512-IYbg1R03CSQGWwl24kGyqrdVtixNSbRaDvBg1r5wyYjTP+VwPQkka1BzTgU5+vxiuwqg04OxdvdJ1xYYFIdUSA==} + engines: {node: '>=20.0.0'} + '@phosphor-icons/webcomponents@2.1.5': resolution: {integrity: sha512-JcvQkZxvcX2jK+QCclm8+e8HXqtdFW9xV4/kk2aL9Y3dJA2oQVt+pzbv1orkumz3rfx4K9mn9fDoMr1He1yr7Q==} @@ -4406,28 +4739,31 @@ packages: resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} - '@playwright/experimental-ct-core@1.57.0': - resolution: {integrity: sha512-Z5Uh+61vR5FDRE+YJIMrnD8m6i2wJmYK525AHCJNcAcGcEC+i7xuMnZmZkg+booi3YHIwql/ApAlm03+jsCIzQ==} - engines: {node: '>=18'} + '@playwright/experimental-ct-core@1.62.1': + resolution: {integrity: sha512-GvaAlFMG6kZ+/00QyGOemjBkyDTk7OC1wGcVmO27i4Ek+x51ACjIBMyyyZrTGXHtQ1QvTFhaQrBhrXIrXEjn5g==} + engines: {node: '>=20'} - '@playwright/experimental-ct-react@1.57.0': - resolution: {integrity: sha512-wNRmkLOxHEXA9OL7QggNYVHnqaGlMOTB5q9FhrnlcFHHRs+M8SH9mQy5//dGFoYKAkhuZf4GPA3poi9bBdkdfQ==} - engines: {node: '>=18'} + '@playwright/experimental-ct-react@1.62.1': + resolution: {integrity: sha512-J1mI20nCPIBHh2htGIXaLHwva5a5lhlX0yJo5Z8fTX9eMEd1wMhgvuUr0EzpGI6oVg6opOFGgb+URUqhSyQd3w==} + engines: {node: '>=20'} hasBin: true - '@playwright/test@1.57.0': - resolution: {integrity: sha512-6TyEnHgd6SArQO8UO2OMTxshln3QMWBtPGrOCgs3wVEmQmwyuNtB10IZMfmYDE0riwNR1cu4q+pPcxMVtaG3TA==} - engines: {node: '>=18'} + '@playwright/test@1.62.1': + resolution: {integrity: sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ==} + engines: {node: '>=20'} hasBin: true '@polka/url@1.0.0-next.29': resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} - '@posthog/core@1.29.11': - resolution: {integrity: sha512-/4EF7oxAFSWJgaXxppT8bdYp7MGAnWFnKz994+MetTz/T6CKbYpjqIXHCofQXtcOXjEclTYj91igA+IkVFKiSg==} + '@posthog/browser-common@0.9.0': + resolution: {integrity: sha512-EWoVzs1vVY7ihpn8yOjj3jyjriHUEEMVSBNL/TW3hk09fTriWRe76vJXrRg0G0yjTYxHmtlSkNn4mOV24ZEzzA==} - '@posthog/types@1.376.2': - resolution: {integrity: sha512-Y3ROpAxNqgcy2G0w6JoG5Gt+P6WNY2lkHTPMPzWqexRwemYbFegDi5AifDyD9/tstKTlOYKTTExtaJ5EBcghyQ==} + '@posthog/core@1.55.2': + resolution: {integrity: sha512-2mYxGbDmTLUs096VbcZqSWo0lrI48/BrX65r54NynxxFq409BOx9w73HxOAtOKZ1vblkdV6/GxQTe7KDcIQidg==} + + '@posthog/types@1.412.4': + resolution: {integrity: sha512-Q7lV9O9TbLngjOYw1ucm3bS3tn48xb1B4ZQdDy8gv7yfKe99hCTeWYG4xZ36nJM80VxpTF9TriiJt5hngDOkBg==} '@protobuf-ts/grpcweb-transport@2.11.1': resolution: {integrity: sha512-1W4utDdvOB+RHMFQ0soL4JdnxjXV+ddeGIUg08DvZrA8Ms6k5NN6GBFU2oHZdTOcJVpPrDJ02RJlqtaoCMNBtw==} @@ -4975,54 +5311,153 @@ packages: '@reown/appkit@1.8.11': resolution: {integrity: sha512-G96zt1P3ASrivV7HRrFQuzkCEzSmy3ca7cSQxaLeIS+P2VVhjE5YAyINArGVbooY0heHCPvQuTNM+YgK4oBmfg==} - '@rollup/pluginutils@5.3.0': - resolution: {integrity: sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q==} - engines: {node: '>=14.0.0'} - peerDependencies: - rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0 - peerDependenciesMeta: - rollup: - optional: true - - '@rollup/rollup-android-arm-eabi@4.60.4': - resolution: {integrity: sha512-F5QXMSiFebS9hKZj02XhWLLnRpJ3B3AROP0tWbFBSj+6kCbg5m9j5JoHKd4mmSVy5mS/IMQloYgYxCuJC0fxEQ==} + '@rolldown/binding-android-arm-eabi@1.2.15': + resolution: {integrity: sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [android] - '@rollup/rollup-android-arm64@4.60.4': - resolution: {integrity: sha512-GxxTKApUpzRhof7poWvCJHRF51C67u1R7D6DiluBE8wKU1u5GWE8t+v81JvJYtbawoBFX1hLv5Ei4eVjkWokaw==} + '@rolldown/binding-android-arm64@1.2.15': + resolution: {integrity: sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@rollup/rollup-darwin-arm64@4.60.4': - resolution: {integrity: sha512-tua0TaJxMOB1R0V0RS1jFZ/RpURFDJIOR2A6jWwQeawuFyS4gBW+rntLRaQd0EQ4bd6Vp44Z2rXW+YYDBsj6IA==} + '@rolldown/binding-darwin-arm64@1.2.15': + resolution: {integrity: sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@rollup/rollup-darwin-x64@4.60.4': - resolution: {integrity: sha512-CSKq7MsP+5PFIcydhAiR1K0UhEI1A2jWXVKHPCBZ151yOutENwvnPocgVHkivu2kviURtCEB6zUQw0vs8RrhMg==} + '@rolldown/binding-darwin-x64@1.2.15': + resolution: {integrity: sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@rollup/rollup-freebsd-arm64@4.60.4': - resolution: {integrity: sha512-+O8OkVdyvXMtJEciu2wS/pzm1IxntEEQx3z5TAVy4l32G0etZn+RsA48ARRrFm6Ri8fvqPQfgrvNxSjKAbnd3g==} - cpu: [arm64] - os: [freebsd] - - '@rollup/rollup-freebsd-x64@4.60.4': - resolution: {integrity: sha512-Iw3oMskH3AfNuhU0MSN7vNbdi4me/NiYo2azqPz/Le16zHSa+3RRmliCMWWQmh4lcndccU40xcJuTYJZxNo/lw==} + '@rolldown/binding-freebsd-x64@1.2.15': + resolution: {integrity: sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@rollup/rollup-linux-arm-gnueabihf@4.60.4': - resolution: {integrity: sha512-EIPRXTVQpHyF8WOo219AD2yEltPehLTcTMz2fn6JsatLYSzQf00hj3rulF+yauOlF9/FtM2WpkT/hJh/KJFGhA==} + '@rolldown/binding-linux-arm-gnueabihf@1.2.15': + resolution: {integrity: sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - libc: [glibc] - '@rollup/rollup-linux-arm-musleabihf@4.60.4': - resolution: {integrity: sha512-J3Yh9PzzF1Ovah2At+lHiGQdsYgArxBbXv/zHfSyaiFQEqvNv7DcW98pCrmdjCZBrqBiKrKKe2V+aaSGWuBe/w==} - cpu: [arm] + '@rolldown/binding-linux-arm64-gnu@1.2.15': + resolution: {integrity: sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.15': + resolution: {integrity: sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.15': + resolution: {integrity: sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.15': + resolution: {integrity: sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.15': + resolution: {integrity: sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.15': + resolution: {integrity: sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.15': + resolution: {integrity: sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.15': + resolution: {integrity: sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.15': + resolution: {integrity: sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@rollup/pluginutils@5.3.0': + resolution: {integrity: sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q==} + engines: {node: '>=14.0.0'} + peerDependencies: + rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0 + peerDependenciesMeta: + rollup: + optional: true + + '@rollup/rollup-android-arm-eabi@4.60.4': + resolution: {integrity: sha512-F5QXMSiFebS9hKZj02XhWLLnRpJ3B3AROP0tWbFBSj+6kCbg5m9j5JoHKd4mmSVy5mS/IMQloYgYxCuJC0fxEQ==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.60.4': + resolution: {integrity: sha512-GxxTKApUpzRhof7poWvCJHRF51C67u1R7D6DiluBE8wKU1u5GWE8t+v81JvJYtbawoBFX1hLv5Ei4eVjkWokaw==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.60.4': + resolution: {integrity: sha512-tua0TaJxMOB1R0V0RS1jFZ/RpURFDJIOR2A6jWwQeawuFyS4gBW+rntLRaQd0EQ4bd6Vp44Z2rXW+YYDBsj6IA==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.60.4': + resolution: {integrity: sha512-CSKq7MsP+5PFIcydhAiR1K0UhEI1A2jWXVKHPCBZ151yOutENwvnPocgVHkivu2kviURtCEB6zUQw0vs8RrhMg==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.60.4': + resolution: {integrity: sha512-+O8OkVdyvXMtJEciu2wS/pzm1IxntEEQx3z5TAVy4l32G0etZn+RsA48ARRrFm6Ri8fvqPQfgrvNxSjKAbnd3g==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.60.4': + resolution: {integrity: sha512-Iw3oMskH3AfNuhU0MSN7vNbdi4me/NiYo2azqPz/Le16zHSa+3RRmliCMWWQmh4lcndccU40xcJuTYJZxNo/lw==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.60.4': + resolution: {integrity: sha512-EIPRXTVQpHyF8WOo219AD2yEltPehLTcTMz2fn6JsatLYSzQf00hj3rulF+yauOlF9/FtM2WpkT/hJh/KJFGhA==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm-musleabihf@4.60.4': + resolution: {integrity: sha512-J3Yh9PzzF1Ovah2At+lHiGQdsYgArxBbXv/zHfSyaiFQEqvNv7DcW98pCrmdjCZBrqBiKrKKe2V+aaSGWuBe/w==} + cpu: [arm] os: [linux] libc: [musl] @@ -5702,11 +6137,39 @@ packages: '@solana/web3.js@1.98.1': resolution: {integrity: sha512-gRAq1YPbfSDAbmho4kY7P/8iLIjMWXAzBJdP9iENFR+dFQSBSueHzjK/ou8fxhqHP9j+J4Msl4p/oDemFcIjlg==} - '@specify-sh/sdk@0.4.2': - resolution: {integrity: sha512-vskPvwpE3SWkmrOPhfMgvmvxvC+XNL93FTTF4SD3cPNZDsry5qfPNIW6TU1OTh3DWk7JMl/3X605CJUUAdEYmw==} + '@specify-sh/core@0.2.0': + resolution: {integrity: sha512-hE6/FVRF5uOwMrAQtZuOOOEZxW2ywH4alJw11b5gPLLcIqCVpPZ/RCRTMsqBv2ws4GPj00LNju97ajc5wEvJTQ==} + + '@specify-sh/publisher-sdk@1.2.0': + resolution: {integrity: sha512-t3reZG6lmC7KIJuHy84P/OLv0jBZ3zQrg4Bih4qAb0BsuUbOIgVQCQScotwYqtIdNvUkF8tYXjfEQ5hsJcpLiw==} + peerDependencies: + react: ^18 || ^19 + peerDependenciesMeta: + react: + optional: true + + '@stryker-mutator/api@10.1.1': + resolution: {integrity: sha512-3s/ECsrD1Tf1WEB7amBk0HxjN7zgkabKvmqnI2C831rTNszJ6o2HoV9PVxtElDEWxb2+t4iavK5x25G+DTUOUA==} + engines: {node: '>=22.0.0'} - '@standard-schema/spec@1.1.0': - resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@stryker-mutator/core@10.1.1': + resolution: {integrity: sha512-4xJAOCw9utJMLyrTk9gINi434tBxnyuwt8lU/InyoKagKd2/zh/2ui7ncWoD0qZeJrxClYzblg8iUh5ewBAB3Q==} + engines: {node: '>=22.0.0'} + hasBin: true + + '@stryker-mutator/instrumenter@10.1.1': + resolution: {integrity: sha512-Vyude2i8LhDciLV1q6J55KtdA7gZpRuMfZcBcmWV6hLHAvWocoPKnCKc5BlZt1mwGWkX3Olc0457I7Ue6F1WEg==} + engines: {node: '>=22.0.0'} + + '@stryker-mutator/util@10.1.1': + resolution: {integrity: sha512-Z0zDzsmhoSykE1gT3DvD1knFxySgNMfBlpSSs1j87kWvjEMfeMqfLOk0bqEPRg/rTFIUNSEXLZapxePUhZmfZA==} + + '@stryker-mutator/vitest-runner@10.1.1': + resolution: {integrity: sha512-w/OmNt1vHD4Yeacy8Rxhl2Ue/9l662iyOW8XxM4rc9huixF6IySHW3cvhTs8JnMvG9tG7vS7ZZ52wUXx7xy1IQ==} + engines: {node: '>=22.0.0'} + peerDependencies: + '@stryker-mutator/core': 10.1.1 + vitest: '>=2.0.0' '@stylistic/eslint-plugin@5.2.3': resolution: {integrity: sha512-oY7GVkJGVMI5benlBDCaRrSC1qPasafyv5dOBLLv5MTilMGnErKhO6ziEfodDDIZbo5QxPUNW360VudJOFODMw==} @@ -5964,9 +6427,6 @@ packages: resolution: {integrity: sha512-qMx1nOrzoB+PF+pzb26Q4Tc2sOlrx9Ba2UBNX9hB31Omrq+QoZ2Gly0KLrQWw4Of1AQ4J9lnD+XOdwOdcdXqqw==} engines: {node: '>=12.20.0'} - '@swc/helpers@0.5.15': - resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==} - '@swc/helpers@0.5.23': resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==} @@ -6032,8 +6492,8 @@ packages: resolution: {integrity: sha512-NKyqCvP6DZKlRf6aGfnKS6Kntn2gnuBxa/ztstjy+oo1t23EHzQ54shtli0yV5WAtygmK1tti/uL2C2p/kW3HQ==} deprecated: Please upgrade to v1 - '@tokenizer/inflate@0.2.7': - resolution: {integrity: sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==} + '@tokenizer/inflate@0.4.1': + resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==} engines: {node: '>=18'} '@tokenizer/token@0.3.0': @@ -6050,18 +6510,6 @@ packages: tree-sitter: optional: true - '@tsconfig/node10@1.0.12': - resolution: {integrity: sha512-UCYBaeFvM11aU2y3YPZ//O5Rhj+xKyzy7mvcIoAjASbigy8mHMryP5cK7dgjlz2hWxh1g5pLw084E0a/wlUSFQ==} - - '@tsconfig/node12@1.0.11': - resolution: {integrity: sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==} - - '@tsconfig/node14@1.0.3': - resolution: {integrity: sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==} - - '@tsconfig/node16@1.0.4': - resolution: {integrity: sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==} - '@turnkey/api-key-stamper@0.4.7': resolution: {integrity: sha512-/0/kW7v+uCnmHnGMoHSXn4Vb/MxLAIivGxX/T0L4vVoIiJalQmqcCtgiWnPWZDiJNGjMKp+jd/8j6VXgbVVozg==} engines: {node: '>=18.0.0'} @@ -6297,6 +6745,9 @@ packages: '@types/filewriter@0.0.33': resolution: {integrity: sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g==} + '@types/gensync@1.0.5': + resolution: {integrity: sha512-MbsRCT7mTikHwKZ0X+LVUTLRrZZRLipTuXEO9qOYO+zmjMVk81axyClMROf6uoPD9MRVu46bx8zoR0Ad9q3NAg==} + '@types/geojson@7946.0.16': resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==} @@ -6321,6 +6772,9 @@ packages: '@types/js-cookie@3.0.6': resolution: {integrity: sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==} + '@types/jsesc@2.5.1': + resolution: {integrity: sha512-9VN+6yxLOPLOav+7PwjZbxiID2bVaeq0ED4qSQmdQTdjnXJSaCVKTR58t15oqH1H5t8Ng2ZX1SabJVoN9Q34bw==} + '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} @@ -6358,11 +6812,8 @@ packages: '@types/node@17.0.45': resolution: {integrity: sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==} - '@types/node@20.16.7': - resolution: {integrity: sha512-QkDQjAY3gkvJNcZOWwzy3BN34RweT0OQ9zJyvLCU0kSK22dO2QYh/NHGfbEAYylPYzRB1/iXcojS79wOg5gFSw==} - - '@types/node@22.12.0': - resolution: {integrity: sha512-Fll2FZ1riMjNmlmJOdAyY5pUbkftXslB5DgEzlIuNaiWhXd00FhWxVC/r4yV/4wBb9JfImTu+jiSvXTkJ7F/gA==} + '@types/node@24.13.4': + resolution: {integrity: sha512-YJ7EqCstVTzIr0fMr7qul/977en+pQHrfmuKIo6Zr9i75Be21dr3MovcfvGtyvi2HAUrRerWps5sMO9I7WaxDw==} '@types/node@25.9.2': resolution: {integrity: sha512-G05zqtJhcDLb8uslf5EjCxXg9G1KQxiV8OS0R26IC//Eoyitzqe8z37I7cqvnZlrlSfgocQRfSn/AHBZJJFyGw==} @@ -6423,18 +6874,9 @@ packages: '@types/responselike@1.0.3': resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==} - '@types/retry@0.12.2': - resolution: {integrity: sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow==} - '@types/semver@7.7.1': resolution: {integrity: sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==} - '@types/sinon@17.0.4': - resolution: {integrity: sha512-RHnIrhfPO3+tJT0s7cFaXGZvsL4bbR3/k7z3P312qMS4JaS2Tk+KiwiLx1S0rQ56ERj00u1/BtdyVd0FY+Pdew==} - - '@types/sinonjs__fake-timers@15.0.1': - resolution: {integrity: sha512-Ko2tjWJq8oozHzHV+reuvS5KYIRAokHnGbDwGh/J64LntgpbuylF74ipEL24HCyRjf9FOlBiBHWBR1RlVKsI1w==} - '@types/swagger-ui-react@5.18.0': resolution: {integrity: sha512-c2M9adVG7t28t1pq19K9Jt20VLQf0P/fwJwnfcmsVVsdkwCWhRmbKDu+tIs0/NGwJ/7GY8lBx+iKZxuDI5gDbw==} @@ -6471,6 +6913,10 @@ packages: '@types/yargs@17.0.35': resolution: {integrity: sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==} + '@typesafe-ai/sdk@0.6.0': + resolution: {integrity: sha512-IddX+Q0XM+VagOUZFeP7wZjaO4SHMdvnh2zEBdrZZnXedWI3BNK1lKhMx3ayrkFWvVLbVcUHJy6AVZlY+e6Jaw==} + engines: {node: '>=20'} + '@typescript-eslint/eslint-plugin@5.62.0': resolution: {integrity: sha512-TiZzBSJja/LbhNPvk6yc0JrX9XqhQ0hdh6M2svYfsHGejaKFIAGd9MQ+ERIMzLGlN/kZoYIgdxFV0PuljTKXag==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -6490,6 +6936,16 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/parser@5.62.0': + resolution: {integrity: sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || ^8.0.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + '@typescript-eslint/parser@8.59.2': resolution: {integrity: sha512-plR3pp6D+SSUn1HM7xvSkx12/DhoHInI2YF35KAcVFNZvlC0gtrWqx7Qq1oH2Ssgi0vlFRCTbP+DZc7B9+TtsQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -6509,6 +6965,12 @@ packages: peerDependencies: typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/project-service@8.70.0': + resolution: {integrity: sha512-hFHbTNqhU9G+2eKFXCBVb1tjFT/LceiJ4+HfLO4pTpDI0KHi6iajpcFFkaSQ9gXmCh7n82A0PthaayEdN6mspQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/scope-manager@5.62.0': resolution: {integrity: sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -6525,6 +6987,10 @@ packages: resolution: {integrity: sha512-pFzqhllJMs+jghLQWzV00ds39xLzuyqPSev5pd8f4Ir0rtKR3ZLUB4/4dhjOFighWb9larvtfJvqL+4yKDI3Xw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/scope-manager@8.70.0': + resolution: {integrity: sha512-8nP3Kwh5hlgZ4FicGvmznAmJe8UL4sdU8tLukrPaMuQmDuk4Y8xYfzu/aYZW4xT2JCgc7H/TpDI5cGlxcWJSqQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/tsconfig-utils@8.59.2': resolution: {integrity: sha512-BKK4alN7oi4C/zv4VqHQ+uRU+lTa6JGIZ7s1juw7b3RHo9OfKB+bKX3u0iVZetdsUCBBkSbdWbarJbmN0fTeSw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -6537,6 +7003,12 @@ packages: peerDependencies: typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/tsconfig-utils@8.70.0': + resolution: {integrity: sha512-adnkeeNq9Sq1sUf4+FRVc0KdgYghzsgFpZSQVZVvY0LCuUuN0FnQgyGzCJeC4fW1cdXseBAjU2EOqUIjbNcZUw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/type-utils@5.62.0': resolution: {integrity: sha512-xsSQreu+VnfbqQpW5vnCJdq1Z3Q0U31qiWmRhr98ONQmcp/yhiPJFPq8MXiJVLiksmOKSjIldZzkebzHuCGzew==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -6554,6 +7026,13 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/type-utils@8.70.0': + resolution: {integrity: sha512-NUMKIhYVaVIVLnRL9CRt+VVcuLgSHUCpXn4/+K8wql+vdInUzvx8BjUO1oJ7cG9shjFJKtF8F8Hh2kCh3/KBVw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/types@5.62.0': resolution: {integrity: sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -6570,6 +7049,10 @@ packages: resolution: {integrity: sha512-AsE7x2XaAK+CVbeih0Fvbn+r1qHxtpLDJ3XUuFcIinT318T90yHMJC+Zgv+jUuDjQQd06HKwxnDu6sz1IcTilA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/types@8.70.0': + resolution: {integrity: sha512-asTOIYhDg4zdzOScCyaytrsV3cR6B4ecPQlXw/dJIm7J/MZTtCtfVII9JD8Geh4jTCrK/Xe6cg5UevoleMcoJQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/typescript-estree@5.62.0': resolution: {integrity: sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -6600,6 +7083,12 @@ packages: peerDependencies: typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/typescript-estree@8.70.0': + resolution: {integrity: sha512-d9NmHMPEKQ7QCLLm1jI3zmoQBwT5KwFYjXBJ9ymZfKCUU+5rmTRykKAFvH5Qn/ZCds3CEAFS9OC9M/jkl0X2bA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/utils@5.62.0': resolution: {integrity: sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -6626,6 +7115,13 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/utils@8.70.0': + resolution: {integrity: sha512-oZmtKJz/4fufZ2p3+Cn3ijEojcdfR+1zYDH2xKYrEly0dR/Q/1xUPRCOlKGxod78nWlU2UnDe09GZ3TaknBFGA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/visitor-keys@5.62.0': resolution: {integrity: sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -6642,6 +7138,10 @@ packages: resolution: {integrity: sha512-9WI52t8ZGLVGrPMBet25yAftqY/n95+zmoUUtJBBQTKDSKUu7OsPTroT2op7U9JatkoRccL0YkWDNMFfC4Sjxg==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/visitor-keys@8.70.0': + resolution: {integrity: sha512-BoC8PiO4Hkdo0TVJh9Ntxr5MxPDI7/oFsrygN5ADelFSeXG/qgNuucIGA+L5Z6JpPTE/uRfcTWtscjbUaufepQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript/typescript-aix-ppc64@7.0.2': resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} engines: {node: '>=16.20.0'} @@ -6920,17 +7420,41 @@ packages: engines: {node: '>=20.18 <=25.x'} os: [darwin, linux, win32] - '@vitejs/plugin-react@4.3.4': - resolution: {integrity: sha512-SCCPBJtYLdE8PX/7ZQAs1QAZ8Jqwih+0VBLum1EGqmCCQal+MIUqLCzj3ZUy8ufbC0cAM4LRlSTm7IQJwWT4ug==} - engines: {node: ^14.18.0 || >=16.0.0} + '@vitejs/plugin-react@6.1.2': + resolution: {integrity: sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==} + engines: {node: ^20.19.0 || >=22.12.0} peerDependencies: - vite: ^4.2.0 || ^5.0.0 || ^6.0.0 + '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 + babel-plugin-react-compiler: ^1.0.0 + oxc-transform-react: ^0.152.0 + vite: ^8.0.0 + peerDependenciesMeta: + '@rolldown/plugin-babel': + optional: true + babel-plugin-react-compiler: + optional: true + oxc-transform-react: + optional: true + + '@vitest/coverage-v8@5.0.0': + resolution: {integrity: sha512-toMg6PZGCIa/lQNCDoASrfb1ly4hsUKXFtFYC9kD4t78o5Y6LyNJU7AENt8eHPr3quYdxaxK7hj2mnbFfUk9NA==} + peerDependencies: + '@vitest/browser': 5.0.0 + vitest: 5.0.0 + peerDependenciesMeta: + '@vitest/browser': + optional: true + + '@vitest/istanbul-lib-coverage@1.0.1': + resolution: {integrity: sha512-k3DJZ8LhMBK9NS4SclF1ASD3OgXEWDorbIcPTRDK0/Zae6fRvu+fJRxtFdLfHsa9Y24beCdPnoNZ4LviTNstfA==} + engines: {node: '>=22'} - '@vitest/expect@4.1.7': - resolution: {integrity: sha512-1R+tw0ortHEbZDGMymm+pN7/AFQ/RkFFdtd7EN+VBpynKmLbP8A3rpEXdshBJ7+8hQ9zBJh/i1s0yKNtxAnU7w==} + '@vitest/istanbul-lib-report@1.0.1': + resolution: {integrity: sha512-1EOLRfsTMnyAr3+kEAsP4o9dhaDlGPpD7H5iLBBeq//YpNB1VIahkPhB+eRp9N2Dkfw8oySROjE3yf9XDeaIkQ==} + engines: {node: '>=22'} - '@vitest/mocker@4.1.7': - resolution: {integrity: sha512-vY7nuamKgfvpA1Koa3oYIw/k7D6kZnpGyNMZW8loow2bsBYla1TFdqTaXncWdRn4pgwNs+90RhnXhJScDwQeJA==} + '@vitest/mocker@5.0.0': + resolution: {integrity: sha512-66PGTMIiVJP3t4a5yxU9qPtf7MdTBs8jmToMvy+HVflB3Yy13WJZTtPePdvU+wjRV02SKK5doLbSA6o9pwOmiA==} peerDependencies: msw: ^2.4.9 vite: ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -6940,20 +7464,8 @@ packages: vite: optional: true - '@vitest/pretty-format@4.1.7': - resolution: {integrity: sha512-umgCarTOYQWIaDMvGDRZij+6b9oVeLIyJzfN+AS88e0ZOU3QTgNNSTtjQOpcvWr3np1N0j4WgZj+sb3oYBDscw==} - - '@vitest/runner@4.1.7': - resolution: {integrity: sha512-BapjmAQ2aI78WdMEfeUWivnfVzB+VPGwWRQcJE0OUq7qEeEcBsCSf+0T5iREBNE5nBb4wA5Ya0W6IA+sghdEFw==} - - '@vitest/snapshot@4.1.7': - resolution: {integrity: sha512-ZacLzja+TmJeZ1h14xW2FB/WpeimUD3haBXQPyJqxvo8jQTmfeA8zv58mtjN2C7EHXZDYVcVYdYmAxjkWVvKCw==} - - '@vitest/spy@4.1.7': - resolution: {integrity: sha512-kbkI5LMWakyuTIvs6fUJ5qdIVb1XVKsYJAT4OJ938cHMROYMSfmoQdZy0aaAnjbbc8F61vkoTqz/Az+/HiIu5Q==} - - '@vitest/utils@4.1.7': - resolution: {integrity: sha512-T532WBu791cBxJlCl6SO+J14l81DQx6uQHm1bQbmCDY7nqlEIgkza/UFnSBNaUtSf41unldDFjdOBYEQC4b5Hw==} + '@vitest/spy@5.0.0': + resolution: {integrity: sha512-uy+luWBAPw9XfthoHi5AkfHUnuPYEESjl0p/r+meoBnU8bxg5GDQ3Ey8MjcJ6sqahkL4PFyrvfMJJBw7LbU06g==} '@volar/language-core@2.4.28': resolution: {integrity: sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==} @@ -6963,6 +7475,11 @@ packages: '@volar/typescript@2.4.28': resolution: {integrity: sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw==} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true '@vue/compiler-core@3.5.35': resolution: {integrity: sha512-BUmHaR1J+O+CKZ9uJucdVTEr1LHsdyvv7vG3eNRhK3CczEHeMd/LtsHAuD7PbrxvI2envCY2v7HI1vC1aBRzKw==} @@ -7560,9 +8077,6 @@ packages: abort-error@1.0.2: resolution: {integrity: sha512-lVgvB2NyPLqbXXhVmXcYFTC1x5K7CiVdPgdY7LGgFQWC8506oN01sPN3i9cl9ynuwF4iJ0TS9exnR7cZ9FuX4w==} - abortable-iterator@5.1.0: - resolution: {integrity: sha512-a3nRG0GOGw3IPFA2hdhrZU+QuD3mA6i+5f4YM/Obe+D5lYccxScI32rAIHAW5ttFV7+beiof09gHav4qUEZDwg==} - abortcontroller-polyfill@1.7.8: resolution: {integrity: sha512-9f1iZ2uWh92VcrU9Y8x+LdM4DLj75VE0MJB8zuF1iUnroEptStw+DQ8EQPMUdfe5k+PkB1uUfDQfWbhstH8LrQ==} @@ -7652,6 +8166,10 @@ packages: alien-signals@0.4.14: resolution: {integrity: sha512-itUAVzhczTmP2U5yX67xVpsbbOiquusbWVyA9N+sy6+r6YVbFkahXvNCeEPWEOMhwDYwbVbGHFkVL03N9I5g+Q==} + angular-html-parser@10.11.0: + resolution: {integrity: sha512-3vERzJ65UFDr3C7uozLJwsNcQS3FS784dSh583oDgDTTZMgXe3/pdyXgKndxiP5R2lvYRfW6gSl145Hnyf2OFA==} + engines: {node: '>= 14'} + anser@1.4.10: resolution: {integrity: sha512-hCv9AqTQ8ycjpSd3upOJd7vFwW1JaoYQ7tpham03GJ1ca8/65rqn0RpaWpItOAd6ylW9wAw6luXYPJIyPFVOww==} @@ -7693,12 +8211,6 @@ packages: apg-lite@1.0.5: resolution: {integrity: sha512-SlI+nLMQDzCZfS39ihzjGp3JNBQfJXyMi6cg9tkLOCPVErgFsUIAEdO9IezR7kbP5Xd0ozcPNQBkf9TO5cHgWw==} - app-module-path@2.2.0: - resolution: {integrity: sha512-gkco+qxENJV+8vFcDiiFhuoSvRXb2a/QPqpSoWhVz829VNJfOTnELbBmPmNKFxf3xdNnw4DWCkzkDaavcX/1YQ==} - - arg@4.1.3: - resolution: {integrity: sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==} - argparse@1.0.10: resolution: {integrity: sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==} @@ -7766,10 +8278,6 @@ packages: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} - ast-module-types@5.0.0: - resolution: {integrity: sha512-JvqziE0Wc0rXQfma0HZC/aY7URXHFuZV84fJRtP8u+lhp0JYCNd5wJzVXP45t0PH0Mej3ynlzvdyITYIu0G4LQ==} - engines: {node: '>=14'} - ast-types-flow@0.0.8: resolution: {integrity: sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==} @@ -7777,6 +8285,9 @@ packages: resolution: {integrity: sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg==} engines: {node: '>=4'} + ast-v8-to-istanbul@1.0.5: + resolution: {integrity: sha512-UPAgKJFSEGMWSDr3LX4tqnAb4f7KGT8O40Tyx8wbYmmZ/yn58lNCm8h3svs3eXgiGd5AXxz8NDOvXWvicq+rJA==} + async-function@1.0.0: resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==} engines: {node: '>= 0.4'} @@ -7845,6 +8356,10 @@ packages: balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + base-x@3.0.11: resolution: {integrity: sha512-xz7wQ8xDhdyP7tQxwdteLYeFfS68tSMNCZ/Y37WJ4bhGfKPpqEIlmIyueQHqOyoPhE6xNUqjzRr8ra0eF9VRvA==} @@ -7889,8 +8404,11 @@ packages: bintrees@1.0.2: resolution: {integrity: sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==} - bl@4.1.0: - resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + birecord@0.1.2: + resolution: {integrity: sha512-5PAPTTmMpMEb+GuMb5DebfBkipRGyIW9+gtwEBSoDA9xkhHILm04+hZQ702pMksu3d8YAuGkmgTzQWcKqTPScA==} + + birnam@1.0.0: + resolution: {integrity: sha512-lropqEwi52w2aoOQQ+V4MGc8KP5mVef9DaEKv73dkVXb8UN6moQ7j/f19NesXPYt/l+8MkkHtMBAQsBKR8BqgQ==} bl@5.1.0: resolution: {integrity: sha512-tv1ZJHLfTDnXE6tMHv73YgSJaWR2AFuPwMntBe7XL/GBFHnT0CLnsHMogfk5+GzCDC5ZWarSCYaIGATZt9dNsQ==} @@ -7902,8 +8420,8 @@ packages: resolution: {integrity: sha512-bZES7RzJ14B4WBT3JuOHSOAvCBmUhqznrojQ8xRjN1Fx9X9N7R+rygOFS3k4wXel2nFg4lwzL3luAYzObaDLng==} engines: {node: '>=16'} - blockstore-core@5.0.4: - resolution: {integrity: sha512-v7wtBEpW2J/kKljN7Z2u4Tnwr7qwnOvW1aPVfynIxEdejlVC7gg4z9k6iJt7n5XMGkdNnH4HOmVcjYcaMnu7yg==} + blockstore-core@7.0.1: + resolution: {integrity: sha512-HgLzdH8oL6DrMC6J7snxmV0TXzJ/BMPSbskH4v7BBuUO9foDBOMEKUfoMX9yoBpxbH+r3Z9afXHDgXlTifMxHQ==} bn.js@4.11.6: resolution: {integrity: sha512-XWwnNNFCuuSQ0m3r3C4LE3EiORltHd9M05pq6FOlVeiophzRbMo50Sbz1ehl8K3Z+jw9+vmgnXefY1hz8X+2wA==} @@ -7926,6 +8444,10 @@ packages: brace-expansion@1.1.12: resolution: {integrity: sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==} + brace-expansion@5.0.9: + resolution: {integrity: sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==} + engines: {node: 20 || >=22} + braces@3.0.3: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} @@ -7965,9 +8487,6 @@ packages: buffer-reverse@1.0.1: resolution: {integrity: sha512-M87YIUBsZ6N924W57vDwT/aOu8hw7ZgdByz6ijksLjmHJELBASmYTTlNHRgjE+pTsT9oJXGaDSgqqwfdHotDUg==} - buffer@5.7.1: - resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} - buffer@6.0.3: resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==} @@ -8026,14 +8545,14 @@ packages: caniuse-lite@1.0.30001793: resolution: {integrity: sha512-iwSsYWaCOoh26cV8NwNRViHlrfUvYsHDfRVcbtmw0Kg6PJIZZXwMkj1442FYLBGkeUf1juAsU3DTfxW579mrPA==} - cborg@4.5.8: - resolution: {integrity: sha512-6/viltD51JklRhq4L7jC3zgy6gryuG5xfZ3kzpE+PravtyeQLeQmCYLREhQH7pWENg5pY4Yu/XCd6a7dKScVlw==} - hasBin: true - cborg@5.1.1: resolution: {integrity: sha512-BDbSRIp6XrQXkTc7g+DN0RB9RrDPTUfals2ecWUlt3juPLjbAvy/V72mJcXY0Ehu0Dq/3WpNCOCT68HUTbW+lw==} hasBin: true + cborg@6.1.3: + resolution: {integrity: sha512-Kb/wD/AFuVcqvVjR+HYNOjNiuhVJ2C+RWxQE2Yqq2WVlVkRjdvVLkkM6QsL3NMsBRh+rgNc+aXmcraA+X0HObQ==} + hasBin: true + centrifuge@5.7.0: resolution: {integrity: sha512-Ptx7ELyVc7/KgzpadVlISTtdTWsuzumze5/vo9sH4RsvtFulJJMhmKr/cNDg6se1eKKbS6ZywIBl4eSZxqY3fw==} @@ -8065,6 +8584,9 @@ packages: character-reference-invalid@2.0.1: resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==} + chardet@2.2.0: + resolution: {integrity: sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==} + charenc@0.0.2: resolution: {integrity: sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==} @@ -8076,9 +8598,6 @@ packages: resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} engines: {node: '>= 20.19.0'} - chownr@1.1.4: - resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==} - chrome-launcher@0.15.2: resolution: {integrity: sha512-zdLEwNo3aUVzIhKhTtXfxhdvZhUghrnmkvcAq2NoDd+LeOHKf03H5jwZ8T/STsAlzyALkBVK552iaG1fGf1xVQ==} engines: {node: '>=12.13.0'} @@ -8120,6 +8639,10 @@ packages: resolution: {integrity: sha512-xRwvIOMGrfOAnM1JYtqQImuaNtDEv9v6oIYAs4LIHwTiKee8uwvIi363igssOC0O5U04i4AlENs79LQLu9tEMw==} engines: {node: '>=20'} + cli-width@4.1.0: + resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==} + engines: {node: '>= 12'} + client-only@0.0.1: resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} @@ -8159,6 +8682,9 @@ packages: codemirror@5.65.21: resolution: {integrity: sha512-6teYk0bA0nR3QP0ihGMoxuKzpl5W80FpnHpBJpgy66NK3cZv5b/d/HY8PnRvfSsCG1MTfr92u2WUl+wT0E40mQ==} + codemirror@6.0.2: + resolution: {integrity: sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==} + color-convert@2.0.1: resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} engines: {node: '>=7.0.0'} @@ -8187,10 +8713,6 @@ packages: comma-separated-tokens@2.0.3: resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} - commander@10.0.1: - resolution: {integrity: sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==} - engines: {node: '>=14'} - commander@12.1.0: resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==} engines: {node: '>=18'} @@ -8254,6 +8776,10 @@ packages: cookie-es@1.2.3: resolution: {integrity: sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw==} + cookie@1.1.1: + resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} + engines: {node: '>=18'} + copy-to-clipboard@3.3.3: resolution: {integrity: sha512-2KV8NhB5JqC3ky0r9PMCAZKbUHSwtEo4CwCs0KXgruG43gX5PMqDEBbVU4OUzw2MuAWUfsuFmWvEKG5QRfSnJA==} @@ -8290,18 +8816,12 @@ packages: engines: {node: '>=0.8'} hasBin: true - create-require@1.1.1: - resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==} - crelt@1.0.6: resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==} cross-fetch@3.2.0: resolution: {integrity: sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q==} - cross-fetch@4.0.0: - resolution: {integrity: sha512-e4a5N8lVvuLgAWgnCrLr2PP0YyDOTHa9H/Rj54dirp61qXnNq46m82bRhNqIA5VccJtWBvPTFRV3TtvHUKPB1g==} - cross-fetch@4.1.0: resolution: {integrity: sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw==} @@ -8593,8 +9113,8 @@ packages: resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==} engines: {node: '>= 0.4'} - datastore-core@10.0.4: - resolution: {integrity: sha512-IctgCO0GA7GHG7aRm3JRruibCsfvN4EXNnNIlLCZMKIv0TPkdAL5UFV3/xTYFYrrZ1jRNrXZNZRvfcVf/R+rAw==} + datastore-core@12.0.1: + resolution: {integrity: sha512-pfgIE5LG0Z5oyc6TxiLaF/0j4Gh1Yrs2+Ck/qssf9Oxw4s4YKC3zpqifuzThnKakAFWONr/vRv+66Koc0yJvyA==} date-fns@2.30.0: resolution: {integrity: sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==} @@ -8726,9 +9246,9 @@ packages: resolution: {integrity: sha512-ReEBKkIfe4ya47wlPYf/gu5ib6yUG0/Aez0JQZQz94kiWtRQvZIQbTiehsnwHvLSWJnQdhVeqYue7Id1dKr0qw==} engines: {node: '>=10'} - delay@6.0.0: - resolution: {integrity: sha512-2NJozoOHQ4NuZuVIr5CWd0iiLVIRSDepakaovIN+9eIDHEhdCAEvSy2cuf1DCrPPQLvHmbqTHODlhHg8UCy4zw==} - engines: {node: '>=16'} + delay@7.0.0: + resolution: {integrity: sha512-C3vaGs818qzZjCvVJ98GQUMVyWeg7dr5w2Nwwb2t5K8G98jOyyVO2ti2bKYk5yoYElqH3F2yA53ykuEnwD6MCg==} + engines: {node: '>=20'} delayed-stream@1.0.0: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} @@ -8738,11 +9258,6 @@ packages: resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} engines: {node: '>= 0.8'} - dependency-tree@10.0.9: - resolution: {integrity: sha512-dwc59FRIsht+HfnTVM0BCjJaEWxdq2YAvEDy4/Hn6CwS3CBWMtFnL3aZGAkQn3XCYxk/YcTDE4jX2Q7bFTwCjA==} - engines: {node: '>=14'} - hasBin: true - dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -8752,6 +9267,9 @@ packages: peerDependencies: valtio: '*' + des.js@1.1.0: + resolution: {integrity: sha512-r17GxjhUCjSRy8aiJpr8/UadFIzMzJGexI3Nmz4ADi9LYSFx4gTBp80+NaX/YsXWWLhpZ7v/v/ubEc/bCNfKwg==} + destr@2.0.5: resolution: {integrity: sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==} @@ -8769,42 +9287,8 @@ packages: detect-node-es@1.1.0: resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==} - detective-amd@5.0.2: - resolution: {integrity: sha512-XFd/VEQ76HSpym80zxM68ieB77unNuoMwopU2TFT/ErUk5n4KvUTwW4beafAVUugrjV48l4BmmR0rh2MglBaiA==} - engines: {node: '>=14'} - hasBin: true - - detective-cjs@5.0.1: - resolution: {integrity: sha512-6nTvAZtpomyz/2pmEmGX1sXNjaqgMplhQkskq2MLrar0ZAIkHMrDhLXkRiK2mvbu9wSWr0V5/IfiTrZqAQMrmQ==} - engines: {node: '>=14'} - - detective-es6@4.0.1: - resolution: {integrity: sha512-k3Z5tB4LQ8UVHkuMrFOlvb3GgFWdJ9NqAa2YLUU/jTaWJIm+JJnEh4PsMc+6dfT223Y8ACKOaC0qcj7diIhBKw==} - engines: {node: '>=14'} - - detective-postcss@6.1.3: - resolution: {integrity: sha512-7BRVvE5pPEvk2ukUWNQ+H2XOq43xENWbH0LcdCE14mwgTBEAMoAx+Fc1rdp76SmyZ4Sp48HlV7VedUnP6GA1Tw==} - engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} - - detective-sass@5.0.3: - resolution: {integrity: sha512-YsYT2WuA8YIafp2RVF5CEfGhhyIVdPzlwQgxSjK+TUm3JoHP+Tcorbk3SfG0cNZ7D7+cYWa0ZBcvOaR0O8+LlA==} - engines: {node: '>=14'} - - detective-scss@4.0.3: - resolution: {integrity: sha512-VYI6cHcD0fLokwqqPFFtDQhhSnlFWvU614J42eY6G0s8c+MBhi9QAWycLwIOGxlmD8I/XvGSOUV1kIDhJ70ZPg==} - engines: {node: '>=14'} - - detective-stylus@4.0.0: - resolution: {integrity: sha512-TfPotjhszKLgFBzBhTOxNHDsutIxx9GTWjrL5Wh7Qx/ydxKhwUrlSFeLIn+ZaHPF+h0siVBkAQSuy6CADyTxgQ==} - engines: {node: '>=14'} - - detective-typescript@11.2.0: - resolution: {integrity: sha512-ARFxjzizOhPqs1fYC/2NMC3N4jrQ6HvVflnXBTRqNEqJuXwyKLRr9CrJwkRcV/SnZt1sNXgsF6FPm0x57Tq0rw==} - engines: {node: ^14.14.0 || >=16.0.0} - - diff@4.0.4: - resolution: {integrity: sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==} - engines: {node: '>=0.3.1'} + diff-match-patch@1.0.5: + resolution: {integrity: sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==} diff@8.0.4: resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==} @@ -8852,6 +9336,9 @@ packages: resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==} engines: {node: '>= 4'} + dompurify@3.4.16: + resolution: {integrity: sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==} + dompurify@3.4.9: resolution: {integrity: sha512-4dPSRMRDqHvs0V4YDFCsaIZo4if5u0xM+llyxiM2fwuZFdKArUBAF3VtI2+n8NKg9P870WMdYk0UhqQNoWXbfQ==} @@ -8931,6 +9418,10 @@ packages: emoji-regex@9.2.2: resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + empathic@2.0.1: + resolution: {integrity: sha512-YGRs8knHhKHVShLkFET/rWAU8kmHbOV5LwN938RHI0pljAJ1Gf6SzXsSmRaEzcXTtOOmVqJ5+WtQPL5uigY50Q==} + engines: {node: '>=14'} + encode-utf8@1.0.3: resolution: {integrity: sha512-ucAnuBEhUK4boH2HjVYG5Q2mQyPorvv0u/ocS+zhdw0S8AlHYY+GOFhP1Gio5z4icpP2ivFSvhtFjQi8+T9ppw==} @@ -8952,10 +9443,6 @@ packages: resolution: {integrity: sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==} engines: {node: '>=10.0.0'} - enhanced-resolve@5.22.0: - resolution: {integrity: sha512-xYcDWrpELkFzz9SpZ3PlI6Eu6eD93Yf0WLDRxikGhWJ3MAir2SNZTIVCVZqZ/NUyx8AdMc2gT9C0gPiw18kG+A==} - engines: {node: '>=10.13.0'} - enhanced-resolve@5.23.0: resolution: {integrity: sha512-yJN/BOOLxcOW2aQgeif9mSnaUB8KtvmMMp56oA1kx1CRfBKbhZm2pJ+NBY+3eOboHxix8lfjWpHE0Ei5U8RbSA==} engines: {node: '>=10.13.0'} @@ -9017,8 +9504,8 @@ packages: resolution: {integrity: sha512-HVLACW1TppGYjJ8H6/jqH/pqOtKRw6wMlrB23xfExmFWxFquAIWCmwoLsOyN96K4a5KbmOf5At9ZUO3GZbetAw==} engines: {node: '>= 0.4'} - es-module-lexer@2.1.0: - resolution: {integrity: sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==} + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} es-object-atoms@1.1.2: resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} @@ -9051,11 +9538,6 @@ packages: es6-promisify@5.0.0: resolution: {integrity: sha512-C+d6UdsYDk0lMebHNR4S2NybQMMngAOnOwYBQjTOiv0MkoJMP0Myw2mgpDLBcpfCmRLxyFqYhS/CfOENq4SJhQ==} - esbuild@0.25.12: - resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==} - engines: {node: '>=18'} - hasBin: true - esbuild@0.28.1: resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==} engines: {node: '>=18'} @@ -9072,20 +9554,6 @@ packages: resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} engines: {node: '>=10'} - escodegen@2.1.0: - resolution: {integrity: sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==} - engines: {node: '>=6.0'} - hasBin: true - - eslint-config-next@16.2.6: - resolution: {integrity: sha512-z2ELYSkyrrJ6cuunTU8vhsT/RpouPkjaSah06nVW6Rg2Hpg0Vs8s497/e5s8G8qtdp4ccsiovz5P1rv+5VSW2Q==} - peerDependencies: - eslint: '>=9.0.0' - typescript: '>=3.3.1' - peerDependenciesMeta: - typescript: - optional: true - eslint-import-resolver-node@0.3.10: resolution: {integrity: sha512-tRrKqFyCaKict5hOd244sL6EQFNycnMQnBe+j8uqGNXYzsImGbGUU4ibtoaBmv5FLwJwcFJNeg1GeVjQfbMrDQ==} @@ -9151,16 +9619,6 @@ packages: '@typescript-eslint/parser': optional: true - eslint-plugin-import@2.32.0: - resolution: {integrity: sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==} - engines: {node: '>=4'} - peerDependencies: - '@typescript-eslint/parser': '*' - eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9 - peerDependenciesMeta: - '@typescript-eslint/parser': - optional: true - eslint-plugin-jsx-a11y@6.10.2: resolution: {integrity: sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==} engines: {node: '>=4.0'} @@ -9173,25 +9631,61 @@ packages: peerDependencies: eslint: '>=8.40.0' + eslint-plugin-react-dom@5.19.0: + resolution: {integrity: sha512-QxWdjdPxQUI3SSMYR7WyrLew7pQzlOn5P3R5raWh2PiyavaBUbkfJhSJ307l1AaJOVLy5JeIB2Rl4bivwHAOIQ==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + eslint-plugin-react-hooks@5.0.0: resolution: {integrity: sha512-hIOwI+5hYGpJEc4uPRmz2ulCjAGD/N13Lukkh8cLV0i2IRk/bdZDYjgLVHj+U9Z704kLIdIO6iueGvxNur0sgw==} engines: {node: '>=10'} peerDependencies: eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 - eslint-plugin-react-hooks@7.1.1: - resolution: {integrity: sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==} - engines: {node: '>=18'} + eslint-plugin-react-jsx@5.19.0: + resolution: {integrity: sha512-Upvpe50vpPi5jWvLqtBXoZEwaCz1pzszzoukK7qf0g1A6ZJ+XDJhi3yKmPQWBlp9c4GOwzwPuXGU5C2e8cHMbQ==} + engines: {node: '>=22.0.0'} peerDependencies: - eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0 + eslint: '*' + typescript: '*' - eslint-plugin-react@7.37.5: - resolution: {integrity: sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==} - engines: {node: '>=4'} + eslint-plugin-react-naming-convention@5.19.0: + resolution: {integrity: sha512-H9ko2t+KYPBDOfr29D5hDAT6CXucHJKGQscI+/ndSmkBl9K/KaGWdhFiCzQPi5S2YwPkjrcuaSXIp/n8+PA5GA==} + engines: {node: '>=22.0.0'} peerDependencies: - eslint: ^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7 + eslint: '*' + typescript: '*' - eslint-plugin-regexp@2.6.0: + eslint-plugin-react-rsc@5.19.0: + resolution: {integrity: sha512-XdfkB2XRS0b1WBkuxnRsWmhivNaBOLAIohBqWQItQycuket6wVliqSY+Q1NcTst4PdJ1bYzLuMgSXYsgwJMV7Q==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + + eslint-plugin-react-web-api@5.19.0: + resolution: {integrity: sha512-wCNdYVHgdLmCikLicH6kfO6EE1SKzi63FlhLLGMGzzEAyvudvyfKI0+ZXDkFyjolvKXLQW6Thb8EeAFbHTZksw==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + + eslint-plugin-react-x@5.19.0: + resolution: {integrity: sha512-HoweOyYhar8G2QEukOctSaK87Y3AzB3bn4ES+0VVhcNOOqBFphRaWqcvoNN8JE+5AKOhhpuzjVKY6DnGPCcAMw==} + engines: {node: '>=22.0.0'} + peerDependencies: + eslint: '*' + typescript: '*' + + eslint-plugin-react@7.37.5: + resolution: {integrity: sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==} + engines: {node: '>=4'} + peerDependencies: + eslint: ^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7 + + eslint-plugin-regexp@2.6.0: resolution: {integrity: sha512-FCL851+kislsTEQEMioAlpDuK5+E5vs0hi1bF8cFlPlHcEjeRhuAzEsGikXRreE+0j4WhW2uO54MqTjXtYOi3A==} engines: {node: ^18 || >=20} peerDependencies: @@ -9233,6 +9727,7 @@ packages: eslint@9.39.2: resolution: {integrity: sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options. hasBin: true peerDependencies: jiti: '*' @@ -9303,9 +9798,6 @@ packages: resolution: {integrity: sha512-/Sn9Y0oKl0uqQuvgFk/zQgR7aw1g36qX/jzSQ5lSwlO0GigPymk4eGQfeNTD03w1dPOqfz8V77Cy43jH56pagw==} engines: {node: '>=6.5.0', npm: '>=3'} - event-iterator@2.0.0: - resolution: {integrity: sha512-KGft0ldl31BZVV//jj+IAIGCxkvvUkkON+ScH6zfoX+l+omX6001ggyRSpI0Io2Hlro0ThXotswCtfzS8UkIiQ==} - event-target-shim@5.0.1: resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==} engines: {node: '>=6'} @@ -9327,12 +9819,12 @@ packages: resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} engines: {node: '>=0.8.x'} - expand-template@2.0.3: - resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==} - engines: {node: '>=6'} + execa@9.6.1: + resolution: {integrity: sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==} + engines: {node: ^18.19.0 || >=20.5.0} - expect-type@1.3.0: - resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} engines: {node: '>=12.0.0'} exponential-backoff@3.1.3: @@ -9445,25 +9937,21 @@ packages: fflate@0.4.8: resolution: {integrity: sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==} - fflate@0.8.3: - resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==} + figures@6.1.0: + resolution: {integrity: sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==} + engines: {node: '>=18'} file-entry-cache@8.0.0: resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} engines: {node: '>=16.0.0'} - file-type@20.5.0: - resolution: {integrity: sha512-BfHZtG/l9iMm4Ecianu7P8HRD2tBHLtjXinm4X62XBOYzi7CYA7jyqfJzOvXHqzVrVPYqBo2/GvbARMaaJkKVg==} - engines: {node: '>=18'} + file-type@22.1.1: + resolution: {integrity: sha512-sEB0oStmeLGtpmSAD88RDNuLsvhv4iC3u0lE25CUvfCULvj49xoQ3l3K525Vn+ZzsZ6DOLajQCV6RmhwwhqiJg==} + engines: {node: '>=22'} file-uri-to-path@1.0.0: resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} - filing-cabinet@4.2.0: - resolution: {integrity: sha512-YZ21ryzRcyqxpyKggdYSoXx//d3sCJzM3lsYoaeg/FyXdADGJrUl+BW1KIglaVLJN5BBcMtWylkygY8zBp2MrQ==} - engines: {node: '>=14'} - hasBin: true - fill-range@7.1.1: resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} engines: {node: '>=8'} @@ -9580,9 +10068,6 @@ packages: from-exponential@1.1.1: resolution: {integrity: sha512-VBE7f5OVnYwdgB3LHa+Qo29h8qVpxhVO9Trlc+AWm+/XNAgks1tAwMFHb33mjeiof77GglsJzeYF7OqXrROP/A==} - fs-constants@1.0.0: - resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} - fs-extra@11.3.5: resolution: {integrity: sha512-eKpRKAovdpZtR1WopLHxlBWvAgPny3c4gX1G5Jhwmmw4XJj0ifSD5qB5TOo8hmA0wlRKDAOAhEE1yVPgs6Fgcg==} engines: {node: '>=14.14'} @@ -9634,10 +10119,6 @@ packages: resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} engines: {node: '>=6.9.0'} - get-amd-module-type@5.0.1: - resolution: {integrity: sha512-jb65zDeHyDjFR1loOVk0HQGM5WNwoGB8aLWy3LKCieMKol0/ProHkhO2X1JxojuN10vbz1qNn09MJ7tNp7qMzw==} - engines: {node: '>=14'} - get-caller-file@2.0.5: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} @@ -9657,9 +10138,6 @@ packages: resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==} engines: {node: '>=6'} - get-own-enumerable-property-symbols@3.0.2: - resolution: {integrity: sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==} - get-port@7.2.0: resolution: {integrity: sha512-afP4W205ONCuMoPBqcR6PSXnzX35KTcJygfJfcp+QY+uwm3p20p1YczWXhlICIzGMCxYBQcySEcOgsJcrkyobg==} engines: {node: '>=16'} @@ -9687,9 +10165,6 @@ packages: resolution: {integrity: sha512-mKZj9JLQrwMBtj5wxi6MH8Z5eSKaERpAwjg43dPtlGI1ZVEgH/qC7T8/6R2OBSUA+zzHBZgICsVJaEIV2tKTDA==} engines: {node: '>=6.0'} - github-from-package@0.0.0: - resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==} - glob-parent@5.1.2: resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} engines: {node: '>= 6'} @@ -9706,10 +10181,6 @@ packages: deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me hasBin: true - glob@7.2.3: - resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} - deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me - glob@8.1.0: resolution: {integrity: sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==} engines: {node: '>=12'} @@ -9731,10 +10202,6 @@ packages: resolution: {integrity: sha512-1+gLErljJFhbOVyaetcwJiJ4+eLe45S2E7P5UiZ9xGfeq3ATQf5DOv9G7MH3gGbKQLkzmNh2DxfZwLdw+j6oTQ==} engines: {node: '>=18'} - globals@16.4.0: - resolution: {integrity: sha512-ob/2LcVVaVGCYN+r14cnwnoDPUufjiYgSqRhiFD0Q1iI4Odora5RE8Iv1D24hAz5oMophRGkGz+yuvQmmUMnMw==} - engines: {node: '>=18'} - globalthis@1.0.4: resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} engines: {node: '>= 0.4'} @@ -9747,14 +10214,6 @@ packages: resolution: {integrity: sha512-QrJia2qDf5BB/V6HYlDTs0I0lBahyjLzpGQg3KT7FnCdTonAyPy2RtY802m2k4ALx6Dp752f82WsOczEVr3l6Q==} engines: {node: '>=20'} - globrex@0.1.2: - resolution: {integrity: sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==} - - gonzales-pe@4.3.0: - resolution: {integrity: sha512-otgSPpUmdWJ43VXyiNgEYE4luzHCL2pz4wQ0OnDluC6Eg4Ko3Vexy/SrSynglw/eR+OhkzmqFCZa/OFa/RgAOQ==} - engines: {node: '>=0.6.0'} - hasBin: true - google-logging-utils@1.1.3: resolution: {integrity: sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==} engines: {node: '>=14'} @@ -9781,7 +10240,7 @@ packages: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} gradient-avatar@https://codeload.github.com/blockscout/gradient-avatar/tar.gz/86810368c2581d2dc3aca089dc648336c8e17045: - resolution: {gitHosted: true, tarball: https://codeload.github.com/blockscout/gradient-avatar/tar.gz/86810368c2581d2dc3aca089dc648336c8e17045} + resolution: {gitHosted: true, integrity: sha512-0O9zIUvqAKbiefYuC8lgxRIsCzSD07ectXRligCwEHxLEIP7WKfvDJiyLnXAudI4LGn6MNAkl1BC9/sTGtTTDg==, tarball: https://codeload.github.com/blockscout/gradient-avatar/tar.gz/86810368c2581d2dc3aca089dc648336c8e17045} version: 1.0.3 engines: {node: '>=8'} @@ -9873,8 +10332,8 @@ packages: resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==} hasBin: true - helia@5.5.1: - resolution: {integrity: sha512-UrTI19VZsNrYc4efwTSIWZeCkJeoxTM4pa/2Zofj5mYLNb6wB09XMJLHBgX1q0dJC7CETVjXeSXcjZgL2s9+AA==} + helia@7.1.16: + resolution: {integrity: sha512-tWqr7DC0soL0Mvi93bPGgIWeSNZYvs5ZIZjTRkuTepRufoFmvd1OOtjixRgR3dSk1x4Z1SvYtfc2fUyO3S0FCA==} help-me@4.2.0: resolution: {integrity: sha512-TAOnTB8Tz5Dw8penUuzHVrKNKlCIbwwbHnXraNJxPwf8LRtE2HlM84RYuezMFcwOJmoYOCWVDyJ8TQGxn9PgxA==} @@ -9882,18 +10341,12 @@ packages: hermes-compiler@250829098.0.10: resolution: {integrity: sha512-TcRlZ0/TlyfJqquRFAWoyElVNnkdYRi/sEp4/Qy8/GYxjg8j2cS9D4MjuaQ+qimkmLN7AmO+44IznRf06mAr0w==} - hermes-estree@0.25.1: - resolution: {integrity: sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==} - hermes-estree@0.33.3: resolution: {integrity: sha512-6kzYZHCk8Fy1Uc+t3HGYyJn3OL4aeqKLTyina4UFtWl8I0kSL7OmKThaiX+Uh2f8nGw3mo4Ifxg0M5Zk3/Oeqg==} hermes-estree@0.35.0: resolution: {integrity: sha512-xVx5Opwy8Oo1I5yGpVRhCvWL/iV3M+ylksSKVNlxxD90cpDpR/AR1jLYqK8HWihm065a6UI3HeyAmYzwS8NOOg==} - hermes-parser@0.25.1: - resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==} - hermes-parser@0.33.3: resolution: {integrity: sha512-Yg3HgaG4CqgyowtYjX/FsnPAuZdHOqSMtnbpylbptsQ9nwwSKsy6uRWcGO5RK0EqiX12q8HvDWKgeAVajRO5DA==} @@ -9943,16 +10396,6 @@ packages: http-cache-semantics@4.2.0: resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==} - http-cookie-agent@6.0.8: - resolution: {integrity: sha512-qnYh3yLSr2jBsTYkw11elq+T361uKAJaZ2dR4cfYZChw1dt9uL5t3zSUwehoqqVb4oldk1BpkXKm2oat8zV+oA==} - engines: {node: '>=18.0.0'} - peerDependencies: - tough-cookie: ^4.0.0 || ^5.0.0 - undici: ^5.11.0 || ^6.0.0 - peerDependenciesMeta: - undici: - optional: true - http-errors@2.0.1: resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==} engines: {node: '>= 0.8'} @@ -9973,6 +10416,10 @@ packages: resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} engines: {node: '>= 14'} + human-signals@8.0.1: + resolution: {integrity: sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==} + engines: {node: '>=18.18.0'} + humanize-duration@3.33.2: resolution: {integrity: sha512-K7Ny/ULO1hDm2nnhvAY+SJV1skxFb61fd073SG1IWJl+D44ULrruCuTyjHKjBVVcSuTlnY99DKtgEG39CM5QOQ==} @@ -9991,6 +10438,10 @@ packages: resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} engines: {node: '>=0.10.0'} + iconv-lite@0.7.3: + resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==} + engines: {node: '>=0.10.0'} + icss-utils@5.1.0: resolution: {integrity: sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==} engines: {node: ^10 || ^12 || >= 14} @@ -10063,21 +10514,21 @@ packages: resolution: {integrity: sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==} engines: {node: ^20.17.0 || >=22.9.0} - interface-blockstore@5.3.2: - resolution: {integrity: sha512-oA9Pjkxun/JHAsZrYEyKX+EoPjLciTzidE7wipLc/3YoHDjzsnXRJzAzFJXNUvogtY4g7hIwxArx8+WKJs2RIg==} + interface-blockstore@7.0.1: + resolution: {integrity: sha512-a3NsgRXpRppVWtQnJjmZ9jxvjcttY1+WNWqHFWwgKhRcNMMGwWGtFNYpQmcZ+mEnIt5NTJVYzNwLCcALMWPNsA==} - interface-datastore@8.3.2: - resolution: {integrity: sha512-R3NLts7pRbJKc3qFdQf+u40hK8XWc0w4Qkx3OFEstC80VoaDUABY/dXA2EJPhtNC+bsrf41Ehvqb6+pnIclyRA==} + interface-datastore@10.0.1: + resolution: {integrity: sha512-DYMj/Og5Cz1Qwkx6/x5KRvR8SYEX7rVAv3KKCm2NzTwWSfpNAC4PahjcYbHyoZBP6zPWrhQv5n5wE+vaDdgSAg==} interface-datastore@9.0.3: resolution: {integrity: sha512-NLZa7Mp+0qn48nSwIY/C36da4uVIKzwG2tuEIpaSJArsuB2RrdyDWwkoDUyjsJ+VrMntXz38VSk9vXTx/ZUpAw==} - interface-store@6.0.3: - resolution: {integrity: sha512-+WvfEZnFUhRwFxgz+QCQi7UC6o9AM0EHM9bpIe2Nhqb100NHCsTvNAn4eJgvgV2/tmLo1MP9nGxQKEcZTAueLA==} - interface-store@7.0.2: resolution: {integrity: sha512-KYOPcDH+1peaPhSeoZujR5nwkVeola1EdrnrlHTIM0HRNUs9B0aTsUQMH5kTmIjaQq1BOowoUyoCamgL8IMyww==} + interface-store@8.0.0: + resolution: {integrity: sha512-e2+s3EEROzM+Wlas4hU3zveTUscvVMf1BOvdsJfpzFm19SoEXLVadpACjWOnM491HqGpvtfFnevyiaN8W+I6Eg==} + internal-slot@1.1.0: resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==} engines: {node: '>= 0.4'} @@ -10101,17 +10552,14 @@ packages: resolution: {integrity: sha512-fOCG6lhoKKakwv+C6KdsOnGvgXnmgfmp0myi3bcNwj3qfwPAxRKWEuFhvEFF7ceYIz6+1jRZ+yguLFAmUNPEfw==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - ipfs-unixfs-exporter@13.7.3: - resolution: {integrity: sha512-sTFjAEnsPu5irh9rvT1j5mNf7nXnW78x5SJrCIrNZb1UqkXQtNX81RjAnTBShUtZ5ujSOc/yrC9Az8il8NVkKQ==} + ipfs-unixfs-exporter@16.2.3: + resolution: {integrity: sha512-U+YXqw9TnWpx8F+/qLZ/1E/hFsDTs4BSQ9i+ifdctwmLZ5wH65X/zVHSUBkpLvbUedCWbXGIH2om6sgWOH7nsg==} - ipfs-unixfs-importer@15.4.0: - resolution: {integrity: sha512-laypY07Q0uGLMSxx5YsfVAEPVzdbV2p9cEC1/HNxqoWoz83LA2nX45usr8dcehalKLHm38u0FwUiRHq5wCHngQ==} + ipfs-unixfs-importer@17.1.1: + resolution: {integrity: sha512-Yw91sINTxlImpXc7/D6S9SZ/SwDr/kCiy4vE6VIdbOhnbS9EsXeLnJl8TDywFP/U0bwKfWC6LuJwP8dKDQ//OA==} - ipfs-unixfs@11.2.5: - resolution: {integrity: sha512-uasYJ0GLPbViaTFsOLnL9YPjX5VmhnqtWRriogAHOe4ApmIi9VAOFBzgDHsUW2ub4pEa/EysbtWk126g2vkU/g==} - - ipns@10.1.6: - resolution: {integrity: sha512-mTACIdTBBXY5kbCo3t/M3ycNWbjajLrSXhTvjD0MEGyOUaI3uMv94JbJSHGaJ2xxRlpOrRk1ifToOsyPZiglnA==} + ipfs-unixfs@13.1.2: + resolution: {integrity: sha512-N8LDphmWAEQbRXu35l4iOXrFbBGmYl0o1PKw9kxsp1dcOHG+CCLdF68gt6jREObFsC48VXm4fbgNXIfoNUIcuA==} iron-webcrypto@1.2.1: resolution: {integrity: sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg==} @@ -10243,10 +10691,6 @@ packages: resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} engines: {node: '>=0.12.0'} - is-obj@1.0.1: - resolution: {integrity: sha512-l4RyHgRqGN4Y3+9JHVrNqO+tN0rV5My76uW5/nuO4K1b6vw5G8d/cmFjP9tRfEsdhZNt0IFdZuK/c2Vr4Nb+Qg==} - engines: {node: '>=0.10.0'} - is-path-inside@4.0.0: resolution: {integrity: sha512-lJJV/5dYS+RcL8uQdBDW9c9uWFLLBNRyFhnAKXw5tVqLlKZ4RMGZKv+YQ/IA3OhD+RpbJa1LLFM1FQPGyIXvOA==} engines: {node: '>=12'} @@ -10278,18 +10722,10 @@ packages: resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} engines: {node: '>= 0.4'} - is-regexp@1.0.0: - resolution: {integrity: sha512-7zjFAPO4/gwyQAAgRRmqeEeyIICSdmCqa3tsVHMdBzaXXRiqopZL4Cyghg/XulGWrtABTpbnYYzzIRffLkP4oA==} - engines: {node: '>=0.10.0'} - is-regexp@3.1.0: resolution: {integrity: sha512-rbku49cWloU5bSMI+zaRaXdQHXnthP6DZ/vLnfdSKyL4zUzuWnomtOEiZZOd+ioQ+avFo/qau3KPTc7Fjy1uPA==} engines: {node: '>=12'} - is-relative-path@1.0.2: - resolution: {integrity: sha512-i1h+y50g+0hRbBD+dbnInl3JlJ702aar58snAeX+MxBAPvzXGej7sYoPMhlnykabt0ZzCJNBEyzMlekuQZN7fA==} - deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. - is-retry-allowed@2.2.0: resolution: {integrity: sha512-XVm7LOeLpTW4jV19QSH38vkswxoLud8sQ57YwJVTPWdiaI9I8keEhGFpBlslyVsgdQy4Opg8QOLb8YRgsyZiQg==} engines: {node: '>=10'} @@ -10326,12 +10762,9 @@ packages: resolution: {integrity: sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==} engines: {node: '>= 0.4'} - is-url-superb@4.0.0: - resolution: {integrity: sha512-GI+WjezhPPcbM+tqE9LnmsY5qqjwHzTvjJ36wxYX5ujNXefSUJ/T17r5bqDV8yLhcgB59KTPNOc9O9cmHTPWsA==} - engines: {node: '>=10'} - - is-url@1.2.4: - resolution: {integrity: sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==} + is-unicode-supported@2.1.0: + resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==} + engines: {node: '>=18'} is-weakmap@2.0.2: resolution: {integrity: sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==} @@ -10387,8 +10820,8 @@ packages: it-batch@3.0.11: resolution: {integrity: sha512-2bvKErkXhtwKYDLKAGdEgveOs8wB0i3RItbaroP/6cC/QlrM7j+HAq/yJq6ci4J7KnzdRi76GyipKlafdOTBgw==} - it-byte-stream@2.0.6: - resolution: {integrity: sha512-lcPo7azQjSfQvLq+Rkb9Wq+ZERK/MGD9Z67BG5c/zcT96S6xO0dY+Lma1+fSuNspYgJNZq7yETWZim8eOfN9ag==} + it-byte-stream@3.0.0: + resolution: {integrity: sha512-dpTm5CaRFuz7Wp8VRo8TLkhVNx4KCNT7fAtVorAz/CxrwBJwyz6a6Au9inPxqDN6kN7VVN3WUweJCziG39T48w==} it-drain@3.0.12: resolution: {integrity: sha512-RaFA9X1PF2Pf1Jlqhgf5PlXLgf6CaZt7tSzhia+EkEVcAJRKa0Uhr8UnjVv0GmOA3Air9jDJfIX2KIvz5hZ1Ag==} @@ -10408,11 +10841,11 @@ packages: it-last@3.0.11: resolution: {integrity: sha512-Fg571l81nPzhZsiYjkw4dkhRqAK4oqIamTPEfAOnXI/5pYXz+dIfMVYmh9ncZs58oFNMkdF3bYFuCBTw/xJK0w==} - it-length-prefixed-stream@2.0.6: - resolution: {integrity: sha512-foGRL4Id5Ypuc9RIPEE5aHWZvpKoGpIASoTBeuAZgH/QMGEy+V0vNgK8U4NBPjKwbhyuhW9gYflXXP43W4ZcKw==} + it-length-prefixed-stream@3.0.1: + resolution: {integrity: sha512-XffBM6F8exghmr9jLQa2TdnwYm/Y5a1zC/v9NFFIiGrDb4lgJfo3YBlXHwjtCqbOJBQ4idO5agY8uUM9VUEb8Q==} - it-length-prefixed@10.0.2: - resolution: {integrity: sha512-RrNBs4d7baK8AKGHleC55l/JtvzxDw6DPXs3CvFgQwdwFzLBFDvlpKgDDNDFwXJjPSy1nEX1A44nL110+EKc3g==} + it-length-prefixed@11.0.1: + resolution: {integrity: sha512-0Cy4RHFiL2CH060Lkigq0N37VaPg7oSylG6YjXErq+ccJFYcNEWNzxNjbqceio/sY1C+q84vZXOCE6/C0flYfQ==} it-length@3.0.11: resolution: {integrity: sha512-j0uukHdr3zoLm4dcozDoyv5khQrOI8dfXMSSEqaxorfOtleh1KwRVbdnTmzj6HVkHgTM1jcx+bhAcnTkbpHl+g==} @@ -10423,12 +10856,8 @@ packages: it-merge@3.0.14: resolution: {integrity: sha512-D3t1Go2G2SQMkTujaA6EVojJPJKA9pFksxlSPDRBfrHKhWl6O40vEP7Itr5eCAjyCQH5p9+BFFVIy9bhLM4ZuQ==} - it-ndjson@1.1.6: - resolution: {integrity: sha512-qseYKspd95qnYUnJ2DE8R25N2+Q+cPCEXTTpyLe7FHaxjbOc/wtyOgKbuzJrQS9bnFJ6yM9wVooC3C0pX44IWQ==} - - it-pair@2.0.6: - resolution: {integrity: sha512-5M0t5RAcYEQYNG5BV7d7cqbdwbCAp5yLdzvkxsZmkuZsLbTdZzah6MQySYfaAQjNDCq6PUnDt0hqBZ4NwMfW6g==} - engines: {node: '>=16.0.0', npm: '>=7.0.0'} + it-ndjson@2.0.0: + resolution: {integrity: sha512-6QOU+X9zBSolfcYGXY5CSJchHb57MgkoDgVJA5Tdh1CwzUHKKJYS0lTzdVR9hefVpiQNhTB/glEU8i37LpP7qw==} it-parallel-batch@3.0.11: resolution: {integrity: sha512-n2gvHRVx14COn25jkio+fOHuKWaA5EVf9f0GbdWgVe8gXRIMYCai+CbmQACIv7o2Jn3ZAUOXD9Ob1Ftod0qtJQ==} @@ -10443,8 +10872,8 @@ packages: resolution: {integrity: sha512-sIoNrQl1qSRg2seYSBH/3QxWhJFn9PKYvOf/bHdtCBF0bnghey44VyASsWzn5dAx0DCDDABq1hZIuzKmtBZmKA==} engines: {node: '>=16.0.0', npm: '>=7.0.0'} - it-protobuf-stream@2.0.6: - resolution: {integrity: sha512-yr1ll0PN4DFrI4gyEMXy4OgcO3Glb7U0J+Scpx1lxOVnuszpcSc0idhxXHMZcDqAIUJgo8JmNHT9Ry6m6vVeJw==} + it-protobuf-stream@3.0.1: + resolution: {integrity: sha512-lKjTCPwL+aKUDovZUt4CyUAsYlOv9z09zyNnnGVWaQmbO6f0n6vV12F4hg0YwWyk9Er6UVWdu1EM7d6P62JnHw==} it-pushable@3.2.4: resolution: {integrity: sha512-WSD7Ss4oCRfDZJT4ldLWr0Bom/muY90xxoJ5PQnU3uSKf0kxCOeehqZtiJX1ARqn+ymXGh1bxpDW9bDNHp2ivQ==} @@ -10459,6 +10888,9 @@ packages: resolution: {integrity: sha512-xdSVkCsVyWmKaE7ZIlqb1QbzitY7Zty7//F2YeZ/9Py5i3RzQHVoPqlHELH+1EouumUdPyfuKoANJ7Q5w4IEBg==} engines: {node: '>=16.0.0', npm: '>=7.0.0'} + it-reader@7.0.0: + resolution: {integrity: sha512-bTWQPHH1if8N1K9XeidDjhTDm51ALbOksMa9uCZVVsQkoIPXP0XVKM88/Ynqr7HS18La/P1Kvu7C73j4rRoKWQ==} + it-sort@3.0.11: resolution: {integrity: sha512-eZ22LAoNLx4i4gVV44tJPoUYf/o+mHKa6+OigdVH/hmsdA2qoJN6MNPvKZyZKBf6+S/8PBE44zyvkzdYGkRhbA==} @@ -10478,9 +10910,8 @@ packages: it-to-buffer@4.0.12: resolution: {integrity: sha512-spgKdZMsY2+d8hJbdbUyPdCArXdz0yJUqY3eXOFUzzgdDV0wk/lWIj4u2HGJhF3jLUun5p7nmPCqGzZGA0WVfw==} - it-ws@6.1.5: - resolution: {integrity: sha512-uWjMtpy5HqhSd/LlrlP3fhYrr7rUfJFFMABv0F5d6n13Q+0glhZthwUKpEAVhDrXY95Tb1RB5lLqqef+QbVNaw==} - engines: {node: '>=16.0.0', npm: '>=7.0.0'} + it-to-buffer@5.0.0: + resolution: {integrity: sha512-DyinWj+79wxFDQNiPZcmV8Fz2PJFOcM3KRRN4GiZiIdEfxO11cCkrZJMfUMrxryy+rLoNhAfh1bpoVUFHPR6pQ==} iterator.prototype@1.1.5: resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==} @@ -10535,9 +10966,15 @@ packages: js-file-download@0.4.12: resolution: {integrity: sha512-rML+NkoD08p5Dllpjo0ffy4jRHeY6Zsapvr/W86N7E0yuzAO6qa5X9+xog6zQNlH102J7IXljNY2FtS6Lj3ucg==} + js-md4@0.3.2: + resolution: {integrity: sha512-/GDnfQYsltsjRswQhN9fhv3EMw2sCpUdrdxyWDOUK7eyD++r3gRhzgiQgc/x4MAv2i1iuQ4lxO5mvqM3vj4bwA==} + js-sha3@0.8.0: resolution: {integrity: sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==} + js-tokens@10.0.0: + resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -10575,6 +11012,9 @@ packages: json-parse-even-better-errors@2.3.1: resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==} + json-rpc-2.0@1.7.1: + resolution: {integrity: sha512-JqZjhjAanbpkXIzFE7u8mE/iFblawwlXtONaCvRqI+pyABVz7B4M1EUNpyVW+dZjqgQ2L5HFmZCmOCgUKm00hg==} + json-rpc-engine@6.1.0: resolution: {integrity: sha512-NEdLrtrq1jUZyfjkr9OCz9EzCNhnRyWtt1PAnvnhwy6e8XETS0Dtc+ZNCO2gvuAoKsIn2+vCSowXTYE4CkgnAQ==} engines: {node: '>=10.0.0'} @@ -10645,8 +11085,8 @@ packages: resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} engines: {node: '>= 0.8.0'} - libp2p@2.10.0: - resolution: {integrity: sha512-tgDz7YuGg1XX7UfxebCUii+IGsly/8V0ZRZdFJSDySY2i3UuqpCTsEbRApH3cBKFhcAf00nx9xj8GL9zfo+XWw==} + libp2p@3.3.11: + resolution: {integrity: sha512-+J3Dw1RnGdcpQaPN1HD+Z6xVS3qY0vnsqE2Tu//pfoiJxabaZVkc2FBNnNQ1Sj+Th2qoloeJ11jvxuNXSa1gtA==} license-report-check@0.1.2: resolution: {integrity: sha512-9q3+aOFhdXFgQcMazMFx2VGeJofTRJSSFAUXa9y2bjOHSBch7tsfSvBtzllpTJz+wDlKhkC2MVvbUCNd3Kqrbg==} @@ -10661,6 +11101,80 @@ packages: lighthouse-logger@1.4.2: resolution: {integrity: sha512-gPWxznF6TKmUHrOQjlVo2UbaL2EJ71mb2CCeRs/2qBpi4L/g4LUVc9+3lKQ6DTUZwJswfM7ainGrLO1+fOqa2g==} + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + lines-and-columns@1.2.4: resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} @@ -10710,6 +11224,9 @@ packages: lodash.debounce@4.0.8: resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==} + lodash.groupby@4.6.0: + resolution: {integrity: sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==} + lodash.merge@4.6.2: resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} @@ -10778,12 +11295,15 @@ packages: magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + magic-string@1.3.1: + resolution: {integrity: sha512-rm91zr2Ou+XueDTohjQQjdQEcYM6zVi8KVUCG8Ec3vHwUEKrhSdCNyfuIywkA6hcCAteIn0ZOtAHA6eGpiX+Pg==} + + magicast@0.5.4: + resolution: {integrity: sha512-llBEhWm1SacoRwgHUoQJYtwp4PBLF4faQi5TCpIGyGs9n4y5+juI0tDgyKIfpqxckRHaHzouUEph3THklWh03w==} + main-event@1.0.4: resolution: {integrity: sha512-sKazUjIy2Jalv5lkQ446iOcrx8Q7TkaCuk6xfnzg5uUqMusMLDMPmRDmSNE2kjSVpSTJo4j1bQZusS+Ib7Bvrg==} - make-error@1.3.6: - resolution: {integrity: sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==} - makeerror@1.0.12: resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==} @@ -10995,9 +11515,6 @@ packages: mixpanel-browser@2.67.0: resolution: {integrity: sha512-LudY4eRIkvjEpAlIAg10i2T2mbtiKZ4XlMGbTyF1kcAhEqMa9JhEEdEcjxYPwiKhuMVSBM3RVkNCZaNqcnE4ww==} - mkdirp-classic@0.5.3: - resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} - mkdirp@1.0.4: resolution: {integrity: sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==} engines: {node: '>=10'} @@ -11009,19 +11526,9 @@ packages: mockdate@3.0.5: resolution: {integrity: sha512-iniQP4rj1FhBdBYS/+eQv7j1tadJ9lJtdzgOpvsOHng/GbcDh2Fhdeq+ZRldrPYdXvCyfFUmFeEwEGXZB5I/AQ==} - module-definition@5.0.1: - resolution: {integrity: sha512-kvw3B4G19IXk+BOXnYq/D/VeO9qfHaapMeuS7w7sNUqmGaA6hywdFHMi+VWeR9wUScXM7XjoryTffCZ5B0/8IA==} - engines: {node: '>=14'} - hasBin: true - module-details-from-path@1.0.4: resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==} - module-lookup-amd@8.0.5: - resolution: {integrity: sha512-vc3rYLjDo5Frjox8NZpiyLXsNWJ5BWshztc/5KSOMzpg9k5cHH652YsJ7VKKmtM4SvaxuE9RkrYGhiSjH3Ehow==} - engines: {node: '>=14'} - hasBin: true - monaco-editor@0.52.2: resolution: {integrity: sha512-GEQWEZmfkOGLdd3XK8ryrfWz3AIP8YymVXiPHEdewrUq7mh0qrKrfHLNCXcbB6sTnMLnOZ3ztSiKcciFUkIJwQ==} @@ -11061,12 +11568,29 @@ packages: multiformats@13.4.2: resolution: {integrity: sha512-eh6eHCrRi1+POZ3dA+Dq1C6jhP1GNtr9CRINMb67OKzqW9I5DUuZM/3jLPlzhgpGeiNUlEGEbkCYChXMCc/8DQ==} - multiformats@14.0.0: - resolution: {integrity: sha512-iWK1RrAS58p2NDfeZFuSUSv3ZPewTIhsGbh/5NgeGGJwJmRljLxGtjRR3nkn+loG3zl+IrfR/W1590QnrSK+Gg==} + multiformats@14.0.5: + resolution: {integrity: sha512-vbIm83F2yZ1pWJGS0yl0ysracIvv56LtbrIyiIQHoLdYDJOMoLfVFsXhh9DUH4SFdkdkFhucyWniihsNzVEjkQ==} multiformats@9.9.0: resolution: {integrity: sha512-HoMUjhH9T8DDBNT+6xzkrd9ga/XiBI4xLr58LJACwK6G3HTOPeMz4nB4KJs33L2BelrIJa7P0VuNaVF3hMYfjg==} + mutation-server-protocol@0.4.1: + resolution: {integrity: sha512-SBGK0j8hLDne7bktgThKI8kGvGTx3rY3LAeQTmOKZ5bVnL/7TorLMvcVF7dIPJCu5RNUWhkkuF53kurygYVt3g==} + engines: {node: '>=18'} + + mutation-testing-elements@3.8.4: + resolution: {integrity: sha512-5CF1SNa7at5ZH33vEr+21wNebTSrtNIVvnzaUlxortHajOrIPaSLczIWvg6sI/fsExekQ7jookwf2cHftkckqQ==} + + mutation-testing-metrics@3.8.4: + resolution: {integrity: sha512-DZcmndJBH6nrNs3tpiB3OcMVq9KkG2cHCpJSnDxSxPwi9qrafRmoec40xjhkbzOoX1n7/4UkDqg5tIj4A6nvCw==} + + mutation-testing-report-schema@3.8.4: + resolution: {integrity: sha512-s4G71R6Lt/PpZ0cqeglIcgyBdzLM8E+SeCHZAPg1wkSsPtRBa4XfPzAozYKdiJk/TLbNEEb7En9t0/bveuPuxA==} + + mute-stream@3.0.0: + resolution: {integrity: sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==} + engines: {node: ^20.17.0 || >=22.9.0} + nanoclone@0.2.1: resolution: {integrity: sha512-wynEP02LmIbLpcYw8uBKpcfF6dmg2vcpKqxeH5UcoKEYdExslsdUA4ugFauuaeYdTB76ez6gJW8XAZ6CgkXYxA==} @@ -11075,8 +11599,8 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true - nanoid@3.3.18: - resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==} + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true @@ -11085,8 +11609,10 @@ packages: engines: {node: ^18 || >=20} hasBin: true - napi-build-utils@2.0.0: - resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==} + nanoid@6.0.2: + resolution: {integrity: sha512-hIvVOb9Qr1p/9CNNLOe0OlWvgx/ziTsVwKN/GDSsuArN2K0wDiafP3s0SWmsm7o2BdnyS8Z9Z64NFBUbn6ziBg==} + engines: {node: ^22 || ^24 || >=26} + hasBin: true napi-postinstall@0.3.4: resolution: {integrity: sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==} @@ -11127,29 +11653,8 @@ packages: react: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc react-dom: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc - next@16.2.6: - resolution: {integrity: sha512-qOVgKJg1+At15NpeUP+eJgCHvTCgXsogweq87Ri/Ix7PkqQHg4sdaXmSFqKlgaIXE4kW0g25LE68W87UANlHtw==} - engines: {node: '>=20.9.0'} - hasBin: true - peerDependencies: - '@opentelemetry/api': ^1.1.0 - '@playwright/test': ^1.51.1 - babel-plugin-react-compiler: '*' - react: ^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0 - react-dom: ^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0 - sass: ^1.3.0 - peerDependenciesMeta: - '@opentelemetry/api': - optional: true - '@playwright/test': - optional: true - babel-plugin-react-compiler: - optional: true - sass: - optional: true - - next@16.3.1: - resolution: {integrity: sha512-hsAp0i7Rh+/dhe7DGIeN2YlpLM1DP4MNxti9EtDMtqcO612X81MvvEj388/oTce9U1EcEIOWDlGq0zRwrBKvuA==} + next@16.4.3: + resolution: {integrity: sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==} engines: {node: '>=20.9.0'} hasBin: true peerDependencies: @@ -11178,10 +11683,6 @@ packages: no-case@3.0.4: resolution: {integrity: sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==} - node-abi@3.92.0: - resolution: {integrity: sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==} - engines: {node: '>=10'} - node-abort-controller@3.1.1: resolution: {integrity: sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==} @@ -11192,6 +11693,10 @@ packages: resolution: {integrity: sha512-c5Ko1fZJIJmzhFIkhRN76WTq+fC6tWnGy9CXA0fA+XygsWZmEwG8vmbkNqxMyoaa0Tin4djul49NzdVcJJcjeA==} engines: {node: ^18 || ^20 || >= 21} + node-datachannel@0.33.4: + resolution: {integrity: sha512-qiUrdh8vY9XhglEnx91HK0N2JEAAu8qTZl0fcR3yQd0fFrdO39NwDeJD/KpG+WKUb9/o4p2UwnP+/HftA/xMbQ==} + engines: {node: '>=18.20.0'} + node-domexception@1.0.0: resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==} engines: {node: '>=10.5.0'} @@ -11238,10 +11743,6 @@ packages: resolution: {integrity: sha512-GYVXHE2KnrzAfsAjl4uP++evGFCrAU1jta4ubEjIG7YWt/64Gqv66a30yKwWczVjA6j3bM4nBwH7Pk1JmDHaxQ==} engines: {node: '>=18'} - node-source-walk@6.0.2: - resolution: {integrity: sha512-jn9vOIK/nfqoFCcpK89/VCVaLg1IHE6UVfDOzvqmANaJ/rWCTEdH8RZ1V278nv2jr36BJdyQXIAavBLXpzdlag==} - engines: {node: '>=14'} - normalize-path@3.0.0: resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} engines: {node: '>=0.10.0'} @@ -11254,6 +11755,10 @@ packages: resolution: {integrity: sha512-JYc0DPlpGWB40kH5g07gGTrYuMqV653k3uBKY6uITPWds3M0ov3GaWGp9lbE3Bzngx8+XkfzgvASb9vk9JDFXQ==} engines: {node: '>=14.16'} + npm-run-path@6.0.0: + resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==} + engines: {node: '>=18'} + nth-check@2.1.1: resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==} @@ -11307,8 +11812,9 @@ packages: resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==} engines: {node: '>= 0.4'} - obug@2.1.1: - resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} ofetch@1.5.1: resolution: {integrity: sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==} @@ -11437,9 +11943,9 @@ packages: resolution: {integrity: sha512-Mr5KC5efvAK5VUptYEIopP1bakB85k2IWXaRC0rsh1uwn1L6M0LVml8OIQ4Gudg4oyZakf7FmeRLkMMtZW1i5A==} engines: {node: '>=12'} - p-event@6.0.1: - resolution: {integrity: sha512-Q6Bekk5wpzW5qIyUP4gdMEujObYstZl6DMMOSenwBvV0BlE5LkDwkjs5yHbZmdCEq2o4RJx4tE1vwxFVf2FG1w==} - engines: {node: '>=16.17'} + p-event@7.1.1: + resolution: {integrity: sha512-T629EpxCTho6yxIZz2dFZwMkyWUM5jh/0h1+u/Xo4+Fllu0DuKQF6ghqIgSWVTluIvHSXL+XBRScH+E+y9TQ0g==} + engines: {node: '>=20'} p-limit@2.3.0: resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} @@ -11457,21 +11963,13 @@ packages: resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} engines: {node: '>=10'} - p-queue@8.1.1: - resolution: {integrity: sha512-aNZ+VfjobsWryoiPnEApGGmf5WmNsCo9xu8dfaYamG5qaLP7ClhLN6NgsFe6SwJ2UbLEBK5dv9x8Mn5+RVhMWQ==} - engines: {node: '>=18'} - p-queue@9.3.0: resolution: {integrity: sha512-7NED7xhQ74Ngp4JP/2e0VZHp7vSWfJfqeiR92jPgxsz6m0Se4P03YoTKa9dDXyZ3r6P616gUXttrB6nnHYKang==} engines: {node: '>=20'} - p-retry@6.2.1: - resolution: {integrity: sha512-hEt02O4hUct5wtwg4H4KcWgDdm+l1bOaEy/hWzd8xtXB9BqxTWBBhb+2ImAtH4Cv4rPjV76xN3Zumqk3k3AhhQ==} - engines: {node: '>=16.17'} - - p-timeout@6.1.4: - resolution: {integrity: sha512-MyIV3ZA/PmyBN/ud8vV9XzwTrNtR4jFrObymZYnZqMmW0zA8Z17vnT0rBgFE/TlohB+YCHqXMgZzb3Csp49vqg==} - engines: {node: '>=14.16'} + p-retry@8.0.1: + resolution: {integrity: sha512-NAigyu8hfvJe7MsS18mnc4is0MZtau3QMdBklaJKK23oBQb6occO3UPM3vHmTckW8KhfyjMZaUOqdTFEYliHgg==} + engines: {node: '>=22'} p-timeout@7.0.1: resolution: {integrity: sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg==} @@ -11481,9 +11979,9 @@ packages: resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} engines: {node: '>=6'} - p-wait-for@5.0.2: - resolution: {integrity: sha512-lwx6u1CotQYPVju77R+D0vFomni/AqRfqLmqQ8hekklqZ6gAY9rONh7lBQ0uxWMkC2AuX9b2DVAl8To0NyP1JA==} - engines: {node: '>=12'} + p-wait-for@6.0.0: + resolution: {integrity: sha512-2kKzMtjS8TVcpCOU/gr3vZ4K/WIyS1AsEFXFWapM/0lERCdyTbB6ZeuCIp+cL1aeLZfQoMdZFCBTHiK4I9UtOw==} + engines: {node: '>=20'} package-json-from-dist@1.0.1: resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} @@ -11512,6 +12010,10 @@ packages: resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==} engines: {node: '>=8'} + parse-ms@4.0.0: + resolution: {integrity: sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==} + engines: {node: '>=18'} + parse5@8.0.1: resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==} @@ -11526,14 +12028,14 @@ packages: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} - path-is-absolute@1.0.1: - resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} - engines: {node: '>=0.10.0'} - path-key@3.1.1: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} + path-key@4.0.0: + resolution: {integrity: sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==} + engines: {node: '>=12'} + path-parse@1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} @@ -11579,6 +12081,10 @@ packages: resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} engines: {node: '>=12'} + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + pify@3.0.0: resolution: {integrity: sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==} engines: {node: '>=4'} @@ -11634,14 +12140,14 @@ packages: pkg-types@2.3.1: resolution: {integrity: sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg==} - playwright-core@1.57.0: - resolution: {integrity: sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ==} - engines: {node: '>=18'} + playwright-core@1.62.1: + resolution: {integrity: sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==} + engines: {node: '>=20'} hasBin: true - playwright@1.57.0: - resolution: {integrity: sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw==} - engines: {node: '>=18'} + playwright@1.62.1: + resolution: {integrity: sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==} + engines: {node: '>=20'} hasBin: true pngjs@5.0.0: @@ -11722,16 +12228,6 @@ packages: postcss-value-parser@4.2.0: resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==} - postcss-values-parser@6.0.2: - resolution: {integrity: sha512-YLJpK0N1brcNJrs9WatuJFtHaV9q5aAOj+S4DI5S7jgHlRfm0PIbDCAFRYMQD5SHq7Fy6xsDhyutgS0QOAs0qw==} - engines: {node: '>=10'} - peerDependencies: - postcss: ^8.2.9 - - postcss@8.4.31: - resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==} - engines: {node: ^10 || ^12 || >=14} - postcss@8.5.15: resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==} engines: {node: ^10 || ^12 || >=14} @@ -11740,6 +12236,10 @@ packages: resolution: {integrity: sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==} engines: {node: ^10 || ^12 || >=14} + postcss@8.5.31: + resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==} + engines: {node: ^10 || ^12 || >=14} + postgres-array@2.0.0: resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==} engines: {node: '>=4'} @@ -11756,8 +12256,16 @@ packages: resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==} engines: {node: '>=0.10.0'} - posthog-js@1.376.2: - resolution: {integrity: sha512-Anz2pCp7dcNbammTExiZpcKC08dxfrHYaJgaXH6rq5x3Zcfj/4FkcMJF2cGCrdQXel5Y4vftiVSseZda0HAQTQ==} + posthog-js@1.434.15: + resolution: {integrity: sha512-ZfBkNrQiFr1Q43G3dR0USzTRdfx+6gKPebyoWDmKnLUhG3yRgYjLH914J6ifEDRnH+RaGOx7rsWKxKcvaSJXHg==} + peerDependencies: + '@types/react': '>=16.8.0' + react: '>=16.8.0' + peerDependenciesMeta: + '@types/react': + optional: true + react: + optional: true preact@10.24.2: resolution: {integrity: sha512-1cSoF0aCC8uaARATfrlz4VCBqE8LwZwRfLgkxJOQwAlQt6ayTmi0D9OF7nXid1POI5SZidFuG9CnlXbDfLqY/Q==} @@ -11765,16 +12273,13 @@ packages: preact@10.29.2: resolution: {integrity: sha512-7tNmwg/7mzzAoB/8kSg6Hl37JraAZw3Z3A0JSY7VXlZwo82Xn0G7wKbNNs2qoF4ZEEsQGTwDAroNdqKs1ofJxQ==} - prebuild-install@7.1.3: - resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==} - engines: {node: '>=10'} - deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available. - hasBin: true - - precinct@11.0.5: - resolution: {integrity: sha512-oHSWLC8cL/0znFhvln26D14KfCQFFn4KOLSw6hmLhd+LQ2SKt9Ljm89but76Pc7flM9Ty1TnXyrA2u16MfRV3w==} - engines: {node: ^14.14.0 || >=16.0.0} - hasBin: true + preact@10.29.8: + resolution: {integrity: sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==} + peerDependencies: + preact-render-to-string: '>=5' + peerDependenciesMeta: + preact-render-to-string: + optional: true prelude-ls@1.2.1: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} @@ -11793,6 +12298,10 @@ packages: resolution: {integrity: sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + pretty-ms@9.3.0: + resolution: {integrity: sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ==} + engines: {node: '>=18'} + prismjs@1.30.0: resolution: {integrity: sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==} engines: {node: '>=6'} @@ -11820,9 +12329,14 @@ packages: progress-events@1.1.0: resolution: {integrity: sha512-82DVc5tI36neVB3IjdXR11ztwGuoBc98em9ijzubeZKxI47OlV2Znq6mlPqE5xPDzO2Uw98GHiQSjj2favBCRQ==} + progress@2.0.3: + resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==} + engines: {node: '>=0.4.0'} + prom-client@15.1.1: resolution: {integrity: sha512-GVA2H96QCg2q71rjc3VYvSrVG7OpnJxyryC7dMzvfJfpJJHzQVwF3TJLfHzKORcwJpElWs1TwXLthlJAFJxq2A==} engines: {node: ^16 || ^18 || >=20} + deprecated: prom-client has been replaced by @prometheus-io/client promise@8.3.0: resolution: {integrity: sha512-rZPNPKTOYVNEEKFaq1HqTgOwZD+4/YHS5ukLzQCypkj+OkYx7iv0mA91lJlpPPZ8vMau3IIGj5Qlwrx+8iiSmg==} @@ -11840,12 +12354,15 @@ packages: resolution: {integrity: sha512-3wY1AxV+VBNW8Yypfd1yQY9pXnqTAN+KwQxL8iYm3/BjKYMNg4i0owhEe26PWDOMaIrzeeF98Lqd5NGz4omiIg==} engines: {node: '>=12.0.0'} - protons-runtime@5.6.0: - resolution: {integrity: sha512-/Kde+sB9DsMFrddJT/UZWe6XqvL7SL5dbag/DBCElFKhkwDj7XKt53S+mzLyaDP5OqS0wXjV5SA572uWDaT0Hg==} - protons-runtime@6.0.2: resolution: {integrity: sha512-hiyjyANwGcgmzc+tXc1/ZcSZhKnl5MDjaVNWkISHBgadaU0sjTgKIKZMZ62d9J9zlSTyKHCs/osPkQ/3Z+7yeA==} + protons-runtime@7.1.2: + resolution: {integrity: sha512-j7Y7MfCwPCxYwopyqDt8+CoJULzdajSBrFAzzfBHEhOTfdvOJ2z1QLK9aK34bSBz6V/9JAAlrsc/rFkIbqppuw==} + + protons-runtime@8.0.1: + resolution: {integrity: sha512-du8V7RuI8QLmRVXJWmZKc2xRngbbeedtP5Hf6+m1YKRKLMyld+ITIkqXyocyBpkzUUkeh/l6mN3zcP2z5RsT9Q==} + proxy-compare@2.6.0: resolution: {integrity: sha512-8xuCeM3l8yqdmbPoYeLbrAXCBWu19XEYc5/F28f5qOaoAIMyfmBUkl5axiK+x9olUvRlcekvnm98AP9RDngOIw==} @@ -11901,6 +12418,10 @@ packages: engines: {node: '>=10.13.0'} hasBin: true + qs@6.15.1: + resolution: {integrity: sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==} + engines: {node: '>=0.6'} + quansync@0.2.11: resolution: {integrity: sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==} @@ -11932,8 +12453,9 @@ packages: resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==} engines: {node: '>=10'} - quote-unquote@1.0.0: - resolution: {integrity: sha512-twwRO/ilhlG/FIgYeKGFqyHhoEhqgnKVkcmqMKi2r524gz3ZbDTcyFt38E9xjJI2vT+KbRNHVbnJ/e0I25Azwg==} + quick-lru@7.3.0: + resolution: {integrity: sha512-k9lSsjl36EJdK7I06v7APZCbyGT2vMTsYSRX1Q2nbYmnkBqgUhRkAuzH08Ciotteu/PLJmIF2+tti7o3C/ts2g==} + engines: {node: '>=18'} rabin-wasm@0.1.5: resolution: {integrity: sha512-uWgQTo7pim1Rnj5TuWcCewRDTf0PEFTSlaUjWP4eY9EbLV9em08v89oCz/WO+wRxpYuO36XEHp4wgYQnAgOHzA==} @@ -11942,12 +12464,12 @@ packages: race-event@1.6.1: resolution: {integrity: sha512-vi7WH5g5KoTFpu2mme/HqZiWH14XSOtg5rfp6raBskBHl7wnmy3F/biAIyY5MsK+BHWhoPhxtZ1Y2R7OHHaWyQ==} - race-signal@1.1.3: - resolution: {integrity: sha512-Mt2NznMgepLfORijhQMncE26IhkmjEphig+/1fKC0OtaKwys/gpvpmswSjoN01SS+VO951mj0L4VIDXdXsjnfA==} - race-signal@2.0.0: resolution: {integrity: sha512-P31bLhE4ByBX/70QDXMutxnqgwrF1WUXea1O8DXuviAgkdbQ1iQMQotNgzJIBC9yUSn08u/acZrMUhgw7w6GpA==} + race-signal@2.0.2: + resolution: {integrity: sha512-IuNNNY5NLriMFEGl3BVei2xq9NIcpkuAklhPWamhu5tRJrJz0w9sloUMz73YXpmUluE2EZocmJm9rpQqXmCPiA==} + radix3@1.1.2: resolution: {integrity: sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==} @@ -11964,6 +12486,10 @@ packages: resolution: {integrity: sha512-U+5l2KrcMNOUPYvazA3h5ekF80FHTUG+87SEAmHZmolh1M+i/WyTCxVzmi+tidIa1tM4BSe8g2Y/D3loWDjj+w==} engines: {node: '>=4'} + random-int@3.1.0: + resolution: {integrity: sha512-h8CRz8cpvzj0hC/iH/1Gapgcl2TQ6xtnCpyOI5WvWfXf/yrDx2DOU+tD9rX23j36IF11xg1KqB9W11Z18JPMdw==} + engines: {node: '>=12'} + randombytes@2.1.0: resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==} @@ -12283,6 +12809,10 @@ packages: resolution: {integrity: sha512-sZuz1dYW/ZsfG17WSAG7eS85r5a0dDsvg+7BiiYR5o6lKCAtUrEwdmRmaGF6rwVj3LcmAeYkOWKEPlbPzN3Y3A==} engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + regexp.escape@2.0.1: + resolution: {integrity: sha512-JItRb4rmyTzmERBkAf6J87LjDPy/RscIwmaJQ3gsFlAzrmZbZU8LwBw5IydFZXW9hqpgbPlGbMhtpqtuAhMgtg==} + engines: {node: '>= 0.4'} + regexp.prototype.flags@1.5.4: resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==} engines: {node: '>= 0.4'} @@ -12325,15 +12855,6 @@ packages: require-main-filename@2.0.0: resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==} - requirejs-config-file@4.0.0: - resolution: {integrity: sha512-jnIre8cbWOyvr8a5F2KuqBnY+SDA4NXr/hzEZJG79Mxm2WiFQz2dzhC8ibtPJS7zkmBEl1mxSwp5HhC1W4qpxw==} - engines: {node: '>=10.13.0'} - - requirejs@2.3.8: - resolution: {integrity: sha512-7/cTSLOdYkNBNJcDMWf+luFvMriVm7eYxp4BcFCsAX0wF421Vyce5SXP17c+Jd5otXKGNehIonFlyQXSowL6Mw==} - engines: {node: '>=0.4.0'} - hasBin: true - requires-port@1.0.0: resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==} @@ -12343,10 +12864,6 @@ packages: resolve-alpn@1.2.1: resolution: {integrity: sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==} - resolve-dependency-path@3.0.2: - resolution: {integrity: sha512-Tz7zfjhLfsvR39ADOSk9us4421J/1ztVBo4rWUkF38hgHK5m0OCZ3NxFVpqHRkjctnwVa15igEUHFJp8MCS7vA==} - engines: {node: '>=14'} - resolve-from@4.0.0: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} engines: {node: '>=4'} @@ -12386,10 +12903,6 @@ packages: retimeable-signal@1.0.1: resolution: {integrity: sha512-Cy26CYfbWnYu8HMoJeDhaMpW/EYFIbne3vMf6G9RSrOyWYXbPehja/BEdzpqmM84uy2bfBD7NPZhoQ4GZEtgvg==} - retry@0.13.1: - resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==} - engines: {node: '>= 4'} - reusify@1.1.0: resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} engines: {iojs: '>=1.0.0', node: '>=0.10.0'} @@ -12407,6 +12920,11 @@ packages: rollbar@2.26.5: resolution: {integrity: sha512-4Of0ALl5+CU2glyDy5dWMRRy9Ty81DrY2r46ucbqjtCikbgHoWJNGXbQUWpDaLxsc8Q71LT/yj1bPb9NHbJIFQ==} + rolldown@1.2.15: + resolution: {integrity: sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + rollup@4.60.4: resolution: {integrity: sha512-WHeFSbZYsPu3+bLoNRUuAO+wavNlocOPf3wSHTP7hcFKVnJeWsYlCDbr3mTS14FCizf9ccIxXA8sGL8zKeQN3g==} engines: {node: '>=18.0.0', npm: '>=8.0.0'} @@ -12430,6 +12948,9 @@ packages: rw@1.3.3: resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==} + rxjs@7.8.2: + resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==} + safe-array-concat@1.1.4: resolution: {integrity: sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==} engines: {node: '>=0.4'} @@ -12458,11 +12979,6 @@ packages: sanitize-filename@1.6.4: resolution: {integrity: sha512-9ZyI08PsvdQl2r/bBIGubpVdR3RR9sY6RDiWFPreA21C/EFlQhmgo20UZlNjZMMZNubusLhAQozkA0Od5J21Eg==} - sass-lookup@5.0.1: - resolution: {integrity: sha512-t0X5PaizPc2H4+rCwszAqHZRtr4bugo4pgiCvrBFvIX0XFxnr29g77LJcpyj9A0DcKf7gXMLcgvRjsonYI6x4g==} - engines: {node: '>=14'} - hasBin: true - sax@1.6.0: resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==} engines: {node: '>=11.0.0'} @@ -12519,11 +13035,6 @@ packages: engines: {node: '>=10'} hasBin: true - semver@7.8.4: - resolution: {integrity: sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==} - engines: {node: '>=10'} - hasBin: true - semver@7.8.5: resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} engines: {node: '>=10'} @@ -12579,12 +13090,8 @@ packages: resolution: {integrity: sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - sharp@0.34.5: - resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - - sharp@0.35.3: - resolution: {integrity: sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==} + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} engines: {node: '>=20.9.0'} peerDependencies: '@types/node': '*' @@ -12631,12 +13138,6 @@ packages: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} - simple-concat@1.0.1: - resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==} - - simple-get@4.0.1: - resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==} - simple-swizzle@0.2.4: resolution: {integrity: sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==} @@ -12694,6 +13195,10 @@ packages: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + source-map-support@0.5.21: resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} @@ -12705,6 +13210,10 @@ packages: resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} engines: {node: '>=0.10.0'} + source-map@0.7.6: + resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} + engines: {node: '>= 12'} + space-separated-tokens@2.0.2: resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==} @@ -12750,8 +13259,8 @@ packages: resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} engines: {node: '>= 0.8'} - std-env@4.1.0: - resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} + std-env@4.2.0: + resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==} stop-iteration-iterator@1.1.0: resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==} @@ -12766,9 +13275,6 @@ packages: stream-shift@1.0.3: resolution: {integrity: sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==} - stream-to-it@1.0.1: - resolution: {integrity: sha512-AqHYAYPHcmvMrcLNgncE/q0Aj/ajP6A4qGhxP6EVn7K3YTNs0bJpJyk57wc2Heb7MUL64jurvmnmui8D9kjZgA==} - strict-uri-encode@2.0.0: resolution: {integrity: sha512-QwiXZgpRcKkhTj2Scnn++4PKtWsH0kpzZ62L2R6c/LUVYv7hVnZqcg2+sMuT6R7Jusu1vviK/MFsu6kNJfWlEQ==} engines: {node: '>=4'} @@ -12783,6 +13289,9 @@ packages: string-template@0.2.1: resolution: {integrity: sha512-Yptehjogou2xm4UJbxJ4CxgZx12HBfeystp0y3x7s4Dj32ltVVG1Gg8YhKjHZkHicuKpZX/ffilA8505VbUbpw==} + string-ts@2.3.1: + resolution: {integrity: sha512-xSJq+BS52SaFFAVxuStmx6n5aYZU571uYUnUrPXkPFCfdHyZMMlbP2v2Wx5sNBnAVzq/2+0+mcBLBa3Xa5ubYw==} + string-width@4.2.3: resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} engines: {node: '>=8'} @@ -12828,10 +13337,6 @@ packages: string_decoder@1.3.0: resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} - stringify-object@3.3.0: - resolution: {integrity: sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==} - engines: {node: '>=4'} - strip-ansi@6.0.1: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} @@ -12844,6 +13349,10 @@ packages: resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} engines: {node: '>=4'} + strip-final-newline@4.0.0: + resolution: {integrity: sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==} + engines: {node: '>=18'} + strip-hex-prefix@1.0.0: resolution: {integrity: sha512-q8d4ue7JGEiVcypji1bALTos+0pWtyGlivAWyPuTkHzuTCJqrK9sWxYQZUq6Nq3cuyv3bm734IhHvHtGGURU6A==} engines: {node: '>=6.5.0', npm: '>=3'} @@ -12885,11 +13394,6 @@ packages: stylis@4.2.0: resolution: {integrity: sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw==} - stylus-lookup@5.0.1: - resolution: {integrity: sha512-tLtJEd5AGvnVy4f9UHQMw4bkJJtaAcmo54N+ovQBjDY3DuWyK9Eltxzr5+KG0q4ew6v2EHyuWWNnHeiw/Eo7rQ==} - engines: {node: '>=14'} - hasBin: true - super-regex@0.2.0: resolution: {integrity: sha512-WZzIx3rC1CvbMDloLsVw0lkZVKJWbrkJ0k1ghKFmcnPrW1+jWbgTkTEWVtD9lMdmI4jZEz40+naBxl1dCUhXXw==} engines: {node: '>=14.16'} @@ -12962,13 +13466,6 @@ packages: resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==} engines: {node: '>=6'} - tar-fs@2.1.4: - resolution: {integrity: sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==} - - tar-stream@2.2.0: - resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==} - engines: {node: '>=6'} - tdigest@0.1.2: resolution: {integrity: sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==} @@ -13058,9 +13555,6 @@ packages: resolution: {integrity: sha512-4oGOVZWTu5sl89PtCDnhQBSt7/vL1zVEwAfxH1p49JhTosxzVQWYBYFRFZ8nJmo0G6f824iyP/44BFAwIoKvIA==} engines: {node: '>= 4.5.0'} - tiny-case@1.0.3: - resolution: {integrity: sha512-Eet/eeMhkO6TX8mnUteS9zgPbUMQa4I6Kkp5ORiBD5476/m+PIRiumP5tmh5ioJpH7k51Kehawy2UDfsnxxY8Q==} - tiny-invariant@1.3.3: resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} @@ -13070,13 +13564,18 @@ packages: tiny-warning@1.0.3: resolution: {integrity: sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA==} - tinybench@2.9.0: - resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + tinybench@6.1.4: + resolution: {integrity: sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ==} + engines: {node: '>=20.0.0'} tinyexec@1.2.2: resolution: {integrity: sha512-M/Q0B2cp4K7kynaT/vnED1j8TlLY+Pp7C6Wl2bl/7u/F0mUVwdyOpwomQb8JpYLitHUssAJRmLZdMCGsrx7i+g==} engines: {node: '>=18'} + tinyexec@1.3.0: + resolution: {integrity: sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==} + engines: {node: '>=18'} + tinyglobby@0.2.16: resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} engines: {node: '>=12.0.0'} @@ -13085,8 +13584,8 @@ packages: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} - tinyrainbow@3.1.0: - resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} + tinyrainbow@3.1.1: + resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} engines: {node: '>=14.0.0'} tldts-core@6.1.86: @@ -13099,10 +13598,6 @@ packages: resolution: {integrity: sha512-TkEq38COU640mzOKPk4D1oH3FFVvwEtMaKIfw/+F/umVsy7ONWu8PPQH0c11qJ/Jq/zbcQGprXGsT8GcaDSmJg==} hasBin: true - tldts@6.1.86: - resolution: {integrity: sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==} - hasBin: true - tldts@7.4.0: resolution: {integrity: sha512-yHBe+zVfzNZ3QfTPW/Z6KK1G2t340gFjMHqI/4KKSt/abzYydzuCnpqdaF5gCCABby+9Yfbj59oR5F2Fd5CBzg==} hasBin: true @@ -13139,10 +13634,6 @@ packages: resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==} engines: {node: '>=6'} - tough-cookie@5.1.2: - resolution: {integrity: sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==} - engines: {node: '>=16'} - tough-cookie@6.0.1: resolution: {integrity: sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==} engines: {node: '>=16'} @@ -13154,6 +13645,10 @@ packages: resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==} engines: {node: '>=20'} + tree-kill@1.2.2: + resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} + hasBin: true + tree-sitter-json@0.24.8: resolution: {integrity: sha512-Tc9ZZYwHyWZ3Tt1VEw7Pa2scu1YO7/d2BCBbKTx5hXwig3UfdQjsOPkPyLpDJOn/m1UBEWYAtSdGAwCSyagBqQ==} peerDependencies: @@ -13190,41 +13685,15 @@ packages: ts-mixer@6.0.4: resolution: {integrity: sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==} - ts-node@10.9.2: - resolution: {integrity: sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==} - hasBin: true - peerDependencies: - '@swc/core': '>=1.2.50' - '@swc/wasm': '>=1.2.50' - '@types/node': '*' - typescript: '>=2.7' - peerDependenciesMeta: - '@swc/core': - optional: true - '@swc/wasm': - optional: true + ts-pattern@5.9.0: + resolution: {integrity: sha512-6s5V71mX8qBUmlgbrfL33xDUwO0fq48rxAu2LBE11WBeGdpCPOsXksQbZJHvHwhrd3QjUusd3mAOM5Gg0mFBLg==} ts-toolbelt@9.6.0: resolution: {integrity: sha512-nsZd8ZeNUzukXPlJmTBwUAuABDe/9qtVDelJeT/qW0ow3ZS3BsQJtNkan1802aM9Uf68/Y8ljw86Hu0h5IUW3w==} - tsconfck@3.1.6: - resolution: {integrity: sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w==} - engines: {node: ^18 || >=20} - deprecated: unmaintained - hasBin: true - peerDependencies: - typescript: ^5.0.0 - peerDependenciesMeta: - typescript: - optional: true - tsconfig-paths@3.15.0: resolution: {integrity: sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==} - tsconfig-paths@4.2.0: - resolution: {integrity: sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==} - engines: {node: '>=6'} - tslib@1.14.1: resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==} @@ -13244,8 +13713,9 @@ packages: resolution: {integrity: sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==} engines: {node: '>= 6.0.0'} - tunnel-agent@0.6.0: - resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==} + tunnel@0.0.6: + resolution: {integrity: sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==} + engines: {node: '>=0.6.11 <=0.7.0 || >=0.7.3'} type-check@0.4.0: resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} @@ -13259,10 +13729,6 @@ packages: resolution: {integrity: sha512-Ne2YiiGN8bmrmJJEuTWTLJR32nh/JdL1+PSicowtNb0WFpn59GK8/lfD61bVtzguz7b3PBt74nxpv/Pw5po5Rg==} engines: {node: '>=8'} - type-fest@2.19.0: - resolution: {integrity: sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==} - engines: {node: '>=12.20'} - type-fest@4.41.0: resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==} engines: {node: '>=16'} @@ -13283,6 +13749,14 @@ packages: resolution: {integrity: sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==} engines: {node: '>= 0.4'} + typed-inject@5.0.0: + resolution: {integrity: sha512-0Ql2ORqBORLMdAW89TQKZsb1PQkFGImFfVmncXWe7a+AA3+7dh7Se9exxZowH4kbnlvKEFkMxUYdHUpjYWFJaA==} + engines: {node: '>=18'} + + typed-rest-client@2.3.1: + resolution: {integrity: sha512-k4kX5Up6qA68D0Cby2AK+6+vM5k3qTxe+/3FqhnHRExjY5cfbOnzjQZbP/LXleF8hVoDvDqxlgk9KK83HoBZlQ==} + engines: {node: '>= 16.0.0'} + types-ramda@0.30.1: resolution: {integrity: sha512-1HTsf5/QVRmLzcGfldPFvkVsAdi1db1BBKzi7iW3KBUlOICg/nKnFS+jGqDJS3YD8VsWbAh7JiHeBvbsw8RPxA==} @@ -13362,11 +13836,11 @@ packages: uncrypto@0.1.3: resolution: {integrity: sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==} - undici-types@6.19.8: - resolution: {integrity: sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==} + underscore@1.13.8: + resolution: {integrity: sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==} - undici-types@6.20.0: - resolution: {integrity: sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==} + undici-types@7.18.2: + resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==} undici-types@7.24.6: resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} @@ -13374,14 +13848,14 @@ packages: undici-types@7.26.0: resolution: {integrity: sha512-OY7qWYg4TsPpqg/kL2FfNnGA8cmAhPpLt45XQ2jd8p9UobYQ7Q09LeiCq5QwZhlKNLBj0iTUlBNhs4M2AVFmxA==} - undici@6.26.0: - resolution: {integrity: sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A==} - engines: {node: '>=18.17'} - undici@7.28.0: resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==} engines: {node: '>=20.18.1'} + undici@8.11.2: + resolution: {integrity: sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==} + engines: {node: '>=22.19.0'} + unicode-canonical-property-names-ecmascript@2.0.1: resolution: {integrity: sha512-dA8WbNeb2a6oQzAQ55YlT5vQAWGV9WXOsi3SskE3bcCdM0P4SDd+24zS/OCacdRq5BkdsRj9q3Pg6YyQoxIGqg==} engines: {node: '>=4'} @@ -13398,6 +13872,10 @@ packages: resolution: {integrity: sha512-hpbDzxUY9BFwX+UeBnxv3Sh1q7HFxj48DTmXchNgRa46lO8uj3/1iEn3MiNUYTg1g9ctIqXCCERn8gYZhHC5lQ==} engines: {node: '>=4'} + unicorn-magic@0.3.0: + resolution: {integrity: sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==} + engines: {node: '>=18'} + unicorn-magic@0.4.0: resolution: {integrity: sha512-wH590V9VNgYH9g3lH9wWjTrUoKsjLF6sGLjhR4sH1LWpLmCOH0Zf7PukhDA8BiS7KHe4oPNkcTHqYkj7SOGUOw==} engines: {node: '>=20'} @@ -13406,6 +13884,10 @@ packages: resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} engines: {node: '>= 10.0.0'} + unlimited-timeout@0.1.0: + resolution: {integrity: sha512-D4g+mxFeQGQHzCfnvij+R35ukJ0658Zzudw7j16p4tBBbNasKkKM4SocYxqhwT5xA7a9JYWDzKkEFyMlRi5sng==} + engines: {node: '>=20'} + unpipe@1.0.0: resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==} engines: {node: '>= 0.8'} @@ -13608,9 +14090,6 @@ packages: deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028). hasBin: true - v8-compile-cache-lib@3.0.1: - resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==} - valibot@1.2.0: resolution: {integrity: sha512-mm1rxUsmOxzrwnX5arGS+U4T25RdvpPjPN4yR0u9pUBov9+zGVtO84tif1eY4r6zWxVxu3KzIyknJy3rxfRZZg==} peerDependencies: @@ -13710,49 +14189,39 @@ packages: vite: optional: true - vite-plugin-svgr@4.5.0: - resolution: {integrity: sha512-W+uoSpmVkSmNOGPSsDCWVW/DDAyv+9fap9AZXBvWiQqrboJ08j2vh0tFxTD/LjwqwAd3yYSVJgm54S/1GhbdnA==} - peerDependencies: - vite: '>=2.6.0' - vite-plugin-svgr@5.2.0: resolution: {integrity: sha512-qj2eAKF8C6PZWemVTvQA0xgQIcP1hHU6Buh7fl6BhvayWwnuxE+z417miKxeDvRWbDrupQ1oK99hfxElopJ3sQ==} peerDependencies: vite: '>=3.0.0' - vite-tsconfig-paths@5.1.4: - resolution: {integrity: sha512-cYj0LRuLV2c2sMqhqhGpaO3LretdtMn/BVX4cPLanIZuwwrkVl+lK84E/miEXkCHWXuq65rhNN4rXsBcOB3S4w==} - peerDependencies: - vite: '*' - peerDependenciesMeta: - vite: - optional: true - - vite@6.4.3: - resolution: {integrity: sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==} - engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + vite@8.3.5: + resolution: {integrity: sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==} + engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: - '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0 + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 + esbuild: ^0.27.0 || ^0.28.0 jiti: '>=1.21.0' - less: '*' - lightningcss: ^1.21.0 - sass: '*' - sass-embedded: '*' - stylus: '*' - sugarss: '*' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 terser: ^5.16.0 tsx: ^4.8.1 yaml: ^2.4.2 peerDependenciesMeta: '@types/node': optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true jiti: optional: true less: optional: true - lightningcss: - optional: true sass: optional: true sass-embedded: @@ -13774,23 +14243,23 @@ packages: peerDependencies: vitest: '>=2.0.0' - vitest@4.1.7: - resolution: {integrity: sha512-flYyaFd2CgoCoU+0UKt3pxksgC+S02iTDN0n3LtqaMeXsI9SBcdNujc2k0DeFLzUn/0k538yNjOSdwgCqcrwJA==} - engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + vitest@5.0.0: + resolution: {integrity: sha512-gpsMNoRhMjMktVxPtstOH4/PJuPyovVaMDr4oDilXaGH1EcqM2OE96SoHT2VIQ6fTGtTjqmHDrEu2X9RQiXf8Q==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} hasBin: true peerDependencies: '@edge-runtime/vm': '*' '@opentelemetry/api': ^1.9.0 - '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': 4.1.7 - '@vitest/browser-preview': 4.1.7 - '@vitest/browser-webdriverio': 4.1.7 - '@vitest/coverage-istanbul': 4.1.7 - '@vitest/coverage-v8': 4.1.7 - '@vitest/ui': 4.1.7 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.0.0 + '@vitest/browser-preview': 5.0.0 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.0.0 + '@vitest/coverage-v8': 5.0.0 + '@vitest/ui': 5.0.0 happy-dom: '*' jsdom: '*' - vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 peerDependenciesMeta: '@edge-runtime/vm': optional: true @@ -13862,6 +14331,9 @@ packages: weald@1.1.3: resolution: {integrity: sha512-vMWtNbYuPb58NeG2+0sKA0Een4VMDwzf+3oHqh68buWRSOMUBlUeRb11LhV28czV+DUpJHRykifijZDuS9bInA==} + weapon-regex@2.0.4: + resolution: {integrity: sha512-ubuhY5Lo4phWcMsJqe8j62m9uhsuo/VpfK5XsSgYGRGDSt10hwVwOBTriPRd0dac+KYbGNXOrfXjM6xCp2NUKg==} + web-streams-polyfill@3.3.3: resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==} engines: {node: '>= 8'} @@ -13869,8 +14341,11 @@ packages: web-tree-sitter@0.24.5: resolution: {integrity: sha512-+J/2VSHN8J47gQUAvF8KDadrfz6uFYVjxoxbKWDoXVsH2u7yLdarCnIURnrMA6uSRkgX3SdmqM5BOoQjPdSh5w==} - web-vitals@5.2.0: - resolution: {integrity: sha512-i2z98bEmaCqSDiHEDu+gHl/dmR4Q+TxFmG3/13KkMO+o8UxQzCqWaDRCiLgEa41nlO4VpXSI0ASa1xWmO9sBlA==} + web-vitals@6.2.1: + resolution: {integrity: sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw==} + + web-vitals@6.2.2: + resolution: {integrity: sha512-oto5x6dLEgrRqfcWed+pZEUb2q6ikbFmqF54CRDhI/QGbn+qxC49b4C4OkbH+kb9C3a8shpFD3SgR9kRcs80ZQ==} web3-utils@1.10.4: resolution: {integrity: sha512-tsu8FiKJLk2PzhDl9fXbGUWTkkVXYhtTA+SmEFkKft+9BgwLxfCRpU96sWv7ICC8zixBNd3JURVoiR3dUXgP8A==} @@ -14092,30 +14567,21 @@ packages: resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} engines: {node: '>=12'} - yn@3.1.1: - resolution: {integrity: sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==} - engines: {node: '>=6'} - yocto-queue@0.1.0: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} + yoctocolors@2.2.0: + resolution: {integrity: sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==} + engines: {node: '>=18'} + yup@0.32.11: resolution: {integrity: sha512-Z2Fe1bn+eLstG8DRR6FTavGD+MeAwyfmouhHsIUgaADz8jvFKbO/fXc2trJKZg+5EBjh4gGm3iU/t3onKlXHIg==} engines: {node: '>=10'} - yup@1.7.1: - resolution: {integrity: sha512-GKHFX2nXul2/4Dtfxhozv701jLQHdf6J34YDh2cEkpqoo8le5Mg6/LrdseVLrFarmFygZTlfIhHx/QKfb/QWXw==} - zenscroll@4.0.2: resolution: {integrity: sha512-jEA1znR7b4C/NnaycInCU6h/d15ZzCd1jmsruqOKnZP6WXQSMH3W2GL+OXbkruslU4h+Tzuos0HdswzRUk/Vgg==} - zod-validation-error@4.0.2: - resolution: {integrity: sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==} - engines: {node: '>=18.0.0'} - peerDependencies: - zod: ^3.25.0 || ^4.0.0 - zod@3.22.4: resolution: {integrity: sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==} @@ -14323,28 +14789,54 @@ snapshots: js-tokens: 4.0.0 picocolors: 1.1.1 + '@babel/code-frame@8.0.0': + dependencies: + '@babel/helper-validator-identifier': 8.0.4 + js-tokens: 10.0.0 + '@babel/compat-data@7.29.7': {} - '@babel/core@7.29.7': + '@babel/compat-data@8.0.0': {} + + '@babel/core@7.29.7(supports-color@10.2.2)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.7 '@babel/helper-compilation-targets': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helpers': 7.29.7 '@babel/parser': 7.29.7 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) '@babel/types': 7.29.7 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 transitivePeerDependencies: - supports-color + '@babel/core@8.0.1': + dependencies: + '@babel/code-frame': 8.0.0 + '@babel/generator': 8.0.0 + '@babel/helper-compilation-targets': 8.0.0 + '@babel/helpers': 8.0.0 + '@babel/parser': 8.0.4 + '@babel/template': 8.0.0 + '@babel/traverse': 8.0.4 + '@babel/types': 8.0.4 + '@types/gensync': 1.0.5 + convert-source-map: 2.0.0 + empathic: 2.0.1 + gensync: 1.0.0-beta.2 + import-meta-resolve: 4.2.0 + json5: 2.2.3 + obug: 2.2.1 + semver: 7.8.5 + '@babel/generator@7.29.7': dependencies: '@babel/parser': 7.29.7 @@ -14353,10 +14845,23 @@ snapshots: '@jridgewell/trace-mapping': 0.3.31 jsesc: 3.1.0 + '@babel/generator@8.0.0': + dependencies: + '@babel/parser': 8.0.4 + '@babel/types': 8.0.4 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + '@types/jsesc': 2.5.1 + jsesc: 3.1.0 + '@babel/helper-annotate-as-pure@7.29.7': dependencies: '@babel/types': 7.29.7 + '@babel/helper-annotate-as-pure@8.0.0': + dependencies: + '@babel/types': 8.0.4 + '@babel/helper-compilation-targets@7.29.7': dependencies: '@babel/compat-data': 7.29.7 @@ -14365,32 +14870,51 @@ snapshots: lru-cache: 5.1.1 semver: 6.3.1 - '@babel/helper-create-class-features-plugin@7.29.7(@babel/core@7.29.7)': + '@babel/helper-compilation-targets@8.0.0': + dependencies: + '@babel/compat-data': 8.0.0 + '@babel/helper-validator-option': 8.0.0 + browserslist: 4.28.2 + lru-cache: 11.5.0 + semver: 7.8.5 + + '@babel/helper-create-class-features-plugin@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-member-expression-to-functions': 7.29.7 + '@babel/helper-member-expression-to-functions': 7.29.7(supports-color@10.2.2) '@babel/helper-optimise-call-expression': 7.29.7 - '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7) - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7(supports-color@10.2.2) semver: 6.3.1 transitivePeerDependencies: - supports-color - '@babel/helper-create-regexp-features-plugin@7.29.7(@babel/core@7.29.7)': + '@babel/helper-create-class-features-plugin@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-annotate-as-pure': 8.0.0 + '@babel/helper-member-expression-to-functions': 8.0.0 + '@babel/helper-optimise-call-expression': 8.0.0 + '@babel/helper-replace-supers': 8.0.1(@babel/core@8.0.1) + '@babel/helper-skip-transparent-expression-wrappers': 8.0.0 + '@babel/traverse': 8.0.4 + semver: 7.8.5 + + '@babel/helper-create-regexp-features-plugin@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-annotate-as-pure': 7.29.7 regexpu-core: 6.4.0 semver: 6.3.1 - '@babel/helper-define-polyfill-provider@0.6.8(@babel/core@7.29.7)': + '@babel/helper-define-polyfill-provider@0.6.8(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-compilation-targets': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) lodash.debounce: 4.0.8 resolve: 1.22.12 transitivePeerDependencies: @@ -14398,70 +14922,115 @@ snapshots: '@babel/helper-globals@7.29.7': {} - '@babel/helper-member-expression-to-functions@7.29.7': + '@babel/helper-globals@8.0.0': {} + + '@babel/helper-member-expression-to-functions@7.29.7(supports-color@10.2.2)': dependencies: - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/helper-module-imports@7.29.7': + '@babel/helper-member-expression-to-functions@8.0.0': + dependencies: + '@babel/traverse': 8.0.4 + '@babel/types': 8.0.4 + + '@babel/helper-module-imports@7.29.7(supports-color@10.2.2)': dependencies: - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + '@babel/helper-module-imports@8.0.0': + dependencies: + '@babel/traverse': 8.0.4 + '@babel/types': 8.0.4 + + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-module-imports': 7.29.7(supports-color@10.2.2) '@babel/helper-validator-identifier': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color + '@babel/helper-module-transforms@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-module-imports': 8.0.0 + '@babel/helper-validator-identifier': 8.0.4 + '@babel/traverse': 8.0.4 + '@babel/helper-optimise-call-expression@7.29.7': dependencies: '@babel/types': 7.29.7 + '@babel/helper-optimise-call-expression@8.0.0': + dependencies: + '@babel/types': 8.0.4 + '@babel/helper-plugin-utils@7.29.7': {} - '@babel/helper-remap-async-to-generator@7.29.7(@babel/core@7.29.7)': + '@babel/helper-plugin-utils@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + + '@babel/helper-remap-async-to-generator@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-wrap-function': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/helper-wrap-function': 7.29.7(supports-color@10.2.2) + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/helper-replace-supers@7.29.7(@babel/core@7.29.7)': + '@babel/helper-replace-supers@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-member-expression-to-functions': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-member-expression-to-functions': 7.29.7(supports-color@10.2.2) '@babel/helper-optimise-call-expression': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/helper-skip-transparent-expression-wrappers@7.29.7': + '@babel/helper-replace-supers@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-member-expression-to-functions': 8.0.0 + '@babel/helper-optimise-call-expression': 8.0.0 + '@babel/traverse': 8.0.4 + + '@babel/helper-skip-transparent-expression-wrappers@7.29.7(supports-color@10.2.2)': dependencies: - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color + '@babel/helper-skip-transparent-expression-wrappers@8.0.0': + dependencies: + '@babel/traverse': 8.0.4 + '@babel/types': 8.0.4 + '@babel/helper-string-parser@7.29.7': {} + '@babel/helper-string-parser@8.0.0': {} + '@babel/helper-validator-identifier@7.29.7': {} + '@babel/helper-validator-identifier@8.0.4': {} + '@babel/helper-validator-option@7.29.7': {} - '@babel/helper-wrap-function@7.29.7': + '@babel/helper-validator-option@8.0.0': {} + + '@babel/helper-wrap-function@7.29.7(supports-color@10.2.2)': dependencies: '@babel/template': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color @@ -14471,578 +15040,668 @@ snapshots: '@babel/template': 7.29.7 '@babel/types': 7.29.7 + '@babel/helpers@8.0.0': + dependencies: + '@babel/template': 8.0.0 + '@babel/types': 8.0.4 + '@babel/parser@7.29.7': dependencies: '@babel/types': 7.29.7 - '@babel/plugin-bugfix-firefox-class-in-computed-class-key@7.29.7(@babel/core@7.29.7)': + '@babel/parser@8.0.4': dependencies: - '@babel/core': 7.29.7 + '@babel/types': 8.0.4 + + '@babel/plugin-bugfix-firefox-class-in-computed-class-key@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-bugfix-safari-class-field-initializer-scope@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-bugfix-safari-class-field-initializer-scope@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 - '@babel/plugin-transform-optional-chaining': 7.29.7(@babel/core@7.29.7) + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@10.2.2) + '@babel/plugin-transform-optional-chaining': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2(@babel/core@7.29.7)': + '@babel/plugin-proposal-decorators@8.0.2(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-create-class-features-plugin': 8.0.1(@babel/core@8.0.1) + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + '@babel/plugin-syntax-decorators': 8.0.1(@babel/core@8.0.1) + + '@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@babel/plugin-syntax-import-assertions@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-syntax-decorators@8.0.1(@babel/core@8.0.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 8.0.1 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + + '@babel/plugin-syntax-import-assertions@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-import-attributes@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-syntax-import-attributes@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-syntax-jsx@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + + '@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-unicode-sets-regex@7.18.6(@babel/core@7.29.7)': + '@babel/plugin-syntax-typescript@8.0.3(@babel/core@8.0.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 8.0.1 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + + '@babel/plugin-syntax-unicode-sets-regex@7.18.6(@babel/core@7.29.7(supports-color@10.2.2))': + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-arrow-functions@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-arrow-functions@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-async-generator-functions@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-async-generator-functions@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-remap-async-to-generator': 7.29.7(@babel/core@7.29.7) - '@babel/traverse': 7.29.7 + '@babel/helper-remap-async-to-generator': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-async-to-generator@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-async-to-generator@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-module-imports': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-remap-async-to-generator': 7.29.7(@babel/core@7.29.7) + '@babel/helper-remap-async-to-generator': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-block-scoped-functions@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-block-scoped-functions@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-block-scoping@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-block-scoping@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-class-properties@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-class-properties@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-class-static-block@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-class-static-block@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-classes@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-classes@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-annotate-as-pure': 7.29.7 '@babel/helper-compilation-targets': 7.29.7 '@babel/helper-globals': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7) - '@babel/traverse': 7.29.7 + '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-computed-properties@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-computed-properties@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 '@babel/template': 7.29.7 - '@babel/plugin-transform-destructuring@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-destructuring@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-dotall-regex@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-destructuring@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + + '@babel/plugin-transform-dotall-regex@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-duplicate-keys@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-duplicate-keys@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-duplicate-named-capturing-groups-regex@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-duplicate-named-capturing-groups-regex@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-dynamic-import@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-dynamic-import@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-explicit-resource-management@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-explicit-resource-management@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-destructuring': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-destructuring': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-exponentiation-operator@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-explicit-resource-management@8.0.1(@babel/core@8.0.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 8.0.1 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + '@babel/plugin-transform-destructuring': 8.0.1(@babel/core@8.0.1) + + '@babel/plugin-transform-exponentiation-operator@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-export-namespace-from@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-export-namespace-from@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-for-of@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-for-of@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-function-name@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-function-name@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-compilation-targets': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-json-strings@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-json-strings@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-literals@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-literals@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-logical-assignment-operators@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-logical-assignment-operators@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-member-expression-literals@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-member-expression-literals@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-modules-amd@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-modules-amd@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-modules-commonjs@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-modules-commonjs@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-modules-systemjs@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-modules-commonjs@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-module-transforms': 8.0.1(@babel/core@8.0.1) + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + + '@babel/plugin-transform-modules-systemjs@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 '@babel/helper-validator-identifier': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-modules-umd@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-modules-umd@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-named-capturing-groups-regex@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-named-capturing-groups-regex@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-new-target@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-new-target@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-nullish-coalescing-operator@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-nullish-coalescing-operator@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-numeric-separator@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-numeric-separator@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-object-rest-spread@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-object-rest-spread@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-compilation-targets': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-destructuring': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-parameters': 7.29.7(@babel/core@7.29.7) - '@babel/traverse': 7.29.7 + '@babel/plugin-transform-destructuring': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-parameters': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/traverse': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-object-super@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-object-super@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7) + '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-optional-catch-binding@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-optional-catch-binding@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-optional-chaining@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-optional-chaining@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-parameters@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-parameters@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-private-methods@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-private-methods@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-private-property-in-object@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-private-property-in-object@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-property-literals@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-property-literals@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-constant-elements@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-constant-elements@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-display-name@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-display-name@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-jsx-development@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-display-name@8.0.1(@babel/core@8.0.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-react-jsx': 7.29.7(@babel/core@7.29.7) - transitivePeerDependencies: - - supports-color + '@babel/core': 8.0.1 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) - '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-development@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-plugin-utils': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/plugin-transform-react-jsx': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + transitivePeerDependencies: + - supports-color - '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-development@8.0.1(@babel/core@8.0.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-plugin-utils': 7.29.7 + '@babel/core': 8.0.1 + '@babel/plugin-transform-react-jsx': 8.0.1(@babel/core@8.0.1) - '@babel/plugin-transform-react-jsx@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/helper-module-imports': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-react-pure-annotations@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-annotate-as-pure': 8.0.0 + '@babel/helper-module-imports': 8.0.0 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + '@babel/plugin-syntax-jsx': 8.0.1(@babel/core@8.0.1) + '@babel/types': 8.0.4 + + '@babel/plugin-transform-react-pure-annotations@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-annotate-as-pure': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-regenerator@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-pure-annotations@8.0.1(@babel/core@8.0.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 8.0.1 + '@babel/helper-annotate-as-pure': 8.0.0 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + + '@babel/plugin-transform-regenerator@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-regexp-modifiers@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-regexp-modifiers@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-reserved-words@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-reserved-words@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-shorthand-properties@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-shorthand-properties@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-spread@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-spread@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-sticky-regex@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-sticky-regex@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-template-literals@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-template-literals@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-typeof-symbol@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-typeof-symbol@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-typescript@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-typescript@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 - '@babel/plugin-syntax-typescript': 7.29.7(@babel/core@7.29.7) + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@10.2.2) + '@babel/plugin-syntax-typescript': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-unicode-escapes@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-typescript@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-annotate-as-pure': 8.0.0 + '@babel/helper-create-class-features-plugin': 8.0.1(@babel/core@8.0.1) + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + '@babel/helper-skip-transparent-expression-wrappers': 8.0.0 + '@babel/plugin-syntax-typescript': 8.0.3(@babel/core@8.0.1) + + '@babel/plugin-transform-unicode-escapes@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-unicode-property-regex@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-unicode-property-regex@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-unicode-regex@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-unicode-regex@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-unicode-sets-regex@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-unicode-sets-regex@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) '@babel/helper-plugin-utils': 7.29.7 - '@babel/preset-env@7.29.7(@babel/core@7.29.7)': + '@babel/preset-env@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: '@babel/compat-data': 7.29.7 - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-compilation-targets': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 '@babel/helper-validator-option': 7.29.7 - '@babel/plugin-bugfix-firefox-class-in-computed-class-key': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-bugfix-safari-class-field-initializer-scope': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-proposal-private-property-in-object': 7.21.0-placeholder-for-preset-env.2(@babel/core@7.29.7) - '@babel/plugin-syntax-import-assertions': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-syntax-import-attributes': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-syntax-unicode-sets-regex': 7.18.6(@babel/core@7.29.7) - '@babel/plugin-transform-arrow-functions': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-async-generator-functions': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-async-to-generator': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-block-scoped-functions': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-block-scoping': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-class-properties': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-class-static-block': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-classes': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-computed-properties': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-destructuring': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-dotall-regex': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-duplicate-keys': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-duplicate-named-capturing-groups-regex': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-dynamic-import': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-explicit-resource-management': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-exponentiation-operator': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-export-namespace-from': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-for-of': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-function-name': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-json-strings': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-literals': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-logical-assignment-operators': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-member-expression-literals': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-modules-amd': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-modules-systemjs': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-modules-umd': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-named-capturing-groups-regex': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-new-target': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-nullish-coalescing-operator': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-numeric-separator': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-object-rest-spread': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-object-super': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-optional-catch-binding': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-optional-chaining': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-parameters': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-methods': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-property-in-object': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-property-literals': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-regenerator': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-regexp-modifiers': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-reserved-words': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-shorthand-properties': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-spread': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-sticky-regex': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-template-literals': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-typeof-symbol': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-escapes': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-property-regex': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-regex': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-sets-regex': 7.29.7(@babel/core@7.29.7) - '@babel/preset-modules': 0.1.6-no-external-plugins(@babel/core@7.29.7) - babel-plugin-polyfill-corejs2: 0.4.17(@babel/core@7.29.7) - babel-plugin-polyfill-corejs3: 0.14.2(@babel/core@7.29.7) - babel-plugin-polyfill-regenerator: 0.6.8(@babel/core@7.29.7) + '@babel/plugin-bugfix-firefox-class-in-computed-class-key': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-bugfix-safari-class-field-initializer-scope': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-proposal-private-property-in-object': 7.21.0-placeholder-for-preset-env.2(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-syntax-import-assertions': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-syntax-import-attributes': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-syntax-unicode-sets-regex': 7.18.6(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-arrow-functions': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-async-generator-functions': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-async-to-generator': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-block-scoped-functions': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-block-scoping': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-class-properties': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-class-static-block': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-classes': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-computed-properties': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-destructuring': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-dotall-regex': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-duplicate-keys': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-duplicate-named-capturing-groups-regex': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-dynamic-import': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-explicit-resource-management': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-exponentiation-operator': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-export-namespace-from': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-for-of': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-function-name': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-json-strings': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-literals': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-logical-assignment-operators': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-member-expression-literals': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-modules-amd': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-modules-systemjs': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-modules-umd': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-named-capturing-groups-regex': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-new-target': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-nullish-coalescing-operator': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-numeric-separator': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-object-rest-spread': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-object-super': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-optional-catch-binding': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-optional-chaining': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-parameters': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-private-methods': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-private-property-in-object': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-property-literals': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-regenerator': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-regexp-modifiers': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-reserved-words': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-shorthand-properties': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-spread': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-sticky-regex': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-template-literals': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-typeof-symbol': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-unicode-escapes': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-unicode-property-regex': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-unicode-regex': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-unicode-sets-regex': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/preset-modules': 0.1.6-no-external-plugins(@babel/core@7.29.7(supports-color@10.2.2)) + babel-plugin-polyfill-corejs2: 0.4.17(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + babel-plugin-polyfill-corejs3: 0.14.2(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + babel-plugin-polyfill-regenerator: 0.6.8(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) core-js-compat: 3.49.0 semver: 6.3.1 transitivePeerDependencies: - supports-color - '@babel/preset-modules@0.1.6-no-external-plugins(@babel/core@7.29.7)': + '@babel/preset-modules@0.1.6-no-external-plugins(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 '@babel/types': 7.29.7 esutils: 2.0.3 - '@babel/preset-react@7.29.7(@babel/core@7.29.7)': + '@babel/preset-react@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 '@babel/helper-validator-option': 7.29.7 - '@babel/plugin-transform-react-display-name': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-development': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-pure-annotations': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-react-display-name': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-react-jsx': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-react-jsx-development': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-react-pure-annotations': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) transitivePeerDependencies: - supports-color - '@babel/preset-typescript@7.29.7(@babel/core@7.29.7)': + '@babel/preset-react@8.0.1(@babel/core@8.0.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 8.0.1 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + '@babel/helper-validator-option': 8.0.0 + '@babel/plugin-transform-react-display-name': 8.0.1(@babel/core@8.0.1) + '@babel/plugin-transform-react-jsx': 8.0.1(@babel/core@8.0.1) + '@babel/plugin-transform-react-jsx-development': 8.0.1(@babel/core@8.0.1) + '@babel/plugin-transform-react-pure-annotations': 8.0.1(@babel/core@8.0.1) + + '@babel/preset-typescript@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.29.7 '@babel/helper-validator-option': 7.29.7 - '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) transitivePeerDependencies: - supports-color + '@babel/preset-typescript@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + '@babel/helper-validator-option': 8.0.0 + '@babel/plugin-transform-modules-commonjs': 8.0.1(@babel/core@8.0.1) + '@babel/plugin-transform-typescript': 8.0.1(@babel/core@8.0.1) + '@babel/runtime-corejs3@7.29.7': dependencies: core-js-pure: 3.49.0 @@ -15055,7 +15714,13 @@ snapshots: '@babel/parser': 7.29.7 '@babel/types': 7.29.7 - '@babel/traverse@7.29.7': + '@babel/template@8.0.0': + dependencies: + '@babel/code-frame': 8.0.0 + '@babel/parser': 8.0.4 + '@babel/types': 8.0.4 + + '@babel/traverse@7.29.7(supports-color@10.2.2)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.7 @@ -15063,24 +15728,39 @@ snapshots: '@babel/parser': 7.29.7 '@babel/template': 7.29.7 '@babel/types': 7.29.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color + '@babel/traverse@8.0.4': + dependencies: + '@babel/code-frame': 8.0.0 + '@babel/generator': 8.0.0 + '@babel/helper-globals': 8.0.0 + '@babel/parser': 8.0.4 + '@babel/template': 8.0.0 + '@babel/types': 8.0.4 + obug: 2.2.1 + '@babel/types@7.29.7': dependencies: '@babel/helper-string-parser': 7.29.7 '@babel/helper-validator-identifier': 7.29.7 - '@base-org/account@1.1.1(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@3.25.76)': + '@babel/types@8.0.4': + dependencies: + '@babel/helper-string-parser': 8.0.0 + '@babel/helper-validator-identifier': 8.0.4 + + '@base-org/account@1.1.1(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@noble/hashes': 1.8.0 clsx: 1.2.1 eventemitter3: 5.0.1 idb-keyval: 6.2.1 - ox: 0.6.9(@typescript/typescript6@6.0.2)(zod@3.25.76) + ox: 0.6.9(@typescript/typescript6@6.0.2)(zod@4.4.3) preact: 10.24.2 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) zustand: 5.0.3(@types/react@19.1.7)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) transitivePeerDependencies: - '@types/react' @@ -15092,16 +15772,16 @@ snapshots: - utf-8-validate - zod - '@base-org/account@2.4.0(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@3.25.76)': + '@base-org/account@2.4.0(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@coinbase/cdp-sdk': 1.50.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(utf-8-validate@6.0.6) + '@coinbase/cdp-sdk': 1.50.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(utf-8-validate@6.0.6) '@noble/hashes': 1.8.0 clsx: 1.2.1 eventemitter3: 5.0.1 idb-keyval: 6.2.1 - ox: 0.6.9(@typescript/typescript6@6.0.2)(zod@3.25.76) + ox: 0.6.9(@typescript/typescript6@6.0.2)(zod@4.4.3) preact: 10.24.2 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) zustand: 5.0.3(@types/react@19.1.7)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) transitivePeerDependencies: - '@types/react' @@ -15115,21 +15795,27 @@ snapshots: - utf-8-validate - zod + '@bcoe/v8-coverage@1.0.2': {} + '@blockscout/admin-rs-types@1.5.1': {} +<<<<<<< HEAD '@blockscout/api-types@0.0.1-beta.d261ddc': {} +======= + '@blockscout/api-types@0.0.1-beta.e1f332f': {} +>>>>>>> v2.13.0 '@blockscout/bens-types@1.7.1': {} '@blockscout/contracts-info-types@1.5.3': {} - '@blockscout/interchain-indexer-types@1.6.0': {} + '@blockscout/interchain-indexer-types@1.11.0': {} - '@blockscout/multichain-aggregator-types@2.1.6': {} + '@blockscout/multichain-aggregator-types@2.1.8': {} '@blockscout/points-types@1.4.1': {} - '@blockscout/stats-types@2.11.1': {} + '@blockscout/stats-types@2.19.1': {} '@blockscout/tac-operation-lifecycle-types@0.0.1-beta.71a05d5': {} @@ -15139,10 +15825,10 @@ snapshots: '@borewit/text-codec@0.2.2': {} - '@boundaries/elements@2.0.1(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint@9.39.2)': + '@boundaries/elements@2.0.1(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - eslint-import-resolver-node: 0.3.9 - eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint-import-resolver-node@0.3.9)(eslint@9.39.2) + eslint-import-resolver-node: 0.3.9(supports-color@10.2.2) + eslint-module-utils: 2.12.1(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-node@0.3.9(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) handlebars: 4.7.9 is-core-module: 2.16.1 micromatch: 4.0.8 @@ -15159,47 +15845,16 @@ snapshots: '@chainsafe/is-ip@2.1.0': {} - '@chainsafe/libp2p-noise@16.1.5': - dependencies: - '@chainsafe/as-chacha20poly1305': 0.1.0 - '@chainsafe/as-sha256': 1.2.4 - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/peer-id': 5.1.9 - '@noble/ciphers': 1.3.0 - '@noble/curves': 1.9.7 - '@noble/hashes': 1.8.0 - it-length-prefixed: 10.0.2 - it-length-prefixed-stream: 2.0.6 - it-pair: 2.0.6 - it-pipe: 3.0.1 - it-stream-types: 2.0.4 - protons-runtime: 5.6.0 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 - wherearewe: 2.0.1 - - '@chainsafe/libp2p-yamux@7.0.4': - dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/utils': 6.7.2 - get-iterator: 2.0.1 - it-foreach: 2.1.7 - it-pushable: 3.2.4 - it-stream-types: 2.0.4 - race-signal: 1.1.3 - uint8arraylist: 2.4.9 - '@chainsafe/netmask@2.0.0': dependencies: '@chainsafe/is-ip': 2.1.0 - '@chakra-ui/cli@3.36.1(@chakra-ui/react@3.36.1(@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4))(react-dom@19.1.4(react@19.1.4))(react@19.1.4))': + '@chakra-ui/cli@3.36.1(@chakra-ui/react@3.36.1(@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4)(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react@19.1.4))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/parser': 7.29.7 - '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7) - '@chakra-ui/react': 3.36.1(@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4))(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@chakra-ui/react': 3.36.1(@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4)(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react@19.1.4) '@clack/prompts': 1.5.1 '@pandacss/is-valid-prop': 1.11.1 '@types/babel__core': 7.20.5 @@ -15209,7 +15864,7 @@ snapshots: chokidar: 5.0.0 cli-table: 0.3.11 commander: 14.0.3 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) dotenv: 17.3.1 esbuild: 0.28.1 get-tsconfig: 4.14.0 @@ -15224,11 +15879,11 @@ snapshots: transitivePeerDependencies: - supports-color - '@chakra-ui/react@3.36.1(@emotion/react@11.14.0(@types/react@18.3.12)(react@19.1.4))(react-dom@19.1.4(react@19.1.4))(react@19.1.4)': + '@chakra-ui/react@3.36.1(@emotion/react@11.14.0(@types/react@18.3.12)(react@19.1.4)(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react@19.1.4)': dependencies: '@ark-ui/react': 5.37.2(react-dom@19.1.4(react@19.1.4))(react@19.1.4) '@emotion/is-prop-valid': 1.4.0 - '@emotion/react': 11.14.0(@types/react@18.3.12)(react@19.1.4) + '@emotion/react': 11.14.0(@types/react@18.3.12)(react@19.1.4)(supports-color@10.2.2) '@emotion/serialize': 1.3.3 '@emotion/use-insertion-effect-with-fallbacks': 1.2.0(react@19.1.4) '@emotion/utils': 1.4.2 @@ -15237,11 +15892,11 @@ snapshots: react: 19.1.4 react-dom: 19.1.4(react@19.1.4) - '@chakra-ui/react@3.36.1(@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4))(react-dom@19.1.4(react@19.1.4))(react@19.1.4)': + '@chakra-ui/react@3.36.1(@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4)(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react@19.1.4)': dependencies: '@ark-ui/react': 5.37.2(react-dom@19.1.4(react@19.1.4))(react@19.1.4) '@emotion/is-prop-valid': 1.4.0 - '@emotion/react': 11.14.0(@types/react@19.1.7)(react@19.1.4) + '@emotion/react': 11.14.0(@types/react@19.1.7)(react@19.1.4)(supports-color@10.2.2) '@emotion/serialize': 1.3.3 '@emotion/use-insertion-effect-with-fallbacks': 1.2.0(react@19.1.4) '@emotion/utils': 1.4.2 @@ -15335,14 +15990,14 @@ snapshots: style-mod: 4.1.3 w3c-keyname: 2.2.8 - '@coinbase/cdp-sdk@1.50.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(utf-8-validate@6.0.6)': + '@coinbase/cdp-sdk@1.50.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(utf-8-validate@6.0.6)': dependencies: '@solana-program/system': 0.10.0(@solana/kit@5.5.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(utf-8-validate@6.0.6)) '@solana-program/token': 0.9.0(@solana/kit@5.5.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(utf-8-validate@6.0.6)) '@solana/kit': 5.5.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(utf-8-validate@6.0.6) abitype: 1.0.6(@typescript/typescript6@6.0.2)(zod@3.25.76) - axios: 1.12.0(debug@4.4.3) - axios-retry: 4.5.0(axios@1.12.0) + axios: 1.12.0(debug@4.4.3(supports-color@10.2.2)) + axios-retry: 4.5.0(axios@1.12.0(debug@4.4.3(supports-color@10.2.2))) bs58: 6.0.0 jose: 6.2.3 md5: 2.3.0 @@ -15356,29 +16011,30 @@ snapshots: - typescript - utf-8-validate - '@coinbase/wallet-sdk@3.9.3': + '@coinbase/wallet-sdk@3.9.3(supports-color@10.2.2)': dependencies: bn.js: 5.2.3 buffer: 6.0.3 clsx: 1.2.1 - eth-block-tracker: 7.1.0 + eth-block-tracker: 7.1.0(supports-color@10.2.2) eth-json-rpc-filters: 6.0.1 eventemitter3: 5.0.4 keccak: 3.0.4 - preact: 10.29.2 + preact: 10.29.8 sha.js: 2.4.12 transitivePeerDependencies: + - preact-render-to-string - supports-color - '@coinbase/wallet-sdk@4.3.6(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@3.25.76)': + '@coinbase/wallet-sdk@4.3.6(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@noble/hashes': 1.8.0 clsx: 1.2.1 eventemitter3: 5.0.1 idb-keyval: 6.2.1 - ox: 0.6.9(@typescript/typescript6@6.0.2)(zod@3.25.76) + ox: 0.6.9(@typescript/typescript6@6.0.2)(zod@4.4.3) preact: 10.24.2 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) zustand: 5.0.3(@types/react@19.1.7)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) transitivePeerDependencies: - '@types/react' @@ -15390,13 +16046,13 @@ snapshots: - utf-8-validate - zod - '@coinbase/wallet-sdk@4.3.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@coinbase/wallet-sdk@4.3.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@noble/hashes': 1.8.0 clsx: 1.2.1 eventemitter3: 5.0.4 preact: 10.29.2 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - bufferutil - typescript @@ -15627,10 +16283,6 @@ snapshots: '@cspell/url@9.8.0': {} - '@cspotcode/source-map-support@0.8.1': - dependencies: - '@jridgewell/trace-mapping': 0.3.9 - '@csstools/color-helpers@6.0.2': {} '@csstools/css-calc@3.2.1(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0)': @@ -15657,24 +16309,44 @@ snapshots: '@csstools/normalize.css@12.1.1': {} - '@dependents/detective-less@4.1.0': + '@discoveryjs/json-ext@0.5.7': {} + + '@dnd-kit/accessibility@3.1.1(react@19.1.4)': + dependencies: + react: 19.1.4 + tslib: 2.8.1 + + '@dnd-kit/core@6.3.1(react-dom@19.1.4(react@19.1.4))(react@19.1.4)': dependencies: - gonzales-pe: 4.3.0 - node-source-walk: 6.0.2 + '@dnd-kit/accessibility': 3.1.1(react@19.1.4) + '@dnd-kit/utilities': 3.2.2(react@19.1.4) + react: 19.1.4 + react-dom: 19.1.4(react@19.1.4) + tslib: 2.8.1 - '@discoveryjs/json-ext@0.5.7': {} + '@dnd-kit/sortable@10.0.0(@dnd-kit/core@6.3.1(react-dom@19.1.4(react@19.1.4))(react@19.1.4))(react@19.1.4)': + dependencies: + '@dnd-kit/core': 6.3.1(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + '@dnd-kit/utilities': 3.2.2(react@19.1.4) + react: 19.1.4 + tslib: 2.8.1 + + '@dnd-kit/utilities@3.2.2(react@19.1.4)': + dependencies: + react: 19.1.4 + tslib: 2.8.1 '@dnsquery/dns-packet@6.1.1': dependencies: '@leichtgewicht/ip-codec': 2.0.5 utf8-codec: 1.0.0 - '@dynamic-labs-connectors/base-account-evm@4.6.9(@dynamic-labs/ethereum-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(@dynamic-labs/wallet-connector-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76)': + '@dynamic-labs-connectors/base-account-evm@4.6.9(30aff48d6969f56fd45e702fc8c5a887)': dependencies: - '@base-org/account': 1.1.1(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@3.25.76) - '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@base-org/account': 1.1.1(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@4.4.3) + '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@types/react' - bufferutil @@ -15685,12 +16357,12 @@ snapshots: - utf-8-validate - zod - '@dynamic-labs-connectors/metamask-evm@4.6.9(fae979a47c6480d6087d4faa1da013ff)': + '@dynamic-labs-connectors/metamask-evm@4.6.9(e8ff8c7474d51c98957326bb7c6d4707)': dependencies: - '@dynamic-labs/ethereum': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) - '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - '@metamask/connect-evm': 1.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) + '@dynamic-labs/ethereum': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) + '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@metamask/connect-evm': 1.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) transitivePeerDependencies: - '@react-native-async-storage/async-storage' - bufferutil @@ -15700,10 +16372,10 @@ snapshots: '@dynamic-labs-sdk/assert-package-version@1.12.1': {} - '@dynamic-labs-sdk/client@1.12.1(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': + '@dynamic-labs-sdk/client@1.12.1(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': dependencies: '@dynamic-labs-sdk/assert-package-version': 1.12.1 - '@dynamic-labs-wallet/browser-wallet-client': 1.0.39(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@dynamic-labs-wallet/browser-wallet-client': 1.0.39(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(debug@4.4.3(supports-color@10.2.2)) '@dynamic-labs-wallet/forward-mpc-client': 0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@dynamic-labs/sdk-api-core': 0.0.1046 '@simplewebauthn/browser': 13.1.0 @@ -15712,7 +16384,7 @@ snapshots: eventemitter3: 5.0.1 zod: 4.0.5 optionalDependencies: - react-native: 0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6) + react-native: 0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6) transitivePeerDependencies: - '@dynamic-labs-wallet/primitives' - bufferutil @@ -15721,40 +16393,40 @@ snapshots: - react-dom - utf-8-validate - '@dynamic-labs-wallet/browser-wallet-client@1.0.39(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))': + '@dynamic-labs-wallet/browser-wallet-client@1.0.39(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(debug@4.4.3(supports-color@10.2.2))': dependencies: - '@dynamic-labs-wallet/core': 1.0.39(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@dynamic-labs-wallet/core': 1.0.39(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(debug@4.4.3(supports-color@10.2.2)) '@dynamic-labs/logger': 4.84.0 '@dynamic-labs/message-transport': 4.84.0 transitivePeerDependencies: - '@dynamic-labs-wallet/forward-mpc-client' - debug - '@dynamic-labs-wallet/browser-wallet-client@1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))': + '@dynamic-labs-wallet/browser-wallet-client@1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(debug@4.4.3(supports-color@10.2.2))': dependencies: - '@dynamic-labs-wallet/core': 1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@dynamic-labs-wallet/core': 1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(debug@4.4.3(supports-color@10.2.2)) '@dynamic-labs/logger': 4.84.0 '@dynamic-labs/message-transport': 4.84.0 transitivePeerDependencies: - '@dynamic-labs-wallet/forward-mpc-client' - debug - '@dynamic-labs-wallet/core@1.0.39(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))': + '@dynamic-labs-wallet/core@1.0.39(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(debug@4.4.3(supports-color@10.2.2))': dependencies: '@dynamic-labs-wallet/forward-mpc-client': 0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@dynamic-labs-wallet/primitives': 1.0.39 '@dynamic-labs/sdk-api-core': 0.0.984 - axios: 1.12.0(debug@4.4.3) + axios: 1.12.0(debug@4.4.3(supports-color@10.2.2)) uuid: 11.1.0 transitivePeerDependencies: - debug - '@dynamic-labs-wallet/core@1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))': + '@dynamic-labs-wallet/core@1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(debug@4.4.3(supports-color@10.2.2))': dependencies: '@dynamic-labs-wallet/forward-mpc-client': 0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@dynamic-labs-wallet/primitives': 1.0.48 '@dynamic-labs/sdk-api-core': 0.0.984 - axios: 1.12.0(debug@4.4.3) + axios: 1.12.0(debug@4.4.3(supports-color@10.2.2)) uuid: 11.1.0 transitivePeerDependencies: - debug @@ -15764,7 +16436,7 @@ snapshots: '@dynamic-labs-wallet/forward-mpc-shared': 0.7.0(@dynamic-labs-wallet/primitives@1.0.48) '@dynamic-labs-wallet/primitives': 1.0.48 '@evervault/wasm-attestation-bindings': 0.3.1 - '@noble/hashes': 1.8.0 + '@noble/hashes': 2.4.0 eventemitter3: 5.0.4 fp-ts: 2.16.11 isows: 1.0.7(ws@8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) @@ -15777,7 +16449,7 @@ snapshots: dependencies: '@dynamic-labs-wallet/primitives': 1.0.48 '@noble/ciphers': 0.4.1 - '@noble/hashes': 1.8.0 + '@noble/hashes': 2.4.0 '@noble/post-quantum': 0.5.4 fp-ts: 2.16.11 io-ts: 2.2.22(fp-ts@2.16.11) @@ -15794,22 +16466,22 @@ snapshots: dependencies: '@dynamic-labs/logger': 4.91.4 - '@dynamic-labs/embedded-wallet-evm@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76)': + '@dynamic-labs/embedded-wallet-evm@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3)': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 - '@dynamic-labs/embedded-wallet': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@dynamic-labs/embedded-wallet': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) '@dynamic-labs/sdk-api-core': 0.0.1046 '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) '@dynamic-labs/webauthn': 4.91.4 '@turnkey/api-key-stamper': 0.4.7 '@turnkey/iframe-stamper': 2.5.0 - '@turnkey/viem': 0.13.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) + '@turnkey/viem': 0.13.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) '@turnkey/webauthn-stamper': 0.5.1 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@dynamic-labs-wallet/primitives' - '@react-native-async-storage/async-storage' @@ -15826,14 +16498,14 @@ snapshots: - utf-8-validate - zod - '@dynamic-labs/embedded-wallet@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': + '@dynamic-labs/embedded-wallet@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 '@dynamic-labs/logger': 4.91.4 '@dynamic-labs/sdk-api-core': 0.0.1046 '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) '@dynamic-labs/webauthn': 4.91.4 '@turnkey/api-key-stamper': 0.4.7 '@turnkey/http': 3.10.0 @@ -15853,16 +16525,16 @@ snapshots: - react-native-passkey - utf-8-validate - '@dynamic-labs/ethereum-aa-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@dynamic-labs/ethereum-aa-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 - '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) '@dynamic-labs/sdk-api-core': 0.0.1046 '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@dynamic-labs-wallet/primitives' - '@react-native-async-storage/async-storage' @@ -15876,21 +16548,21 @@ snapshots: - react-native-passkey - utf-8-validate - '@dynamic-labs/ethereum-aa@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@zerodev/webauthn-key@5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@dynamic-labs/ethereum-aa@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@zerodev/webauthn-key@5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 - '@dynamic-labs/ethereum-aa-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@dynamic-labs/ethereum-aa-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) '@dynamic-labs/logger': 4.91.4 '@dynamic-labs/sdk-api-core': 0.0.1046 '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - '@zerodev/ecdsa-validator': 5.4.9(@zerodev/sdk@5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - '@zerodev/multi-chain-ecdsa-validator': 5.4.5(@zerodev/sdk@5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(@zerodev/webauthn-key@5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - '@zerodev/sdk': 5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@zerodev/ecdsa-validator': 5.4.9(@zerodev/sdk@5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@zerodev/multi-chain-ecdsa-validator': 5.4.5(@zerodev/sdk@5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(@zerodev/webauthn-key@5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@zerodev/sdk': 5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@dynamic-labs-wallet/primitives' - '@react-native-async-storage/async-storage' @@ -15905,7 +16577,7 @@ snapshots: - react-native-passkey - utf-8-validate - '@dynamic-labs/ethereum-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@dynamic-labs/ethereum-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 '@dynamic-labs/logger': 4.91.4 @@ -15914,8 +16586,8 @@ snapshots: '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@dynamic-labs-wallet/primitives' - '@react-native-async-storage/async-storage' @@ -15929,7 +16601,7 @@ snapshots: - react-native-passkey - utf-8-validate - '@dynamic-labs/ethereum-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@dynamic-labs/ethereum-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 '@dynamic-labs/logger': 4.91.4 @@ -15938,8 +16610,8 @@ snapshots: '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - viem: 2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + viem: 2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@dynamic-labs-wallet/primitives' - '@react-native-async-storage/async-storage' @@ -15953,25 +16625,25 @@ snapshots: - react-native-passkey - utf-8-validate - '@dynamic-labs/ethereum@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76)': + '@dynamic-labs/ethereum@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3)': dependencies: - '@coinbase/wallet-sdk': 4.3.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@dynamic-labs-connectors/base-account-evm': 4.6.9(@dynamic-labs/ethereum-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(@dynamic-labs/wallet-connector-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) - '@dynamic-labs-connectors/metamask-evm': 4.6.9(fae979a47c6480d6087d4faa1da013ff) + '@coinbase/wallet-sdk': 4.3.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@dynamic-labs-connectors/base-account-evm': 4.6.9(30aff48d6969f56fd45e702fc8c5a887) + '@dynamic-labs-connectors/metamask-evm': 4.6.9(e8ff8c7474d51c98957326bb7c6d4707) '@dynamic-labs/assert-package-version': 4.91.4 - '@dynamic-labs/embedded-wallet-evm': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) - '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@dynamic-labs/embedded-wallet-evm': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) + '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) '@dynamic-labs/logger': 4.91.4 '@dynamic-labs/rpc-providers': 4.91.4 '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 - '@dynamic-labs/waas-evm': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@dynamic-labs/waas-evm': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - '@walletconnect/ethereum-provider': 2.23.2(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@walletconnect/ethereum-provider': 2.23.2(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) buffer: 6.0.3 eventemitter3: 5.0.1 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -16022,11 +16694,11 @@ snapshots: sharp: 0.33.5 url: 0.11.0 - '@dynamic-labs/locale@4.91.4(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)': + '@dynamic-labs/locale@4.91.4(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 i18next: 23.4.6 - react-i18next: 13.5.0(i18next@23.4.6)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4) + react-i18next: 13.5.0(i18next@23.4.6)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4) transitivePeerDependencies: - react - react-dom @@ -16048,7 +16720,7 @@ snapshots: '@vue/reactivity': 3.5.35 eventemitter3: 5.0.1 - '@dynamic-labs/multi-wallet@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': + '@dynamic-labs/multi-wallet@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 '@dynamic-labs/rpc-providers': 4.91.4 @@ -16056,7 +16728,7 @@ snapshots: '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) tslib: 2.4.1 transitivePeerDependencies: - '@dynamic-labs-wallet/primitives' @@ -16082,23 +16754,23 @@ snapshots: '@dynamic-labs/sdk-api-core@0.0.985': {} - '@dynamic-labs/sdk-react-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': + '@dynamic-labs/sdk-react-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': dependencies: - '@dynamic-labs-sdk/client': 1.12.1(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - '@dynamic-labs-wallet/browser-wallet-client': 1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@dynamic-labs-sdk/client': 1.12.1(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs-wallet/browser-wallet-client': 1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(debug@4.4.3(supports-color@10.2.2)) '@dynamic-labs-wallet/forward-mpc-client': 0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@dynamic-labs/assert-package-version': 4.91.4 '@dynamic-labs/iconic': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/locale': 4.91.4(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4) + '@dynamic-labs/locale': 4.91.4(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4) '@dynamic-labs/logger': 4.91.4 - '@dynamic-labs/multi-wallet': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/multi-wallet': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) '@dynamic-labs/rpc-providers': 4.91.4 '@dynamic-labs/sdk-api-core': 0.0.1046 '@dynamic-labs/store': 4.91.4 '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) '@hcaptcha/react-hcaptcha': 1.4.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) '@thumbmarkjs/thumbmarkjs': 0.16.0 bs58: 5.0.0 @@ -16110,7 +16782,7 @@ snapshots: react: 19.1.4 react-dom: 19.1.4(react@19.1.4) react-focus-lock: 2.13.6(@types/react@19.1.7)(react@19.1.4) - react-i18next: 13.5.0(i18next@23.4.6)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4) + react-i18next: 13.5.0(i18next@23.4.6)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4) react-international-phone: 4.5.0(react@19.1.4) yup: 0.32.11 transitivePeerDependencies: @@ -16125,7 +16797,7 @@ snapshots: - react-native-passkey - utf-8-validate - '@dynamic-labs/solana-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': + '@dynamic-labs/solana-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 '@dynamic-labs/rpc-providers': 4.91.4 @@ -16133,7 +16805,7 @@ snapshots: '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) '@solana/spl-token': 0.4.14(@solana/web3.js@1.98.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(utf-8-validate@6.0.6) '@solana/web3.js': 1.98.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) eventemitter3: 5.0.1 @@ -16158,7 +16830,7 @@ snapshots: '@dynamic-labs/assert-package-version': 4.91.4 '@dynamic-labs/logger': 4.91.4 - '@dynamic-labs/sui-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': + '@dynamic-labs/sui-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 '@dynamic-labs/logger': 4.91.4 @@ -16167,7 +16839,7 @@ snapshots: '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) '@mysten/sui': 1.45.2(@typescript/typescript6@6.0.2) '@mysten/wallet-standard': 0.19.9(@typescript/typescript6@6.0.2) text-encoding: 0.7.0 @@ -16217,17 +16889,17 @@ snapshots: eventemitter3: 5.0.1 tldts: 6.0.16 - '@dynamic-labs/waas-evm@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@dynamic-labs/waas-evm@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 - '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) '@dynamic-labs/logger': 4.91.4 '@dynamic-labs/sdk-api-core': 0.0.1046 '@dynamic-labs/types': 4.91.4 '@dynamic-labs/utils': 4.91.4 - '@dynamic-labs/waas': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - viem: 2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@dynamic-labs/waas': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + viem: 2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@dynamic-labs-wallet/primitives' - '@gql.tada/svelte-support' @@ -16247,20 +16919,20 @@ snapshots: - utf-8-validate - zod - '@dynamic-labs/waas@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@dynamic-labs/waas@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: - '@dynamic-labs-sdk/client': 1.12.1(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - '@dynamic-labs-wallet/browser-wallet-client': 1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@dynamic-labs-sdk/client': 1.12.1(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs-wallet/browser-wallet-client': 1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(debug@4.4.3(supports-color@10.2.2)) '@dynamic-labs-wallet/forward-mpc-client': 0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@dynamic-labs/assert-package-version': 4.91.4 - '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) '@dynamic-labs/logger': 4.91.4 '@dynamic-labs/sdk-api-core': 0.0.1046 - '@dynamic-labs/solana-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - '@dynamic-labs/sui-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/solana-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/sui-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) '@dynamic-labs/utils': 4.91.4 '@dynamic-labs/wallet-book': 4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) transitivePeerDependencies: - '@dynamic-labs-wallet/primitives' - '@gql.tada/svelte-support' @@ -16280,20 +16952,20 @@ snapshots: - utf-8-validate - viem - '@dynamic-labs/wagmi-connector@4.91.4(cd9ebb1a64f614b48e624e4e0701fe2e)': + '@dynamic-labs/wagmi-connector@4.91.4(86bf20e8ca9767cde8328256d5f07007)': dependencies: '@dynamic-labs/assert-package-version': 4.91.4 - '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@dynamic-labs/ethereum-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) '@dynamic-labs/logger': 4.91.4 '@dynamic-labs/rpc-providers': 4.91.4 - '@dynamic-labs/sdk-react-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs/sdk-react-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(@types/react@19.1.7)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) '@dynamic-labs/types': 4.91.4 - '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@dynamic-labs/wallet-connector-core': 4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) eventemitter3: 5.0.1 react: 19.1.4 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) '@dynamic-labs/wallet-book@4.91.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4)': dependencies: @@ -16307,10 +16979,10 @@ snapshots: util: 0.12.5 zod: 4.0.5 - '@dynamic-labs/wallet-connector-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': + '@dynamic-labs/wallet-connector-core@4.91.4(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)': dependencies: - '@dynamic-labs-sdk/client': 1.12.1(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) - '@dynamic-labs-wallet/browser-wallet-client': 1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@dynamic-labs-sdk/client': 1.12.1(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6) + '@dynamic-labs-wallet/browser-wallet-client': 1.0.48(@dynamic-labs-wallet/forward-mpc-client@0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(debug@4.4.3(supports-color@10.2.2)) '@dynamic-labs-wallet/forward-mpc-client': 0.12.0(@dynamic-labs-wallet/primitives@1.0.48)(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@dynamic-labs/assert-package-version': 4.91.4 '@dynamic-labs/logger': 4.91.4 @@ -16365,9 +17037,9 @@ snapshots: tslib: 2.8.1 optional: true - '@emotion/babel-plugin@11.13.5': + '@emotion/babel-plugin@11.13.5(supports-color@10.2.2)': dependencies: - '@babel/helper-module-imports': 7.29.7 + '@babel/helper-module-imports': 7.29.7(supports-color@10.2.2) '@babel/runtime': 7.29.7 '@emotion/hash': 0.9.2 '@emotion/memoize': 0.9.0 @@ -16397,10 +17069,10 @@ snapshots: '@emotion/memoize@0.9.0': {} - '@emotion/react@11.14.0(@types/react@18.3.12)(react@19.1.4)': + '@emotion/react@11.14.0(@types/react@18.3.12)(react@19.1.4)(supports-color@10.2.2)': dependencies: '@babel/runtime': 7.29.7 - '@emotion/babel-plugin': 11.13.5 + '@emotion/babel-plugin': 11.13.5(supports-color@10.2.2) '@emotion/cache': 11.14.0 '@emotion/serialize': 1.3.3 '@emotion/use-insertion-effect-with-fallbacks': 1.2.0(react@19.1.4) @@ -16413,10 +17085,10 @@ snapshots: transitivePeerDependencies: - supports-color - '@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4)': + '@emotion/react@11.14.0(@types/react@19.1.7)(react@19.1.4)(supports-color@10.2.2)': dependencies: '@babel/runtime': 7.29.7 - '@emotion/babel-plugin': 11.13.5 + '@emotion/babel-plugin': 11.13.5(supports-color@10.2.2) '@emotion/cache': 11.14.0 '@emotion/serialize': 1.3.3 '@emotion/use-insertion-effect-with-fallbacks': 1.2.0(react@19.1.4) @@ -16449,177 +17121,185 @@ snapshots: '@emotion/weak-memoize@0.4.0': {} - '@esbuild/aix-ppc64@0.25.12': - optional: true - '@esbuild/aix-ppc64@0.28.1': optional: true - '@esbuild/android-arm64@0.25.12': - optional: true - '@esbuild/android-arm64@0.28.1': optional: true - '@esbuild/android-arm@0.25.12': - optional: true - '@esbuild/android-arm@0.28.1': optional: true - '@esbuild/android-x64@0.25.12': - optional: true - '@esbuild/android-x64@0.28.1': optional: true - '@esbuild/darwin-arm64@0.25.12': - optional: true - '@esbuild/darwin-arm64@0.28.1': optional: true - '@esbuild/darwin-x64@0.25.12': - optional: true - '@esbuild/darwin-x64@0.28.1': optional: true - '@esbuild/freebsd-arm64@0.25.12': - optional: true - '@esbuild/freebsd-arm64@0.28.1': optional: true - '@esbuild/freebsd-x64@0.25.12': - optional: true - '@esbuild/freebsd-x64@0.28.1': optional: true - '@esbuild/linux-arm64@0.25.12': - optional: true - '@esbuild/linux-arm64@0.28.1': optional: true - '@esbuild/linux-arm@0.25.12': - optional: true - '@esbuild/linux-arm@0.28.1': optional: true - '@esbuild/linux-ia32@0.25.12': - optional: true - '@esbuild/linux-ia32@0.28.1': optional: true - '@esbuild/linux-loong64@0.25.12': - optional: true - '@esbuild/linux-loong64@0.28.1': optional: true - '@esbuild/linux-mips64el@0.25.12': - optional: true - '@esbuild/linux-mips64el@0.28.1': optional: true - '@esbuild/linux-ppc64@0.25.12': - optional: true - '@esbuild/linux-ppc64@0.28.1': optional: true - '@esbuild/linux-riscv64@0.25.12': - optional: true - '@esbuild/linux-riscv64@0.28.1': optional: true - '@esbuild/linux-s390x@0.25.12': - optional: true - '@esbuild/linux-s390x@0.28.1': optional: true - '@esbuild/linux-x64@0.25.12': - optional: true - '@esbuild/linux-x64@0.28.1': optional: true - '@esbuild/netbsd-arm64@0.25.12': - optional: true - '@esbuild/netbsd-arm64@0.28.1': optional: true - '@esbuild/netbsd-x64@0.25.12': - optional: true - '@esbuild/netbsd-x64@0.28.1': optional: true - '@esbuild/openbsd-arm64@0.25.12': - optional: true - '@esbuild/openbsd-arm64@0.28.1': optional: true - '@esbuild/openbsd-x64@0.25.12': - optional: true - '@esbuild/openbsd-x64@0.28.1': optional: true - '@esbuild/openharmony-arm64@0.25.12': - optional: true - '@esbuild/openharmony-arm64@0.28.1': optional: true - '@esbuild/sunos-x64@0.25.12': - optional: true - '@esbuild/sunos-x64@0.28.1': optional: true - '@esbuild/win32-arm64@0.25.12': - optional: true - '@esbuild/win32-arm64@0.28.1': optional: true - '@esbuild/win32-ia32@0.25.12': - optional: true - '@esbuild/win32-ia32@0.28.1': optional: true - '@esbuild/win32-x64@0.25.12': - optional: true - '@esbuild/win32-x64@0.28.1': optional: true - '@eslint-community/eslint-utils@4.9.1(eslint@9.39.2)': + '@eslint-community/eslint-utils@4.9.1(eslint@9.39.2(supports-color@10.2.2))': dependencies: - eslint: 9.39.2 + eslint: 9.39.2(supports-color@10.2.2) eslint-visitor-keys: 3.4.3 '@eslint-community/regexpp@4.12.2': {} - '@eslint/compat@1.2.2(eslint@9.39.2)': - optionalDependencies: - eslint: 9.39.2 - - '@eslint/config-array@0.21.2': + '@eslint-react/ast@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/typescript-estree': 8.70.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + string-ts: 2.3.1 + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@eslint-react/core@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@eslint-react/ast': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/eslint': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/shared': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/var': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/scope-manager': 8.70.0 + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + ts-pattern: 5.9.0 + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@eslint-react/eslint-plugin@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@eslint-react/shared': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + eslint-plugin-react-dom: 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint-plugin-react-jsx: 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint-plugin-react-naming-convention: 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint-plugin-react-rsc: 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint-plugin-react-web-api: 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint-plugin-react-x: 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@eslint-react/eslint@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@eslint-react/jsx@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@eslint-react/ast': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/eslint': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/shared': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/var': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + ts-pattern: 5.9.0 + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@eslint-react/shared@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@eslint-react/eslint': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + ts-pattern: 5.9.0 + typescript: '@typescript/typescript6@6.0.2' + zod: 4.4.3 + transitivePeerDependencies: + - supports-color + + '@eslint-react/var@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@eslint-react/ast': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/eslint': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/scope-manager': 8.70.0 + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + ts-pattern: 5.9.0 + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@eslint/compat@1.2.2(eslint@9.39.2(supports-color@10.2.2))': + optionalDependencies: + eslint: 9.39.2(supports-color@10.2.2) + + '@eslint/config-array@0.21.2(supports-color@10.2.2)': dependencies: '@eslint/object-schema': 2.1.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) minimatch: 3.1.5 transitivePeerDependencies: - supports-color @@ -16632,10 +17312,10 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/eslintrc@3.3.5': + '@eslint/eslintrc@3.3.5(supports-color@10.2.2)': dependencies: ajv: 6.15.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) espree: 10.4.0 globals: 14.0.0 ignore: 5.3.2 @@ -16756,11 +17436,11 @@ snapshots: '@formkit/auto-animate@0.8.4': {} - '@gemini-wallet/core@0.3.2(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@gemini-wallet/core@0.3.2(supports-color@10.2.2)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: - '@metamask/rpc-errors': 7.0.2 + '@metamask/rpc-errors': 7.0.2(supports-color@10.2.2) eventemitter3: 5.0.1 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - supports-color @@ -16777,9 +17457,9 @@ snapshots: graphql: 16.14.0 typescript: '@typescript/typescript6@6.0.2' - '@graphiql/plugin-doc-explorer@0.2.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@20.16.7)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))': + '@graphiql/plugin-doc-explorer@0.2.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@24.13.4)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))': dependencies: - '@graphiql/react': 0.34.1(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@20.16.7)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) + '@graphiql/react': 0.34.1(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@24.13.4)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) '@headlessui/react': 2.2.10(react-dom@19.1.4(react@19.1.4))(react@19.1.4) graphql: 16.14.0 react: 19.1.4 @@ -16796,10 +17476,10 @@ snapshots: - immer - use-sync-external-store - '@graphiql/plugin-history@0.2.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@20.16.7)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))': + '@graphiql/plugin-history@0.2.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@24.13.4)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))': dependencies: - '@graphiql/react': 0.34.1(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@20.16.7)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) - '@graphiql/toolkit': 0.11.3(@types/node@20.16.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0) + '@graphiql/react': 0.34.1(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@24.13.4)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) + '@graphiql/toolkit': 0.11.3(@types/node@24.13.4)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0) react: 19.1.4 react-compiler-runtime: 19.1.0-rc.1(react@19.1.4) react-dom: 19.1.4(react@19.1.4) @@ -16815,9 +17495,9 @@ snapshots: - immer - use-sync-external-store - '@graphiql/react@0.34.1(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@20.16.7)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))': + '@graphiql/react@0.34.1(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@24.13.4)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))': dependencies: - '@graphiql/toolkit': 0.11.3(@types/node@20.16.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0) + '@graphiql/toolkit': 0.11.3(@types/node@24.13.4)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0) '@radix-ui/react-dialog': 1.1.15(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) '@radix-ui/react-dropdown-menu': 2.1.16(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) '@radix-ui/react-tooltip': 1.2.8(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) @@ -16847,11 +17527,11 @@ snapshots: - immer - use-sync-external-store - '@graphiql/toolkit@0.11.3(@types/node@20.16.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)': + '@graphiql/toolkit@0.11.3(@types/node@24.13.4)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)': dependencies: '@n1ru4l/push-pull-async-iterable-iterator': 3.2.0 graphql: 16.14.0 - meros: 1.3.2(@types/node@20.16.7) + meros: 1.3.2(@types/node@24.13.4) optionalDependencies: graphql-ws: 5.16.2(graphql@16.14.0) transitivePeerDependencies: @@ -16898,211 +17578,279 @@ snapshots: react-dom: 19.1.4(react@19.1.4) use-sync-external-store: 1.6.0(react@19.1.4) - '@helia/bitswap@2.2.0': + '@helia/bitswap@4.0.20(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6)': dependencies: - '@helia/interface': 5.4.0 - '@helia/utils': 1.4.0 - '@libp2p/interface': 2.11.0 - '@libp2p/logger': 5.2.0 - '@libp2p/peer-collections': 6.0.35 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 + '@helia/interface': 7.1.2 + '@helia/libp2p': 2.1.5(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6) + '@helia/utils': 3.0.6 + '@libp2p/interface': 3.3.0 + '@libp2p/logger': 6.2.13 + '@libp2p/peer-collections': 7.0.28 + '@libp2p/peer-id': 6.0.15 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 any-signal: 4.2.0 - interface-blockstore: 5.3.2 - interface-store: 6.0.3 + interface-blockstore: 7.0.1 + interface-store: 8.0.0 it-drain: 3.0.12 - it-length-prefixed: 10.0.2 + it-length-prefixed: 11.0.1 it-map: 3.1.6 - it-pipe: 3.0.1 + it-pushable: 3.2.4 it-take: 3.0.11 - multiformats: 13.4.2 + it-to-buffer: 5.0.0 + multiformats: 14.0.5 p-defer: 4.0.1 progress-events: 1.1.0 - protons-runtime: 5.6.0 + protons-runtime: 8.0.1 race-event: 1.6.1 - uint8-varint: 2.0.5 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 - - '@helia/block-brokers@4.2.4': - dependencies: - '@helia/bitswap': 2.2.0 - '@helia/interface': 5.4.0 - '@helia/utils': 1.4.0 - '@libp2p/interface': 2.11.0 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-matcher': 2.0.2 - '@multiformats/multiaddr-to-uri': 11.0.2 - interface-blockstore: 5.3.2 - interface-store: 6.0.3 - multiformats: 13.4.2 - progress-events: 1.1.0 - uint8arraylist: 2.4.9 + uint8-varint: 3.0.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 + transitivePeerDependencies: + - bufferutil + - react-native + - supports-color + - utf-8-validate - '@helia/car@4.2.0': + '@helia/car@6.0.9': dependencies: - '@helia/interface': 5.4.0 + '@helia/interface': 7.1.2 + '@helia/utils': 3.0.6 '@ipld/car': 5.4.6 '@ipld/dag-pb': 4.1.7 - '@libp2p/interface': 2.11.0 - '@libp2p/utils': 6.7.2 - interface-blockstore: 5.3.2 - ipfs-unixfs: 11.2.5 + '@libp2p/interface': 3.3.0 + '@libp2p/utils': 7.4.1 + any-signal: 4.2.0 + interface-blockstore: 7.0.1 + ipfs-unixfs: 13.1.2 + ipfs-unixfs-exporter: 16.2.3 it-drain: 3.0.12 it-map: 3.1.6 - multiformats: 13.4.2 - p-defer: 4.0.1 - p-queue: 8.1.1 + it-to-buffer: 5.0.0 + multiformats: 14.0.5 progress-events: 1.1.0 + race-signal: 2.0.0 + + '@helia/delegated-routing-client@1.0.7': + dependencies: + '@helia/delegated-routing-v1-http-api-client': 9.0.2 + '@helia/interface': 7.1.2 + '@libp2p/interface': 3.3.0 + it-first: 3.0.11 + it-map: 3.1.6 + multiformats: 14.0.5 + uint8arrays: 6.1.1 - '@helia/delegated-routing-v1-http-api-client@4.2.5': + '@helia/delegated-routing-v1-http-api-client@9.0.2': dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/logger': 5.2.0 - '@libp2p/peer-id': 5.1.9 - '@multiformats/multiaddr': 12.5.1 + '@libp2p/interface': 3.2.2 + '@libp2p/peer-id': 6.0.15 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 any-signal: 4.2.0 browser-readablestream-to-it: 2.0.12 - ipns: 10.1.6 it-first: 3.0.11 it-map: 3.1.6 - it-ndjson: 1.1.6 - multiformats: 13.4.2 - p-defer: 4.0.1 - p-queue: 8.1.1 - uint8arrays: 5.1.1 + it-ndjson: 2.0.0 + multiformats: 14.0.5 + race-signal: 2.0.2 + uint8arrays: 6.1.1 - '@helia/interface@5.4.0': + '@helia/dnslink@2.0.2': dependencies: - '@libp2p/interface': 2.11.0 + '@libp2p/interface': 3.3.0 '@multiformats/dns': 1.0.13 - '@multiformats/multiaddr': 12.5.1 - interface-blockstore: 5.3.2 - interface-datastore: 8.3.2 - interface-store: 6.0.3 - multiformats: 13.4.2 + multiformats: 14.0.5 progress-events: 1.1.0 + quick-lru: 7.3.0 - '@helia/ipns@8.2.4': + '@helia/fallback-router@1.1.2': dependencies: - '@helia/interface': 5.4.0 - '@libp2p/interface': 2.11.0 - '@libp2p/kad-dht': 15.1.11 - '@libp2p/logger': 5.2.0 - '@libp2p/peer-id': 5.1.9 - '@multiformats/dns': 1.0.13 - interface-datastore: 8.3.2 - ipns: 10.1.6 - multiformats: 13.4.2 + '@helia/interface': 7.1.2 + '@multiformats/uri-to-multiaddr': 10.0.0 + multiformats: 14.0.5 + uint8arrays: 6.1.1 + + '@helia/http@4.0.8': + dependencies: + '@helia/delegated-routing-client': 1.0.7 + '@helia/fallback-router': 1.1.2 + '@helia/interface': 7.1.2 + '@helia/trustless-gateway-client': 1.0.7 + + '@helia/interface@7.1.2': + dependencies: + '@ipshipyard/crypto': 1.1.0 + '@ipshipyard/keychain': 1.0.2 + '@libp2p/interface': 3.3.0 + '@multiformats/dns': 1.0.15 + '@multiformats/multiaddr': 13.0.3 + abort-error: 1.0.2 + birnam: 1.0.0 + interface-blockstore: 7.0.1 + interface-datastore: 10.0.1 + main-event: 1.0.4 + multiformats: 14.0.5 progress-events: 1.1.0 - uint8arrays: 5.1.1 - '@helia/routers@3.1.3': + '@helia/ipns@10.2.2': dependencies: - '@helia/delegated-routing-v1-http-api-client': 4.2.5 - '@helia/interface': 5.4.0 - '@libp2p/interface': 2.11.0 - '@libp2p/peer-id': 5.1.9 - '@multiformats/uri-to-multiaddr': 9.0.2 - ipns: 10.1.6 - it-first: 3.0.11 + '@helia/interface': 7.1.2 + '@ipld/dag-cbor': 10.0.1 + '@ipshipyard/crypto': 1.1.0 + '@ipshipyard/keychain': 1.0.2 + '@libp2p/fetch': 4.1.13 + '@libp2p/interface': 3.3.0 + '@libp2p/kad-dht': 16.4.5 + '@libp2p/logger': 6.2.13 + '@libp2p/peer-collections': 7.0.28 + '@libp2p/utils': 7.4.1 + abort-error: 1.0.2 + any-signal: 4.2.0 + delay: 7.0.0 + interface-datastore: 10.0.1 + multiformats: 14.0.5 + progress-events: 1.1.0 + protons-runtime: 8.0.1 + race-signal: 2.0.0 + timestamp-nano: 1.0.1 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 + + '@helia/libp2p@2.1.5(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6)': + dependencies: + '@helia/delegated-routing-client': 1.0.7 + '@helia/delegated-routing-v1-http-api-client': 9.0.2 + '@helia/interface': 7.1.2 + '@ipshipyard/libp2p-auto-tls': 2.0.2(supports-color@10.2.2) + '@libp2p/autonat': 3.0.28 + '@libp2p/bootstrap': 12.0.32 + '@libp2p/circuit-relay-v2': 4.2.13 + '@libp2p/config': 1.1.37 + '@libp2p/dcutr': 3.0.28 + '@libp2p/http': 2.0.6 + '@libp2p/identify': 4.1.14 + '@libp2p/interface': 3.3.0 + '@libp2p/kad-dht': 16.4.5 + '@libp2p/keychain': 6.1.7 + '@libp2p/mdns': 12.0.32 + '@libp2p/mplex': 12.0.32 + '@libp2p/noise': 17.0.3 + '@libp2p/peer-id': 6.0.15 + '@libp2p/ping': 3.1.13 + '@libp2p/tcp': 11.0.28 + '@libp2p/tls': 3.1.10 + '@libp2p/upnp-nat': 4.0.28 + '@libp2p/webrtc': 6.0.33(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2) + '@libp2p/websockets': 10.1.21(bufferutil@4.1.0)(utf-8-validate@6.0.6) + '@libp2p/yamux': 8.0.3 + '@multiformats/multiaddr': 13.0.3 + it-foreach: 2.1.7 it-map: 3.1.6 - multiformats: 13.4.2 - uint8arrays: 5.1.1 + libp2p: 3.3.11 + multiformats: 14.0.5 + uint8arrays: 6.1.1 + transitivePeerDependencies: + - bufferutil + - react-native + - supports-color + - utf-8-validate + + '@helia/trustless-gateway-client@1.0.7': + dependencies: + '@helia/interface': 7.1.2 + '@helia/utils': 3.0.6 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 + '@multiformats/multiaddr-to-uri': 12.0.0 + '@multiformats/uri-to-multiaddr': 10.0.0 + abort-error: 1.0.2 + birnam: 1.0.0 + multiformats: 14.0.5 + progress-events: 1.1.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@helia/unixfs@5.1.0': + '@helia/unixfs@8.0.9(supports-color@10.2.2)': dependencies: - '@helia/interface': 5.4.0 + '@helia/interface': 7.1.2 '@ipld/dag-pb': 4.1.7 - '@libp2p/interface': 2.11.0 - '@libp2p/logger': 5.2.0 - '@libp2p/utils': 6.7.2 + '@libp2p/interface': 3.3.0 + '@libp2p/logger': 6.2.13 + '@libp2p/utils': 7.4.1 '@multiformats/murmur3': 2.2.5 - hamt-sharding: 3.0.8 - interface-blockstore: 5.3.2 - ipfs-unixfs: 11.2.5 - ipfs-unixfs-exporter: 13.7.3 - ipfs-unixfs-importer: 15.4.0 + interface-blockstore: 7.0.1 + ipfs-unixfs: 13.1.2 + ipfs-unixfs-exporter: 16.2.3 + ipfs-unixfs-importer: 17.1.1(supports-color@10.2.2) it-all: 3.0.11 it-first: 3.0.11 it-glob: 3.0.6 it-last: 3.0.11 it-pipe: 3.0.1 - multiformats: 13.4.2 + it-to-buffer: 5.0.0 + multiformats: 14.0.5 progress-events: 1.1.0 sparse-array: 1.3.2 - uint8arrays: 5.1.1 + uint8arrays: 6.1.1 transitivePeerDependencies: - encoding - supports-color - '@helia/utils@1.4.0': + '@helia/utils@3.0.6': dependencies: - '@helia/interface': 5.4.0 - '@ipld/dag-cbor': 9.2.7 - '@ipld/dag-json': 10.2.9 - '@ipld/dag-pb': 4.1.7 - '@libp2p/interface': 2.11.0 - '@libp2p/keychain': 5.2.9 - '@libp2p/logger': 5.2.0 - '@libp2p/utils': 6.7.2 - '@multiformats/dns': 1.0.13 - '@multiformats/multiaddr': 12.5.1 - any-signal: 4.2.0 - blockstore-core: 5.0.4 - cborg: 4.5.8 - interface-blockstore: 5.3.2 - interface-datastore: 8.3.2 - interface-store: 6.0.3 - it-drain: 3.0.12 + '@helia/interface': 7.1.2 + '@libp2p/interface': 3.3.0 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 it-filter: 3.1.6 - it-foreach: 2.1.7 - it-merge: 3.0.14 - libp2p: 2.10.0 - mortice: 3.3.1 - multiformats: 13.4.2 + it-to-buffer: 5.0.0 + multiformats: 14.0.5 p-defer: 4.0.1 progress-events: 1.1.0 - uint8arrays: 5.1.1 - - '@helia/verified-fetch@2.6.12(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(utf-8-validate@6.0.6)': - dependencies: - '@helia/block-brokers': 4.2.4 - '@helia/car': 4.2.0 - '@helia/delegated-routing-v1-http-api-client': 4.2.5 - '@helia/interface': 5.4.0 - '@helia/ipns': 8.2.4 - '@helia/routers': 3.1.3 - '@helia/unixfs': 5.1.0 - '@ipld/dag-cbor': 9.2.7 - '@ipld/dag-json': 10.2.9 + race-signal: 2.0.2 + + '@helia/verified-fetch@8.1.2(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6)': + dependencies: + '@helia/bitswap': 4.0.20(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6) + '@helia/car': 6.0.9 + '@helia/delegated-routing-v1-http-api-client': 9.0.2 + '@helia/dnslink': 2.0.2 + '@helia/http': 4.0.8 + '@helia/interface': 7.1.2 + '@helia/ipns': 10.2.2 + '@helia/libp2p': 2.1.5(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6) + '@helia/unixfs': 8.0.9(supports-color@10.2.2) + '@ipld/dag-cbor': 10.0.1 + '@ipld/dag-json': 11.0.1 '@ipld/dag-pb': 4.1.7 - '@libp2p/interface': 2.11.0 - '@libp2p/kad-dht': 15.1.11 - '@libp2p/logger': 5.2.0 - '@libp2p/peer-id': 5.1.9 - '@libp2p/webrtc': 5.2.24(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)) - '@libp2p/websockets': 9.2.19(bufferutil@4.1.0)(utf-8-validate@6.0.6) + '@libp2p/interface': 3.2.2 + '@libp2p/peer-id': 6.0.15 + '@libp2p/utils': 7.4.1 + '@libp2p/webrtc': 6.0.33(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2) + '@libp2p/websockets': 10.1.21(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@multiformats/dns': 1.0.13 - abortable-iterator: 5.1.0 - cborg: 4.5.8 - file-type: 20.5.0 - hashlru: 2.3.0 - helia: 5.5.1(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(utf-8-validate@6.0.6) - interface-blockstore: 5.3.2 - interface-datastore: 8.3.2 - ipfs-unixfs-exporter: 13.7.3 - ipns: 10.1.6 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 + cborg: 6.1.3 + file-type: 22.1.1(supports-color@10.2.2) + helia: 7.1.16(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6) + interface-blockstore: 7.0.1 + ipfs-unixfs-exporter: 16.2.3 + it-first: 3.0.11 + it-last: 3.0.11 it-map: 3.1.6 it-pipe: 3.0.1 it-tar: 6.0.5 it-to-browser-readablestream: 2.0.14 - libp2p: 2.10.0 - lru-cache: 11.5.0 - multiformats: 13.4.2 + it-to-buffer: 5.0.0 + libp2p: 3.3.11 + multiformats: 14.0.5 progress-events: 1.1.0 - uint8arrays: 5.1.1 + quick-lru: 7.3.0 + regexp.escape: 2.0.1 + uint8arrays: 6.1.1 transitivePeerDependencies: - bufferutil - encoding @@ -17152,14 +17900,9 @@ snapshots: '@img/sharp-libvips-darwin-arm64': 1.0.4 optional: true - '@img/sharp-darwin-arm64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.2.4 - optional: true - - '@img/sharp-darwin-arm64@0.35.3': + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.3.2 + '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true '@img/sharp-darwin-x64@0.33.5': @@ -17167,103 +17910,68 @@ snapshots: '@img/sharp-libvips-darwin-x64': 1.0.4 optional: true - '@img/sharp-darwin-x64@0.34.5': + '@img/sharp-darwin-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.2.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true - '@img/sharp-darwin-x64@0.35.3': - optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.3.2 - optional: true - - '@img/sharp-freebsd-wasm32@0.35.3': + '@img/sharp-freebsd-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.3 + '@img/sharp-wasm32': 0.35.5 optional: true '@img/sharp-libvips-darwin-arm64@1.0.4': optional: true - '@img/sharp-libvips-darwin-arm64@1.2.4': - optional: true - - '@img/sharp-libvips-darwin-arm64@1.3.2': + '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true '@img/sharp-libvips-darwin-x64@1.0.4': optional: true - '@img/sharp-libvips-darwin-x64@1.2.4': - optional: true - - '@img/sharp-libvips-darwin-x64@1.3.2': + '@img/sharp-libvips-darwin-x64@1.3.4': optional: true '@img/sharp-libvips-linux-arm64@1.0.4': optional: true - '@img/sharp-libvips-linux-arm64@1.2.4': - optional: true - - '@img/sharp-libvips-linux-arm64@1.3.2': + '@img/sharp-libvips-linux-arm64@1.3.4': optional: true '@img/sharp-libvips-linux-arm@1.0.5': optional: true - '@img/sharp-libvips-linux-arm@1.2.4': - optional: true - - '@img/sharp-libvips-linux-arm@1.3.2': - optional: true - - '@img/sharp-libvips-linux-ppc64@1.2.4': - optional: true - - '@img/sharp-libvips-linux-ppc64@1.3.2': + '@img/sharp-libvips-linux-arm@1.3.4': optional: true - '@img/sharp-libvips-linux-riscv64@1.2.4': + '@img/sharp-libvips-linux-ppc64@1.3.4': optional: true - '@img/sharp-libvips-linux-riscv64@1.3.2': + '@img/sharp-libvips-linux-riscv64@1.3.4': optional: true '@img/sharp-libvips-linux-s390x@1.0.4': optional: true - '@img/sharp-libvips-linux-s390x@1.2.4': - optional: true - - '@img/sharp-libvips-linux-s390x@1.3.2': + '@img/sharp-libvips-linux-s390x@1.3.4': optional: true '@img/sharp-libvips-linux-x64@1.0.4': optional: true - '@img/sharp-libvips-linux-x64@1.2.4': - optional: true - - '@img/sharp-libvips-linux-x64@1.3.2': + '@img/sharp-libvips-linux-x64@1.3.4': optional: true '@img/sharp-libvips-linuxmusl-arm64@1.0.4': optional: true - '@img/sharp-libvips-linuxmusl-arm64@1.2.4': - optional: true - - '@img/sharp-libvips-linuxmusl-arm64@1.3.2': + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': optional: true '@img/sharp-libvips-linuxmusl-x64@1.0.4': optional: true - '@img/sharp-libvips-linuxmusl-x64@1.2.4': - optional: true - - '@img/sharp-libvips-linuxmusl-x64@1.3.2': + '@img/sharp-libvips-linuxmusl-x64@1.3.4': optional: true '@img/sharp-linux-arm64@0.33.5': @@ -17271,14 +17979,9 @@ snapshots: '@img/sharp-libvips-linux-arm64': 1.0.4 optional: true - '@img/sharp-linux-arm64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.2.4 - optional: true - - '@img/sharp-linux-arm64@0.35.3': + '@img/sharp-linux-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.3.2 + '@img/sharp-libvips-linux-arm64': 1.3.4 optional: true '@img/sharp-linux-arm@0.33.5': @@ -17286,34 +17989,19 @@ snapshots: '@img/sharp-libvips-linux-arm': 1.0.5 optional: true - '@img/sharp-linux-arm@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.2.4 - optional: true - - '@img/sharp-linux-arm@0.35.3': - optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.3.2 - optional: true - - '@img/sharp-linux-ppc64@0.34.5': + '@img/sharp-linux-arm@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-ppc64': 1.2.4 + '@img/sharp-libvips-linux-arm': 1.3.4 optional: true - '@img/sharp-linux-ppc64@0.35.3': + '@img/sharp-linux-ppc64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-ppc64': 1.3.2 + '@img/sharp-libvips-linux-ppc64': 1.3.4 optional: true - '@img/sharp-linux-riscv64@0.34.5': + '@img/sharp-linux-riscv64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-riscv64': 1.2.4 - optional: true - - '@img/sharp-linux-riscv64@0.35.3': - optionalDependencies: - '@img/sharp-libvips-linux-riscv64': 1.3.2 + '@img/sharp-libvips-linux-riscv64': 1.3.4 optional: true '@img/sharp-linux-s390x@0.33.5': @@ -17321,14 +18009,9 @@ snapshots: '@img/sharp-libvips-linux-s390x': 1.0.4 optional: true - '@img/sharp-linux-s390x@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.2.4 - optional: true - - '@img/sharp-linux-s390x@0.35.3': + '@img/sharp-linux-s390x@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.3.2 + '@img/sharp-libvips-linux-s390x': 1.3.4 optional: true '@img/sharp-linux-x64@0.33.5': @@ -17336,14 +18019,9 @@ snapshots: '@img/sharp-libvips-linux-x64': 1.0.4 optional: true - '@img/sharp-linux-x64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.2.4 - optional: true - - '@img/sharp-linux-x64@0.35.3': + '@img/sharp-linux-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.3.2 + '@img/sharp-libvips-linux-x64': 1.3.4 optional: true '@img/sharp-linuxmusl-arm64@0.33.5': @@ -17351,14 +18029,9 @@ snapshots: '@img/sharp-libvips-linuxmusl-arm64': 1.0.4 optional: true - '@img/sharp-linuxmusl-arm64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.2.4 - optional: true - - '@img/sharp-linuxmusl-arm64@0.35.3': + '@img/sharp-linuxmusl-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.3.2 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 optional: true '@img/sharp-linuxmusl-x64@0.33.5': @@ -17366,14 +18039,9 @@ snapshots: '@img/sharp-libvips-linuxmusl-x64': 1.0.4 optional: true - '@img/sharp-linuxmusl-x64@0.34.5': + '@img/sharp-linuxmusl-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.2.4 - optional: true - - '@img/sharp-linuxmusl-x64@0.35.3': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.3.2 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 optional: true '@img/sharp-wasm32@0.33.5': @@ -17381,44 +18049,149 @@ snapshots: '@emnapi/runtime': 1.10.0 optional: true - '@img/sharp-wasm32@0.34.5': - dependencies: - '@emnapi/runtime': 1.10.0 - optional: true - - '@img/sharp-wasm32@0.35.3': + '@img/sharp-wasm32@0.35.5': dependencies: '@emnapi/runtime': 1.11.3 optional: true - '@img/sharp-webcontainers-wasm32@0.35.3': + '@img/sharp-webcontainers-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.3 - optional: true - - '@img/sharp-win32-arm64@0.34.5': + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-win32-arm64@0.35.3': + '@img/sharp-win32-arm64@0.35.5': optional: true '@img/sharp-win32-ia32@0.33.5': optional: true - '@img/sharp-win32-ia32@0.34.5': - optional: true - - '@img/sharp-win32-ia32@0.35.3': + '@img/sharp-win32-ia32@0.35.5': optional: true '@img/sharp-win32-x64@0.33.5': optional: true - '@img/sharp-win32-x64@0.34.5': + '@img/sharp-win32-x64@0.35.5': optional: true - '@img/sharp-win32-x64@0.35.3': - optional: true + '@inquirer/ansi@2.0.7': {} + + '@inquirer/checkbox@5.2.2(@types/node@24.13.4)': + dependencies: + '@inquirer/ansi': 2.0.7 + '@inquirer/core': 12.0.0(@types/node@24.13.4) + '@inquirer/figures': 2.0.8 + '@inquirer/type': 4.0.7(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/confirm@6.2.0(@types/node@24.13.4)': + dependencies: + '@inquirer/core': 12.0.0(@types/node@24.13.4) + '@inquirer/type': 4.0.7(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/core@12.0.0(@types/node@24.13.4)': + dependencies: + '@inquirer/ansi': 2.0.7 + '@inquirer/figures': 2.0.8 + '@inquirer/type': 4.0.7(@types/node@24.13.4) + cli-width: 4.1.0 + fast-wrap-ansi: 0.2.2 + mute-stream: 3.0.0 + signal-exit: 4.1.0 + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/editor@5.3.0(@types/node@24.13.4)': + dependencies: + '@inquirer/core': 12.0.0(@types/node@24.13.4) + '@inquirer/external-editor': 3.0.4(@types/node@24.13.4) + '@inquirer/type': 4.0.7(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/expand@5.1.2(@types/node@24.13.4)': + dependencies: + '@inquirer/core': 12.0.0(@types/node@24.13.4) + '@inquirer/type': 4.0.7(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/external-editor@3.0.4(@types/node@24.13.4)': + dependencies: + chardet: 2.2.0 + iconv-lite: 0.7.3 + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/figures@2.0.8': {} + + '@inquirer/input@5.1.3(@types/node@24.13.4)': + dependencies: + '@inquirer/core': 12.0.0(@types/node@24.13.4) + '@inquirer/type': 4.0.7(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/number@4.2.0(@types/node@24.13.4)': + dependencies: + '@inquirer/core': 12.0.0(@types/node@24.13.4) + '@inquirer/type': 4.0.7(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/password@5.1.2(@types/node@24.13.4)': + dependencies: + '@inquirer/ansi': 2.0.7 + '@inquirer/core': 12.0.0(@types/node@24.13.4) + '@inquirer/type': 4.0.7(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/prompts@8.6.0(@types/node@24.13.4)': + dependencies: + '@inquirer/checkbox': 5.2.2(@types/node@24.13.4) + '@inquirer/confirm': 6.2.0(@types/node@24.13.4) + '@inquirer/editor': 5.3.0(@types/node@24.13.4) + '@inquirer/expand': 5.1.2(@types/node@24.13.4) + '@inquirer/input': 5.1.3(@types/node@24.13.4) + '@inquirer/number': 4.2.0(@types/node@24.13.4) + '@inquirer/password': 5.1.2(@types/node@24.13.4) + '@inquirer/rawlist': 5.3.2(@types/node@24.13.4) + '@inquirer/search': 4.3.0(@types/node@24.13.4) + '@inquirer/select': 5.2.2(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/rawlist@5.3.2(@types/node@24.13.4)': + dependencies: + '@inquirer/core': 12.0.0(@types/node@24.13.4) + '@inquirer/type': 4.0.7(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/search@4.3.0(@types/node@24.13.4)': + dependencies: + '@inquirer/core': 12.0.0(@types/node@24.13.4) + '@inquirer/figures': 2.0.8 + '@inquirer/type': 4.0.7(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/select@5.2.2(@types/node@24.13.4)': + dependencies: + '@inquirer/ansi': 2.0.7 + '@inquirer/core': 12.0.0(@types/node@24.13.4) + '@inquirer/figures': 2.0.8 + '@inquirer/type': 4.0.7(@types/node@24.13.4) + optionalDependencies: + '@types/node': 24.13.4 + + '@inquirer/type@4.0.7(@types/node@24.13.4)': + optionalDependencies: + '@types/node': 24.13.4 '@internationalized/date@3.12.2': dependencies: @@ -17436,54 +18209,67 @@ snapshots: dependencies: '@ipld/dag-cbor': 10.0.1 cborg: 5.1.1 - multiformats: 14.0.0 + multiformats: 14.0.5 varint: 6.0.0 '@ipld/dag-cbor@10.0.1': dependencies: cborg: 5.1.1 - multiformats: 14.0.0 - - '@ipld/dag-cbor@9.2.7': - dependencies: - cborg: 5.1.1 - multiformats: 13.4.2 + multiformats: 14.0.5 - '@ipld/dag-json@10.2.9': + '@ipld/dag-json@11.0.1': dependencies: - cborg: 5.1.1 - multiformats: 13.4.2 + cborg: 6.1.3 + multiformats: 14.0.5 '@ipld/dag-pb@4.1.7': dependencies: - multiformats: 14.0.0 + multiformats: 14.0.5 - '@ipshipyard/libp2p-auto-tls@1.0.0': + '@ipld/dag-pb@4.2.0': dependencies: - '@chainsafe/is-ip': 2.1.0 - '@libp2p/crypto': 5.1.18 - '@libp2p/http-fetch': 2.2.2 - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/keychain': 5.2.9 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-matcher': 1.8.0 - '@peculiar/x509': 1.14.3 - acme-client: 5.4.0 - any-signal: 4.2.0 - delay: 6.0.0 - interface-datastore: 8.3.2 - multiformats: 13.4.2 - uint8arrays: 5.1.1 - transitivePeerDependencies: - - supports-color + multiformats: 14.0.5 - '@ipshipyard/node-datachannel@0.26.6': + '@ipshipyard/crypto@1.1.0': dependencies: - prebuild-install: 7.1.3 + abort-error: 1.0.2 + multiformats: 14.0.5 + protons-runtime: 7.1.2 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@isaacs/cliui@8.0.2': + '@ipshipyard/keychain@1.0.2': + dependencies: + '@ipshipyard/crypto': 1.1.0 + abort-error: 1.0.2 + interface-datastore: 10.0.1 + multiformats: 14.0.5 + sanitize-filename: 1.6.4 + uint8arrays: 6.1.1 + + '@ipshipyard/libp2p-auto-tls@2.0.2(supports-color@10.2.2)': + dependencies: + '@chainsafe/is-ip': 2.1.0 + '@libp2p/crypto': 5.1.18 + '@libp2p/http': 2.0.6 + '@libp2p/interface': 3.2.2 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/keychain': 6.1.1 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 + '@peculiar/x509': 2.1.0 + acme-client: 5.4.0(supports-color@10.2.2) + any-signal: 4.2.0 + delay: 7.0.0 + interface-datastore: 10.0.1 + multiformats: 14.0.5 + reflect-metadata: 0.2.2 + uint8arrays: 6.1.1 + transitivePeerDependencies: + - supports-color + + '@isaacs/cliui@8.0.2': dependencies: string-width: 5.1.2 string-width-cjs: string-width@4.2.3 @@ -17503,13 +18289,13 @@ snapshots: '@jest/schemas': 29.6.3 '@types/istanbul-lib-coverage': 2.0.6 '@types/istanbul-reports': 3.0.4 - '@types/node': 22.12.0 + '@types/node': 24.13.4 '@types/yargs': 17.0.35 chalk: 4.1.2 '@jridgewell/gen-mapping@0.3.13': dependencies: - '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/sourcemap-codec': 1.6.0 '@jridgewell/trace-mapping': 0.3.31 '@jridgewell/remapping@2.3.5': @@ -17526,15 +18312,12 @@ snapshots: '@jridgewell/sourcemap-codec@1.5.5': {} - '@jridgewell/trace-mapping@0.3.31': - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/sourcemap-codec@1.6.0': {} - '@jridgewell/trace-mapping@0.3.9': + '@jridgewell/trace-mapping@0.3.31': dependencies: '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/sourcemap-codec': 1.6.0 '@js-sdsl/ordered-map@4.4.2': {} @@ -17554,158 +18337,211 @@ snapshots: dependencies: '@lezer/common': 1.5.2 - '@libp2p/autonat@2.0.38': + '@libp2p/autonat@3.0.28': dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/peer-collections': 6.0.35 - '@libp2p/peer-id': 5.1.9 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/peer-collections': 7.0.28 + '@libp2p/peer-id': 6.0.15 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 any-signal: 4.2.0 - it-protobuf-stream: 2.0.6 main-event: 1.0.4 - multiformats: 13.4.2 - protons-runtime: 5.6.0 - uint8arraylist: 2.4.9 + multiformats: 14.0.5 + protons-runtime: 7.1.2 + uint8arraylist: 3.0.2 - '@libp2p/bootstrap@11.0.47': + '@libp2p/bootstrap@12.0.32': dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/peer-id': 5.1.9 - '@multiformats/mafmt': 12.1.6 - '@multiformats/multiaddr': 12.5.1 + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/peer-id': 6.0.15 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 main-event: 1.0.4 - '@libp2p/circuit-relay-v2@3.2.24': + '@libp2p/circuit-relay-v2@4.2.13': dependencies: - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/peer-collections': 6.0.35 - '@libp2p/peer-id': 5.1.9 - '@libp2p/peer-record': 8.0.35 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-matcher': 2.0.2 + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/peer-collections': 7.0.28 + '@libp2p/peer-id': 6.0.15 + '@libp2p/peer-record': 9.0.16 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 any-signal: 4.2.0 - it-protobuf-stream: 2.0.6 - it-stream-types: 2.0.4 main-event: 1.0.4 - multiformats: 13.4.2 - nanoid: 5.1.11 + multiformats: 14.0.5 + nanoid: 6.0.2 progress-events: 1.1.0 - protons-runtime: 5.6.0 + protons-runtime: 7.1.2 retimeable-signal: 1.0.1 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/config@1.1.31': + '@libp2p/config@1.1.37': dependencies: - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 3.2.2 - '@libp2p/keychain': 6.1.1 - '@libp2p/logger': 6.2.7 - interface-datastore: 9.0.3 + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@libp2p/keychain': 6.1.7 + '@libp2p/logger': 6.2.13 + interface-datastore: 10.0.1 '@libp2p/crypto@5.1.18': dependencies: '@libp2p/interface': 3.2.2 '@noble/curves': 2.2.0 - '@noble/hashes': 1.8.0 + '@noble/hashes': 2.4.0 multiformats: 13.4.2 protons-runtime: 6.0.2 uint8arraylist: 2.4.9 uint8arrays: 5.1.1 - '@libp2p/dcutr@2.0.38': + '@libp2p/crypto@5.1.23': dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-matcher': 2.0.2 - delay: 6.0.0 - it-protobuf-stream: 2.0.6 - protons-runtime: 5.6.0 - uint8arraylist: 2.4.9 + '@libp2p/interface': 3.3.0 + '@noble/curves': 2.2.0 + '@noble/hashes': 2.4.0 + multiformats: 14.0.5 + protons-runtime: 7.1.2 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/http-fetch@2.2.2': + '@libp2p/dcutr@3.0.28': + dependencies: + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 + delay: 7.0.0 + protons-runtime: 7.1.2 + uint8arraylist: 3.0.2 + + '@libp2p/fetch@4.1.13': + dependencies: + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/utils': 7.4.1 + main-event: 1.0.4 + protons-runtime: 7.1.2 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 + + '@libp2p/http-fetch@4.0.4': dependencies: '@achingbrain/http-parser-js': 0.5.9 - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/peer-id': 5.1.9 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-to-uri': 11.0.2 - http-cookie-agent: 6.0.8(tough-cookie@5.1.2)(undici@6.26.0) - p-defer: 4.0.1 - tough-cookie: 5.1.2 - uint8-varint: 2.0.5 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 - undici: 6.26.0 + '@libp2p/http-utils': 2.0.6 + '@libp2p/interface': 3.2.2 + uint8arrays: 6.1.1 - '@libp2p/identify@3.0.39': + '@libp2p/http-peer-id-auth@2.0.3': dependencies: '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/peer-id': 5.1.9 - '@libp2p/peer-record': 8.0.35 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-matcher': 2.0.2 + '@libp2p/interface': 3.2.2 + '@libp2p/peer-id': 6.0.15 + uint8-varint: 3.0.0 + uint8arrays: 6.1.1 + + '@libp2p/http-utils@2.0.6': + dependencies: + '@achingbrain/http-parser-js': 0.5.9 + '@libp2p/interface': 3.2.2 + '@libp2p/peer-id': 6.0.15 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-to-uri': 12.0.0 + '@multiformats/uri-to-multiaddr': 10.0.0 + it-to-browser-readablestream: 2.0.14 + multiformats: 14.0.5 + race-event: 1.6.1 + readable-stream: 4.7.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 + + '@libp2p/http-websocket@2.0.4': + dependencies: + '@achingbrain/http-parser-js': 0.5.9 + '@libp2p/http-utils': 2.0.6 + '@libp2p/interface': 3.2.2 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + multiformats: 14.0.5 + race-event: 1.6.1 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 + + '@libp2p/http@2.0.6': + dependencies: + '@libp2p/http-fetch': 4.0.4 + '@libp2p/http-peer-id-auth': 2.0.3 + '@libp2p/http-utils': 2.0.6 + '@libp2p/http-websocket': 2.0.4 + '@libp2p/interface': 3.2.2 + '@libp2p/interface-internal': 3.1.13 + '@multiformats/multiaddr': 13.0.3 + cookie: 1.1.1 + undici: 8.11.2 + + '@libp2p/identify@4.1.14': + dependencies: + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/peer-id': 6.0.15 + '@libp2p/peer-record': 9.0.16 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 it-drain: 3.0.12 it-parallel: 3.0.15 - it-protobuf-stream: 2.0.6 main-event: 1.0.4 - protons-runtime: 5.6.0 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + protons-runtime: 7.1.2 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/interface-internal@2.3.19': + '@libp2p/interface-internal@3.1.13': dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/peer-collections': 6.0.35 - '@multiformats/multiaddr': 12.5.1 + '@libp2p/interface': 3.3.0 + '@libp2p/peer-collections': 7.0.28 + '@multiformats/multiaddr': 13.0.3 progress-events: 1.1.0 - '@libp2p/interface@2.11.0': + '@libp2p/interface@3.2.2': dependencies: '@multiformats/dns': 1.0.13 - '@multiformats/multiaddr': 12.5.1 - it-pushable: 3.2.4 - it-stream-types: 2.0.4 + '@multiformats/multiaddr': 13.0.3 main-event: 1.0.4 multiformats: 13.4.2 progress-events: 1.1.0 uint8arraylist: 2.4.9 - '@libp2p/interface@3.2.2': + '@libp2p/interface@3.3.0': dependencies: - '@multiformats/dns': 1.0.13 + '@multiformats/dns': 1.0.15 '@multiformats/multiaddr': 13.0.3 main-event: 1.0.4 - multiformats: 13.4.2 + multiformats: 14.0.5 progress-events: 1.1.0 - uint8arraylist: 2.4.9 + uint8arraylist: 3.0.2 - '@libp2p/kad-dht@15.1.11': + '@libp2p/kad-dht@16.4.5': dependencies: - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/peer-collections': 6.0.35 - '@libp2p/peer-id': 5.1.9 - '@libp2p/ping': 2.0.37 - '@libp2p/record': 4.0.12 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/peer-collections': 7.0.28 + '@libp2p/peer-id': 6.0.15 + '@libp2p/ping': 3.1.13 + '@libp2p/record': 4.0.15 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 any-signal: 4.2.0 - interface-datastore: 8.3.2 + interface-datastore: 10.0.1 it-all: 3.0.11 it-drain: 3.0.12 it-length: 3.0.11 @@ -17713,49 +18549,47 @@ snapshots: it-merge: 3.0.14 it-parallel: 3.0.15 it-pipe: 3.0.1 - it-protobuf-stream: 2.0.6 it-pushable: 3.2.4 it-take: 3.0.11 main-event: 1.0.4 - multiformats: 13.4.2 + multiformats: 14.0.5 p-defer: 4.0.1 - p-event: 6.0.1 + p-event: 7.1.1 progress-events: 1.1.0 - protons-runtime: 5.6.0 - race-signal: 1.1.3 - uint8-varint: 2.0.5 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + protons-runtime: 7.1.2 + race-signal: 2.0.0 + uint8-varint: 3.0.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/keychain@5.2.9': + '@libp2p/keychain@6.1.1': dependencies: '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/utils': 6.7.2 - '@noble/hashes': 1.8.0 + '@libp2p/interface': 3.2.2 + '@noble/hashes': 2.4.0 asn1js: 3.0.10 - interface-datastore: 8.3.2 + interface-datastore: 9.0.3 multiformats: 13.4.2 sanitize-filename: 1.6.4 uint8arrays: 5.1.1 - '@libp2p/keychain@6.1.1': + '@libp2p/keychain@6.1.7': dependencies: - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 3.2.2 - '@noble/hashes': 1.8.0 + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@noble/hashes': 2.4.0 asn1js: 3.0.10 - interface-datastore: 9.0.3 - multiformats: 13.4.2 + interface-datastore: 10.0.1 + multiformats: 14.0.5 sanitize-filename: 1.6.4 - uint8arrays: 5.1.1 + uint8arrays: 6.1.1 - '@libp2p/logger@5.2.0': + '@libp2p/logger@6.2.13': dependencies: - '@libp2p/interface': 2.11.0 - '@multiformats/multiaddr': 12.5.1 - interface-datastore: 8.3.2 - multiformats: 13.4.2 + '@libp2p/interface': 3.3.0 + '@multiformats/multiaddr': 13.0.3 + interface-datastore: 10.0.1 + multiformats: 14.0.5 weald: 1.1.3 '@libp2p/logger@6.2.7': @@ -17766,229 +18600,250 @@ snapshots: multiformats: 13.4.2 weald: 1.1.3 - '@libp2p/mdns@11.0.47': + '@libp2p/mdns@12.0.32': dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/peer-id': 5.1.9 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/peer-id': 6.0.15 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 '@types/multicast-dns': 7.2.4 dns-packet: 5.6.1 main-event: 1.0.4 multicast-dns: 7.2.5 - '@libp2p/mplex@11.0.47': + '@libp2p/mplex@12.0.32': dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/utils': 6.7.2 - it-pipe: 3.0.1 + '@libp2p/interface': 3.3.0 + '@libp2p/utils': 7.4.1 it-pushable: 3.2.4 - it-stream-types: 2.0.4 - uint8-varint: 2.0.5 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + uint8-varint: 3.0.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/multistream-select@6.0.29': + '@libp2p/multistream-select@7.0.28': dependencies: - '@libp2p/interface': 2.11.0 - it-length-prefixed: 10.0.2 - it-length-prefixed-stream: 2.0.6 - it-stream-types: 2.0.4 - p-defer: 4.0.1 - race-signal: 1.1.3 - uint8-varint: 2.0.5 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + '@libp2p/interface': 3.3.0 + '@libp2p/utils': 7.4.1 + it-length-prefixed: 11.0.1 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/peer-collections@6.0.35': + '@libp2p/noise@17.0.3': dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/peer-id': 5.1.9 - '@libp2p/utils': 6.7.2 - multiformats: 13.4.2 + '@chainsafe/as-chacha20poly1305': 0.1.0 + '@chainsafe/as-sha256': 1.2.4 + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@libp2p/peer-id': 6.0.15 + '@libp2p/utils': 7.4.1 + '@noble/ciphers': 2.4.0 + '@noble/curves': 2.2.0 + '@noble/hashes': 2.4.0 + protons-runtime: 7.1.2 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 + wherearewe: 2.0.1 - '@libp2p/peer-id@5.1.9': + '@libp2p/peer-collections@7.0.28': dependencies: - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - multiformats: 13.4.2 - uint8arrays: 5.1.1 + '@libp2p/interface': 3.3.0 + '@libp2p/peer-id': 6.0.15 + '@libp2p/utils': 7.4.1 + multiformats: 14.0.5 - '@libp2p/peer-record@8.0.35': + '@libp2p/peer-id@6.0.15': dependencies: - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/peer-id': 5.1.9 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 - multiformats: 13.4.2 - protons-runtime: 5.6.0 - uint8-varint: 2.0.5 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + multiformats: 14.0.5 + uint8arrays: 6.1.1 - '@libp2p/peer-store@11.2.7': + '@libp2p/peer-record@9.0.16': dependencies: - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/peer-collections': 6.0.35 - '@libp2p/peer-id': 5.1.9 - '@libp2p/peer-record': 8.0.35 - '@multiformats/multiaddr': 12.5.1 - interface-datastore: 8.3.2 + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@libp2p/peer-id': 6.0.15 + '@multiformats/multiaddr': 13.0.3 + multiformats: 14.0.5 + protons-runtime: 7.1.2 + uint8-varint: 3.0.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 + + '@libp2p/peer-store@12.0.28': + dependencies: + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@libp2p/peer-collections': 7.0.28 + '@libp2p/peer-id': 6.0.15 + '@libp2p/peer-record': 9.0.16 + '@multiformats/multiaddr': 13.0.3 + interface-datastore: 10.0.1 it-all: 3.0.11 main-event: 1.0.4 mortice: 3.3.1 - multiformats: 13.4.2 - protons-runtime: 5.6.0 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + multiformats: 14.0.5 + protons-runtime: 7.1.2 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/ping@2.0.37': + '@libp2p/ping@3.1.13': dependencies: - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@multiformats/multiaddr': 12.5.1 - it-byte-stream: 2.0.6 - main-event: 1.0.4 - uint8arrays: 5.1.1 + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + p-event: 7.1.1 + race-signal: 2.0.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/record@4.0.12': + '@libp2p/record@4.0.15': dependencies: - protons-runtime: 6.0.2 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + protons-runtime: 7.1.2 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/tcp@10.1.19': + '@libp2p/tcp@11.0.28': dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-matcher': 2.0.2 - '@types/sinon': 17.0.4 + '@libp2p/interface': 3.3.0 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 main-event: 1.0.4 - p-defer: 4.0.1 - p-event: 6.0.1 + p-event: 7.1.1 progress-events: 1.1.0 - race-event: 1.6.1 - stream-to-it: 1.0.1 + uint8arraylist: 3.0.2 - '@libp2p/tls@2.2.7': + '@libp2p/tls@3.1.10': dependencies: - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/peer-id': 5.1.9 + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@libp2p/peer-id': 6.0.15 + '@libp2p/utils': 7.4.1 '@peculiar/asn1-schema': 2.7.0 '@peculiar/asn1-x509': 2.7.0 '@peculiar/webcrypto': 1.7.1 - '@peculiar/x509': 1.14.3 + '@peculiar/x509': 2.1.0 asn1js: 3.0.10 - it-queueless-pushable: 2.0.5 - it-stream-types: 2.0.4 - protons-runtime: 5.6.0 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + p-event: 7.1.1 + protons-runtime: 7.1.2 + reflect-metadata: 0.2.2 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/upnp-nat@3.1.22': + '@libp2p/upnp-nat@4.0.28': dependencies: '@achingbrain/nat-port-mapper': 4.0.5 '@chainsafe/is-ip': 2.1.0 - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-matcher': 2.0.2 + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 main-event: 1.0.4 p-defer: 4.0.1 - race-signal: 1.1.3 + race-signal: 2.0.0 - '@libp2p/utils@6.7.2': + '@libp2p/utils@7.4.1': dependencies: '@chainsafe/is-ip': 2.1.0 '@chainsafe/netmask': 2.0.0 - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/logger': 5.2.0 - '@multiformats/multiaddr': 12.5.1 + '@libp2p/interface': 3.3.0 + '@libp2p/logger': 6.2.13 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 '@sindresorhus/fnv1a': 3.1.0 any-signal: 4.2.0 - delay: 6.0.0 - get-iterator: 2.0.1 + cborg: 6.1.3 + delay: 7.0.0 is-loopback-addr: 2.0.2 - is-plain-obj: 4.1.0 - it-foreach: 2.1.7 + it-length-prefixed: 11.0.1 it-pipe: 3.0.1 it-pushable: 3.2.4 it-stream-types: 2.0.4 main-event: 1.0.4 netmask: 2.1.1 p-defer: 4.0.1 - race-event: 1.6.1 - race-signal: 1.1.3 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + p-event: 7.1.1 + progress-events: 1.1.0 + protons-runtime: 7.1.2 + race-signal: 2.0.0 + uint8-varint: 3.0.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 - '@libp2p/webrtc@5.2.24(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))': + '@libp2p/webrtc@6.0.33(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)': dependencies: '@chainsafe/is-ip': 2.1.0 - '@chainsafe/libp2p-noise': 16.1.5 - '@ipshipyard/node-datachannel': 0.26.6 - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/keychain': 5.2.9 - '@libp2p/peer-id': 5.1.9 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-matcher': 2.0.2 + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/keychain': 6.1.7 + '@libp2p/noise': 17.0.3 + '@libp2p/peer-id': 6.0.15 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 '@peculiar/webcrypto': 1.7.1 - '@peculiar/x509': 1.14.3 - any-signal: 4.2.0 - detect-browser: 5.3.0 + '@peculiar/x509': 2.1.0 get-port: 7.2.0 - interface-datastore: 8.3.2 - it-length-prefixed: 10.0.2 - it-protobuf-stream: 2.0.6 + interface-datastore: 10.0.1 + it-length-prefixed: 11.0.1 + it-protobuf-stream: 3.0.1 it-pushable: 3.2.4 it-stream-types: 2.0.4 main-event: 1.0.4 - multiformats: 13.4.2 + multiformats: 14.0.5 + node-datachannel: 0.33.4 p-defer: 4.0.1 - p-timeout: 6.1.4 - p-wait-for: 5.0.2 + p-event: 7.1.1 + p-timeout: 7.0.1 + p-wait-for: 6.0.0 progress-events: 1.1.0 - protons-runtime: 5.6.0 - race-event: 1.6.1 - race-signal: 1.1.3 - react-native-webrtc: 124.0.7(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)) - uint8-varint: 2.0.5 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + protons-runtime: 7.1.2 + race-signal: 2.0.0 + react-native-webrtc: 124.0.7(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2) + reflect-metadata: 0.2.2 + uint8-varint: 3.0.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 transitivePeerDependencies: - react-native - supports-color - '@libp2p/websockets@9.2.19(bufferutil@4.1.0)(utf-8-validate@6.0.6)': + '@libp2p/websockets@10.1.21(bufferutil@4.1.0)(utf-8-validate@6.0.6)': dependencies: - '@libp2p/interface': 2.11.0 - '@libp2p/utils': 6.7.2 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-matcher': 2.0.2 - '@multiformats/multiaddr-to-uri': 11.0.2 - '@types/ws': 8.18.1 - it-ws: 6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6) + '@libp2p/interface': 3.3.0 + '@libp2p/utils': 7.4.1 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 + '@multiformats/multiaddr-to-uri': 12.0.0 main-event: 1.0.4 - p-defer: 4.0.1 - p-event: 6.0.1 + p-event: 7.1.1 progress-events: 1.1.0 - race-signal: 1.1.3 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil - utf-8-validate + '@libp2p/yamux@8.0.3': + dependencies: + '@libp2p/interface': 3.3.0 + '@libp2p/utils': 7.4.1 + race-signal: 2.0.0 + uint8arraylist: 3.0.2 + + ? '@lifi/widget-light@4.3.2(patch_hash=8ee9f6665560f5ce16422afed5a38522d274ad98ca518fe83619f682b53ed378)(@wagmi/core@2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(@wallet-standard/base@1.1.0)(react@19.1.4)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(wagmi@2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3))' + : dependencies: + react: 19.1.4 + optionalDependencies: + '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@wallet-standard/base': 1.1.0 + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) + '@lit-labs/ssr-dom-shim@1.6.0': {} '@lit/react@1.0.8(@types/react@19.1.7)': @@ -18024,11 +18879,11 @@ snapshots: dependencies: openapi-fetch: 0.13.8 - '@metamask/connect-evm@1.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)': + '@metamask/connect-evm@1.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': dependencies: '@metamask/analytics': 0.5.0 - '@metamask/connect-multichain': 0.14.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@metamask/utils': 11.11.0 + '@metamask/connect-multichain': 0.14.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + '@metamask/utils': 11.11.0(supports-color@10.2.2) transitivePeerDependencies: - '@react-native-async-storage/async-storage' - bufferutil @@ -18036,16 +18891,16 @@ snapshots: - supports-color - utf-8-validate - '@metamask/connect-multichain@0.14.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)': + '@metamask/connect-multichain@0.14.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': dependencies: '@metamask/analytics': 0.5.0 '@metamask/mobile-wallet-protocol-core': 0.4.0 - '@metamask/mobile-wallet-protocol-dapp-client': 0.3.0 + '@metamask/mobile-wallet-protocol-dapp-client': 0.3.0(supports-color@10.2.2) '@metamask/multichain-api-client': 0.10.1 '@metamask/multichain-ui': 0.4.1 '@metamask/onboarding': 1.0.1 - '@metamask/rpc-errors': 7.0.3 - '@metamask/utils': 11.11.0 + '@metamask/rpc-errors': 7.0.3(supports-color@10.2.2) + '@metamask/utils': 11.11.0(supports-color@10.2.2) '@paulmillr/qr': 0.2.1 bowser: 2.14.1 buffer: 6.0.3 @@ -18061,35 +18916,35 @@ snapshots: - supports-color - utf-8-validate - '@metamask/eth-json-rpc-provider@1.0.1': + '@metamask/eth-json-rpc-provider@1.0.1(supports-color@10.2.2)': dependencies: - '@metamask/json-rpc-engine': 7.3.3 + '@metamask/json-rpc-engine': 7.3.3(supports-color@10.2.2) '@metamask/safe-event-emitter': 3.1.2 - '@metamask/utils': 5.0.2 + '@metamask/utils': 5.0.2(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@metamask/json-rpc-engine@7.3.3': + '@metamask/json-rpc-engine@7.3.3(supports-color@10.2.2)': dependencies: - '@metamask/rpc-errors': 6.4.0 + '@metamask/rpc-errors': 6.4.0(supports-color@10.2.2) '@metamask/safe-event-emitter': 3.1.2 - '@metamask/utils': 8.5.0 + '@metamask/utils': 8.5.0(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@metamask/json-rpc-engine@8.0.2': + '@metamask/json-rpc-engine@8.0.2(supports-color@10.2.2)': dependencies: - '@metamask/rpc-errors': 6.4.0 + '@metamask/rpc-errors': 6.4.0(supports-color@10.2.2) '@metamask/safe-event-emitter': 3.1.2 - '@metamask/utils': 8.5.0 + '@metamask/utils': 8.5.0(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@metamask/json-rpc-middleware-stream@7.0.2': + '@metamask/json-rpc-middleware-stream@7.0.2(supports-color@10.2.2)': dependencies: - '@metamask/json-rpc-engine': 8.0.2 + '@metamask/json-rpc-engine': 8.0.2(supports-color@10.2.2) '@metamask/safe-event-emitter': 3.1.2 - '@metamask/utils': 8.5.0 + '@metamask/utils': 8.5.0(supports-color@10.2.2) readable-stream: 3.6.2 transitivePeerDependencies: - supports-color @@ -18101,10 +18956,10 @@ snapshots: eventemitter3: 5.0.4 uuid: 11.1.0 - '@metamask/mobile-wallet-protocol-dapp-client@0.3.0': + '@metamask/mobile-wallet-protocol-dapp-client@0.3.0(supports-color@10.2.2)': dependencies: '@metamask/mobile-wallet-protocol-core': 0.4.0 - '@metamask/utils': 9.3.0 + '@metamask/utils': 9.3.0(supports-color@10.2.2) uuid: 11.1.0 transitivePeerDependencies: - supports-color @@ -18131,9 +18986,9 @@ snapshots: dependencies: bowser: 2.14.1 - '@metamask/post-message-stream@7.0.0': + '@metamask/post-message-stream@7.0.0(supports-color@10.2.2)': dependencies: - '@metamask/utils': 5.0.2 + '@metamask/utils': 5.0.2(supports-color@10.2.2) readable-stream: 3.6.2 transitivePeerDependencies: - supports-color @@ -18153,14 +19008,14 @@ snapshots: pump: 3.0.4 webextension-polyfill-ts: 0.25.0 - '@metamask/providers@16.1.0': + '@metamask/providers@16.1.0(supports-color@10.2.2)': dependencies: - '@metamask/json-rpc-engine': 8.0.2 - '@metamask/json-rpc-middleware-stream': 7.0.2 + '@metamask/json-rpc-engine': 8.0.2(supports-color@10.2.2) + '@metamask/json-rpc-middleware-stream': 7.0.2(supports-color@10.2.2) '@metamask/object-multiplex': 2.1.0 - '@metamask/rpc-errors': 6.4.0 + '@metamask/rpc-errors': 6.4.0(supports-color@10.2.2) '@metamask/safe-event-emitter': 3.1.2 - '@metamask/utils': 8.5.0 + '@metamask/utils': 8.5.0(supports-color@10.2.2) detect-browser: 5.3.0 extension-port-stream: 3.0.0 fast-deep-equal: 3.1.3 @@ -18170,23 +19025,23 @@ snapshots: transitivePeerDependencies: - supports-color - '@metamask/rpc-errors@6.4.0': + '@metamask/rpc-errors@6.4.0(supports-color@10.2.2)': dependencies: - '@metamask/utils': 9.3.0 + '@metamask/utils': 9.3.0(supports-color@10.2.2) fast-safe-stringify: 2.1.1 transitivePeerDependencies: - supports-color - '@metamask/rpc-errors@7.0.2': + '@metamask/rpc-errors@7.0.2(supports-color@10.2.2)': dependencies: - '@metamask/utils': 11.11.0 + '@metamask/utils': 11.11.0(supports-color@10.2.2) fast-safe-stringify: 2.1.1 transitivePeerDependencies: - supports-color - '@metamask/rpc-errors@7.0.3': + '@metamask/rpc-errors@7.0.3(supports-color@10.2.2)': dependencies: - '@metamask/utils': 11.11.0 + '@metamask/utils': 11.11.0(supports-color@10.2.2) fast-safe-stringify: 2.1.1 transitivePeerDependencies: - supports-color @@ -18199,17 +19054,17 @@ snapshots: dependencies: openapi-fetch: 0.13.8 - '@metamask/sdk-communication-layer@0.33.1(cross-fetch@4.1.0)(eciesjs@0.4.18)(eventemitter2@6.4.9)(readable-stream@3.6.2)(socket.io-client@4.8.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))': + '@metamask/sdk-communication-layer@0.33.1(cross-fetch@4.1.0)(eciesjs@0.4.18)(eventemitter2@6.4.9)(readable-stream@3.6.2)(socket.io-client@4.8.3(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)': dependencies: '@metamask/sdk-analytics': 0.0.5 bufferutil: 4.1.0 cross-fetch: 4.1.0 date-fns: 2.30.0 - debug: 4.3.4 + debug: 4.3.4(supports-color@10.2.2) eciesjs: 0.4.18 eventemitter2: 6.4.9 readable-stream: 3.6.2 - socket.io-client: 4.8.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) + socket.io-client: 4.8.3(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) utf-8-validate: 5.0.10 uuid: 8.3.2 transitivePeerDependencies: @@ -18219,25 +19074,25 @@ snapshots: dependencies: '@paulmillr/qr': 0.2.1 - '@metamask/sdk@0.33.1(bufferutil@4.1.0)(utf-8-validate@6.0.6)': + '@metamask/sdk@0.33.1(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': dependencies: '@babel/runtime': 7.29.7 '@metamask/onboarding': 1.0.1 - '@metamask/providers': 16.1.0 + '@metamask/providers': 16.1.0(supports-color@10.2.2) '@metamask/sdk-analytics': 0.0.5 - '@metamask/sdk-communication-layer': 0.33.1(cross-fetch@4.1.0)(eciesjs@0.4.18)(eventemitter2@6.4.9)(readable-stream@3.6.2)(socket.io-client@4.8.3(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@metamask/sdk-communication-layer': 0.33.1(cross-fetch@4.1.0)(eciesjs@0.4.18)(eventemitter2@6.4.9)(readable-stream@3.6.2)(socket.io-client@4.8.3(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2) '@metamask/sdk-install-modal-web': 0.32.1 '@paulmillr/qr': 0.2.1 bowser: 2.14.1 cross-fetch: 4.1.0 - debug: 4.3.4 + debug: 4.3.4(supports-color@10.2.2) eciesjs: 0.4.18 eth-rpc-errors: 4.0.3 eventemitter2: 6.4.9 obj-multiplex: 1.0.0 pump: 3.0.4 readable-stream: 3.6.2 - socket.io-client: 4.8.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) + socket.io-client: 4.8.3(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) tslib: 2.8.1 util: 0.12.5 uuid: 8.3.2 @@ -18249,7 +19104,7 @@ snapshots: '@metamask/superstruct@3.2.1': {} - '@metamask/utils@11.11.0': + '@metamask/utils@11.11.0(supports-color@10.2.2)': dependencies: '@ethereumjs/tx': 4.2.0 '@metamask/superstruct': 3.2.1 @@ -18257,69 +19112,69 @@ snapshots: '@scure/base': 1.1.9 '@types/debug': 4.1.13 '@types/lodash': 4.17.24 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) lodash: 4.18.1 pony-cause: 2.1.11 - semver: 7.8.4 + semver: 7.8.5 uuid: 9.0.1 transitivePeerDependencies: - supports-color - '@metamask/utils@5.0.2': + '@metamask/utils@5.0.2(supports-color@10.2.2)': dependencies: '@ethereumjs/tx': 4.2.0 '@types/debug': 4.1.13 - debug: 4.4.3 - semver: 7.8.1 + debug: 4.4.3(supports-color@10.2.2) + semver: 7.8.5 superstruct: 1.0.4 transitivePeerDependencies: - supports-color - '@metamask/utils@8.5.0': + '@metamask/utils@8.5.0(supports-color@10.2.2)': dependencies: '@ethereumjs/tx': 4.2.0 '@metamask/superstruct': 3.2.1 '@noble/hashes': 1.8.0 '@scure/base': 1.1.9 '@types/debug': 4.1.13 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) pony-cause: 2.1.11 - semver: 7.8.4 + semver: 7.8.5 uuid: 9.0.1 transitivePeerDependencies: - supports-color - '@metamask/utils@9.3.0': + '@metamask/utils@9.3.0(supports-color@10.2.2)': dependencies: '@ethereumjs/tx': 4.2.0 '@metamask/superstruct': 3.2.1 '@noble/hashes': 1.8.0 '@scure/base': 1.1.9 '@types/debug': 4.1.13 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) pony-cause: 2.1.11 - semver: 7.8.4 + semver: 7.8.5 uuid: 9.0.1 transitivePeerDependencies: - supports-color - '@microsoft/api-extractor-model@7.33.8(@types/node@20.16.7)': + '@microsoft/api-extractor-model@7.33.8(@types/node@24.13.4)': dependencies: '@microsoft/tsdoc': 0.16.0 '@microsoft/tsdoc-config': 0.18.1 - '@rushstack/node-core-library': 5.23.1(@types/node@20.16.7) + '@rushstack/node-core-library': 5.23.1(@types/node@24.13.4) transitivePeerDependencies: - '@types/node' - '@microsoft/api-extractor@7.58.7(@types/node@20.16.7)': + '@microsoft/api-extractor@7.58.7(@types/node@24.13.4)': dependencies: - '@microsoft/api-extractor-model': 7.33.8(@types/node@20.16.7) + '@microsoft/api-extractor-model': 7.33.8(@types/node@24.13.4) '@microsoft/tsdoc': 0.16.0 '@microsoft/tsdoc-config': 0.18.1 - '@rushstack/node-core-library': 5.23.1(@types/node@20.16.7) + '@rushstack/node-core-library': 5.23.1(@types/node@24.13.4) '@rushstack/rig-package': 0.7.3 - '@rushstack/terminal': 0.24.0(@types/node@20.16.7) - '@rushstack/ts-command-line': 5.3.9(@types/node@20.16.7) + '@rushstack/terminal': 0.24.0(@types/node@24.13.4) + '@rushstack/ts-command-line': 5.3.9(@types/node@24.13.4) diff: 8.0.4 minimatch: 10.2.3 resolve: 1.22.12 @@ -18360,63 +19215,52 @@ snapshots: progress-events: 1.1.0 uint8arrays: 5.1.1 - '@multiformats/mafmt@12.1.6': + '@multiformats/dns@1.0.15': dependencies: - '@multiformats/multiaddr': 12.5.1 - - '@multiformats/multiaddr-matcher@1.8.0': - dependencies: - '@chainsafe/is-ip': 2.1.0 - '@multiformats/multiaddr': 12.5.1 - multiformats: 13.4.2 - - '@multiformats/multiaddr-matcher@2.0.2': - dependencies: - '@multiformats/multiaddr': 12.5.1 + '@dnsquery/dns-packet': 6.1.1 + '@libp2p/interface': 3.3.0 + hashlru: 2.3.0 + p-queue: 9.3.0 + progress-events: 1.1.0 + uint8arrays: 6.1.1 - '@multiformats/multiaddr-to-uri@11.0.2': + '@multiformats/multiaddr-matcher@3.0.2': dependencies: - '@multiformats/multiaddr': 12.5.1 + '@multiformats/multiaddr': 13.0.3 - '@multiformats/multiaddr@12.5.1': + '@multiformats/multiaddr-to-uri@12.0.0': dependencies: - '@chainsafe/is-ip': 2.1.0 - '@chainsafe/netmask': 2.0.0 - '@multiformats/dns': 1.0.13 - abort-error: 1.0.2 - multiformats: 13.4.2 - uint8-varint: 2.0.5 - uint8arrays: 5.1.1 + '@multiformats/multiaddr': 13.0.3 '@multiformats/multiaddr@13.0.3': dependencies: '@chainsafe/is-ip': 2.1.0 - multiformats: 14.0.0 + multiformats: 14.0.5 uint8-varint: 3.0.0 uint8arrays: 6.1.1 '@multiformats/murmur3@2.2.5': dependencies: - multiformats: 14.0.0 + multiformats: 14.0.5 - '@multiformats/uri-to-multiaddr@9.0.2': + '@multiformats/uri-to-multiaddr@10.0.0': dependencies: - '@multiformats/multiaddr': 12.5.1 + '@multiformats/multiaddr': 13.0.3 is-ip: 5.0.1 - '@multisender.app/multisender-react-widget@0.2.3(b9d9ab1f9c537c8f45225bdc5044ccc9)': + '@multisender.app/multisender-react-widget@0.2.3(4c18776c2376832d04d8e6a63f20812b)': dependencies: '@codemirror/commands': 6.10.3 '@csstools/normalize.css': 12.1.1 '@formkit/auto-animate': 0.8.4 '@mantine/core': 8.3.18(@mantine/hooks@8.3.18(react@19.1.4))(@types/react@19.1.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) '@mantine/hooks': 8.3.18(react@19.1.4) - '@reown/appkit': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-adapter-wagmi': 1.7.20(09e58c13ebbf9932f0a56e13a5b340ff) + '@reown/appkit': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-adapter-wagmi': 1.7.20(df3f0d3afef4414b7f4264d6db7d6a30) '@tabler/icons-react': 3.44.0(react@19.1.4) '@tanstack/react-query': 5.55.4(react@19.1.4) - '@uiw/react-codemirror': 4.25.10(@babel/runtime@7.29.7)(@codemirror/autocomplete@6.20.2)(@codemirror/language@6.0.0)(@codemirror/lint@6.9.6)(@codemirror/search@6.7.0)(@codemirror/state@6.6.0)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.43.0)(codemirror@5.65.21)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) - axios: 1.12.0(debug@4.4.3) + '@uiw/react-codemirror': 4.25.10(@babel/runtime@7.29.7)(@codemirror/autocomplete@6.20.2)(@codemirror/language@6.0.0)(@codemirror/lint@6.9.6)(@codemirror/search@6.7.0)(@codemirror/state@6.6.0)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.43.0)(codemirror@6.0.2)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + axios: 1.12.0(debug@4.4.3(supports-color@10.2.2)) clsx: 2.1.1 es-toolkit: 1.39.10 from-exponential: 1.1.1 @@ -18424,12 +19268,12 @@ snapshots: idb: 8.0.3 luxon: 3.7.2 nanoid: 5.1.11 - posthog-js: 1.376.2 + posthog-js: 1.434.15(@types/react@19.1.7)(react@19.1.4) react: 19.1.4 react-dom: 19.1.4(react@19.1.4) react-papaparse: 4.4.0 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) transitivePeerDependencies: - '@babel/runtime' - '@codemirror/autocomplete' @@ -18442,6 +19286,7 @@ snapshots: - '@types/react' - codemirror - debug + - preact-render-to-string '@mysten/bcs@1.9.2': dependencies: @@ -18501,60 +19346,34 @@ snapshots: '@next/env@13.5.11': {} - '@next/env@16.2.6': {} - - '@next/env@16.3.1': {} + '@next/env@16.4.3': {} '@next/eslint-plugin-next@16.2.6': dependencies: fast-glob: 3.3.1 - '@next/swc-darwin-arm64@16.2.6': - optional: true - - '@next/swc-darwin-arm64@16.3.1': - optional: true - - '@next/swc-darwin-x64@16.2.6': - optional: true - - '@next/swc-darwin-x64@16.3.1': - optional: true - - '@next/swc-linux-arm64-gnu@16.2.6': - optional: true - - '@next/swc-linux-arm64-gnu@16.3.1': - optional: true - - '@next/swc-linux-arm64-musl@16.2.6': - optional: true - - '@next/swc-linux-arm64-musl@16.3.1': - optional: true - - '@next/swc-linux-x64-gnu@16.2.6': + '@next/swc-darwin-arm64@16.4.3': optional: true - '@next/swc-linux-x64-gnu@16.3.1': + '@next/swc-darwin-x64@16.4.3': optional: true - '@next/swc-linux-x64-musl@16.2.6': + '@next/swc-linux-arm64-gnu@16.4.3': optional: true - '@next/swc-linux-x64-musl@16.3.1': + '@next/swc-linux-arm64-musl@16.4.3': optional: true - '@next/swc-win32-arm64-msvc@16.2.6': + '@next/swc-linux-x64-gnu@16.4.3': optional: true - '@next/swc-win32-arm64-msvc@16.3.1': + '@next/swc-linux-x64-musl@16.4.3': optional: true - '@next/swc-win32-x64-msvc@16.2.6': + '@next/swc-win32-arm64-msvc@16.4.3': optional: true - '@next/swc-win32-x64-msvc@16.3.1': + '@next/swc-win32-x64-msvc@16.4.3': optional: true '@noble/ciphers@0.4.1': {} @@ -18563,6 +19382,8 @@ snapshots: '@noble/ciphers@1.3.0': {} + '@noble/ciphers@2.4.0': {} + '@noble/curves@1.4.2': dependencies: '@noble/hashes': 1.8.0 @@ -18597,18 +19418,51 @@ snapshots: '@noble/curves@2.0.1': dependencies: - '@noble/hashes': 1.8.0 + '@noble/hashes': 2.0.1 '@noble/curves@2.2.0': dependencies: - '@noble/hashes': 1.8.0 + '@noble/hashes': 2.2.0 '@noble/hashes@1.8.0': {} + '@noble/hashes@2.0.1': {} + + '@noble/hashes@2.2.0': {} + + '@noble/hashes@2.4.0': {} + '@noble/post-quantum@0.5.4': dependencies: '@noble/curves': 2.0.1 - '@noble/hashes': 1.8.0 + '@noble/hashes': 2.0.1 + + '@node-datachannel/android-arm64@0.33.4': + optional: true + + '@node-datachannel/darwin-arm64@0.33.4': + optional: true + + '@node-datachannel/darwin-x64@0.33.4': + optional: true + + '@node-datachannel/linux-arm64-gnu@0.33.4': + optional: true + + '@node-datachannel/linux-arm64-musl@0.33.4': + optional: true + + '@node-datachannel/linux-x64-gnu@0.33.4': + optional: true + + '@node-datachannel/linux-x64-musl@0.33.4': + optional: true + + '@node-datachannel/win32-arm64-msvc@0.33.4': + optional: true + + '@node-datachannel/win32-x64-msvc@0.33.4': + optional: true '@nodelib/fs.scandir@2.1.5': dependencies: @@ -18622,23 +19476,20 @@ snapshots: '@nodelib/fs.scandir': 2.1.5 fastq: 1.20.1 - '@nolyfill/is-core-module@1.0.39': {} + '@nolyfill/is-core-module@1.0.39': + optional: true '@nouns/assets@0.10.0': dependencies: '@ethersproject/bignumber': 5.8.0 '@ethersproject/solidity': 5.8.0 - '@nouns/sdk@1.2.0(@tanstack/react-query@5.55.4(react@19.1.4))(@wagmi/core@2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(wagmi@2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76))': + '@nouns/sdk@1.2.0(@tanstack/react-query@5.55.4(react@19.1.4))(@wagmi/core@2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(wagmi@2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3))': dependencies: - '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) optionalDependencies: '@tanstack/react-query': 5.55.4(react@19.1.4) - wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) - - '@opentelemetry/api-logs@0.208.0': - dependencies: - '@opentelemetry/api': 1.9.1 + wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) '@opentelemetry/api-logs@0.217.0': dependencies: @@ -18650,58 +19501,58 @@ snapshots: '@opentelemetry/api@1.9.1': {} - '@opentelemetry/auto-instrumentations-node@0.75.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.8.0(@opentelemetry/api@1.9.1))': + '@opentelemetry/auto-instrumentations-node@0.75.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.8.0(@opentelemetry/api@1.9.1))(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-amqplib': 0.64.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-aws-lambda': 0.69.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-aws-sdk': 0.72.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-bunyan': 0.62.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-cassandra-driver': 0.62.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-connect': 0.60.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-cucumber': 0.33.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-dataloader': 0.34.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-dns': 0.60.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-express': 0.65.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-fs': 0.36.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-generic-pool': 0.60.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-graphql': 0.65.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-grpc': 0.217.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-hapi': 0.63.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-http': 0.217.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-ioredis': 0.65.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-kafkajs': 0.26.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-knex': 0.61.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-koa': 0.65.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-lru-memoizer': 0.61.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-memcached': 0.60.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-mongodb': 0.70.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-mongoose': 0.63.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-mysql': 0.63.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-mysql2': 0.63.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-nestjs-core': 0.63.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-net': 0.61.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-openai': 0.15.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-oracledb': 0.42.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-pg': 0.69.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-pino': 0.63.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-redis': 0.65.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-restify': 0.62.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-router': 0.61.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-runtime-node': 0.30.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-socket.io': 0.64.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-tedious': 0.36.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-undici': 0.27.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation-winston': 0.61.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-amqplib': 0.64.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-aws-lambda': 0.69.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-aws-sdk': 0.72.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-bunyan': 0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-cassandra-driver': 0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-connect': 0.60.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-cucumber': 0.33.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-dataloader': 0.34.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-dns': 0.60.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-express': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-fs': 0.36.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-generic-pool': 0.60.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-graphql': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-grpc': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-hapi': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-http': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-ioredis': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-kafkajs': 0.26.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-knex': 0.61.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-koa': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-lru-memoizer': 0.61.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-memcached': 0.60.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-mongodb': 0.70.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-mongoose': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-mysql': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-mysql2': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-nestjs-core': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-net': 0.61.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-openai': 0.15.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-oracledb': 0.42.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-pg': 0.69.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-pino': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-redis': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-restify': 0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-router': 0.61.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-runtime-node': 0.30.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-socket.io': 0.64.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-tedious': 0.36.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-undici': 0.27.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-winston': 0.61.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/resource-detector-alibaba-cloud': 0.33.8(@opentelemetry/api@1.9.1) '@opentelemetry/resource-detector-aws': 2.18.0(@opentelemetry/api@1.9.1) '@opentelemetry/resource-detector-azure': 0.25.0(@opentelemetry/api@1.9.1) '@opentelemetry/resource-detector-container': 0.8.9(@opentelemetry/api@1.9.1) - '@opentelemetry/resource-detector-gcp': 0.52.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-node': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/resource-detector-gcp': 0.52.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-node': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -18725,11 +19576,6 @@ snapshots: dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/core@2.2.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/semantic-conventions': 1.41.1 - '@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -18768,15 +19614,6 @@ snapshots: '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/api@1.9.1) '@opentelemetry/sdk-logs': 0.218.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-logs-otlp-http@0.208.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.208.0 - '@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-logs-otlp-http@0.217.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -18961,264 +19798,264 @@ snapshots: '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/api@1.9.1) '@opentelemetry/semantic-conventions': 1.41.1 - '@opentelemetry/instrumentation-amqplib@0.64.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-amqplib@0.64.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-aws-lambda@0.69.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-aws-lambda@0.69.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 '@types/aws-lambda': 8.10.162 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-aws-sdk@0.72.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-aws-sdk@0.72.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-bunyan@0.62.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-bunyan@0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/api-logs': 0.217.0 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@types/bunyan': 1.8.11 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-cassandra-driver@0.62.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-cassandra-driver@0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-connect@0.60.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-connect@0.60.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 '@types/connect': 3.4.38 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-cucumber@0.33.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-cucumber@0.33.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-dataloader@0.34.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-dataloader@0.34.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-dns@0.60.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-dns@0.60.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-express@0.65.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-express@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-fs@0.36.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-fs@0.36.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-generic-pool@0.60.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-generic-pool@0.60.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-graphql@0.65.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-graphql@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-grpc@0.217.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-grpc@0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-hapi@0.63.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-hapi@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-http@0.217.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-http@0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 forwarded-parse: 2.1.2 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-ioredis@0.65.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-ioredis@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/redis-common': 0.38.3 '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-kafkajs@0.26.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-kafkajs@0.26.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-knex@0.61.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-knex@0.61.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-koa@0.65.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-koa@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-lru-memoizer@0.61.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-lru-memoizer@0.61.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-memcached@0.60.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-memcached@0.60.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 '@types/memcached': 2.2.10 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-mongodb@0.70.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-mongodb@0.70.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-mongoose@0.63.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-mongoose@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-mysql2@0.63.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-mysql2@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 '@opentelemetry/sql-common': 0.41.2(@opentelemetry/api@1.9.1) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-mysql@0.63.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-mysql@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 '@types/mysql': 2.15.27 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-nestjs-core@0.63.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-nestjs-core@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-net@0.61.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-net@0.61.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-openai@0.15.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-openai@0.15.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/api-logs': 0.217.0 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-oracledb@0.42.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-oracledb@0.42.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 '@types/oracledb': 6.5.2 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-pg@0.69.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-pg@0.69.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 '@opentelemetry/sql-common': 0.41.2(@opentelemetry/api@1.9.1) '@types/pg': 8.15.6 @@ -19226,105 +20063,99 @@ snapshots: transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-pino@0.63.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-pino@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/api-logs': 0.217.0 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-redis@0.65.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-redis@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/redis-common': 0.38.3 '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-restify@0.62.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-restify@0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-router@0.61.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-router@0.61.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-runtime-node@0.30.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-runtime-node@0.30.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-socket.io@0.64.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-socket.io@0.64.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-tedious@0.36.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-tedious@0.36.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 '@types/tedious': 4.0.14 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-undici@0.27.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-undici@0.27.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.41.1 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-winston@0.61.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation-winston@0.61.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/api-logs': 0.217.0 - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation@0.217.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation@0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/api-logs': 0.217.0 import-in-the-middle: 3.0.2 - require-in-the-middle: 8.0.1 + require-in-the-middle: 8.0.1(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation@0.218.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/instrumentation@0.218.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/api-logs': 0.218.0 import-in-the-middle: 3.0.2 - require-in-the-middle: 8.0.1 + require-in-the-middle: 8.0.1(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/otlp-exporter-base@0.208.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base@0.217.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -19353,17 +20184,6 @@ snapshots: '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/api@1.9.1) '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer@0.208.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.208.0 - '@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-metrics': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-trace-base': 2.2.0(@opentelemetry/api@1.9.1) - protobufjs: 7.5.5 - '@opentelemetry/otlp-transformer@0.217.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -19401,43 +20221,37 @@ snapshots: dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) '@opentelemetry/resource-detector-aws@2.18.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) '@opentelemetry/semantic-conventions': 1.41.1 '@opentelemetry/resource-detector-azure@0.25.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) '@opentelemetry/semantic-conventions': 1.41.1 '@opentelemetry/resource-detector-container@0.8.9(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resource-detector-gcp@0.52.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/resource-detector-gcp@0.52.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) - gcp-metadata: 8.1.3 + '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) + gcp-metadata: 8.1.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/resources@2.2.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/semantic-conventions': 1.41.1 - '@opentelemetry/resources@2.7.1(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -19450,13 +20264,6 @@ snapshots: '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) '@opentelemetry/semantic-conventions': 1.41.1 - '@opentelemetry/sdk-logs@0.208.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.208.0 - '@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-logs@0.217.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -19473,12 +20280,6 @@ snapshots: '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) '@opentelemetry/semantic-conventions': 1.41.1 - '@opentelemetry/sdk-metrics@2.2.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-metrics@2.7.1(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -19491,7 +20292,7 @@ snapshots: '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-node@0.217.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/sdk-node@0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/api-logs': 0.217.0 @@ -19509,7 +20310,7 @@ snapshots: '@opentelemetry/exporter-trace-otlp-http': 0.217.0(@opentelemetry/api@1.9.1) '@opentelemetry/exporter-trace-otlp-proto': 0.217.0(@opentelemetry/api@1.9.1) '@opentelemetry/exporter-zipkin': 2.7.1(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/api@1.9.1) '@opentelemetry/propagator-b3': 2.7.1(@opentelemetry/api@1.9.1) '@opentelemetry/propagator-jaeger': 2.7.1(@opentelemetry/api@1.9.1) @@ -19522,7 +20323,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@opentelemetry/sdk-node@0.218.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/sdk-node@0.218.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/api-logs': 0.218.0 @@ -19540,7 +20341,7 @@ snapshots: '@opentelemetry/exporter-trace-otlp-http': 0.218.0(@opentelemetry/api@1.9.1) '@opentelemetry/exporter-trace-otlp-proto': 0.218.0(@opentelemetry/api@1.9.1) '@opentelemetry/exporter-zipkin': 2.7.1(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.218.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.218.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/api@1.9.1) '@opentelemetry/propagator-b3': 2.7.1(@opentelemetry/api@1.9.1) '@opentelemetry/propagator-jaeger': 2.7.1(@opentelemetry/api@1.9.1) @@ -19553,13 +20354,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@opentelemetry/sdk-trace-base@2.2.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.2.0(@opentelemetry/api@1.9.1) - '@opentelemetry/semantic-conventions': 1.41.1 - '@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -19601,10 +20395,28 @@ snapshots: '@openzeppelin/contracts@5.4.0': {} + '@oxc-project/types@0.155.0': {} + '@pandacss/is-valid-prop@1.11.1': {} '@paulmillr/qr@0.2.1': {} + '@peculiar/asn1-asym-key@2.10.0': + dependencies: + '@peculiar/asn1-pkcs8': 2.10.0 + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/asn1-x509': 2.10.0 + asn1js: 3.0.10 + tslib: 2.8.1 + + '@peculiar/asn1-cms@2.10.0': + dependencies: + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/asn1-x509': 2.10.0 + '@peculiar/asn1-x509-attr': 2.10.0 + asn1js: 3.0.10 + tslib: 2.8.1 + '@peculiar/asn1-cms@2.7.0': dependencies: '@peculiar/asn1-schema': 2.7.0 @@ -19613,6 +20425,13 @@ snapshots: asn1js: 3.0.10 tslib: 2.8.1 + '@peculiar/asn1-csr@2.10.0': + dependencies: + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/asn1-x509': 2.10.0 + asn1js: 3.0.10 + tslib: 2.8.1 + '@peculiar/asn1-csr@2.7.0': dependencies: '@peculiar/asn1-schema': 2.7.0 @@ -19620,6 +20439,13 @@ snapshots: asn1js: 3.0.10 tslib: 2.8.1 + '@peculiar/asn1-ecc@2.10.0': + dependencies: + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/asn1-x509': 2.10.0 + asn1js: 3.0.10 + tslib: 2.8.1 + '@peculiar/asn1-ecc@2.7.0': dependencies: '@peculiar/asn1-schema': 2.7.0 @@ -19627,6 +20453,15 @@ snapshots: asn1js: 3.0.10 tslib: 2.8.1 + '@peculiar/asn1-pfx@2.10.0': + dependencies: + '@peculiar/asn1-cms': 2.10.0 + '@peculiar/asn1-pkcs8': 2.10.0 + '@peculiar/asn1-rsa': 2.10.0 + '@peculiar/asn1-schema': 2.10.0 + asn1js: 3.0.10 + tslib: 2.8.1 + '@peculiar/asn1-pfx@2.7.0': dependencies: '@peculiar/asn1-cms': 2.7.0 @@ -19636,6 +20471,13 @@ snapshots: asn1js: 3.0.10 tslib: 2.8.1 + '@peculiar/asn1-pkcs8@2.10.0': + dependencies: + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/asn1-x509': 2.10.0 + asn1js: 3.0.10 + tslib: 2.8.1 + '@peculiar/asn1-pkcs8@2.7.0': dependencies: '@peculiar/asn1-schema': 2.7.0 @@ -19643,6 +20485,17 @@ snapshots: asn1js: 3.0.10 tslib: 2.8.1 + '@peculiar/asn1-pkcs9@2.10.0': + dependencies: + '@peculiar/asn1-cms': 2.10.0 + '@peculiar/asn1-pfx': 2.10.0 + '@peculiar/asn1-pkcs8': 2.10.0 + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/asn1-x509': 2.10.0 + '@peculiar/asn1-x509-attr': 2.10.0 + asn1js: 3.0.10 + tslib: 2.8.1 + '@peculiar/asn1-pkcs9@2.7.0': dependencies: '@peculiar/asn1-cms': 2.7.0 @@ -19654,6 +20507,13 @@ snapshots: asn1js: 3.0.10 tslib: 2.8.1 + '@peculiar/asn1-rsa@2.10.0': + dependencies: + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/asn1-x509': 2.10.0 + asn1js: 3.0.10 + tslib: 2.8.1 + '@peculiar/asn1-rsa@2.7.0': dependencies: '@peculiar/asn1-schema': 2.7.0 @@ -19661,12 +20521,25 @@ snapshots: asn1js: 3.0.10 tslib: 2.8.1 + '@peculiar/asn1-schema@2.10.0': + dependencies: + '@peculiar/utils': 2.0.3 + asn1js: 3.0.10 + tslib: 2.8.1 + '@peculiar/asn1-schema@2.7.0': dependencies: '@peculiar/utils': 2.0.3 asn1js: 3.0.10 tslib: 2.8.1 + '@peculiar/asn1-x509-attr@2.10.0': + dependencies: + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/asn1-x509': 2.10.0 + asn1js: 3.0.10 + tslib: 2.8.1 + '@peculiar/asn1-x509-attr@2.7.0': dependencies: '@peculiar/asn1-schema': 2.7.0 @@ -19674,6 +20547,21 @@ snapshots: asn1js: 3.0.10 tslib: 2.8.1 + '@peculiar/asn1-x509-post-quantum@2.10.0': + dependencies: + '@peculiar/asn1-asym-key': 2.10.0 + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/asn1-x509': 2.10.0 + asn1js: 3.0.10 + tslib: 2.8.1 + + '@peculiar/asn1-x509@2.10.0': + dependencies: + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/utils': 2.0.3 + asn1js: 3.0.10 + tslib: 2.8.1 + '@peculiar/asn1-x509@2.7.0': dependencies: '@peculiar/asn1-schema': 2.7.0 @@ -19711,6 +20599,20 @@ snapshots: tslib: 2.8.1 tsyringe: 4.10.0 + '@peculiar/x509@2.1.0': + dependencies: + '@peculiar/asn1-cms': 2.10.0 + '@peculiar/asn1-csr': 2.10.0 + '@peculiar/asn1-ecc': 2.10.0 + '@peculiar/asn1-pkcs9': 2.10.0 + '@peculiar/asn1-rsa': 2.10.0 + '@peculiar/asn1-schema': 2.10.0 + '@peculiar/asn1-x509': 2.10.0 + '@peculiar/asn1-x509-post-quantum': 2.10.0 + pvtsutils: 1.3.6 + tslib: 2.8.1 + tsyringe: 4.10.0 + '@phosphor-icons/webcomponents@2.1.5': dependencies: lit: 3.3.0 @@ -19718,16 +20620,17 @@ snapshots: '@pkgjs/parseargs@0.11.0': optional: true - '@playwright/experimental-ct-core@1.57.0(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)': + '@playwright/experimental-ct-core@1.62.1(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)': dependencies: - playwright: 1.57.0 - playwright-core: 1.57.0 - vite: 6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0) + playwright: 1.62.1 + playwright-core: 1.62.1 + vite: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) transitivePeerDependencies: - '@types/node' + - '@vitejs/devtools' + - esbuild - jiti - less - - lightningcss - sass - sass-embedded - stylus @@ -19736,36 +20639,44 @@ snapshots: - tsx - yaml - '@playwright/experimental-ct-react@1.57.0(@types/node@20.16.7)(terser@5.48.0)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0))(yaml@2.9.0)': + '@playwright/experimental-ct-react@1.62.1(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0))(yaml@2.9.0)': dependencies: - '@playwright/experimental-ct-core': 1.57.0(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0) - '@vitejs/plugin-react': 4.3.4(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) + '@playwright/experimental-ct-core': 1.62.1(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) + '@vitejs/plugin-react': 6.1.2(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) transitivePeerDependencies: + - '@rolldown/plugin-babel' - '@types/node' + - '@vitejs/devtools' + - babel-plugin-react-compiler + - esbuild - jiti - less - - lightningcss + - oxc-transform-react - sass - sass-embedded - stylus - sugarss - - supports-color - terser - tsx - vite - yaml - '@playwright/test@1.57.0': + '@playwright/test@1.62.1': dependencies: - playwright: 1.57.0 + playwright: 1.62.1 '@polka/url@1.0.0-next.29': {} - '@posthog/core@1.29.11': + '@posthog/browser-common@0.9.0': dependencies: - '@posthog/types': 1.376.2 + '@posthog/core': 1.55.2 + '@posthog/types': 1.412.4 - '@posthog/types@1.376.2': {} + '@posthog/core@1.55.2': + dependencies: + '@posthog/types': 1.412.4 + + '@posthog/types@1.412.4': {} '@protobuf-ts/grpcweb-transport@2.11.1': dependencies: @@ -20133,9 +21044,9 @@ snapshots: '@react-native/assets-registry@0.85.3': {} - '@react-native/codegen@0.85.3(@babel/core@7.29.7)': + '@react-native/codegen@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/parser': 7.29.7 hermes-parser: 0.33.3 invariant: 2.2.4 @@ -20143,13 +21054,13 @@ snapshots: tinyglobby: 0.2.17 yargs: 17.7.2 - '@react-native/community-cli-plugin@0.85.3(bufferutil@4.1.0)(utf-8-validate@6.0.6)': + '@react-native/community-cli-plugin@0.85.3(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': dependencies: - '@react-native/dev-middleware': 0.85.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) - debug: 4.4.3 + '@react-native/dev-middleware': 0.85.3(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + debug: 4.4.3(supports-color@10.2.2) invariant: 2.2.4 - metro: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) - metro-config: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) + metro: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + metro-config: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) metro-core: 0.84.4 semver: 7.8.5 transitivePeerDependencies: @@ -20159,27 +21070,27 @@ snapshots: '@react-native/debugger-frontend@0.85.3': {} - '@react-native/debugger-shell@0.85.3': + '@react-native/debugger-shell@0.85.3(supports-color@10.2.2)': dependencies: cross-spawn: 7.0.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) fb-dotslash: 0.5.8 transitivePeerDependencies: - supports-color - '@react-native/dev-middleware@0.85.3(bufferutil@4.1.0)(utf-8-validate@6.0.6)': + '@react-native/dev-middleware@0.85.3(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6)': dependencies: '@isaacs/ttlcache': 1.4.1 '@react-native/debugger-frontend': 0.85.3 - '@react-native/debugger-shell': 0.85.3 - chrome-launcher: 0.15.2 - chromium-edge-launcher: 0.3.0 - connect: 3.7.0 - debug: 4.4.3 + '@react-native/debugger-shell': 0.85.3(supports-color@10.2.2) + chrome-launcher: 0.15.2(supports-color@10.2.2) + chromium-edge-launcher: 0.3.0(supports-color@10.2.2) + connect: 3.7.0(supports-color@10.2.2) + debug: 4.4.3(supports-color@10.2.2) invariant: 2.2.4 nullthrows: 1.1.1 open: 7.4.2 - serve-static: 1.16.3 + serve-static: 1.16.3(supports-color@10.2.2) ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil @@ -20192,12 +21103,12 @@ snapshots: '@react-native/normalize-colors@0.85.3': {} - '@react-native/virtualized-lists@0.85.3(@types/react@19.1.7)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)': + '@react-native/virtualized-lists@0.85.3(@types/react@19.1.7)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)': dependencies: invariant: 2.2.4 nullthrows: 1.1.1 react: 19.1.4 - react-native: 0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6) + react-native: 0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6) optionalDependencies: '@types/react': 19.1.7 @@ -20205,22 +21116,22 @@ snapshots: dependencies: react: 19.1.4 - '@reown/appkit-adapter-wagmi@1.7.20(09e58c13ebbf9932f0a56e13a5b340ff)': + '@reown/appkit-adapter-wagmi@1.7.20(df3f0d3afef4414b7f4264d6db7d6a30)': dependencies: - '@reown/appkit': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-polyfills': 1.7.20 - '@reown/appkit-scaffold-ui': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) - '@reown/appkit-utils': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) + '@reown/appkit-scaffold-ui': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) + '@reown/appkit-utils': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) '@reown/appkit-wallet': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - '@walletconnect/universal-provider': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@walletconnect/universal-provider': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) valtio: 2.1.5(@types/react@19.1.7)(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) optionalDependencies: - '@wagmi/connectors': 6.2.0(09e58c13ebbf9932f0a56e13a5b340ff) + '@wagmi/connectors': 6.2.0(df3f0d3afef4414b7f4264d6db7d6a30) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -20250,6 +21161,7 @@ snapshots: - fastestsmallesttextencoderdecoder - immer - ioredis + - preact-render-to-string - react - react-native - supports-color @@ -20270,11 +21182,11 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-common@1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-common@1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: big.js: 6.2.2 dayjs: 1.11.13 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - bufferutil - typescript @@ -20292,11 +21204,11 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-common@1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-common@1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: big.js: 6.2.2 dayjs: 1.11.13 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - bufferutil - typescript @@ -20314,24 +21226,24 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-common@1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-common@1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: big.js: 6.2.2 dayjs: 1.11.13 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - bufferutil - typescript - utf-8-validate - zod - '@reown/appkit-controllers@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-controllers@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-wallet': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@walletconnect/universal-provider': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/universal-provider': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) valtio: 2.1.5(@types/react@19.1.7)(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -20360,13 +21272,13 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-controllers@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-controllers@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-wallet': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@walletconnect/universal-provider': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/universal-provider': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) valtio: 1.13.2(@types/react@19.1.7)(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -20395,13 +21307,13 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-controllers@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-controllers@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-wallet': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@walletconnect/universal-provider': 2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/universal-provider': 2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) valtio: 2.1.7(@types/react@19.1.7)(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -20430,12 +21342,12 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-pay@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-pay@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-ui': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-utils': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) + '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-ui': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-utils': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) lit: 3.3.0 valtio: 2.1.5(@types/react@19.1.7)(react@19.1.4) transitivePeerDependencies: @@ -20466,12 +21378,12 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-pay@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-pay@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-ui': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-utils': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) + '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-ui': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-utils': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) lit: 3.3.0 valtio: 1.13.2(@types/react@19.1.7)(react@19.1.4) transitivePeerDependencies: @@ -20502,12 +21414,12 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-pay@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-pay@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-ui': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-utils': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) + '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-ui': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-utils': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) lit: 3.3.0 valtio: 2.1.7(@types/react@19.1.7)(react@19.1.4) transitivePeerDependencies: @@ -20550,12 +21462,12 @@ snapshots: dependencies: buffer: 6.0.3 - '@reown/appkit-scaffold-ui@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76)': + '@reown/appkit-scaffold-ui@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-ui': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-utils': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) + '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-ui': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-utils': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) '@reown/appkit-wallet': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) lit: 3.3.0 transitivePeerDependencies: @@ -20587,12 +21499,12 @@ snapshots: - valtio - zod - '@reown/appkit-scaffold-ui@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76)': + '@reown/appkit-scaffold-ui@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-ui': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-utils': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) + '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-ui': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-utils': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) '@reown/appkit-wallet': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) lit: 3.3.0 transitivePeerDependencies: @@ -20624,12 +21536,12 @@ snapshots: - valtio - zod - '@reown/appkit-scaffold-ui@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76)': + '@reown/appkit-scaffold-ui@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-ui': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-utils': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) + '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-ui': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-utils': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) '@reown/appkit-wallet': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) lit: 3.3.0 transitivePeerDependencies: @@ -20661,10 +21573,10 @@ snapshots: - valtio - zod - '@reown/appkit-ui@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-ui@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-wallet': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) lit: 3.3.0 qrcode: 1.5.3 @@ -20696,10 +21608,10 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-ui@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-ui@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-wallet': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) lit: 3.3.0 qrcode: 1.5.3 @@ -20731,11 +21643,11 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-ui@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit-ui@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@phosphor-icons/webcomponents': 2.1.5 - '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-wallet': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) lit: 3.3.0 qrcode: 1.5.3 @@ -20767,17 +21679,17 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-utils@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76)': + '@reown/appkit-utils@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-polyfills': 1.7.20 '@reown/appkit-wallet': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@wallet-standard/wallet': 1.1.0 '@walletconnect/logger': 2.1.2 - '@walletconnect/universal-provider': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/universal-provider': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) valtio: 2.1.5(@types/react@19.1.7)(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -20806,16 +21718,16 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-utils@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76)': + '@reown/appkit-utils@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-polyfills': 1.7.8 '@reown/appkit-wallet': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@walletconnect/logger': 2.1.2 - '@walletconnect/universal-provider': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/universal-provider': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) valtio: 1.13.2(@types/react@19.1.7)(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -20844,17 +21756,17 @@ snapshots: - utf-8-validate - zod - '@reown/appkit-utils@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76)': + '@reown/appkit-utils@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-polyfills': 1.8.11 '@reown/appkit-wallet': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@wallet-standard/wallet': 1.1.0 '@walletconnect/logger': 3.0.2 - '@walletconnect/universal-provider': 2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/universal-provider': 2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) valtio: 2.1.7(@types/react@19.1.7)(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -20916,21 +21828,21 @@ snapshots: - typescript - utf-8-validate - '@reown/appkit@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit@1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-pay': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-pay': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-polyfills': 1.7.20 - '@reown/appkit-scaffold-ui': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) - '@reown/appkit-ui': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-utils': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) + '@reown/appkit-scaffold-ui': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) + '@reown/appkit-ui': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-utils': 1.7.20(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.5(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) '@reown/appkit-wallet': 1.7.20(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@walletconnect/universal-provider': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/universal-provider': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) bs58: 6.0.0 semver: 7.7.2 valtio: 2.1.5(@types/react@19.1.7)(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) optionalDependencies: '@lit/react': 1.0.8(@types/react@19.1.7) transitivePeerDependencies: @@ -20961,21 +21873,21 @@ snapshots: - utf-8-validate - zod - '@reown/appkit@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit@1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-pay': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-pay': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-polyfills': 1.7.8 - '@reown/appkit-scaffold-ui': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) - '@reown/appkit-ui': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-utils': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) + '@reown/appkit-scaffold-ui': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) + '@reown/appkit-ui': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-utils': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) '@reown/appkit-wallet': 1.7.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@walletconnect/types': 2.21.0 - '@walletconnect/universal-provider': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/universal-provider': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) bs58: 6.0.0 valtio: 1.13.2(@types/react@19.1.7)(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -21004,21 +21916,21 @@ snapshots: - utf-8-validate - zod - '@reown/appkit@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@reown/appkit@1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-controllers': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-pay': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit-common': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-controllers': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-pay': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@reown/appkit-polyfills': 1.8.11 - '@reown/appkit-scaffold-ui': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) - '@reown/appkit-ui': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - '@reown/appkit-utils': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@3.25.76) + '@reown/appkit-scaffold-ui': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) + '@reown/appkit-ui': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + '@reown/appkit-utils': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(valtio@2.1.7(@types/react@19.1.7)(react@19.1.4))(zod@4.4.3) '@reown/appkit-wallet': 1.8.11(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@walletconnect/universal-provider': 2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/universal-provider': 2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) bs58: 6.0.0 semver: 7.7.2 valtio: 2.1.7(@types/react@19.1.7)(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) optionalDependencies: '@lit/react': 1.0.8(@types/react@19.1.7) transitivePeerDependencies: @@ -21049,6 +21961,53 @@ snapshots: - utf-8-validate - zod + '@rolldown/binding-android-arm-eabi@1.2.15': + optional: true + + '@rolldown/binding-android-arm64@1.2.15': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.15': + optional: true + + '@rolldown/binding-darwin-x64@1.2.15': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.15': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.15': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.15': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.15': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.15': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.15': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.15': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.15': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + '@rollup/pluginutils@5.3.0(rollup@4.60.4)': dependencies: '@types/estree': 1.0.9 @@ -21138,7 +22097,7 @@ snapshots: '@rtsao/scc@1.1.0': {} - '@rushstack/node-core-library@5.23.1(@types/node@20.16.7)': + '@rushstack/node-core-library@5.23.1(@types/node@24.13.4)': dependencies: ajv: 8.18.0 ajv-draft-04: 1.0.0(ajv@8.18.0) @@ -21149,37 +22108,37 @@ snapshots: resolve: 1.22.12 semver: 7.7.4 optionalDependencies: - '@types/node': 20.16.7 + '@types/node': 24.13.4 - '@rushstack/problem-matcher@0.2.1(@types/node@20.16.7)': + '@rushstack/problem-matcher@0.2.1(@types/node@24.13.4)': optionalDependencies: - '@types/node': 20.16.7 + '@types/node': 24.13.4 '@rushstack/rig-package@0.7.3': dependencies: jju: 1.4.0 resolve: 1.22.12 - '@rushstack/terminal@0.24.0(@types/node@20.16.7)': + '@rushstack/terminal@0.24.0(@types/node@24.13.4)': dependencies: - '@rushstack/node-core-library': 5.23.1(@types/node@20.16.7) - '@rushstack/problem-matcher': 0.2.1(@types/node@20.16.7) + '@rushstack/node-core-library': 5.23.1(@types/node@24.13.4) + '@rushstack/problem-matcher': 0.2.1(@types/node@24.13.4) supports-color: 8.1.1 optionalDependencies: - '@types/node': 20.16.7 + '@types/node': 24.13.4 - '@rushstack/ts-command-line@5.3.9(@types/node@20.16.7)': + '@rushstack/ts-command-line@5.3.9(@types/node@24.13.4)': dependencies: - '@rushstack/terminal': 0.24.0(@types/node@20.16.7) + '@rushstack/terminal': 0.24.0(@types/node@24.13.4) '@types/argparse': 1.0.38 argparse: 1.0.10 string-argv: 0.3.2 transitivePeerDependencies: - '@types/node' - '@safe-global/safe-apps-provider@0.18.6(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@safe-global/safe-apps-provider@0.18.6(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@safe-global/safe-apps-sdk': 9.1.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@safe-global/safe-apps-sdk': 9.1.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) events: 3.3.0 transitivePeerDependencies: - bufferutil @@ -21187,10 +22146,10 @@ snapshots: - utf-8-validate - zod - '@safe-global/safe-apps-sdk@9.1.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@safe-global/safe-apps-sdk@9.1.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@safe-global/safe-gateway-typescript-sdk': 3.23.1 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - bufferutil - typescript @@ -21848,118 +22807,184 @@ snapshots: - typescript - utf-8-validate - '@specify-sh/sdk@0.4.2': + '@specify-sh/core@0.2.0': {} + + '@specify-sh/publisher-sdk@1.2.0(react@19.1.4)': + dependencies: + '@specify-sh/core': 0.2.0 + optionalDependencies: + react: 19.1.4 + + '@stryker-mutator/api@10.1.1': + dependencies: + mutation-testing-metrics: 3.8.4 + mutation-testing-report-schema: 3.8.4 + tslib: 2.8.1 + typed-inject: 5.0.0 + + '@stryker-mutator/core@10.1.1(@types/node@24.13.4)': dependencies: - cross-fetch: 4.0.0 + '@inquirer/prompts': 8.6.0(@types/node@24.13.4) + '@stryker-mutator/api': 10.1.1 + '@stryker-mutator/instrumenter': 10.1.1 + '@stryker-mutator/util': 10.1.1 + ajv: 8.20.0 + chalk: 5.6.2 + commander: 14.0.3 + diff-match-patch: 1.0.5 + emoji-regex: 10.6.0 + execa: 9.6.1 + json-rpc-2.0: 1.7.1 + lodash.groupby: 4.6.0 + minimatch: 10.2.5 + mutation-server-protocol: 0.4.1 + mutation-testing-elements: 3.8.4 + mutation-testing-metrics: 3.8.4 + mutation-testing-report-schema: 3.8.4 + npm-run-path: 6.0.0 + progress: 2.0.3 + rxjs: 7.8.2 + semver: 7.8.5 + source-map: 0.7.6 + tree-kill: 1.2.2 + tslib: 2.8.1 + typed-inject: 5.0.0 + typed-rest-client: 2.3.1 transitivePeerDependencies: - - encoding + - '@types/node' + + '@stryker-mutator/instrumenter@10.1.1': + dependencies: + '@babel/core': 8.0.1 + '@babel/generator': 8.0.0 + '@babel/parser': 8.0.4 + '@babel/plugin-proposal-decorators': 8.0.2(@babel/core@8.0.1) + '@babel/plugin-transform-explicit-resource-management': 8.0.1(@babel/core@8.0.1) + '@babel/preset-react': 8.0.1(@babel/core@8.0.1) + '@babel/preset-typescript': 8.0.1(@babel/core@8.0.1) + '@babel/traverse': 8.0.4 + '@stryker-mutator/api': 10.1.1 + '@stryker-mutator/util': 10.1.1 + angular-html-parser: 10.11.0 + semver: 7.8.5 + tslib: 2.8.1 + weapon-regex: 2.0.4 - '@standard-schema/spec@1.1.0': {} + '@stryker-mutator/util@10.1.1': {} + + '@stryker-mutator/vitest-runner@10.1.1(@stryker-mutator/core@10.1.1(@types/node@24.13.4))(vitest@5.0.0)': + dependencies: + '@stryker-mutator/api': 10.1.1 + '@stryker-mutator/core': 10.1.1(@types/node@24.13.4) + '@stryker-mutator/util': 10.1.1 + semver: 7.8.5 + tslib: 2.8.1 + vitest: 5.0.0(@opentelemetry/api@1.9.1)(@types/node@24.13.4)(@vitest/coverage-v8@5.0.0)(jsdom@27.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6))(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) - '@stylistic/eslint-plugin@5.2.3(eslint@9.39.2)': + '@stylistic/eslint-plugin@5.2.3(eslint@9.39.2(supports-color@10.2.2))': dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(supports-color@10.2.2)) '@typescript-eslint/types': 8.60.0 - eslint: 9.39.2 + eslint: 9.39.2(supports-color@10.2.2) eslint-visitor-keys: 4.2.1 espree: 10.4.0 estraverse: 5.3.0 picomatch: 4.0.4 - '@svgr/babel-plugin-add-jsx-attribute@6.5.1(@babel/core@7.29.7)': + '@svgr/babel-plugin-add-jsx-attribute@6.5.1(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-add-jsx-attribute@8.0.0(@babel/core@7.29.7)': + '@svgr/babel-plugin-add-jsx-attribute@8.0.0(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-remove-jsx-attribute@8.0.0(@babel/core@7.29.7)': + '@svgr/babel-plugin-remove-jsx-attribute@8.0.0(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-remove-jsx-empty-expression@8.0.0(@babel/core@7.29.7)': + '@svgr/babel-plugin-remove-jsx-empty-expression@8.0.0(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-replace-jsx-attribute-value@6.5.1(@babel/core@7.29.7)': + '@svgr/babel-plugin-replace-jsx-attribute-value@6.5.1(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-replace-jsx-attribute-value@8.0.0(@babel/core@7.29.7)': + '@svgr/babel-plugin-replace-jsx-attribute-value@8.0.0(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-svg-dynamic-title@6.5.1(@babel/core@7.29.7)': + '@svgr/babel-plugin-svg-dynamic-title@6.5.1(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-svg-dynamic-title@8.0.0(@babel/core@7.29.7)': + '@svgr/babel-plugin-svg-dynamic-title@8.0.0(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-svg-em-dimensions@6.5.1(@babel/core@7.29.7)': + '@svgr/babel-plugin-svg-em-dimensions@6.5.1(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-svg-em-dimensions@8.0.0(@babel/core@7.29.7)': + '@svgr/babel-plugin-svg-em-dimensions@8.0.0(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-transform-react-native-svg@6.5.1(@babel/core@7.29.7)': + '@svgr/babel-plugin-transform-react-native-svg@6.5.1(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-transform-react-native-svg@8.1.0(@babel/core@7.29.7)': + '@svgr/babel-plugin-transform-react-native-svg@8.1.0(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-transform-svg-component@6.5.1(@babel/core@7.29.7)': + '@svgr/babel-plugin-transform-svg-component@6.5.1(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-plugin-transform-svg-component@8.0.0(@babel/core@7.29.7)': + '@svgr/babel-plugin-transform-svg-component@8.0.0(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) - '@svgr/babel-preset@6.5.1(@babel/core@7.29.7)': + '@svgr/babel-preset@6.5.1(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 - '@svgr/babel-plugin-add-jsx-attribute': 6.5.1(@babel/core@7.29.7) - '@svgr/babel-plugin-remove-jsx-attribute': 8.0.0(@babel/core@7.29.7) - '@svgr/babel-plugin-remove-jsx-empty-expression': 8.0.0(@babel/core@7.29.7) - '@svgr/babel-plugin-replace-jsx-attribute-value': 6.5.1(@babel/core@7.29.7) - '@svgr/babel-plugin-svg-dynamic-title': 6.5.1(@babel/core@7.29.7) - '@svgr/babel-plugin-svg-em-dimensions': 6.5.1(@babel/core@7.29.7) - '@svgr/babel-plugin-transform-react-native-svg': 6.5.1(@babel/core@7.29.7) - '@svgr/babel-plugin-transform-svg-component': 6.5.1(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@svgr/babel-plugin-add-jsx-attribute': 6.5.1(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-remove-jsx-attribute': 8.0.0(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-remove-jsx-empty-expression': 8.0.0(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-replace-jsx-attribute-value': 6.5.1(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-svg-dynamic-title': 6.5.1(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-svg-em-dimensions': 6.5.1(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-transform-react-native-svg': 6.5.1(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-transform-svg-component': 6.5.1(@babel/core@7.29.7(supports-color@10.2.2)) - '@svgr/babel-preset@8.1.0(@babel/core@7.29.7)': + '@svgr/babel-preset@8.1.0(@babel/core@7.29.7(supports-color@10.2.2))': dependencies: - '@babel/core': 7.29.7 - '@svgr/babel-plugin-add-jsx-attribute': 8.0.0(@babel/core@7.29.7) - '@svgr/babel-plugin-remove-jsx-attribute': 8.0.0(@babel/core@7.29.7) - '@svgr/babel-plugin-remove-jsx-empty-expression': 8.0.0(@babel/core@7.29.7) - '@svgr/babel-plugin-replace-jsx-attribute-value': 8.0.0(@babel/core@7.29.7) - '@svgr/babel-plugin-svg-dynamic-title': 8.0.0(@babel/core@7.29.7) - '@svgr/babel-plugin-svg-em-dimensions': 8.0.0(@babel/core@7.29.7) - '@svgr/babel-plugin-transform-react-native-svg': 8.1.0(@babel/core@7.29.7) - '@svgr/babel-plugin-transform-svg-component': 8.0.0(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@svgr/babel-plugin-add-jsx-attribute': 8.0.0(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-remove-jsx-attribute': 8.0.0(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-remove-jsx-empty-expression': 8.0.0(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-replace-jsx-attribute-value': 8.0.0(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-svg-dynamic-title': 8.0.0(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-svg-em-dimensions': 8.0.0(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-transform-react-native-svg': 8.1.0(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/babel-plugin-transform-svg-component': 8.0.0(@babel/core@7.29.7(supports-color@10.2.2)) - '@svgr/core@6.5.1': + '@svgr/core@6.5.1(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@svgr/babel-preset': 6.5.1(@babel/core@7.29.7) - '@svgr/plugin-jsx': 6.5.1(@svgr/core@6.5.1) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@svgr/babel-preset': 6.5.1(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/plugin-jsx': 6.5.1(@svgr/core@6.5.1(supports-color@10.2.2))(supports-color@10.2.2) camelcase: 6.3.0 cosmiconfig: 7.1.0 transitivePeerDependencies: - supports-color - '@svgr/core@8.1.0(@typescript/typescript6@6.0.2)': + '@svgr/core@8.1.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@svgr/babel-preset': 8.1.0(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@svgr/babel-preset': 8.1.0(@babel/core@7.29.7(supports-color@10.2.2)) camelcase: 6.3.0 cosmiconfig: 8.3.6(@typescript/typescript6@6.0.2) snake-case: 3.0.4 @@ -21977,43 +23002,43 @@ snapshots: '@babel/types': 7.29.7 entities: 4.5.0 - '@svgr/plugin-jsx@6.5.1(@svgr/core@6.5.1)': + '@svgr/plugin-jsx@6.5.1(@svgr/core@6.5.1(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@svgr/babel-preset': 6.5.1(@babel/core@7.29.7) - '@svgr/core': 6.5.1 + '@babel/core': 7.29.7(supports-color@10.2.2) + '@svgr/babel-preset': 6.5.1(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/core': 6.5.1(supports-color@10.2.2) '@svgr/hast-util-to-babel-ast': 6.5.1 svg-parser: 2.0.4 transitivePeerDependencies: - supports-color - '@svgr/plugin-jsx@8.1.0(@svgr/core@8.1.0(@typescript/typescript6@6.0.2))': + '@svgr/plugin-jsx@8.1.0(@svgr/core@8.1.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@svgr/babel-preset': 8.1.0(@babel/core@7.29.7) - '@svgr/core': 8.1.0(@typescript/typescript6@6.0.2) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@svgr/babel-preset': 8.1.0(@babel/core@7.29.7(supports-color@10.2.2)) + '@svgr/core': 8.1.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) '@svgr/hast-util-to-babel-ast': 8.0.0 svg-parser: 2.0.4 transitivePeerDependencies: - supports-color - '@svgr/plugin-svgo@6.5.1(@svgr/core@6.5.1)': + '@svgr/plugin-svgo@6.5.1(@svgr/core@6.5.1(supports-color@10.2.2))': dependencies: - '@svgr/core': 6.5.1 + '@svgr/core': 6.5.1(supports-color@10.2.2) cosmiconfig: 7.1.0 deepmerge: 4.3.1 svgo: 2.8.2 - '@svgr/webpack@6.5.1': + '@svgr/webpack@6.5.1(supports-color@10.2.2)': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-react-constant-elements': 7.29.7(@babel/core@7.29.7) - '@babel/preset-env': 7.29.7(@babel/core@7.29.7) - '@babel/preset-react': 7.29.7(@babel/core@7.29.7) - '@babel/preset-typescript': 7.29.7(@babel/core@7.29.7) - '@svgr/core': 6.5.1 - '@svgr/plugin-jsx': 6.5.1(@svgr/core@6.5.1) - '@svgr/plugin-svgo': 6.5.1(@svgr/core@6.5.1) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/plugin-transform-react-constant-elements': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/preset-env': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/preset-react': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@babel/preset-typescript': 7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@svgr/core': 6.5.1(supports-color@10.2.2) + '@svgr/plugin-jsx': 6.5.1(@svgr/core@6.5.1(supports-color@10.2.2))(supports-color@10.2.2) + '@svgr/plugin-svgo': 6.5.1(@svgr/core@6.5.1(supports-color@10.2.2)) transitivePeerDependencies: - supports-color @@ -22402,13 +23427,13 @@ snapshots: web-tree-sitter: 0.24.5 optional: true - '@swagger-api/apidom-reference@1.11.1': + '@swagger-api/apidom-reference@1.11.1(debug@4.4.3(supports-color@10.2.2))': dependencies: '@babel/runtime-corejs3': 7.29.7 '@swagger-api/apidom-core': 1.11.1 '@swagger-api/apidom-error': 1.11.1 '@types/ramda': 0.30.2 - axios: 1.12.0(debug@4.4.3) + axios: 1.12.0(debug@4.4.3(supports-color@10.2.2)) minimatch: 10.2.5 ramda: 0.30.1 ramda-adjunct: 5.1.0(ramda@0.30.1) @@ -22449,10 +23474,6 @@ snapshots: dependencies: apg-lite: 1.0.5 - '@swc/helpers@0.5.15': - dependencies: - tslib: 2.8.1 - '@swc/helpers@0.5.23': dependencies: tslib: 2.8.1 @@ -22468,10 +23489,10 @@ snapshots: '@tabler/icons@3.44.0': {} - '@tanstack/eslint-plugin-query@5.100.5(@typescript/typescript6@6.0.2)(eslint@9.39.2)': + '@tanstack/eslint-plugin-query@5.100.5(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@typescript-eslint/utils': 8.60.0(@typescript/typescript6@6.0.2)(eslint@9.39.2) - eslint: 9.39.2 + '@typescript-eslint/utils': 8.60.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: @@ -22521,10 +23542,9 @@ snapshots: '@thumbmarkjs/thumbmarkjs@0.16.0': {} - '@tokenizer/inflate@0.2.7': + '@tokenizer/inflate@0.4.1(supports-color@10.2.2)': dependencies: - debug: 4.4.3 - fflate: 0.8.3 + debug: 4.4.3(supports-color@10.2.2) token-types: 6.1.2 transitivePeerDependencies: - supports-color @@ -22541,14 +23561,6 @@ snapshots: tree-sitter: 0.22.4 optional: true - '@tsconfig/node10@1.0.12': {} - - '@tsconfig/node12@1.0.11': {} - - '@tsconfig/node14@1.0.3': {} - - '@tsconfig/node16@1.0.4': {} - '@turnkey/api-key-stamper@0.4.7': dependencies: '@noble/curves': 1.9.7 @@ -22582,7 +23594,7 @@ snapshots: '@turnkey/api-key-stamper': 0.4.7 '@turnkey/encoding': 0.5.0 - '@turnkey/sdk-browser@5.8.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@turnkey/sdk-browser@5.8.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@turnkey/api-key-stamper': 0.4.7 '@turnkey/crypto': 2.5.0 @@ -22591,7 +23603,7 @@ snapshots: '@turnkey/iframe-stamper': 2.5.0 '@turnkey/indexed-db-stamper': 1.1.1 '@turnkey/sdk-types': 0.3.0 - '@turnkey/wallet-stamper': 1.0.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@turnkey/wallet-stamper': 1.0.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@turnkey/webauthn-stamper': 0.5.1 bs58check: 4.0.0 buffer: 6.0.3 @@ -22604,11 +23616,11 @@ snapshots: - utf-8-validate - zod - '@turnkey/sdk-server@4.7.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@turnkey/sdk-server@4.7.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@turnkey/api-key-stamper': 0.4.7 '@turnkey/http': 3.10.0 - '@turnkey/wallet-stamper': 1.0.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@turnkey/wallet-stamper': 1.0.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) buffer: 6.0.3 cross-fetch: 3.2.0 transitivePeerDependencies: @@ -22620,16 +23632,16 @@ snapshots: '@turnkey/sdk-types@0.3.0': {} - '@turnkey/viem@0.13.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76)': + '@turnkey/viem@0.13.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3)': dependencies: '@noble/curves': 1.8.0 '@openzeppelin/contracts': 4.9.6 '@turnkey/api-key-stamper': 0.4.7 '@turnkey/http': 3.10.0 - '@turnkey/sdk-browser': 5.8.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@turnkey/sdk-server': 4.7.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@turnkey/sdk-browser': 5.8.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@turnkey/sdk-server': 4.7.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) cross-fetch: 4.1.0 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - bufferutil - encoding @@ -22637,12 +23649,12 @@ snapshots: - utf-8-validate - zod - '@turnkey/wallet-stamper@1.0.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@turnkey/wallet-stamper@1.0.8(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@turnkey/crypto': 2.5.0 '@turnkey/encoding': 0.5.0 optionalDependencies: - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - bufferutil - typescript @@ -22687,13 +23699,13 @@ snapshots: '@types/bunyan@1.8.11': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/cacheable-request@6.0.3': dependencies: '@types/http-cache-semantics': 4.2.0 '@types/keyv': 3.1.4 - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/responselike': 1.0.3 '@types/chai@5.2.3': @@ -22718,7 +23730,7 @@ snapshots: '@types/connect@3.4.38': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/crypto-js@4.2.2': {} @@ -22863,11 +23875,12 @@ snapshots: '@types/dns-packet@5.6.5': dependencies: - '@types/node': 22.12.0 + '@types/node': 24.13.4 '@types/dom-to-image@2.6.7': {} - '@types/estree@1.0.8': {} + '@types/estree@1.0.8': + optional: true '@types/estree@1.0.9': {} @@ -22877,6 +23890,8 @@ snapshots: '@types/filewriter@0.0.33': {} + '@types/gensync@1.0.5': {} + '@types/geojson@7946.0.16': {} '@types/har-format@1.2.16': {} @@ -22899,19 +23914,21 @@ snapshots: '@types/js-cookie@3.0.6': {} + '@types/jsesc@2.5.1': {} + '@types/json-schema@7.0.15': {} '@types/json5@0.0.29': {} '@types/keyv@3.1.4': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/lodash@4.17.24': {} '@types/memcached@2.2.10': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/mixpanel-browser@2.66.0': dependencies: @@ -22922,11 +23939,11 @@ snapshots: '@types/multicast-dns@7.2.4': dependencies: '@types/dns-packet': 5.6.5 - '@types/node': 22.12.0 + '@types/node': 24.13.4 '@types/mysql@2.15.27': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/node@12.20.55': {} @@ -22934,26 +23951,21 @@ snapshots: '@types/node@17.0.45': {} - '@types/node@20.16.7': - dependencies: - undici-types: 6.19.8 - - '@types/node@22.12.0': + '@types/node@24.13.4': dependencies: - undici-types: 6.20.0 + undici-types: 7.18.2 '@types/node@25.9.2': dependencies: undici-types: 7.24.6 - optional: true '@types/oracledb@6.5.2': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/papaparse@5.5.2': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/parse-json@4.0.2': {} @@ -22963,13 +23975,13 @@ snapshots: '@types/pg@8.15.6': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 pg-protocol: 1.14.0 pg-types: 2.2.0 '@types/pg@8.6.1': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 pg-protocol: 1.14.0 pg-types: 2.2.0 @@ -22981,7 +23993,7 @@ snapshots: '@types/qrcode@1.5.6': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/ramda@0.30.2': dependencies: @@ -23014,25 +24026,17 @@ snapshots: '@types/responselike@1.0.3': dependencies: - '@types/node': 22.12.0 - - '@types/retry@0.12.2': {} + '@types/node': 25.9.2 '@types/semver@7.7.1': {} - '@types/sinon@17.0.4': - dependencies: - '@types/sinonjs__fake-timers': 15.0.1 - - '@types/sinonjs__fake-timers@15.0.1': {} - '@types/swagger-ui-react@5.18.0': dependencies: '@types/react': 19.1.7 '@types/tedious@4.0.14': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/tern@0.23.9': dependencies: @@ -23050,11 +24054,11 @@ snapshots: '@types/ws@7.4.7': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/ws@8.18.1': dependencies: - '@types/node': 22.12.0 + '@types/node': 25.9.2 '@types/yargs-parser@21.0.3': {} @@ -23062,15 +24066,17 @@ snapshots: dependencies: '@types/yargs-parser': 21.0.3 - '@typescript-eslint/eslint-plugin@5.62.0(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2)': + '@typesafe-ai/sdk@0.6.0': {} + + '@typescript-eslint/eslint-plugin@5.62.0(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) + '@typescript-eslint/parser': 5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) '@typescript-eslint/scope-manager': 5.62.0 - '@typescript-eslint/type-utils': 5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2) - '@typescript-eslint/utils': 5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2) - debug: 4.4.3 - eslint: 9.39.2 + '@typescript-eslint/type-utils': 5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/utils': 5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + debug: 4.4.3(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) graphemer: 1.4.0 ignore: 5.3.2 natural-compare-lite: 1.4.0 @@ -23081,15 +24087,15 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/eslint-plugin@8.59.2(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2)': + '@typescript-eslint/eslint-plugin@8.59.2(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) + '@typescript-eslint/parser': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) '@typescript-eslint/scope-manager': 8.59.2 - '@typescript-eslint/type-utils': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) - '@typescript-eslint/utils': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) + '@typescript-eslint/type-utils': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/utils': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) '@typescript-eslint/visitor-keys': 8.59.2 - eslint: 9.39.2 + eslint: 9.39.2(supports-color@10.2.2) ignore: 7.0.5 natural-compare: 1.4.0 ts-api-utils: 2.5.0(@typescript/typescript6@6.0.2) @@ -23097,32 +24103,53 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2)': + '@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@typescript-eslint/scope-manager': 5.62.0 + '@typescript-eslint/types': 5.62.0 + '@typescript-eslint/typescript-estree': 5.62.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + debug: 4.4.3(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + optionalDependencies: + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: '@typescript-eslint/scope-manager': 8.59.2 '@typescript-eslint/types': 8.59.2 - '@typescript-eslint/typescript-estree': 8.59.2(@typescript/typescript6@6.0.2) + '@typescript-eslint/typescript-estree': 8.59.2(@typescript/typescript6@6.0.2)(supports-color@10.2.2) '@typescript-eslint/visitor-keys': 8.59.2 - debug: 4.4.3 - eslint: 9.39.2 + debug: 4.4.3(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color - '@typescript-eslint/project-service@8.59.2(@typescript/typescript6@6.0.2)': + '@typescript-eslint/project-service@8.59.2(@typescript/typescript6@6.0.2)(supports-color@10.2.2)': dependencies: '@typescript-eslint/tsconfig-utils': 8.59.2(@typescript/typescript6@6.0.2) '@typescript-eslint/types': 8.59.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color - '@typescript-eslint/project-service@8.60.0(@typescript/typescript6@6.0.2)': + '@typescript-eslint/project-service@8.60.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2)': dependencies: '@typescript-eslint/tsconfig-utils': 8.60.0(@typescript/typescript6@6.0.2) '@typescript-eslint/types': 8.60.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/project-service@8.70.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2)': + dependencies: + '@typescript-eslint/tsconfig-utils': 8.70.0(@typescript/typescript6@6.0.2) + '@typescript-eslint/types': 8.70.0 + debug: 4.4.3(supports-color@10.2.2) typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color @@ -23147,6 +24174,11 @@ snapshots: '@typescript-eslint/types': 8.60.0 '@typescript-eslint/visitor-keys': 8.60.0 + '@typescript-eslint/scope-manager@8.70.0': + dependencies: + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/visitor-keys': 8.70.0 + '@typescript-eslint/tsconfig-utils@8.59.2(@typescript/typescript6@6.0.2)': dependencies: typescript: '@typescript/typescript6@6.0.2' @@ -23155,25 +24187,41 @@ snapshots: dependencies: typescript: '@typescript/typescript6@6.0.2' - '@typescript-eslint/type-utils@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2)': + '@typescript-eslint/tsconfig-utils@8.70.0(@typescript/typescript6@6.0.2)': + dependencies: + typescript: '@typescript/typescript6@6.0.2' + + '@typescript-eslint/type-utils@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@typescript-eslint/typescript-estree': 5.62.0(@typescript/typescript6@6.0.2) - '@typescript-eslint/utils': 5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2) - debug: 4.4.3 - eslint: 9.39.2 + '@typescript-eslint/typescript-estree': 5.62.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + '@typescript-eslint/utils': 5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + debug: 4.4.3(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) tsutils: 3.21.0(@typescript/typescript6@6.0.2) optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color - '@typescript-eslint/type-utils@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2)': + '@typescript-eslint/type-utils@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: '@typescript-eslint/types': 8.59.2 - '@typescript-eslint/typescript-estree': 8.59.2(@typescript/typescript6@6.0.2) - '@typescript-eslint/utils': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) - debug: 4.4.3 - eslint: 9.39.2 + '@typescript-eslint/typescript-estree': 8.59.2(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + '@typescript-eslint/utils': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + debug: 4.4.3(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + ts-api-utils: 2.5.0(@typescript/typescript6@6.0.2) + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/type-utils@8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/typescript-estree': 8.70.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + debug: 4.4.3(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) ts-api-utils: 2.5.0(@typescript/typescript6@6.0.2) typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: @@ -23187,123 +24235,137 @@ snapshots: '@typescript-eslint/types@8.60.0': {} - '@typescript-eslint/typescript-estree@5.62.0(@typescript/typescript6@6.0.2)': + '@typescript-eslint/types@8.70.0': {} + + '@typescript-eslint/typescript-estree@5.62.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2)': dependencies: '@typescript-eslint/types': 5.62.0 '@typescript-eslint/visitor-keys': 5.62.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) globby: 11.1.0 is-glob: 4.0.3 - semver: 7.8.1 + semver: 7.8.5 tsutils: 3.21.0(@typescript/typescript6@6.0.2) optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color - '@typescript-eslint/typescript-estree@5.62.0(typescript@5.9.3)': - dependencies: - '@typescript-eslint/types': 5.62.0 - '@typescript-eslint/visitor-keys': 5.62.0 - debug: 4.4.3 - globby: 11.1.0 - is-glob: 4.0.3 - semver: 7.8.1 - tsutils: 3.21.0(typescript@5.9.3) - optionalDependencies: - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/typescript-estree@7.18.0(@typescript/typescript6@6.0.2)': + '@typescript-eslint/typescript-estree@7.18.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2)': dependencies: '@typescript-eslint/types': 7.18.0 '@typescript-eslint/visitor-keys': 7.18.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) globby: 11.1.0 is-glob: 4.0.3 minimatch: 9.0.9 - semver: 7.8.1 + semver: 7.8.5 ts-api-utils: 1.4.3(@typescript/typescript6@6.0.2) optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color - '@typescript-eslint/typescript-estree@8.59.2(@typescript/typescript6@6.0.2)': + '@typescript-eslint/typescript-estree@8.59.2(@typescript/typescript6@6.0.2)(supports-color@10.2.2)': dependencies: - '@typescript-eslint/project-service': 8.59.2(@typescript/typescript6@6.0.2) + '@typescript-eslint/project-service': 8.59.2(@typescript/typescript6@6.0.2)(supports-color@10.2.2) '@typescript-eslint/tsconfig-utils': 8.59.2(@typescript/typescript6@6.0.2) '@typescript-eslint/types': 8.59.2 '@typescript-eslint/visitor-keys': 8.59.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) minimatch: 10.2.5 - semver: 7.8.1 + semver: 7.8.5 tinyglobby: 0.2.16 ts-api-utils: 2.5.0(@typescript/typescript6@6.0.2) typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color - '@typescript-eslint/typescript-estree@8.60.0(@typescript/typescript6@6.0.2)': + '@typescript-eslint/typescript-estree@8.60.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2)': dependencies: - '@typescript-eslint/project-service': 8.60.0(@typescript/typescript6@6.0.2) + '@typescript-eslint/project-service': 8.60.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) '@typescript-eslint/tsconfig-utils': 8.60.0(@typescript/typescript6@6.0.2) '@typescript-eslint/types': 8.60.0 '@typescript-eslint/visitor-keys': 8.60.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) minimatch: 10.2.5 - semver: 7.8.1 + semver: 7.8.5 tinyglobby: 0.2.16 ts-api-utils: 2.5.0(@typescript/typescript6@6.0.2) typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2)': + '@typescript-eslint/typescript-estree@8.70.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2)': + dependencies: + '@typescript-eslint/project-service': 8.70.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + '@typescript-eslint/tsconfig-utils': 8.70.0(@typescript/typescript6@6.0.2) + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/visitor-keys': 8.70.0 + debug: 4.4.3(supports-color@10.2.2) + minimatch: 10.2.5 + semver: 7.8.5 + tinyglobby: 0.2.17 + ts-api-utils: 2.5.0(@typescript/typescript6@6.0.2) + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/utils@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(supports-color@10.2.2)) '@types/json-schema': 7.0.15 '@types/semver': 7.7.1 '@typescript-eslint/scope-manager': 5.62.0 '@typescript-eslint/types': 5.62.0 - '@typescript-eslint/typescript-estree': 5.62.0(@typescript/typescript6@6.0.2) - eslint: 9.39.2 + '@typescript-eslint/typescript-estree': 5.62.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) eslint-scope: 5.1.1 - semver: 7.8.1 + semver: 7.8.5 transitivePeerDependencies: - supports-color - typescript - '@typescript-eslint/utils@7.18.0(@typescript/typescript6@6.0.2)(eslint@9.39.2)': + '@typescript-eslint/utils@7.18.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(supports-color@10.2.2)) '@typescript-eslint/scope-manager': 7.18.0 '@typescript-eslint/types': 7.18.0 - '@typescript-eslint/typescript-estree': 7.18.0(@typescript/typescript6@6.0.2) - eslint: 9.39.2 + '@typescript-eslint/typescript-estree': 7.18.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) transitivePeerDependencies: - supports-color - typescript - '@typescript-eslint/utils@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2)': + '@typescript-eslint/utils@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(supports-color@10.2.2)) '@typescript-eslint/scope-manager': 8.59.2 '@typescript-eslint/types': 8.59.2 - '@typescript-eslint/typescript-estree': 8.59.2(@typescript/typescript6@6.0.2) - eslint: 9.39.2 + '@typescript-eslint/typescript-estree': 8.59.2(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@8.60.0(@typescript/typescript6@6.0.2)(eslint@9.39.2)': + '@typescript-eslint/utils@8.60.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(supports-color@10.2.2)) '@typescript-eslint/scope-manager': 8.60.0 '@typescript-eslint/types': 8.60.0 - '@typescript-eslint/typescript-estree': 8.60.0(@typescript/typescript6@6.0.2) - eslint: 9.39.2 + '@typescript-eslint/typescript-estree': 8.60.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/utils@8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(supports-color@10.2.2)) + '@typescript-eslint/scope-manager': 8.70.0 + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/typescript-estree': 8.70.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color @@ -23328,6 +24390,11 @@ snapshots: '@typescript-eslint/types': 8.60.0 eslint-visitor-keys: 5.0.1 + '@typescript-eslint/visitor-keys@8.70.0': + dependencies: + '@typescript-eslint/types': 8.70.0 + eslint-visitor-keys: 5.0.1 + '@typescript/typescript-aix-ppc64@7.0.2': optional: true @@ -23407,7 +24474,7 @@ snapshots: '@codemirror/state': 6.6.0 '@codemirror/view': 6.43.0 - '@uiw/react-codemirror@4.25.10(@babel/runtime@7.29.7)(@codemirror/autocomplete@6.20.2)(@codemirror/language@6.0.0)(@codemirror/lint@6.9.6)(@codemirror/search@6.7.0)(@codemirror/state@6.6.0)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.43.0)(codemirror@5.65.21)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)': + '@uiw/react-codemirror@4.25.10(@babel/runtime@7.29.7)(@codemirror/autocomplete@6.20.2)(@codemirror/language@6.0.0)(@codemirror/lint@6.9.6)(@codemirror/search@6.7.0)(@codemirror/state@6.6.0)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.43.0)(codemirror@6.0.2)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)': dependencies: '@babel/runtime': 7.29.7 '@codemirror/commands': 6.10.3 @@ -23415,7 +24482,7 @@ snapshots: '@codemirror/theme-one-dark': 6.1.3 '@codemirror/view': 6.43.0 '@uiw/codemirror-extensions-basic-setup': 4.25.10(@codemirror/autocomplete@6.20.2)(@codemirror/commands@6.10.3)(@codemirror/language@6.0.0)(@codemirror/lint@6.9.6)(@codemirror/search@6.7.0)(@codemirror/state@6.6.0)(@codemirror/view@6.43.0) - codemirror: 5.65.21 + codemirror: 6.0.2 react: 19.1.4 react-dom: 19.1.4(react@19.1.4) transitivePeerDependencies: @@ -23496,57 +24563,39 @@ snapshots: '@visulima/boxen@2.0.10': {} - '@vitejs/plugin-react@4.3.4(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0))': - dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7) - '@types/babel__core': 7.20.5 - react-refresh: 0.14.2 - vite: 6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0) - transitivePeerDependencies: - - supports-color - - '@vitest/expect@4.1.7': + '@vitejs/plugin-react@6.1.2(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0))': dependencies: - '@standard-schema/spec': 1.1.0 - '@types/chai': 5.2.3 - '@vitest/spy': 4.1.7 - '@vitest/utils': 4.1.7 - chai: 6.2.2 - tinyrainbow: 3.1.0 + '@rolldown/pluginutils': 1.0.1 + vite: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) - '@vitest/mocker@4.1.7(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0))': + '@vitest/coverage-v8@5.0.0(vitest@5.0.0)': dependencies: - '@vitest/spy': 4.1.7 - estree-walker: 3.0.3 - magic-string: 0.30.21 - optionalDependencies: - vite: 6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0) + '@bcoe/v8-coverage': 1.0.2 + '@vitest/istanbul-lib-coverage': 1.0.1 + '@vitest/istanbul-lib-report': 1.0.1 + ast-v8-to-istanbul: 1.0.5 + magicast: 0.5.4 + obug: 2.2.1 + std-env: 4.2.0 + tinyrainbow: 3.1.1 + vitest: 5.0.0(@opentelemetry/api@1.9.1)(@types/node@24.13.4)(@vitest/coverage-v8@5.0.0)(jsdom@27.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6))(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) - '@vitest/pretty-format@4.1.7': - dependencies: - tinyrainbow: 3.1.0 + '@vitest/istanbul-lib-coverage@1.0.1': {} - '@vitest/runner@4.1.7': + '@vitest/istanbul-lib-report@1.0.1': dependencies: - '@vitest/utils': 4.1.7 - pathe: 2.0.3 + '@vitest/istanbul-lib-coverage': 1.0.1 - '@vitest/snapshot@4.1.7': + '@vitest/mocker@5.0.0(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0))': dependencies: - '@vitest/pretty-format': 4.1.7 - '@vitest/utils': 4.1.7 - magic-string: 0.30.21 - pathe: 2.0.3 - - '@vitest/spy@4.1.7': {} + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.0 + estree-walker: 3.0.3 + magic-string: 1.3.1 + optionalDependencies: + vite: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) - '@vitest/utils@4.1.7': - dependencies: - '@vitest/pretty-format': 4.1.7 - convert-source-map: 2.0.0 - tinyrainbow: 3.1.0 + '@vitest/spy@5.0.0': {} '@volar/language-core@2.4.28': dependencies: @@ -23554,11 +24603,13 @@ snapshots: '@volar/source-map@2.4.28': {} - '@volar/typescript@2.4.28': + '@volar/typescript@2.4.28(@typescript/typescript6@6.0.2)': dependencies: '@volar/language-core': 2.4.28 path-browserify: 1.0.1 vscode-uri: 3.1.0 + optionalDependencies: + typescript: '@typescript/typescript6@6.0.2' '@vue/compiler-core@3.5.35': dependencies: @@ -23597,19 +24648,19 @@ snapshots: '@vue/shared@3.5.35': {} - '@wagmi/connectors@6.2.0(09e58c13ebbf9932f0a56e13a5b340ff)': - dependencies: - '@base-org/account': 2.4.0(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@3.25.76) - '@coinbase/wallet-sdk': 4.3.6(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@3.25.76) - '@gemini-wallet/core': 0.3.2(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - '@metamask/sdk': 0.33.1(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@safe-global/safe-apps-provider': 0.18.6(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@safe-global/safe-apps-sdk': 9.1.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - '@walletconnect/ethereum-provider': 2.21.1(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) - cbw-sdk: '@coinbase/wallet-sdk@3.9.3' - porto: 0.2.35(71352da693451397413658bdd9d79753) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@wagmi/connectors@6.2.0(df3f0d3afef4414b7f4264d6db7d6a30)': + dependencies: + '@base-org/account': 2.4.0(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@4.4.3) + '@coinbase/wallet-sdk': 4.3.6(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(utf-8-validate@6.0.6)(zod@4.4.3) + '@gemini-wallet/core': 0.3.2(supports-color@10.2.2)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@metamask/sdk': 0.33.1(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + '@safe-global/safe-apps-provider': 0.18.6(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@safe-global/safe-apps-sdk': 9.1.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@walletconnect/ethereum-provider': 2.21.1(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) + cbw-sdk: '@coinbase/wallet-sdk@3.9.3(supports-color@10.2.2)' + porto: 0.2.35(8095bfa4b9e61ff0a46bb10857184fb4) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: @@ -23641,6 +24692,7 @@ snapshots: - fastestsmallesttextencoderdecoder - immer - ioredis + - preact-render-to-string - react - react-native - supports-color @@ -23650,11 +24702,11 @@ snapshots: - wagmi - zod - '@wagmi/core@2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@wagmi/core@2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: eventemitter3: 5.0.1 mipd: 0.0.7(@typescript/typescript6@6.0.2) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) zustand: 5.0.0(@types/react@19.1.7)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) optionalDependencies: '@tanstack/query-core': 5.55.4 @@ -23692,7 +24744,7 @@ snapshots: dependencies: '@wallet-standard/base': 1.1.0 - '@walletconnect/core@2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/core@2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@walletconnect/heartbeat': 1.2.2 '@walletconnect/jsonrpc-provider': 1.0.14 @@ -23706,7 +24758,7 @@ snapshots: '@walletconnect/safe-json': 1.0.2 '@walletconnect/time': 1.0.2 '@walletconnect/types': 2.21.0 - '@walletconnect/utils': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/utils': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/window-getters': 1.0.1 es-toolkit: 1.33.0 events: 3.3.0 @@ -23736,7 +24788,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/core@2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/core@2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@walletconnect/heartbeat': 1.2.2 '@walletconnect/jsonrpc-provider': 1.0.14 @@ -23750,7 +24802,7 @@ snapshots: '@walletconnect/safe-json': 1.0.2 '@walletconnect/time': 1.0.2 '@walletconnect/types': 2.21.1 - '@walletconnect/utils': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/utils': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/window-getters': 1.0.1 es-toolkit: 1.33.0 events: 3.3.0 @@ -23780,7 +24832,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/core@2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/core@2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@walletconnect/heartbeat': 1.2.2 '@walletconnect/jsonrpc-provider': 1.0.14 @@ -23794,7 +24846,7 @@ snapshots: '@walletconnect/safe-json': 1.0.2 '@walletconnect/time': 1.0.2 '@walletconnect/types': 2.21.7 - '@walletconnect/utils': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/utils': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/window-getters': 1.0.1 es-toolkit: 1.39.3 events: 3.3.0 @@ -23824,7 +24876,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/core@2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/core@2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@walletconnect/heartbeat': 1.2.2 '@walletconnect/jsonrpc-provider': 1.0.14 @@ -23838,7 +24890,7 @@ snapshots: '@walletconnect/safe-json': 1.0.2 '@walletconnect/time': 1.0.2 '@walletconnect/types': 2.22.4 - '@walletconnect/utils': 2.22.4(@typescript/typescript6@6.0.2)(zod@3.25.76) + '@walletconnect/utils': 2.22.4(@typescript/typescript6@6.0.2)(zod@4.4.3) '@walletconnect/window-getters': 1.0.1 es-toolkit: 1.39.3 events: 3.3.0 @@ -23868,7 +24920,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/core@2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/core@2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@walletconnect/heartbeat': 1.2.2 '@walletconnect/jsonrpc-provider': 1.0.14 @@ -23882,7 +24934,7 @@ snapshots: '@walletconnect/safe-json': 1.0.2 '@walletconnect/time': 1.0.2 '@walletconnect/types': 2.23.2 - '@walletconnect/utils': 2.23.2(@typescript/typescript6@6.0.2)(zod@3.25.76) + '@walletconnect/utils': 2.23.2(@typescript/typescript6@6.0.2)(zod@4.4.3) '@walletconnect/window-getters': 1.0.1 es-toolkit: 1.39.3 events: 3.3.0 @@ -23916,18 +24968,18 @@ snapshots: dependencies: tslib: 1.14.1 - '@walletconnect/ethereum-provider@2.21.1(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/ethereum-provider@2.21.1(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit': 1.7.8(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/jsonrpc-http-connection': 1.0.8 '@walletconnect/jsonrpc-provider': 1.0.14 '@walletconnect/jsonrpc-types': 1.0.4 '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/keyvaluestorage': 1.1.1 - '@walletconnect/sign-client': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/sign-client': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/types': 2.21.1 - '@walletconnect/universal-provider': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@walletconnect/utils': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/universal-provider': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@walletconnect/utils': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) events: 3.3.0 transitivePeerDependencies: - '@azure/app-configuration' @@ -23957,19 +25009,19 @@ snapshots: - utf-8-validate - zod - '@walletconnect/ethereum-provider@2.23.2(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/ethereum-provider@2.23.2(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@reown/appkit': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@3.25.76) + '@reown/appkit': 1.8.11(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/jsonrpc-http-connection': 1.0.8 '@walletconnect/jsonrpc-provider': 1.0.14 '@walletconnect/jsonrpc-types': 1.0.4 '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/keyvaluestorage': 1.1.1 '@walletconnect/logger': 3.0.2 - '@walletconnect/sign-client': 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/sign-client': 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/types': 2.23.2 - '@walletconnect/universal-provider': 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) - '@walletconnect/utils': 2.23.2(@typescript/typescript6@6.0.2)(zod@3.25.76) + '@walletconnect/universal-provider': 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) + '@walletconnect/utils': 2.23.2(@typescript/typescript6@6.0.2)(zod@4.4.3) events: 3.3.0 transitivePeerDependencies: - '@azure/app-configuration' @@ -24102,16 +25154,16 @@ snapshots: dependencies: tslib: 1.14.1 - '@walletconnect/sign-client@2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/sign-client@2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@walletconnect/core': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/core': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/events': 1.0.1 '@walletconnect/heartbeat': 1.2.2 '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/logger': 2.1.2 '@walletconnect/time': 1.0.2 '@walletconnect/types': 2.21.0 - '@walletconnect/utils': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/utils': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) events: 3.3.0 transitivePeerDependencies: - '@azure/app-configuration' @@ -24138,16 +25190,16 @@ snapshots: - utf-8-validate - zod - '@walletconnect/sign-client@2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/sign-client@2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@walletconnect/core': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/core': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/events': 1.0.1 '@walletconnect/heartbeat': 1.2.2 '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/logger': 2.1.2 '@walletconnect/time': 1.0.2 '@walletconnect/types': 2.21.1 - '@walletconnect/utils': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/utils': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) events: 3.3.0 transitivePeerDependencies: - '@azure/app-configuration' @@ -24174,16 +25226,16 @@ snapshots: - utf-8-validate - zod - '@walletconnect/sign-client@2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/sign-client@2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@walletconnect/core': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/core': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/events': 1.0.1 '@walletconnect/heartbeat': 1.2.2 '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/logger': 2.1.2 '@walletconnect/time': 1.0.2 '@walletconnect/types': 2.21.7 - '@walletconnect/utils': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/utils': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) events: 3.3.0 transitivePeerDependencies: - '@azure/app-configuration' @@ -24210,16 +25262,16 @@ snapshots: - utf-8-validate - zod - '@walletconnect/sign-client@2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/sign-client@2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@walletconnect/core': 2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/core': 2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/events': 1.0.1 '@walletconnect/heartbeat': 1.2.2 '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/logger': 3.0.0 '@walletconnect/time': 1.0.2 '@walletconnect/types': 2.22.4 - '@walletconnect/utils': 2.22.4(@typescript/typescript6@6.0.2)(zod@3.25.76) + '@walletconnect/utils': 2.22.4(@typescript/typescript6@6.0.2)(zod@4.4.3) events: 3.3.0 transitivePeerDependencies: - '@azure/app-configuration' @@ -24246,16 +25298,16 @@ snapshots: - utf-8-validate - zod - '@walletconnect/sign-client@2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/sign-client@2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: - '@walletconnect/core': 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/core': 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/events': 1.0.1 '@walletconnect/heartbeat': 1.2.2 '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/logger': 3.0.2 '@walletconnect/time': 1.0.2 '@walletconnect/types': 2.23.2 - '@walletconnect/utils': 2.23.2(@typescript/typescript6@6.0.2)(zod@3.25.76) + '@walletconnect/utils': 2.23.2(@typescript/typescript6@6.0.2)(zod@4.4.3) events: 3.3.0 transitivePeerDependencies: - '@azure/app-configuration' @@ -24431,7 +25483,7 @@ snapshots: - ioredis - uploadthing - '@walletconnect/universal-provider@2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/universal-provider@2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@walletconnect/events': 1.0.1 '@walletconnect/jsonrpc-http-connection': 1.0.8 @@ -24440,9 +25492,9 @@ snapshots: '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/keyvaluestorage': 1.1.1 '@walletconnect/logger': 2.1.2 - '@walletconnect/sign-client': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/sign-client': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/types': 2.21.0 - '@walletconnect/utils': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/utils': 2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) es-toolkit: 1.33.0 events: 3.3.0 transitivePeerDependencies: @@ -24471,7 +25523,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/universal-provider@2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/universal-provider@2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@walletconnect/events': 1.0.1 '@walletconnect/jsonrpc-http-connection': 1.0.8 @@ -24480,9 +25532,9 @@ snapshots: '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/keyvaluestorage': 1.1.1 '@walletconnect/logger': 2.1.2 - '@walletconnect/sign-client': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/sign-client': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/types': 2.21.1 - '@walletconnect/utils': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/utils': 2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) es-toolkit: 1.33.0 events: 3.3.0 transitivePeerDependencies: @@ -24511,7 +25563,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/universal-provider@2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/universal-provider@2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@walletconnect/events': 1.0.1 '@walletconnect/jsonrpc-http-connection': 1.0.8 @@ -24520,9 +25572,9 @@ snapshots: '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/keyvaluestorage': 1.1.1 '@walletconnect/logger': 2.1.2 - '@walletconnect/sign-client': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/sign-client': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/types': 2.21.7 - '@walletconnect/utils': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/utils': 2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) es-toolkit: 1.39.3 events: 3.3.0 transitivePeerDependencies: @@ -24551,7 +25603,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/universal-provider@2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/universal-provider@2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@walletconnect/events': 1.0.1 '@walletconnect/jsonrpc-http-connection': 1.0.8 @@ -24560,9 +25612,9 @@ snapshots: '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/keyvaluestorage': 1.1.1 '@walletconnect/logger': 3.0.0 - '@walletconnect/sign-client': 2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/sign-client': 2.22.4(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/types': 2.22.4 - '@walletconnect/utils': 2.22.4(@typescript/typescript6@6.0.2)(zod@3.25.76) + '@walletconnect/utils': 2.22.4(@typescript/typescript6@6.0.2)(zod@4.4.3) es-toolkit: 1.39.3 events: 3.3.0 transitivePeerDependencies: @@ -24591,7 +25643,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/universal-provider@2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/universal-provider@2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@walletconnect/events': 1.0.1 '@walletconnect/jsonrpc-http-connection': 1.0.8 @@ -24600,9 +25652,9 @@ snapshots: '@walletconnect/jsonrpc-utils': 1.0.8 '@walletconnect/keyvaluestorage': 1.1.1 '@walletconnect/logger': 3.0.2 - '@walletconnect/sign-client': 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@walletconnect/sign-client': 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) '@walletconnect/types': 2.23.2 - '@walletconnect/utils': 2.23.2(@typescript/typescript6@6.0.2)(zod@3.25.76) + '@walletconnect/utils': 2.23.2(@typescript/typescript6@6.0.2)(zod@4.4.3) es-toolkit: 1.39.3 events: 3.3.0 transitivePeerDependencies: @@ -24631,7 +25683,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/utils@2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/utils@2.21.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@noble/ciphers': 1.2.1 '@noble/curves': 1.8.1 @@ -24649,7 +25701,7 @@ snapshots: detect-browser: 5.3.0 query-string: 7.1.3 uint8arrays: 3.1.0 - viem: 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -24675,7 +25727,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/utils@2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/utils@2.21.1(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@noble/ciphers': 1.2.1 '@noble/curves': 1.8.1 @@ -24693,7 +25745,7 @@ snapshots: detect-browser: 5.3.0 query-string: 7.1.3 uint8arrays: 3.1.0 - viem: 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -24719,7 +25771,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/utils@2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)': + '@walletconnect/utils@2.21.7(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)': dependencies: '@msgpack/msgpack': 3.1.2 '@noble/ciphers': 1.3.0 @@ -24740,7 +25792,7 @@ snapshots: detect-browser: 5.3.0 query-string: 7.1.3 uint8arrays: 3.1.1 - viem: 2.31.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.31.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -24766,7 +25818,7 @@ snapshots: - utf-8-validate - zod - '@walletconnect/utils@2.22.4(@typescript/typescript6@6.0.2)(zod@3.25.76)': + '@walletconnect/utils@2.22.4(@typescript/typescript6@6.0.2)(zod@4.4.3)': dependencies: '@msgpack/msgpack': 3.1.2 '@noble/ciphers': 1.3.0 @@ -24786,7 +25838,7 @@ snapshots: blakejs: 1.2.1 bs58: 6.0.0 detect-browser: 5.3.0 - ox: 0.9.3(@typescript/typescript6@6.0.2)(zod@3.25.76) + ox: 0.9.3(@typescript/typescript6@6.0.2)(zod@4.4.3) uint8arrays: 3.1.1 transitivePeerDependencies: - '@azure/app-configuration' @@ -24811,7 +25863,7 @@ snapshots: - uploadthing - zod - '@walletconnect/utils@2.23.2(@typescript/typescript6@6.0.2)(zod@3.25.76)': + '@walletconnect/utils@2.23.2(@typescript/typescript6@6.0.2)(zod@4.4.3)': dependencies: '@msgpack/msgpack': 3.1.2 '@noble/ciphers': 1.3.0 @@ -24831,7 +25883,7 @@ snapshots: blakejs: 1.2.1 bs58: 6.0.0 detect-browser: 5.3.0 - ox: 0.9.3(@typescript/typescript6@6.0.2)(zod@3.25.76) + ox: 0.9.3(@typescript/typescript6@6.0.2)(zod@4.4.3) uint8arrays: 3.1.1 transitivePeerDependencies: - '@azure/app-configuration' @@ -25514,55 +26566,50 @@ snapshots: '@zag-js/utils@1.41.2': {} - '@zerodev/ecdsa-validator@5.4.9(@zerodev/sdk@5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@zerodev/ecdsa-validator@5.4.9(@zerodev/sdk@5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: - '@zerodev/sdk': 5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + '@zerodev/sdk': 5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) - '@zerodev/multi-chain-ecdsa-validator@5.4.5(@zerodev/sdk@5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(@zerodev/webauthn-key@5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@zerodev/multi-chain-ecdsa-validator@5.4.5(@zerodev/sdk@5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(@zerodev/webauthn-key@5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: '@simplewebauthn/browser': 9.0.1 '@simplewebauthn/typescript-types': 8.3.4 - '@zerodev/sdk': 5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) - '@zerodev/webauthn-key': 5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@zerodev/sdk': 5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) + '@zerodev/webauthn-key': 5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) merkletreejs: 0.3.11 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) - '@zerodev/sdk@5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@zerodev/sdk@5.5.7(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: - semver: 7.8.4 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + semver: 7.8.5 + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) - '@zerodev/webauthn-key@5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))': + '@zerodev/webauthn-key@5.5.0(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))': dependencies: '@noble/curves': 1.9.7 '@simplewebauthn/browser': 8.3.7 '@simplewebauthn/types': 12.0.0 - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) abitype@1.0.6(@typescript/typescript6@6.0.2)(zod@3.25.76): optionalDependencies: typescript: '@typescript/typescript6@6.0.2' zod: 3.25.76 - abitype@1.0.8(@typescript/typescript6@6.0.2)(zod@3.25.76): + abitype@1.0.8(@typescript/typescript6@6.0.2)(zod@4.4.3): optionalDependencies: typescript: '@typescript/typescript6@6.0.2' - zod: 3.25.76 + zod: 4.4.3 abitype@1.1.0(@typescript/typescript6@6.0.2)(zod@3.22.4): optionalDependencies: typescript: '@typescript/typescript6@6.0.2' zod: 3.22.4 - abitype@1.1.0(@typescript/typescript6@6.0.2)(zod@3.25.76): + abitype@1.1.0(@typescript/typescript6@6.0.2)(zod@4.4.3): optionalDependencies: typescript: '@typescript/typescript6@6.0.2' - zod: 3.25.76 - - abitype@1.1.0(typescript@7.0.2)(zod@4.4.3): - optionalDependencies: - typescript: 7.0.2 zod: 4.4.3 abitype@1.2.3(@typescript/typescript6@6.0.2)(zod@3.22.4): @@ -25580,11 +26627,6 @@ snapshots: typescript: '@typescript/typescript6@6.0.2' zod: 4.4.3 - abitype@1.2.3(typescript@7.0.2)(zod@4.4.3): - optionalDependencies: - typescript: 7.0.2 - zod: 4.4.3 - ably@2.17.1(bufferutil@4.1.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(utf-8-validate@6.0.6): dependencies: '@ably/msgpack-js': 0.4.1 @@ -25606,11 +26648,6 @@ snapshots: abort-error@1.0.2: {} - abortable-iterator@5.1.0: - dependencies: - get-iterator: 2.0.1 - it-stream-types: 2.0.4 - abortcontroller-polyfill@1.7.8: {} accepts@2.0.0: @@ -25618,12 +26655,12 @@ snapshots: mime-types: 3.0.2 negotiator: 1.0.0 - acme-client@5.4.0: + acme-client@5.4.0(supports-color@10.2.2): dependencies: '@peculiar/x509': 1.14.3 asn1js: 3.0.10 - axios: 1.12.0(debug@4.4.3) - debug: 4.4.3 + axios: 1.12.0(debug@4.4.3(supports-color@10.2.2)) + debug: 4.4.3(supports-color@10.2.2) node-forge: 1.3.2 transitivePeerDependencies: - supports-color @@ -25702,6 +26739,8 @@ snapshots: alien-signals@0.4.14: {} + angular-html-parser@10.11.0: {} + anser@1.4.10: {} ansi-color@0.2.2: {} @@ -25731,10 +26770,6 @@ snapshots: apg-lite@1.0.5: {} - app-module-path@2.2.0: {} - - arg@4.1.3: {} - argparse@1.0.10: dependencies: sprintf-js: 1.0.3 @@ -25832,14 +26867,18 @@ snapshots: assertion-error@2.0.1: {} - ast-module-types@5.0.0: {} - ast-types-flow@0.0.8: {} ast-types@0.16.1: dependencies: tslib: 2.8.1 + ast-v8-to-istanbul@1.0.5: + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + estree-walker: 3.0.3 + js-tokens: 10.0.0 + async-function@1.0.0: {} async-mutex@0.2.6: @@ -25866,14 +26905,14 @@ snapshots: axe-core@4.11.4: {} - axios-retry@4.5.0(axios@1.12.0): + axios-retry@4.5.0(axios@1.12.0(debug@4.4.3(supports-color@10.2.2))): dependencies: - axios: 1.12.0(debug@4.4.3) + axios: 1.12.0(debug@4.4.3(supports-color@10.2.2)) is-retry-allowed: 2.2.0 - axios@1.12.0(debug@4.4.3): + axios@1.12.0(debug@4.4.3(supports-color@10.2.2)): dependencies: - follow-redirects: 1.16.0(debug@4.4.3) + follow-redirects: 1.16.0(debug@4.4.3(supports-color@10.2.2)) form-data: 4.0.6 proxy-from-env: 1.1.0 transitivePeerDependencies: @@ -25887,27 +26926,27 @@ snapshots: cosmiconfig: 7.1.0 resolve: 1.22.12 - babel-plugin-polyfill-corejs2@0.4.17(@babel/core@7.29.7): + babel-plugin-polyfill-corejs2@0.4.17(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2): dependencies: '@babel/compat-data': 7.29.7 - '@babel/core': 7.29.7 - '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) semver: 6.3.1 transitivePeerDependencies: - supports-color - babel-plugin-polyfill-corejs3@0.14.2(@babel/core@7.29.7): + babel-plugin-polyfill-corejs3@0.14.2(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2): dependencies: - '@babel/core': 7.29.7 - '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) core-js-compat: 3.49.0 transitivePeerDependencies: - supports-color - babel-plugin-polyfill-regenerator@0.6.8(@babel/core@7.29.7): + babel-plugin-polyfill-regenerator@0.6.8(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2): dependencies: - '@babel/core': 7.29.7 - '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -25917,6 +26956,8 @@ snapshots: balanced-match@1.0.2: {} + balanced-match@4.0.4: {} + base-x@3.0.11: dependencies: safe-buffer: 5.2.1 @@ -25951,11 +26992,12 @@ snapshots: bintrees@1.0.2: {} - bl@4.1.0: + birecord@0.1.2: {} + + birnam@1.0.0: dependencies: - buffer: 5.7.1 - inherits: 2.0.4 - readable-stream: 3.6.2 + multiformats: 14.0.5 + weald: 1.1.3 bl@5.1.0: dependencies: @@ -25967,14 +27009,16 @@ snapshots: blo@1.2.0: {} - blockstore-core@5.0.4: + blockstore-core@7.0.1: dependencies: - '@libp2p/logger': 5.2.0 - interface-blockstore: 5.3.2 - interface-store: 6.0.3 + '@libp2p/logger': 6.2.13 + abort-error: 1.0.2 + interface-blockstore: 7.0.1 + interface-store: 8.0.0 + it-all: 3.0.11 it-filter: 3.1.6 it-merge: 3.0.14 - multiformats: 13.4.2 + multiformats: 14.0.5 bn.js@4.11.6: {} @@ -26000,6 +27044,10 @@ snapshots: balanced-match: 1.0.2 concat-map: 0.0.1 + brace-expansion@5.0.9: + dependencies: + balanced-match: 4.0.4 + braces@3.0.3: dependencies: fill-range: 7.1.1 @@ -26046,11 +27094,6 @@ snapshots: buffer-reverse@1.0.1: {} - buffer@5.7.1: - dependencies: - base64-js: 1.5.1 - ieee754: 1.2.1 - buffer@6.0.3: dependencies: base64-js: 1.5.1 @@ -26118,10 +27161,10 @@ snapshots: caniuse-lite@1.0.30001793: {} - cborg@4.5.8: {} - cborg@5.1.1: {} + cborg@6.1.3: {} + centrifuge@5.7.0: dependencies: events: 3.3.0 @@ -26148,6 +27191,8 @@ snapshots: character-reference-invalid@2.0.1: {} + chardet@2.2.0: {} + charenc@0.0.2: {} chokidar@4.0.3: @@ -26158,25 +27203,23 @@ snapshots: dependencies: readdirp: 5.0.0 - chownr@1.1.4: {} - - chrome-launcher@0.15.2: + chrome-launcher@0.15.2(supports-color@10.2.2): dependencies: - '@types/node': 22.12.0 + '@types/node': 24.13.4 escape-string-regexp: 4.0.0 is-wsl: 2.2.0 - lighthouse-logger: 1.4.2 + lighthouse-logger: 1.4.2(supports-color@10.2.2) transitivePeerDependencies: - supports-color chrome-trace-event@1.0.4: {} - chromium-edge-launcher@0.3.0: + chromium-edge-launcher@0.3.0(supports-color@10.2.2): dependencies: - '@types/node': 22.12.0 + '@types/node': 24.13.4 escape-string-regexp: 4.0.0 is-wsl: 2.2.0 - lighthouse-logger: 1.4.2 + lighthouse-logger: 1.4.2(supports-color@10.2.2) mkdirp: 1.0.4 transitivePeerDependencies: - supports-color @@ -26207,6 +27250,8 @@ snapshots: slice-ansi: 8.0.0 string-width: 8.2.1 + cli-width@4.1.0: {} + client-only@0.0.1: {} cliui@6.0.0: @@ -26246,6 +27291,16 @@ snapshots: codemirror@5.65.21: {} + codemirror@6.0.2: + dependencies: + '@codemirror/autocomplete': 6.20.2 + '@codemirror/commands': 6.10.3 + '@codemirror/language': 6.12.3 + '@codemirror/lint': 6.9.6 + '@codemirror/search': 6.7.0 + '@codemirror/state': 6.6.0 + '@codemirror/view': 6.43.0 + color-convert@2.0.1: dependencies: color-name: 1.1.4 @@ -26272,8 +27327,6 @@ snapshots: comma-separated-tokens@2.0.3: {} - commander@10.0.1: {} - commander@12.1.0: {} commander@13.1.0: {} @@ -26301,10 +27354,10 @@ snapshots: confbox@0.2.4: {} - connect@3.7.0: + connect@3.7.0(supports-color@10.2.2): dependencies: - debug: 2.6.9 - finalhandler: 1.1.2 + debug: 2.6.9(supports-color@10.2.2) + finalhandler: 1.1.2(supports-color@10.2.2) parseurl: 1.3.3 utils-merge: 1.0.1 transitivePeerDependencies: @@ -26320,6 +27373,8 @@ snapshots: cookie-es@1.2.3: {} + cookie@1.1.1: {} + copy-to-clipboard@3.3.3: dependencies: toggle-selection: 1.0.6 @@ -26355,8 +27410,6 @@ snapshots: crc-32@1.2.2: {} - create-require@1.1.1: {} - crelt@1.0.6: {} cross-fetch@3.2.0: @@ -26365,12 +27418,6 @@ snapshots: transitivePeerDependencies: - encoding - cross-fetch@4.0.0: - dependencies: - node-fetch: 2.7.0 - transitivePeerDependencies: - - encoding - cross-fetch@4.1.0: dependencies: node-fetch: 2.7.0 @@ -26482,7 +27529,7 @@ snapshots: semver: 7.8.1 tinyglobby: 0.2.16 - css-loader@6.11.0(webpack@5.107.2(esbuild@0.25.12)(postcss@8.5.15)): + css-loader@6.11.0(webpack@5.107.2(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3)): dependencies: icss-utils: 5.1.0(postcss@8.5.15) postcss: 8.5.15 @@ -26493,7 +27540,7 @@ snapshots: postcss-value-parser: 4.2.0 semver: 7.8.1 optionalDependencies: - webpack: 5.107.2(esbuild@0.25.12)(postcss@8.5.15) + webpack: 5.107.2(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3) css-select@4.3.0: dependencies: @@ -26519,7 +27566,7 @@ snapshots: css-tree@2.2.1: dependencies: mdn-data: 2.0.28 - source-map-js: 1.2.1 + source-map-js: 1.2.2 css-tree@2.3.1: dependencies: @@ -26725,11 +27772,11 @@ snapshots: damerau-levenshtein@1.0.8: {} - dappscout-iframe@0.4.0(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)): + dappscout-iframe@0.4.0(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)): dependencies: react: 19.1.4 react-dom: 19.1.4(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) data-uri-to-buffer@4.0.1: {} @@ -26756,11 +27803,12 @@ snapshots: es-errors: 1.3.0 is-data-view: 1.0.2 - datastore-core@10.0.4: + datastore-core@12.0.1: dependencies: - '@libp2p/logger': 5.2.0 - interface-datastore: 8.3.2 - interface-store: 6.0.3 + '@libp2p/logger': 6.2.13 + abort-error: 1.0.2 + interface-datastore: 10.0.1 + interface-store: 8.0.0 it-drain: 3.0.12 it-filter: 3.1.6 it-map: 3.1.6 @@ -26785,21 +27833,29 @@ snapshots: debounce@1.2.1: {} - debug@2.6.9: + debug@2.6.9(supports-color@10.2.2): dependencies: ms: 2.0.0 + optionalDependencies: + supports-color: 10.2.2 - debug@3.2.7: + debug@3.2.7(supports-color@10.2.2): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 10.2.2 - debug@4.3.4: + debug@4.3.4(supports-color@10.2.2): dependencies: ms: 2.1.2 + optionalDependencies: + supports-color: 10.2.2 - debug@4.4.3: + debug@4.4.3(supports-color@10.2.2): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 10.2.2 decamelize@1.2.0: {} @@ -26879,27 +27935,26 @@ snapshots: delay@5.0.0: {} - delay@6.0.0: {} + delay@7.0.0: + dependencies: + random-int: 3.1.0 + unlimited-timeout: 0.1.0 delayed-stream@1.0.0: {} depd@2.0.0: {} - dependency-tree@10.0.9: - dependencies: - commander: 10.0.1 - filing-cabinet: 4.2.0 - precinct: 11.0.5 - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - dequal@2.0.3: {} derive-valtio@0.1.0(valtio@1.13.2(@types/react@19.1.7)(react@19.1.4)): dependencies: valtio: 1.13.2(@types/react@19.1.7)(react@19.1.4) + des.js@1.1.0: + dependencies: + inherits: 2.0.4 + minimalistic-assert: 1.0.1 + destr@2.0.5: {} destroy@1.2.0: {} @@ -26910,50 +27965,7 @@ snapshots: detect-node-es@1.1.0: {} - detective-amd@5.0.2: - dependencies: - ast-module-types: 5.0.0 - escodegen: 2.1.0 - get-amd-module-type: 5.0.1 - node-source-walk: 6.0.2 - - detective-cjs@5.0.1: - dependencies: - ast-module-types: 5.0.0 - node-source-walk: 6.0.2 - - detective-es6@4.0.1: - dependencies: - node-source-walk: 6.0.2 - - detective-postcss@6.1.3: - dependencies: - is-url: 1.2.4 - postcss: 8.5.15 - postcss-values-parser: 6.0.2(postcss@8.5.15) - - detective-sass@5.0.3: - dependencies: - gonzales-pe: 4.3.0 - node-source-walk: 6.0.2 - - detective-scss@4.0.3: - dependencies: - gonzales-pe: 4.3.0 - node-source-walk: 6.0.2 - - detective-stylus@4.0.0: {} - - detective-typescript@11.2.0: - dependencies: - '@typescript-eslint/typescript-estree': 5.62.0(typescript@5.9.3) - ast-module-types: 5.0.0 - node-source-walk: 6.0.2 - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - diff@4.0.4: {} + diff-match-patch@1.0.5: {} diff@8.0.4: {} @@ -26999,6 +28011,10 @@ snapshots: dependencies: domelementtype: 2.3.0 + dompurify@3.4.16: + optionalDependencies: + '@types/trusted-types': 2.0.7 + dompurify@3.4.9: optionalDependencies: '@types/trusted-types': 2.0.7 @@ -27093,6 +28109,8 @@ snapshots: emoji-regex@9.2.2: {} + empathic@2.0.1: {} + encode-utf8@1.0.3: {} encodeurl@1.0.2: {} @@ -27103,10 +28121,10 @@ snapshots: dependencies: once: 1.4.0 - engine.io-client@6.6.5(bufferutil@4.1.0)(utf-8-validate@6.0.6): + engine.io-client@6.6.5(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6): dependencies: '@socket.io/component-emitter': 3.1.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) engine.io-parser: 5.2.3 ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) xmlhttprequest-ssl: 2.1.2 @@ -27117,11 +28135,6 @@ snapshots: engine.io-parser@5.2.3: {} - enhanced-resolve@5.22.0: - dependencies: - graceful-fs: 4.2.11 - tapable: 2.3.3 - enhanced-resolve@5.23.0: dependencies: graceful-fs: 4.2.11 @@ -27182,7 +28195,7 @@ snapshots: has-property-descriptors: 1.0.2 has-proto: 1.2.0 has-symbols: 1.1.0 - hasown: 2.0.3 + hasown: 2.0.4 internal-slot: 1.1.0 is-array-buffer: 3.0.5 is-callable: 1.2.7 @@ -27250,7 +28263,7 @@ snapshots: iterator.prototype: 1.1.5 math-intrinsics: 1.1.0 - es-module-lexer@2.1.0: {} + es-module-lexer@2.3.2: {} es-object-atoms@1.1.2: dependencies: @@ -27285,35 +28298,6 @@ snapshots: dependencies: es6-promise: 4.2.8 - esbuild@0.25.12: - optionalDependencies: - '@esbuild/aix-ppc64': 0.25.12 - '@esbuild/android-arm': 0.25.12 - '@esbuild/android-arm64': 0.25.12 - '@esbuild/android-x64': 0.25.12 - '@esbuild/darwin-arm64': 0.25.12 - '@esbuild/darwin-x64': 0.25.12 - '@esbuild/freebsd-arm64': 0.25.12 - '@esbuild/freebsd-x64': 0.25.12 - '@esbuild/linux-arm': 0.25.12 - '@esbuild/linux-arm64': 0.25.12 - '@esbuild/linux-ia32': 0.25.12 - '@esbuild/linux-loong64': 0.25.12 - '@esbuild/linux-mips64el': 0.25.12 - '@esbuild/linux-ppc64': 0.25.12 - '@esbuild/linux-riscv64': 0.25.12 - '@esbuild/linux-s390x': 0.25.12 - '@esbuild/linux-x64': 0.25.12 - '@esbuild/netbsd-arm64': 0.25.12 - '@esbuild/netbsd-x64': 0.25.12 - '@esbuild/openbsd-arm64': 0.25.12 - '@esbuild/openbsd-x64': 0.25.12 - '@esbuild/openharmony-arm64': 0.25.12 - '@esbuild/sunos-x64': 0.25.12 - '@esbuild/win32-arm64': 0.25.12 - '@esbuild/win32-ia32': 0.25.12 - '@esbuild/win32-x64': 0.25.12 - esbuild@0.28.1: optionalDependencies: '@esbuild/aix-ppc64': 0.28.1 @@ -27349,93 +28333,67 @@ snapshots: escape-string-regexp@4.0.0: {} - escodegen@2.1.0: - dependencies: - esprima: 4.0.1 - estraverse: 5.3.0 - esutils: 2.0.3 - optionalDependencies: - source-map: 0.6.1 - - eslint-config-next@16.2.6(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2): - dependencies: - '@next/eslint-plugin-next': 16.2.6 - eslint: 9.39.2 - eslint-import-resolver-node: 0.3.10 - eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.2) - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2) - eslint-plugin-jsx-a11y: 6.10.2(eslint@9.39.2) - eslint-plugin-react: 7.37.5(eslint@9.39.2) - eslint-plugin-react-hooks: 7.1.1(eslint@9.39.2) - globals: 16.4.0 - typescript-eslint: 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) - optionalDependencies: - typescript: '@typescript/typescript6@6.0.2' - transitivePeerDependencies: - - '@typescript-eslint/parser' - - eslint-import-resolver-webpack - - eslint-plugin-import-x - - supports-color - - eslint-import-resolver-node@0.3.10: + eslint-import-resolver-node@0.3.10(supports-color@10.2.2): dependencies: - debug: 3.2.7 + debug: 3.2.7(supports-color@10.2.2) is-core-module: 2.16.2 resolve: 2.0.0-next.7 transitivePeerDependencies: - supports-color - eslint-import-resolver-node@0.3.9: + eslint-import-resolver-node@0.3.9(supports-color@10.2.2): dependencies: - debug: 3.2.7 + debug: 3.2.7(supports-color@10.2.2) is-core-module: 2.16.2 resolve: 1.22.12 transitivePeerDependencies: - supports-color - eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.2): + eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.31.0)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): dependencies: '@nolyfill/is-core-module': 1.0.39 - debug: 4.4.3 - eslint: 9.39.2 + debug: 4.4.3(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) get-tsconfig: 4.14.0 is-bun-module: 2.0.0 stable-hash: 0.0.5 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 unrs-resolver: 1.12.2 optionalDependencies: - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2) + eslint-plugin-import: 2.31.0(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) transitivePeerDependencies: - supports-color + optional: true - eslint-module-utils@2.12.1(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint-import-resolver-node@0.3.10)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2): + eslint-module-utils@2.12.1(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-node@0.3.10(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): dependencies: - debug: 3.2.7 + debug: 3.2.7(supports-color@10.2.2) optionalDependencies: - '@typescript-eslint/parser': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) - eslint: 9.39.2 - eslint-import-resolver-node: 0.3.10 - eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.2) + '@typescript-eslint/parser': 5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + eslint-import-resolver-node: 0.3.10(supports-color@10.2.2) + eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.31.0)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) transitivePeerDependencies: - supports-color - eslint-module-utils@2.12.1(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint-import-resolver-node@0.3.9)(eslint@9.39.2): + eslint-module-utils@2.12.1(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-node@0.3.9(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): dependencies: - debug: 3.2.7 + debug: 3.2.7(supports-color@10.2.2) optionalDependencies: - '@typescript-eslint/parser': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) - eslint: 9.39.2 - eslint-import-resolver-node: 0.3.9 + '@typescript-eslint/parser': 5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + eslint-import-resolver-node: 0.3.9(supports-color@10.2.2) + eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.31.0)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) transitivePeerDependencies: - supports-color - eslint-plugin-boundaries@6.0.2(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint@9.39.2): + eslint-plugin-boundaries@6.0.2(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): dependencies: - '@boundaries/elements': 2.0.1(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint@9.39.2) + '@boundaries/elements': 2.0.1(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) chalk: 4.1.2 - eslint: 9.39.2 - eslint-import-resolver-node: 0.3.9 - eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint-import-resolver-node@0.3.9)(eslint@9.39.2) + eslint: 9.39.2(supports-color@10.2.2) + eslint-import-resolver-node: 0.3.9(supports-color@10.2.2) + eslint-module-utils: 2.12.1(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-node@0.3.9(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) handlebars: 4.7.9 micromatch: 4.0.8 transitivePeerDependencies: @@ -27449,51 +28407,22 @@ snapshots: lodash: 4.18.1 pkg-dir: 5.0.0 - eslint-plugin-import-helpers@2.0.1(eslint@9.39.2): - dependencies: - eslint: 9.39.2 - - eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint@9.39.2): + eslint-plugin-import-helpers@2.0.1(eslint@9.39.2(supports-color@10.2.2)): dependencies: - '@rtsao/scc': 1.1.0 - array-includes: 3.1.9 - array.prototype.findlastindex: 1.2.6 - array.prototype.flat: 1.3.3 - array.prototype.flatmap: 1.3.3 - debug: 3.2.7 - doctrine: 2.1.0 - eslint: 9.39.2 - eslint-import-resolver-node: 0.3.10 - eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint-import-resolver-node@0.3.10)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2) - hasown: 2.0.3 - is-core-module: 2.16.2 - is-glob: 4.0.3 - minimatch: 3.1.5 - object.fromentries: 2.0.8 - object.groupby: 1.0.3 - object.values: 1.2.1 - semver: 6.3.1 - string.prototype.trimend: 1.0.9 - tsconfig-paths: 3.15.0 - optionalDependencies: - '@typescript-eslint/parser': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) - transitivePeerDependencies: - - eslint-import-resolver-typescript - - eslint-import-resolver-webpack - - supports-color + eslint: 9.39.2(supports-color@10.2.2) - eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2): + eslint-plugin-import@2.31.0(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): dependencies: '@rtsao/scc': 1.1.0 array-includes: 3.1.9 array.prototype.findlastindex: 1.2.6 array.prototype.flat: 1.3.3 array.prototype.flatmap: 1.3.3 - debug: 3.2.7 + debug: 3.2.7(supports-color@10.2.2) doctrine: 2.1.0 - eslint: 9.39.2 - eslint-import-resolver-node: 0.3.10 - eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(eslint-import-resolver-node@0.3.10)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2) + eslint: 9.39.2(supports-color@10.2.2) + eslint-import-resolver-node: 0.3.10(supports-color@10.2.2) + eslint-module-utils: 2.12.1(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(eslint-import-resolver-node@0.3.10(supports-color@10.2.2))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) hasown: 2.0.3 is-core-module: 2.16.2 is-glob: 4.0.3 @@ -27505,13 +28434,13 @@ snapshots: string.prototype.trimend: 1.0.9 tsconfig-paths: 3.15.0 optionalDependencies: - '@typescript-eslint/parser': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) + '@typescript-eslint/parser': 5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) transitivePeerDependencies: - eslint-import-resolver-typescript - eslint-import-resolver-webpack - supports-color - eslint-plugin-jsx-a11y@6.10.2(eslint@9.39.2): + eslint-plugin-jsx-a11y@6.10.2(eslint@9.39.2(supports-color@10.2.2)): dependencies: aria-query: 5.3.2 array-includes: 3.1.9 @@ -27521,7 +28450,7 @@ snapshots: axobject-query: 4.1.0 damerau-levenshtein: 1.0.8 emoji-regex: 9.2.2 - eslint: 9.39.2 + eslint: 9.39.2(supports-color@10.2.2) hasown: 2.0.3 jsx-ast-utils: 3.3.5 language-tags: 1.0.9 @@ -27530,27 +28459,111 @@ snapshots: safe-regex-test: 1.1.0 string.prototype.includes: 2.0.1 - eslint-plugin-playwright@2.0.1(eslint@9.39.2): + eslint-plugin-playwright@2.0.1(eslint@9.39.2(supports-color@10.2.2)): dependencies: - eslint: 9.39.2 + eslint: 9.39.2(supports-color@10.2.2) globals: 13.24.0 - eslint-plugin-react-hooks@5.0.0(eslint@9.39.2): + eslint-plugin-react-dom@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): dependencies: - eslint: 9.39.2 + '@eslint-react/ast': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/eslint': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/jsx': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/shared': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + compare-versions: 6.1.1 + eslint: 9.39.2(supports-color@10.2.2) + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color - eslint-plugin-react-hooks@7.1.1(eslint@9.39.2): + eslint-plugin-react-hooks@5.0.0(eslint@9.39.2(supports-color@10.2.2)): dependencies: - '@babel/core': 7.29.7 - '@babel/parser': 7.29.7 - eslint: 9.39.2 - hermes-parser: 0.25.1 - zod: 4.4.3 - zod-validation-error: 4.0.2(zod@4.4.3) + eslint: 9.39.2(supports-color@10.2.2) + + eslint-plugin-react-jsx@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): + dependencies: + '@eslint-react/ast': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/core': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/eslint': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/jsx': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/shared': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + eslint-plugin-react-naming-convention@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): + dependencies: + '@eslint-react/ast': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/core': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/eslint': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/shared': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/var': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + ts-pattern: 5.9.0 + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + eslint-plugin-react-rsc@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): + dependencies: + '@eslint-react/ast': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/core': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/eslint': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/shared': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/var': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + eslint-plugin-react-web-api@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): + dependencies: + '@eslint-react/ast': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/core': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/eslint': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/shared': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/var': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + birecord: 0.1.2 + eslint: 9.39.2(supports-color@10.2.2) + ts-pattern: 5.9.0 + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - supports-color + + eslint-plugin-react-x@5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): + dependencies: + '@eslint-react/ast': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/core': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/eslint': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/jsx': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/shared': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@eslint-react/var': 5.19.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/scope-manager': 8.70.0 + '@typescript-eslint/type-utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/types': 8.70.0 + '@typescript-eslint/typescript-estree': 8.70.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + '@typescript-eslint/utils': 8.70.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + compare-versions: 6.1.1 + eslint: 9.39.2(supports-color@10.2.2) + string-ts: 2.3.1 + ts-api-utils: 2.5.0(@typescript/typescript6@6.0.2) + ts-pattern: 5.9.0 + typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color - eslint-plugin-react@7.37.5(eslint@9.39.2): + eslint-plugin-react@7.37.5(eslint@9.39.2(supports-color@10.2.2)): dependencies: array-includes: 3.1.9 array.prototype.findlast: 1.2.5 @@ -27558,7 +28571,7 @@ snapshots: array.prototype.tosorted: 1.1.4 doctrine: 2.1.0 es-iterator-helpers: 1.3.2 - eslint: 9.39.2 + eslint: 9.39.2(supports-color@10.2.2) estraverse: 5.3.0 hasown: 2.0.3 jsx-ast-utils: 3.3.5 @@ -27572,24 +28585,24 @@ snapshots: string.prototype.matchall: 4.0.12 string.prototype.repeat: 1.0.0 - eslint-plugin-regexp@2.6.0(eslint@9.39.2): + eslint-plugin-regexp@2.6.0(eslint@9.39.2(supports-color@10.2.2)): dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(supports-color@10.2.2)) '@eslint-community/regexpp': 4.12.2 comment-parser: 1.4.7 - eslint: 9.39.2 + eslint: 9.39.2(supports-color@10.2.2) jsdoc-type-pratt-parser: 4.8.0 refa: 0.12.1 regexp-ast-analysis: 0.7.1 scslre: 0.3.0 - eslint-plugin-vitest@0.5.4(@typescript-eslint/eslint-plugin@5.62.0(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2)(vitest@4.1.7(@opentelemetry/api@1.9.1)(@types/node@20.16.7)(jsdom@27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6))(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0))): + eslint-plugin-vitest@0.5.4(@typescript-eslint/eslint-plugin@5.62.0(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2)(vitest@5.0.0): dependencies: - '@typescript-eslint/utils': 7.18.0(@typescript/typescript6@6.0.2)(eslint@9.39.2) - eslint: 9.39.2 + '@typescript-eslint/utils': 7.18.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) optionalDependencies: - '@typescript-eslint/eslint-plugin': 5.62.0(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2) - vitest: 4.1.7(@opentelemetry/api@1.9.1)(@types/node@20.16.7)(jsdom@27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6))(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) + '@typescript-eslint/eslint-plugin': 5.62.0(@typescript-eslint/parser@5.62.0(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + vitest: 5.0.0(@opentelemetry/api@1.9.1)(@types/node@24.13.4)(@vitest/coverage-v8@5.0.0)(jsdom@27.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6))(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) transitivePeerDependencies: - supports-color - typescript @@ -27610,14 +28623,14 @@ snapshots: eslint-visitor-keys@5.0.1: {} - eslint@9.39.2: + eslint@9.39.2(supports-color@10.2.2): dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.2(supports-color@10.2.2)) '@eslint-community/regexpp': 4.12.2 - '@eslint/config-array': 0.21.2 + '@eslint/config-array': 0.21.2(supports-color@10.2.2) '@eslint/config-helpers': 0.4.2 '@eslint/core': 0.17.0 - '@eslint/eslintrc': 3.3.5 + '@eslint/eslintrc': 3.3.5(supports-color@10.2.2) '@eslint/js': 9.39.2 '@eslint/plugin-kit': 0.4.1 '@humanfs/node': 0.16.8 @@ -27627,7 +28640,7 @@ snapshots: ajv: 6.15.0 chalk: 4.1.2 cross-spawn: 7.0.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) escape-string-regexp: 4.0.0 eslint-scope: 8.4.0 eslint-visitor-keys: 4.2.1 @@ -27679,11 +28692,11 @@ snapshots: etag@1.8.1: {} - eth-block-tracker@7.1.0: + eth-block-tracker@7.1.0(supports-color@10.2.2): dependencies: - '@metamask/eth-json-rpc-provider': 1.0.1 + '@metamask/eth-json-rpc-provider': 1.0.1(supports-color@10.2.2) '@metamask/safe-event-emitter': 3.1.2 - '@metamask/utils': 5.0.2 + '@metamask/utils': 5.0.2(supports-color@10.2.2) json-rpc-random-id: 1.0.1 pify: 3.0.0 transitivePeerDependencies: @@ -27722,8 +28735,6 @@ snapshots: bn.js: 4.11.6 number-to-bn: 1.7.0 - event-iterator@2.0.0: {} - event-target-shim@5.0.1: {} event-target-shim@6.0.2: {} @@ -27736,9 +28747,22 @@ snapshots: events@3.3.0: {} - expand-template@2.0.3: {} + execa@9.6.1: + dependencies: + '@sindresorhus/merge-streams': 4.0.0 + cross-spawn: 7.0.6 + figures: 6.1.0 + get-stream: 9.0.1 + human-signals: 8.0.1 + is-plain-obj: 4.1.0 + is-stream: 4.0.1 + npm-run-path: 6.0.0 + pretty-ms: 9.3.0 + signal-exit: 4.1.0 + strip-final-newline: 4.0.0 + yoctocolors: 2.2.0 - expect-type@1.3.0: {} + expect-type@1.4.0: {} exponential-backoff@3.1.3: {} @@ -27831,6 +28855,10 @@ snapshots: optionalDependencies: picomatch: 4.0.4 + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + fetch-blob@3.2.0: dependencies: node-domexception: 1.0.0 @@ -27838,15 +28866,17 @@ snapshots: fflate@0.4.8: {} - fflate@0.8.3: {} + figures@6.1.0: + dependencies: + is-unicode-supported: 2.1.0 file-entry-cache@8.0.0: dependencies: flat-cache: 4.0.1 - file-type@20.5.0: + file-type@22.1.1(supports-color@10.2.2): dependencies: - '@tokenizer/inflate': 0.2.7 + '@tokenizer/inflate': 0.4.1(supports-color@10.2.2) strtok3: 10.3.5 token-types: 6.1.2 uint8array-extras: 1.5.0 @@ -27855,30 +28885,15 @@ snapshots: file-uri-to-path@1.0.0: {} - filing-cabinet@4.2.0: - dependencies: - app-module-path: 2.2.0 - commander: 10.0.1 - enhanced-resolve: 5.22.0 - is-relative-path: 1.0.2 - module-definition: 5.0.1 - module-lookup-amd: 8.0.5 - resolve: 1.22.12 - resolve-dependency-path: 3.0.2 - sass-lookup: 5.0.1 - stylus-lookup: 5.0.1 - tsconfig-paths: 4.2.0 - typescript: 5.9.3 - fill-range@7.1.1: dependencies: to-regex-range: 5.0.1 filter-obj@1.1.0: {} - finalhandler@1.1.2: + finalhandler@1.1.2(supports-color@10.2.2): dependencies: - debug: 2.6.9 + debug: 2.6.9(supports-color@10.2.2) encodeurl: 1.0.2 escape-html: 1.0.3 on-finished: 2.3.0 @@ -27917,9 +28932,9 @@ snapshots: focus-visible@5.2.1: {} - follow-redirects@1.16.0(debug@4.4.3): + follow-redirects@1.16.0(debug@4.4.3(supports-color@10.2.2)): optionalDependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) fontfaceobserver@2.1.0: {} @@ -27979,8 +28994,6 @@ snapshots: from-exponential@1.1.1: {} - fs-constants@1.0.0: {} - fs-extra@11.3.5: dependencies: graceful-fs: 4.2.11 @@ -28005,23 +29018,23 @@ snapshots: call-bound: 1.0.4 define-properties: 1.2.1 functions-have-names: 1.2.3 - hasown: 2.0.3 + hasown: 2.0.4 is-callable: 1.2.7 functions-have-names@1.2.3: {} - gaxios@7.1.3: + gaxios@7.1.3(supports-color@10.2.2): dependencies: extend: 3.0.2 - https-proxy-agent: 7.0.6 + https-proxy-agent: 7.0.6(supports-color@10.2.2) node-fetch: 3.3.2 rimraf: 5.0.10 transitivePeerDependencies: - supports-color - gcp-metadata@8.1.3: + gcp-metadata@8.1.3(supports-color@10.2.2): dependencies: - gaxios: 7.1.3 + gaxios: 7.1.3(supports-color@10.2.2) google-logging-utils: 1.1.3 json-bigint: 1.0.0 transitivePeerDependencies: @@ -28033,11 +29046,6 @@ snapshots: gensync@1.0.0-beta.2: {} - get-amd-module-type@5.0.1: - dependencies: - ast-module-types: 5.0.0 - node-source-walk: 6.0.2 - get-caller-file@2.0.5: {} get-east-asian-width@1.6.0: {} @@ -28059,8 +29067,6 @@ snapshots: get-nonce@1.0.1: {} - get-own-enumerable-property-symbols@3.0.2: {} - get-port@7.2.0: {} get-proto@1.0.1: @@ -28091,8 +29097,6 @@ snapshots: dependencies: isobject: 3.0.1 - github-from-package@0.0.0: {} - glob-parent@5.1.2: dependencies: is-glob: 4.0.3 @@ -28112,15 +29116,6 @@ snapshots: package-json-from-dist: 1.0.1 path-scurry: 1.11.1 - glob@7.2.3: - dependencies: - fs.realpath: 1.0.0 - inflight: 1.0.6 - inherits: 2.0.4 - minimatch: 3.1.5 - once: 1.4.0 - path-is-absolute: 1.0.1 - glob@8.1.0: dependencies: fs.realpath: 1.0.0 @@ -28141,8 +29136,6 @@ snapshots: globals@15.12.0: {} - globals@16.4.0: {} - globalthis@1.0.4: dependencies: define-properties: 1.2.1 @@ -28166,12 +29159,6 @@ snapshots: slash: 5.1.0 unicorn-magic: 0.4.0 - globrex@0.1.2: {} - - gonzales-pe@4.3.0: - dependencies: - minimist: 1.2.8 - google-logging-utils@1.1.3: {} gopd@1.2.0: {} @@ -28227,11 +29214,11 @@ snapshots: graphemer@1.4.0: {} - graphiql@4.1.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@20.16.7)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)): + graphiql@4.1.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@24.13.4)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)): dependencies: - '@graphiql/plugin-doc-explorer': 0.2.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@20.16.7)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) - '@graphiql/plugin-history': 0.2.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@20.16.7)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) - '@graphiql/react': 0.34.1(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@20.16.7)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) + '@graphiql/plugin-doc-explorer': 0.2.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@24.13.4)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) + '@graphiql/plugin-history': 0.2.2(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@24.13.4)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) + '@graphiql/react': 0.34.1(@codemirror/language@6.0.0)(@emotion/is-prop-valid@1.4.0)(@types/node@24.13.4)(@types/react-dom@19.1.6(@types/react@19.1.7))(@types/react@19.1.7)(graphql-ws@5.16.2(graphql@16.14.0))(graphql@16.14.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) graphql: 16.14.0 react: 19.1.4 react-compiler-runtime: 19.1.0-rc.1(react@19.1.4) @@ -28336,40 +29323,39 @@ snapshots: he@1.2.0: {} - helia@5.5.1(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(utf-8-validate@6.0.6): - dependencies: - '@chainsafe/libp2p-noise': 16.1.5 - '@chainsafe/libp2p-yamux': 7.0.4 - '@helia/block-brokers': 4.2.4 - '@helia/delegated-routing-v1-http-api-client': 4.2.5 - '@helia/interface': 5.4.0 - '@helia/routers': 3.1.3 - '@helia/utils': 1.4.0 - '@ipshipyard/libp2p-auto-tls': 1.0.0 - '@libp2p/autonat': 2.0.38 - '@libp2p/bootstrap': 11.0.47 - '@libp2p/circuit-relay-v2': 3.2.24 - '@libp2p/config': 1.1.31 - '@libp2p/dcutr': 2.0.38 - '@libp2p/identify': 3.0.39 - '@libp2p/interface': 2.11.0 - '@libp2p/kad-dht': 15.1.11 - '@libp2p/keychain': 5.2.9 - '@libp2p/mdns': 11.0.47 - '@libp2p/mplex': 11.0.47 - '@libp2p/ping': 2.0.37 - '@libp2p/tcp': 10.1.19 - '@libp2p/tls': 2.2.7 - '@libp2p/upnp-nat': 3.1.22 - '@libp2p/webrtc': 5.2.24(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)) - '@libp2p/websockets': 9.2.19(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@multiformats/dns': 1.0.13 - blockstore-core: 5.0.4 - datastore-core: 10.0.4 - interface-datastore: 8.3.2 - ipns: 10.1.6 - libp2p: 2.10.0 - multiformats: 13.4.2 + helia@7.1.16(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6): + dependencies: + '@helia/bitswap': 4.0.20(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6) + '@helia/http': 4.0.8 + '@helia/interface': 7.1.2 + '@helia/libp2p': 2.1.5(bufferutil@4.1.0)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2)(utf-8-validate@6.0.6) + '@helia/utils': 3.0.6 + '@ipld/dag-cbor': 10.0.1 + '@ipld/dag-json': 11.0.1 + '@ipld/dag-pb': 4.2.0 + '@ipshipyard/crypto': 1.1.0 + '@ipshipyard/keychain': 1.0.2 + '@libp2p/interface': 3.3.0 + '@libp2p/utils': 7.4.1 + '@multiformats/dns': 1.0.15 + '@multiformats/multiaddr': 13.0.3 + abort-error: 1.0.2 + any-signal: 4.2.0 + birnam: 1.0.0 + blockstore-core: 7.0.1 + cborg: 6.1.3 + datastore-core: 12.0.1 + interface-blockstore: 7.0.1 + interface-datastore: 10.0.1 + it-drain: 3.0.12 + it-filter: 3.1.6 + it-foreach: 2.1.7 + it-merge: 3.0.14 + main-event: 1.0.4 + mortice: 3.3.1 + multiformats: 14.0.5 + progress-events: 1.1.0 + uint8arrays: 6.1.1 transitivePeerDependencies: - bufferutil - react-native @@ -28383,16 +29369,10 @@ snapshots: hermes-compiler@250829098.0.10: {} - hermes-estree@0.25.1: {} - hermes-estree@0.33.3: {} hermes-estree@0.35.0: {} - hermes-parser@0.25.1: - dependencies: - hermes-estree: 0.25.1 - hermes-parser@0.33.3: dependencies: hermes-estree: 0.33.3 @@ -28442,13 +29422,6 @@ snapshots: http-cache-semantics@4.2.0: {} - http-cookie-agent@6.0.8(tough-cookie@5.1.2)(undici@6.26.0): - dependencies: - agent-base: 7.1.4 - tough-cookie: 5.1.2 - optionalDependencies: - undici: 6.26.0 - http-errors@2.0.1: dependencies: depd: 2.0.0 @@ -28457,10 +29430,10 @@ snapshots: statuses: 2.0.2 toidentifier: 1.0.1 - http-proxy-agent@7.0.2: + http-proxy-agent@7.0.2(supports-color@10.2.2): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -28474,13 +29447,15 @@ snapshots: quick-lru: 5.1.1 resolve-alpn: 1.2.1 - https-proxy-agent@7.0.6: + https-proxy-agent@7.0.6(supports-color@10.2.2): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color + human-signals@8.0.1: {} + humanize-duration@3.33.2: {} humanize-ms@1.2.1: @@ -28497,6 +29472,10 @@ snapshots: dependencies: safer-buffer: 2.1.2 + iconv-lite@0.7.3: + dependencies: + safer-buffer: 2.1.2 + icss-utils@5.1.0(postcss@8.5.15): dependencies: postcss: 8.5.15 @@ -28550,25 +29529,28 @@ snapshots: ini@6.0.0: {} - interface-blockstore@5.3.2: + interface-blockstore@7.0.1: dependencies: - interface-store: 6.0.3 - multiformats: 13.4.2 + interface-store: 8.0.0 + multiformats: 14.0.5 - interface-datastore@8.3.2: + interface-datastore@10.0.1: dependencies: - interface-store: 6.0.3 - uint8arrays: 5.1.1 + abort-error: 1.0.2 + interface-store: 8.0.0 + uint8arrays: 6.1.1 interface-datastore@9.0.3: dependencies: interface-store: 7.0.2 uint8arrays: 5.1.1 - interface-store@6.0.3: {} - interface-store@7.0.2: {} + interface-store@8.0.0: + dependencies: + abort-error: 1.0.2 + internal-slot@1.1.0: dependencies: es-errors: 1.3.0 @@ -28589,63 +29571,51 @@ snapshots: ip-regex@5.0.0: {} - ipfs-unixfs-exporter@13.7.3: + ipfs-unixfs-exporter@16.2.3: dependencies: - '@ipld/dag-cbor': 9.2.7 - '@ipld/dag-json': 10.2.9 - '@ipld/dag-pb': 4.1.7 + '@ipld/dag-cbor': 10.0.1 + '@ipld/dag-json': 11.0.1 + '@ipld/dag-pb': 4.2.0 '@multiformats/murmur3': 2.2.5 hamt-sharding: 3.0.8 - interface-blockstore: 5.3.2 - ipfs-unixfs: 11.2.5 - it-filter: 3.1.6 + interface-blockstore: 7.0.1 + ipfs-unixfs: 13.1.2 it-last: 3.0.11 it-map: 3.1.6 it-parallel: 3.0.15 it-pipe: 3.0.1 it-pushable: 3.2.4 - multiformats: 13.4.2 - p-queue: 8.1.1 + it-to-buffer: 5.0.0 + multiformats: 14.0.5 + p-queue: 9.3.0 progress-events: 1.1.0 - ipfs-unixfs-importer@15.4.0: + ipfs-unixfs-importer@17.1.1(supports-color@10.2.2): dependencies: - '@ipld/dag-pb': 4.1.7 + '@ipld/dag-pb': 4.2.0 '@multiformats/murmur3': 2.2.5 + blockstore-core: 7.0.1 hamt-sharding: 3.0.8 - interface-blockstore: 5.3.2 - interface-store: 6.0.3 - ipfs-unixfs: 11.2.5 + interface-blockstore: 7.0.1 + ipfs-unixfs: 13.1.2 it-all: 3.0.11 it-batch: 3.0.11 it-first: 3.0.11 it-parallel-batch: 3.0.11 - multiformats: 13.4.2 + multiformats: 14.0.5 progress-events: 1.1.0 - rabin-wasm: 0.1.5 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + rabin-wasm: 0.1.5(supports-color@10.2.2) + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 transitivePeerDependencies: - encoding - supports-color - ipfs-unixfs@11.2.5: - dependencies: - protons-runtime: 5.6.0 - uint8arraylist: 2.4.9 - - ipns@10.1.6: + ipfs-unixfs@13.1.2: dependencies: - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 3.2.2 - '@libp2p/logger': 6.2.7 - cborg: 5.1.1 - interface-datastore: 9.0.3 - multiformats: 13.4.2 - protons-runtime: 6.0.2 - timestamp-nano: 1.0.1 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + protons-runtime: 8.0.1 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 iron-webcrypto@1.2.1: {} @@ -28692,7 +29662,8 @@ snapshots: is-bun-module@2.0.0: dependencies: - semver: 7.8.1 + semver: 7.8.5 + optional: true is-callable@1.2.7: {} @@ -28702,7 +29673,7 @@ snapshots: is-core-module@2.16.2: dependencies: - hasown: 2.0.3 + hasown: 2.0.4 is-data-view@1.0.2: dependencies: @@ -28769,8 +29740,6 @@ snapshots: is-number@7.0.0: {} - is-obj@1.0.1: {} - is-path-inside@4.0.0: {} is-plain-obj@2.1.0: {} @@ -28792,14 +29761,10 @@ snapshots: call-bound: 1.0.4 gopd: 1.2.0 has-tostringtag: 1.0.2 - hasown: 2.0.3 - - is-regexp@1.0.0: {} + hasown: 2.0.4 is-regexp@3.1.0: {} - is-relative-path@1.0.2: {} - is-retry-allowed@2.2.0: {} is-safe-filename@0.1.1: {} @@ -28829,9 +29794,7 @@ snapshots: dependencies: which-typed-array: 1.1.21 - is-url-superb@4.0.0: {} - - is-url@1.2.4: {} + is-unicode-supported@2.1.0: {} is-weakmap@2.0.2: {} @@ -28874,13 +29837,13 @@ snapshots: it-batch@3.0.11: {} - it-byte-stream@2.0.6: + it-byte-stream@3.0.0: dependencies: abort-error: 1.0.2 it-queueless-pushable: 2.0.5 it-stream-types: 2.0.4 race-signal: 2.0.0 - uint8arraylist: 2.4.9 + uint8arraylist: 3.0.2 it-drain@3.0.12: {} @@ -28900,21 +29863,21 @@ snapshots: it-last@3.0.11: {} - it-length-prefixed-stream@2.0.6: + it-length-prefixed-stream@3.0.1: dependencies: abort-error: 1.0.2 - it-byte-stream: 2.0.6 + it-byte-stream: 3.0.0 it-stream-types: 2.0.4 - uint8-varint: 2.0.5 - uint8arraylist: 2.4.9 + uint8-varint: 3.0.0 + uint8arraylist: 3.0.2 - it-length-prefixed@10.0.2: + it-length-prefixed@11.0.1: dependencies: - it-reader: 6.0.5 + it-reader: 7.0.0 it-stream-types: 2.0.4 - uint8-varint: 2.0.5 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + uint8-varint: 3.0.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 it-length@3.0.11: {} @@ -28926,14 +29889,9 @@ snapshots: dependencies: it-queueless-pushable: 2.0.5 - it-ndjson@1.1.6: - dependencies: - uint8arraylist: 2.4.9 - - it-pair@2.0.6: + it-ndjson@2.0.0: dependencies: - it-stream-types: 2.0.4 - p-defer: 4.0.1 + uint8arraylist: 3.0.2 it-parallel-batch@3.0.11: dependencies: @@ -28951,12 +29909,12 @@ snapshots: it-pushable: 3.2.4 it-stream-types: 2.0.4 - it-protobuf-stream@2.0.6: + it-protobuf-stream@3.0.1: dependencies: abort-error: 1.0.2 - it-length-prefixed-stream: 2.0.6 + it-length-prefixed-stream: 3.0.1 it-stream-types: 2.0.4 - uint8arraylist: 2.4.9 + uint8arraylist: 3.0.2 it-pushable@3.2.4: dependencies: @@ -28968,7 +29926,7 @@ snapshots: it-pushable: 3.2.4 main-event: 1.0.4 race-event: 1.6.1 - race-signal: 2.0.0 + race-signal: 2.0.2 it-queueless-pushable@2.0.5: dependencies: @@ -28981,6 +29939,11 @@ snapshots: it-stream-types: 2.0.4 uint8arraylist: 2.4.9 + it-reader@7.0.0: + dependencies: + it-stream-types: 2.0.4 + uint8arraylist: 3.0.2 + it-sort@3.0.11: dependencies: it-all: 3.0.11 @@ -29007,16 +29970,9 @@ snapshots: dependencies: uint8arrays: 5.1.1 - it-ws@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6): + it-to-buffer@5.0.0: dependencies: - '@types/ws': 8.18.1 - event-iterator: 2.0.0 - it-stream-types: 2.0.4 - uint8arrays: 5.1.1 - ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) - transitivePeerDependencies: - - bufferutil - - utf-8-validate + uint8arrays: 6.1.1 iterator.prototype@1.1.5: dependencies: @@ -29064,7 +30020,7 @@ snapshots: jest-util@29.7.0: dependencies: '@jest/types': 29.6.3 - '@types/node': 22.12.0 + '@types/node': 24.13.4 chalk: 4.1.2 ci-info: 3.9.0 graceful-fs: 4.2.11 @@ -29081,13 +30037,13 @@ snapshots: jest-worker@27.5.1: dependencies: - '@types/node': 22.12.0 + '@types/node': 24.13.4 merge-stream: 2.0.0 supports-color: 8.1.1 jest-worker@29.7.0: dependencies: - '@types/node': 22.12.0 + '@types/node': 24.13.4 jest-util: 29.7.0 merge-stream: 2.0.0 supports-color: 8.1.1 @@ -29102,8 +30058,12 @@ snapshots: js-file-download@0.4.12: {} + js-md4@0.3.2: {} + js-sha3@0.8.0: {} + js-tokens@10.0.0: {} + js-tokens@4.0.0: {} js-yaml@4.1.1: @@ -29114,7 +30074,7 @@ snapshots: jsdoc-type-pratt-parser@4.8.0: {} - jsdom@27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6): + jsdom@27.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6): dependencies: '@acemir/cssom': 0.9.31 '@asamuzakjp/dom-selector': 6.8.1 @@ -29122,8 +30082,8 @@ snapshots: data-urls: 6.0.1 decimal.js: 10.6.0 html-encoding-sniffer: 4.0.0 - http-proxy-agent: 7.0.2 - https-proxy-agent: 7.0.6 + http-proxy-agent: 7.0.2(supports-color@10.2.2) + https-proxy-agent: 7.0.6(supports-color@10.2.2) is-potential-custom-element-name: 1.0.1 parse5: 8.0.1 saxes: 6.0.0 @@ -29151,6 +30111,8 @@ snapshots: json-parse-even-better-errors@2.3.1: {} + json-rpc-2.0@1.7.1: {} + json-rpc-engine@6.1.0: dependencies: '@metamask/safe-event-emitter': 2.0.0 @@ -29222,36 +30184,35 @@ snapshots: prelude-ls: 1.2.1 type-check: 0.4.0 - libp2p@2.10.0: + libp2p@3.3.11: dependencies: '@chainsafe/is-ip': 2.1.0 '@chainsafe/netmask': 2.0.0 - '@libp2p/crypto': 5.1.18 - '@libp2p/interface': 2.11.0 - '@libp2p/interface-internal': 2.3.19 - '@libp2p/logger': 5.2.0 - '@libp2p/multistream-select': 6.0.29 - '@libp2p/peer-collections': 6.0.35 - '@libp2p/peer-id': 5.1.9 - '@libp2p/peer-store': 11.2.7 - '@libp2p/utils': 6.7.2 + '@libp2p/crypto': 5.1.23 + '@libp2p/interface': 3.3.0 + '@libp2p/interface-internal': 3.1.13 + '@libp2p/logger': 6.2.13 + '@libp2p/multistream-select': 7.0.28 + '@libp2p/peer-collections': 7.0.28 + '@libp2p/peer-id': 6.0.15 + '@libp2p/peer-store': 12.0.28 + '@libp2p/utils': 7.4.1 '@multiformats/dns': 1.0.13 - '@multiformats/multiaddr': 12.5.1 - '@multiformats/multiaddr-matcher': 2.0.2 + '@multiformats/multiaddr': 13.0.3 + '@multiformats/multiaddr-matcher': 3.0.2 any-signal: 4.2.0 - datastore-core: 10.0.4 - interface-datastore: 8.3.2 - it-byte-stream: 2.0.6 + datastore-core: 12.0.1 + interface-datastore: 10.0.1 it-merge: 3.0.14 it-parallel: 3.0.15 main-event: 1.0.4 - multiformats: 13.4.2 + multiformats: 14.0.5 p-defer: 4.0.1 - p-retry: 6.2.1 + p-event: 7.1.1 + p-retry: 8.0.1 progress-events: 1.1.0 - race-event: 1.6.1 - race-signal: 1.1.3 - uint8arrays: 5.1.1 + race-signal: 2.0.0 + uint8arrays: 6.1.1 license-report-check@0.1.2: dependencies: @@ -29259,10 +30220,10 @@ snapshots: rc: 1.2.8 stream-json: 1.9.1 - license-report@6.8.1: + license-report@6.8.1(supports-color@10.2.2): dependencies: '@kessler/tableify': 1.0.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) eol: 0.10.0 find-up-simple: 1.0.1 got: 14.6.6 @@ -29275,13 +30236,62 @@ snapshots: transitivePeerDependencies: - supports-color - lighthouse-logger@1.4.2: + lighthouse-logger@1.4.2(supports-color@10.2.2): dependencies: - debug: 2.6.9 + debug: 2.6.9(supports-color@10.2.2) marky: 1.3.0 transitivePeerDependencies: - supports-color + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + lines-and-columns@1.2.4: {} linkify-it@5.0.1: @@ -29344,6 +30354,8 @@ snapshots: lodash.debounce@4.0.8: {} + lodash.groupby@4.6.0: {} + lodash.merge@4.6.2: {} lodash.throttle@4.1.1: {} @@ -29401,9 +30413,17 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 - main-event@1.0.4: {} + magic-string@1.3.1: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 - make-error@1.3.6: {} + magicast@0.5.4: + dependencies: + '@babel/parser': 7.29.7 + '@babel/types': 7.29.7 + source-map-js: 1.2.1 + + main-event@1.0.4: {} makeerror@1.0.12: dependencies: @@ -29456,15 +30476,15 @@ snapshots: treeify: 1.1.0 web3-utils: 1.10.4 - meros@1.3.2(@types/node@20.16.7): + meros@1.3.2(@types/node@24.13.4): optionalDependencies: - '@types/node': 20.16.7 + '@types/node': 24.13.4 mersenne-twister@1.1.0: {} - metro-babel-transformer@0.84.4: + metro-babel-transformer@0.84.4(supports-color@10.2.2): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) flow-enums-runtime: 0.0.6 hermes-parser: 0.35.0 metro-cache-key: 0.84.4 @@ -29476,22 +30496,22 @@ snapshots: dependencies: flow-enums-runtime: 0.0.6 - metro-cache@0.84.4: + metro-cache@0.84.4(supports-color@10.2.2): dependencies: exponential-backoff: 3.1.3 flow-enums-runtime: 0.0.6 - https-proxy-agent: 7.0.6 + https-proxy-agent: 7.0.6(supports-color@10.2.2) metro-core: 0.84.4 transitivePeerDependencies: - supports-color - metro-config@0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6): + metro-config@0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6): dependencies: - connect: 3.7.0 + connect: 3.7.0(supports-color@10.2.2) flow-enums-runtime: 0.0.6 jest-validate: 29.7.0 - metro: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) - metro-cache: 0.84.4 + metro: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + metro-cache: 0.84.4(supports-color@10.2.2) metro-core: 0.84.4 metro-runtime: 0.84.4 yaml: 2.9.0 @@ -29506,9 +30526,9 @@ snapshots: lodash.throttle: 4.1.1 metro-resolver: 0.84.4 - metro-file-map@0.84.4: + metro-file-map@0.84.4(supports-color@10.2.2): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) fb-watchman: 2.0.2 flow-enums-runtime: 0.0.6 graceful-fs: 4.2.11 @@ -29534,9 +30554,9 @@ snapshots: '@babel/runtime': 7.29.7 flow-enums-runtime: 0.0.6 - metro-source-map@0.84.4: + metro-source-map@0.84.4(supports-color@10.2.2): dependencies: - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) '@babel/types': 7.29.7 flow-enums-runtime: 0.0.6 invariant: 2.2.4 @@ -29552,57 +30572,55 @@ snapshots: dependencies: flow-enums-runtime: 0.0.6 invariant: 2.2.4 - metro-source-map: 0.84.4 + metro-source-map: 0.84.4(supports-color@10.2.2) nullthrows: 1.1.1 source-map: 0.5.7 vlq: 1.0.1 - transitivePeerDependencies: - - supports-color - metro-transform-plugins@0.84.4: + metro-transform-plugins@0.84.4(supports-color@10.2.2): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/generator': 7.29.7 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) flow-enums-runtime: 0.0.6 nullthrows: 1.1.1 transitivePeerDependencies: - supports-color - metro-transform-worker@0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6): + metro-transform-worker@0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/generator': 7.29.7 '@babel/parser': 7.29.7 '@babel/types': 7.29.7 flow-enums-runtime: 0.0.6 - metro: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) - metro-babel-transformer: 0.84.4 - metro-cache: 0.84.4 + metro: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + metro-babel-transformer: 0.84.4(supports-color@10.2.2) + metro-cache: 0.84.4(supports-color@10.2.2) metro-cache-key: 0.84.4 metro-minify-terser: 0.84.4 - metro-source-map: 0.84.4 - metro-transform-plugins: 0.84.4 + metro-source-map: 0.84.4(supports-color@10.2.2) + metro-transform-plugins: 0.84.4(supports-color@10.2.2) nullthrows: 1.1.1 transitivePeerDependencies: - bufferutil - supports-color - utf-8-validate - metro@0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6): + metro@0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6): dependencies: '@babel/code-frame': 7.29.7 - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@10.2.2) '@babel/generator': 7.29.7 '@babel/parser': 7.29.7 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@10.2.2) '@babel/types': 7.29.7 accepts: 2.0.0 ci-info: 2.0.0 - connect: 3.7.0 - debug: 4.4.3 + connect: 3.7.0(supports-color@10.2.2) + debug: 4.4.3(supports-color@10.2.2) error-stack-parser: 2.1.4 flow-enums-runtime: 0.0.6 graceful-fs: 4.2.11 @@ -29612,18 +30630,18 @@ snapshots: jest-worker: 29.7.0 jsc-safe-url: 0.2.4 lodash.throttle: 4.1.1 - metro-babel-transformer: 0.84.4 - metro-cache: 0.84.4 + metro-babel-transformer: 0.84.4(supports-color@10.2.2) + metro-cache: 0.84.4(supports-color@10.2.2) metro-cache-key: 0.84.4 - metro-config: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) + metro-config: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) metro-core: 0.84.4 - metro-file-map: 0.84.4 + metro-file-map: 0.84.4(supports-color@10.2.2) metro-resolver: 0.84.4 metro-runtime: 0.84.4 - metro-source-map: 0.84.4 + metro-source-map: 0.84.4(supports-color@10.2.2) metro-symbolicate: 0.84.4 - metro-transform-plugins: 0.84.4 - metro-transform-worker: 0.84.4(bufferutil@4.1.0)(utf-8-validate@6.0.6) + metro-transform-plugins: 0.84.4(supports-color@10.2.2) + metro-transform-worker: 0.84.4(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) mime-types: 3.0.2 nullthrows: 1.1.1 serialize-error: 2.1.0 @@ -29673,11 +30691,11 @@ snapshots: minimatch@10.2.3: dependencies: - brace-expansion: 1.1.12 + brace-expansion: 5.0.9 minimatch@10.2.5: dependencies: - brace-expansion: 1.1.12 + brace-expansion: 5.0.9 minimatch@3.1.5: dependencies: @@ -29705,8 +30723,6 @@ snapshots: dependencies: rrweb: 2.0.0-alpha.18 - mkdirp-classic@0.5.3: {} - mkdirp@1.0.4: {} mlly@1.8.2: @@ -29718,20 +30734,8 @@ snapshots: mockdate@3.0.5: {} - module-definition@5.0.1: - dependencies: - ast-module-types: 5.0.0 - node-source-walk: 6.0.2 - module-details-from-path@1.0.4: {} - module-lookup-amd@8.0.5: - dependencies: - commander: 10.0.1 - glob: 7.2.3 - requirejs: 2.3.8 - requirejs-config-file: 4.0.0 - monaco-editor@0.52.2: {} mortice@3.3.1: @@ -29765,21 +30769,36 @@ snapshots: multiformats@13.4.2: {} - multiformats@14.0.0: {} + multiformats@14.0.5: {} multiformats@9.9.0: {} + mutation-server-protocol@0.4.1: + dependencies: + zod: 4.4.3 + + mutation-testing-elements@3.8.4: {} + + mutation-testing-metrics@3.8.4: + dependencies: + mutation-testing-report-schema: 3.8.4 + + mutation-testing-report-schema@3.8.4: {} + + mute-stream@3.0.0: {} + nanoclone@0.2.1: {} nanoid@3.3.12: {} - nanoid@3.3.18: {} + nanoid@3.3.20: {} nanoid@5.1.11: {} - napi-build-utils@2.0.0: {} + nanoid@6.0.2: {} - napi-postinstall@0.3.4: {} + napi-postinstall@0.3.4: + optional: true natural-compare-lite@1.4.0: {} @@ -29793,86 +30812,83 @@ snapshots: netmask@2.1.1: {} - next-sitemap@4.2.3(next@16.3.1(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.57.0)(@types/node@20.16.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)): + next-sitemap@4.2.3(next@16.4.3(@babel/core@8.0.1)(@opentelemetry/api@1.9.1)(@playwright/test@1.62.1)(@types/node@24.13.4)(babel-plugin-macros@3.1.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)): dependencies: '@corex/deepmerge': 4.0.43 '@next/env': 13.5.11 fast-glob: 3.3.3 minimist: 1.2.8 - next: 16.3.1(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.57.0)(@types/node@20.16.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + next: 16.4.3(@babel/core@8.0.1)(@opentelemetry/api@1.9.1)(@playwright/test@1.62.1)(@types/node@24.13.4)(babel-plugin-macros@3.1.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) next-themes@0.4.4(react-dom@19.1.4(react@19.1.4))(react@19.1.4): dependencies: react: 19.1.4 react-dom: 19.1.4(react@19.1.4) - next@16.2.6(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.57.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4): + next@16.4.3(@babel/core@7.29.7(supports-color@10.2.2))(@opentelemetry/api@1.9.1)(@playwright/test@1.62.1)(@types/node@24.13.4)(babel-plugin-macros@3.1.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4): dependencies: - '@next/env': 16.2.6 - '@swc/helpers': 0.5.15 + '@next/env': 16.4.3 + '@swc/helpers': 0.5.23 baseline-browser-mapping: 2.10.32 caniuse-lite: 1.0.30001793 - postcss: 8.4.31 + postcss: 8.5.23 react: 19.1.4 react-dom: 19.1.4(react@19.1.4) - styled-jsx: 5.1.6(@babel/core@7.29.7)(react@19.1.4) + styled-jsx: 5.1.6(@babel/core@7.29.7(supports-color@10.2.2))(babel-plugin-macros@3.1.0)(react@19.1.4) optionalDependencies: - '@next/swc-darwin-arm64': 16.2.6 - '@next/swc-darwin-x64': 16.2.6 - '@next/swc-linux-arm64-gnu': 16.2.6 - '@next/swc-linux-arm64-musl': 16.2.6 - '@next/swc-linux-x64-gnu': 16.2.6 - '@next/swc-linux-x64-musl': 16.2.6 - '@next/swc-win32-arm64-msvc': 16.2.6 - '@next/swc-win32-x64-msvc': 16.2.6 + '@next/swc-darwin-arm64': 16.4.3 + '@next/swc-darwin-x64': 16.4.3 + '@next/swc-linux-arm64-gnu': 16.4.3 + '@next/swc-linux-arm64-musl': 16.4.3 + '@next/swc-linux-x64-gnu': 16.4.3 + '@next/swc-linux-x64-musl': 16.4.3 + '@next/swc-win32-arm64-msvc': 16.4.3 + '@next/swc-win32-x64-msvc': 16.4.3 '@opentelemetry/api': 1.9.1 - '@playwright/test': 1.57.0 - sharp: 0.34.5 + '@playwright/test': 1.62.1 + sharp: 0.35.5(@types/node@24.13.4) transitivePeerDependencies: - '@babel/core' + - '@types/node' - babel-plugin-macros - next@16.3.1(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.57.0)(@types/node@20.16.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4): + next@16.4.3(@babel/core@8.0.1)(@opentelemetry/api@1.9.1)(@playwright/test@1.62.1)(@types/node@24.13.4)(babel-plugin-macros@3.1.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4): dependencies: - '@next/env': 16.3.1 + '@next/env': 16.4.3 '@swc/helpers': 0.5.23 baseline-browser-mapping: 2.10.32 caniuse-lite: 1.0.30001793 postcss: 8.5.23 react: 19.1.4 react-dom: 19.1.4(react@19.1.4) - styled-jsx: 5.1.6(@babel/core@7.29.7)(react@19.1.4) + styled-jsx: 5.1.6(@babel/core@8.0.1)(babel-plugin-macros@3.1.0)(react@19.1.4) optionalDependencies: - '@next/swc-darwin-arm64': 16.3.1 - '@next/swc-darwin-x64': 16.3.1 - '@next/swc-linux-arm64-gnu': 16.3.1 - '@next/swc-linux-arm64-musl': 16.3.1 - '@next/swc-linux-x64-gnu': 16.3.1 - '@next/swc-linux-x64-musl': 16.3.1 - '@next/swc-win32-arm64-msvc': 16.3.1 - '@next/swc-win32-x64-msvc': 16.3.1 + '@next/swc-darwin-arm64': 16.4.3 + '@next/swc-darwin-x64': 16.4.3 + '@next/swc-linux-arm64-gnu': 16.4.3 + '@next/swc-linux-arm64-musl': 16.4.3 + '@next/swc-linux-x64-gnu': 16.4.3 + '@next/swc-linux-x64-musl': 16.4.3 + '@next/swc-win32-arm64-msvc': 16.4.3 + '@next/swc-win32-x64-msvc': 16.4.3 '@opentelemetry/api': 1.9.1 - '@playwright/test': 1.57.0 - sharp: 0.35.3(@types/node@20.16.7) + '@playwright/test': 1.62.1 + sharp: 0.35.5(@types/node@24.13.4) transitivePeerDependencies: - '@babel/core' - '@types/node' - babel-plugin-macros - nextjs-routes@2.2.5(next@16.3.1(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.57.0)(@types/node@20.16.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)): + nextjs-routes@2.2.5(next@16.4.3(@babel/core@7.29.7(supports-color@10.2.2))(@opentelemetry/api@1.9.1)(@playwright/test@1.62.1)(@types/node@24.13.4)(babel-plugin-macros@3.1.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4)): dependencies: chokidar: 4.0.3 - next: 16.3.1(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@playwright/test@1.57.0)(@types/node@20.16.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) + next: 16.4.3(@babel/core@7.29.7(supports-color@10.2.2))(@opentelemetry/api@1.9.1)(@playwright/test@1.62.1)(@types/node@24.13.4)(babel-plugin-macros@3.1.0)(react-dom@19.1.4(react@19.1.4))(react@19.1.4) no-case@3.0.4: dependencies: lower-case: 2.0.2 tslib: 2.8.1 - node-abi@3.92.0: - dependencies: - semver: 7.8.4 - node-abort-controller@3.1.1: {} node-addon-api@2.0.2: {} @@ -29880,6 +30896,20 @@ snapshots: node-addon-api@8.8.0: optional: true + node-datachannel@0.33.4: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + '@node-datachannel/android-arm64': 0.33.4 + '@node-datachannel/darwin-arm64': 0.33.4 + '@node-datachannel/darwin-x64': 0.33.4 + '@node-datachannel/linux-arm64-gnu': 0.33.4 + '@node-datachannel/linux-arm64-musl': 0.33.4 + '@node-datachannel/linux-x64-gnu': 0.33.4 + '@node-datachannel/linux-x64-musl': 0.33.4 + '@node-datachannel/win32-arm64-msvc': 0.33.4 + '@node-datachannel/win32-x64-msvc': 0.33.4 + node-domexception@1.0.0: {} node-exports-info@1.6.0: @@ -29916,16 +30946,17 @@ snapshots: node-releases@2.0.46: {} - node-source-walk@6.0.2: - dependencies: - '@babel/parser': 7.29.7 - normalize-path@3.0.0: {} normalize-url@6.1.0: {} normalize-url@8.1.1: {} + npm-run-path@6.0.0: + dependencies: + path-key: 4.0.0 + unicorn-magic: 0.3.0 + nth-check@2.1.1: dependencies: boolbase: 1.0.0 @@ -29994,7 +31025,7 @@ snapshots: define-properties: 1.2.1 es-object-atoms: 1.1.2 - obug@2.1.1: {} + obug@2.2.1: {} ofetch@1.5.1: dependencies: @@ -30075,54 +31106,54 @@ snapshots: transitivePeerDependencies: - zod - ox@0.6.7(@typescript/typescript6@6.0.2)(zod@3.25.76): + ox@0.14.25(@typescript/typescript6@6.0.2)(zod@4.4.3): dependencies: '@adraffy/ens-normalize': 1.11.1 - '@noble/curves': 1.9.7 + '@noble/ciphers': 1.3.0 + '@noble/curves': 1.9.1 '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 - abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@3.25.76) + abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@4.4.3) eventemitter3: 5.0.1 optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - zod - ox@0.6.9(@typescript/typescript6@6.0.2)(zod@3.25.76): + ox@0.6.7(@typescript/typescript6@6.0.2)(zod@4.4.3): dependencies: '@adraffy/ens-normalize': 1.11.1 '@noble/curves': 1.9.7 '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 - abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@3.25.76) + abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@4.4.3) eventemitter3: 5.0.1 optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - zod - ox@0.7.1(@typescript/typescript6@6.0.2)(zod@3.25.76): + ox@0.6.9(@typescript/typescript6@6.0.2)(zod@4.4.3): dependencies: '@adraffy/ens-normalize': 1.11.1 - '@noble/ciphers': 1.3.0 '@noble/curves': 1.9.7 '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 - abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@3.25.76) + abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@4.4.3) eventemitter3: 5.0.1 optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - zod - ox@0.9.17(@typescript/typescript6@6.0.2)(zod@4.4.3): + ox@0.7.1(@typescript/typescript6@6.0.2)(zod@4.4.3): dependencies: '@adraffy/ens-normalize': 1.11.1 '@noble/ciphers': 1.3.0 - '@noble/curves': 1.9.1 + '@noble/curves': 1.9.7 '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 @@ -30133,7 +31164,7 @@ snapshots: transitivePeerDependencies: - zod - ox@0.9.3(@typescript/typescript6@6.0.2)(zod@3.25.76): + ox@0.9.17(@typescript/typescript6@6.0.2)(zod@4.4.3): dependencies: '@adraffy/ens-normalize': 1.11.1 '@noble/ciphers': 1.3.0 @@ -30141,14 +31172,14 @@ snapshots: '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 - abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@3.25.76) + abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@4.4.3) eventemitter3: 5.0.1 optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - zod - ox@0.9.6(@typescript/typescript6@6.0.2)(zod@3.22.4): + ox@0.9.3(@typescript/typescript6@6.0.2)(zod@4.4.3): dependencies: '@adraffy/ens-normalize': 1.11.1 '@noble/ciphers': 1.3.0 @@ -30156,14 +31187,14 @@ snapshots: '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 - abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@3.22.4) + abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@4.4.3) eventemitter3: 5.0.1 optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - zod - ox@0.9.6(@typescript/typescript6@6.0.2)(zod@3.25.76): + ox@0.9.6(@typescript/typescript6@6.0.2)(zod@3.22.4): dependencies: '@adraffy/ens-normalize': 1.11.1 '@noble/ciphers': 1.3.0 @@ -30171,14 +31202,14 @@ snapshots: '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 - abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@3.25.76) + abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@3.22.4) eventemitter3: 5.0.1 optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - zod - ox@0.9.6(typescript@7.0.2)(zod@4.4.3): + ox@0.9.6(@typescript/typescript6@6.0.2)(zod@4.4.3): dependencies: '@adraffy/ens-normalize': 1.11.1 '@noble/ciphers': 1.3.0 @@ -30186,10 +31217,10 @@ snapshots: '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 - abitype: 1.2.3(typescript@7.0.2)(zod@4.4.3) + abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@4.4.3) eventemitter3: 5.0.1 optionalDependencies: - typescript: 7.0.2 + typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - zod @@ -30199,9 +31230,9 @@ snapshots: p-defer@4.0.1: {} - p-event@6.0.1: + p-event@7.1.1: dependencies: - p-timeout: 6.1.4 + p-timeout: 7.0.1 p-limit@2.3.0: dependencies: @@ -30219,31 +31250,20 @@ snapshots: dependencies: p-limit: 3.1.0 - p-queue@8.1.1: - dependencies: - eventemitter3: 5.0.4 - p-timeout: 6.1.4 - p-queue@9.3.0: dependencies: eventemitter3: 5.0.4 p-timeout: 7.0.1 - p-retry@6.2.1: + p-retry@8.0.1: dependencies: - '@types/retry': 0.12.2 is-network-error: 1.3.2 - retry: 0.13.1 - - p-timeout@6.1.4: {} p-timeout@7.0.1: {} p-try@2.2.0: {} - p-wait-for@5.0.2: - dependencies: - p-timeout: 6.1.4 + p-wait-for@6.0.0: {} package-json-from-dist@1.0.1: {} @@ -30278,6 +31298,8 @@ snapshots: json-parse-even-better-errors: 2.3.1 lines-and-columns: 1.2.4 + parse-ms@4.0.0: {} + parse5@8.0.1: dependencies: entities: 8.0.0 @@ -30288,10 +31310,10 @@ snapshots: path-exists@4.0.0: {} - path-is-absolute@1.0.1: {} - path-key@3.1.1: {} + path-key@4.0.0: {} + path-parse@1.0.7: {} path-scurry@1.11.1: @@ -30327,6 +31349,8 @@ snapshots: picomatch@4.0.4: {} + picomatch@4.0.7: {} + pify@3.0.0: {} pify@5.0.0: {} @@ -30433,11 +31457,11 @@ snapshots: exsolve: 1.0.8 pathe: 2.0.3 - playwright-core@1.57.0: {} + playwright-core@1.62.1: {} - playwright@1.57.0: + playwright@1.62.1: dependencies: - playwright-core: 1.57.0 + playwright-core: 1.62.1 optionalDependencies: fsevents: 2.3.2 @@ -30445,22 +31469,22 @@ snapshots: pony-cause@2.1.11: {} - porto@0.2.35(71352da693451397413658bdd9d79753): + porto@0.2.35(8095bfa4b9e61ff0a46bb10857184fb4): dependencies: - '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) hono: 4.12.25 idb-keyval: 6.2.4 mipd: 0.0.7(@typescript/typescript6@6.0.2) ox: 0.9.17(@typescript/typescript6@6.0.2)(zod@4.4.3) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) zod: 4.4.3 zustand: 5.0.13(@types/react@19.1.7)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4)) optionalDependencies: '@tanstack/react-query': 5.55.4(react@19.1.4) react: 19.1.4 - react-native: 0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6) + react-native: 0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6) typescript: '@typescript/typescript6@6.0.2' - wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76) + wagmi: 2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3) transitivePeerDependencies: - '@types/react' - immer @@ -30498,30 +31522,23 @@ snapshots: postcss-value-parser@4.2.0: {} - postcss-values-parser@6.0.2(postcss@8.5.15): - dependencies: - color-name: 1.1.4 - is-url-superb: 4.0.0 - postcss: 8.5.15 - quote-unquote: 1.0.0 - - postcss@8.4.31: + postcss@8.5.15: dependencies: nanoid: 3.3.12 picocolors: 1.1.1 source-map-js: 1.2.1 - postcss@8.5.15: + postcss@8.5.23: dependencies: - nanoid: 3.3.12 + nanoid: 3.3.20 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 - postcss@8.5.23: + postcss@8.5.31: dependencies: - nanoid: 3.3.18 + nanoid: 3.3.20 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 postgres-array@2.0.0: {} @@ -30533,57 +31550,29 @@ snapshots: dependencies: xtend: 4.0.2 - posthog-js@1.376.2: + posthog-js@1.434.15(@types/react@19.1.7)(react@19.1.4): dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.208.0 - '@opentelemetry/exporter-logs-otlp-http': 0.208.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/api@1.9.1) - '@posthog/core': 1.29.11 - '@posthog/types': 1.376.2 + '@posthog/browser-common': 0.9.0 + '@posthog/core': 1.55.2 + '@posthog/types': 1.412.4 core-js: 3.49.0 - dompurify: 3.4.9 + dompurify: 3.4.16 fflate: 0.4.8 - preact: 10.29.2 + preact: 10.29.8 query-selector-shadow-dom: 1.0.1 - web-vitals: 5.2.0 + web-vitals: 6.2.2 + web-vitals-soft-navs: web-vitals@6.2.1 + optionalDependencies: + '@types/react': 19.1.7 + react: 19.1.4 + transitivePeerDependencies: + - preact-render-to-string preact@10.24.2: {} preact@10.29.2: {} - prebuild-install@7.1.3: - dependencies: - detect-libc: 2.1.2 - expand-template: 2.0.3 - github-from-package: 0.0.0 - minimist: 1.2.8 - mkdirp-classic: 0.5.3 - napi-build-utils: 2.0.0 - node-abi: 3.92.0 - pump: 3.0.4 - rc: 1.2.8 - simple-get: 4.0.1 - tar-fs: 2.1.4 - tunnel-agent: 0.6.0 - - precinct@11.0.5: - dependencies: - '@dependents/detective-less': 4.1.0 - commander: 10.0.1 - detective-amd: 5.0.2 - detective-cjs: 5.0.1 - detective-es6: 4.0.1 - detective-postcss: 6.1.3 - detective-sass: 5.0.3 - detective-scss: 4.0.3 - detective-stylus: 4.0.0 - detective-typescript: 11.2.0 - module-definition: 5.0.1 - node-source-walk: 6.0.2 - transitivePeerDependencies: - - supports-color + preact@10.29.8: {} prelude-ls@1.2.1: {} @@ -30601,6 +31590,10 @@ snapshots: ansi-styles: 5.2.0 react-is: 18.3.1 + pretty-ms@9.3.0: + dependencies: + parse-ms: 4.0.0 + prismjs@1.30.0: {} process-nextick-args@2.0.1: {} @@ -30617,6 +31610,8 @@ snapshots: progress-events@1.1.0: {} + progress@2.0.3: {} + prom-client@15.1.1: dependencies: '@opentelemetry/api': 1.9.1 @@ -30648,20 +31643,26 @@ snapshots: '@protobufjs/path': 1.1.2 '@protobufjs/pool': 1.1.0 '@protobufjs/utf8': 1.1.1 - '@types/node': 22.12.0 + '@types/node': 25.9.2 long: 5.3.2 - protons-runtime@5.6.0: + protons-runtime@6.0.2: dependencies: uint8-varint: 2.0.5 uint8arraylist: 2.4.9 uint8arrays: 5.1.1 - protons-runtime@6.0.2: + protons-runtime@7.1.2: dependencies: - uint8-varint: 2.0.5 - uint8arraylist: 2.4.9 - uint8arrays: 5.1.1 + uint8-varint: 3.0.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 + + protons-runtime@8.0.1: + dependencies: + uint8-varint: 3.0.0 + uint8arraylist: 3.0.2 + uint8arrays: 6.1.1 proxy-compare@2.6.0: {} @@ -30716,6 +31717,10 @@ snapshots: pngjs: 5.0.0 yargs: 15.4.1 + qs@6.15.1: + dependencies: + side-channel: 1.1.0 + quansync@0.2.11: {} query-selector-shadow-dom@1.0.1: {} @@ -30741,13 +31746,13 @@ snapshots: quick-lru@5.1.1: {} - quote-unquote@1.0.0: {} + quick-lru@7.3.0: {} - rabin-wasm@0.1.5: + rabin-wasm@0.1.5(supports-color@10.2.2): dependencies: '@assemblyscript/loader': 0.9.4 bl: 5.1.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) minimist: 1.2.8 node-fetch: 2.7.0 readable-stream: 3.6.2 @@ -30759,10 +31764,10 @@ snapshots: dependencies: abort-error: 1.0.2 - race-signal@1.1.3: {} - race-signal@2.0.0: {} + race-signal@2.0.2: {} + radix3@1.1.2: {} ramda-adjunct@5.1.0(ramda@0.30.1): @@ -30776,6 +31781,8 @@ snapshots: drange: 1.1.1 ret: 0.2.2 + random-int@3.1.0: {} + randombytes@2.1.0: dependencies: safe-buffer: 5.2.1 @@ -30873,7 +31880,7 @@ snapshots: dependencies: react: 19.1.4 - react-i18next@13.5.0(i18next@23.4.6)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4): + react-i18next@13.5.0(i18next@23.4.6)(react-dom@19.1.4(react@19.1.4))(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4): dependencies: '@babel/runtime': 7.29.7 html-parse-stringify: 3.0.1 @@ -30881,7 +31888,7 @@ snapshots: react: 19.1.4 optionalDependencies: react-dom: 19.1.4(react@19.1.4) - react-native: 0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6) + react-native: 0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6) react-identicons@1.2.5(react-dom@19.1.4(react@19.1.4))(react@19.1.4): dependencies: @@ -30925,24 +31932,24 @@ snapshots: react: 19.1.4 react-dom: 19.1.4(react@19.1.4) - react-native-webrtc@124.0.7(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6)): + react-native-webrtc@124.0.7(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(supports-color@10.2.2): dependencies: base64-js: 1.5.1 - debug: 4.3.4 + debug: 4.3.4(supports-color@10.2.2) event-target-shim: 6.0.2 - react-native: 0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6) + react-native: 0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6) transitivePeerDependencies: - supports-color - react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6): + react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6): dependencies: '@react-native/assets-registry': 0.85.3 - '@react-native/codegen': 0.85.3(@babel/core@7.29.7) - '@react-native/community-cli-plugin': 0.85.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) + '@react-native/codegen': 0.85.3(@babel/core@7.29.7(supports-color@10.2.2)) + '@react-native/community-cli-plugin': 0.85.3(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) '@react-native/gradle-plugin': 0.85.3 '@react-native/js-polyfills': 0.85.3 '@react-native/normalize-colors': 0.85.3 - '@react-native/virtualized-lists': 0.85.3(@types/react@19.1.7)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4) + '@react-native/virtualized-lists': 0.85.3(@types/react@19.1.7)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4) abort-controller: 3.0.0 anser: 1.4.10 ansi-regex: 5.0.1 @@ -30954,7 +31961,7 @@ snapshots: invariant: 2.2.4 memoize-one: 5.2.1 metro-runtime: 0.84.4 - metro-source-map: 0.84.4 + metro-source-map: 0.84.4(supports-color@10.2.2) nullthrows: 1.1.1 pretty-format: 29.7.0 promise: 8.3.0 @@ -31153,6 +32160,15 @@ snapshots: '@eslint-community/regexpp': 4.12.2 refa: 0.12.1 + regexp.escape@2.0.1: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + for-each: 0.3.5 + safe-regex-test: 1.1.0 + regexp.prototype.flags@1.5.4: dependencies: call-bind: 1.0.9 @@ -31190,30 +32206,21 @@ snapshots: require-from-string@2.0.2: {} - require-in-the-middle@8.0.1: + require-in-the-middle@8.0.1(supports-color@10.2.2): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) module-details-from-path: 1.0.4 transitivePeerDependencies: - supports-color require-main-filename@2.0.0: {} - requirejs-config-file@4.0.0: - dependencies: - esprima: 4.0.1 - stringify-object: 3.3.0 - - requirejs@2.3.8: {} - requires-port@1.0.0: {} reselect@5.2.0: {} resolve-alpn@1.2.1: {} - resolve-dependency-path@3.0.2: {} - resolve-from@4.0.0: {} resolve-from@5.0.0: {} @@ -31253,8 +32260,6 @@ snapshots: retimeable-signal@1.0.1: {} - retry@0.13.1: {} - reusify@1.1.0: {} rfdc@1.4.1: {} @@ -31275,6 +32280,27 @@ snapshots: request-ip: 3.3.0 source-map: 0.5.7 + rolldown@1.2.15: + dependencies: + '@oxc-project/types': 0.155.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.15 + '@rolldown/binding-android-arm64': 1.2.15 + '@rolldown/binding-darwin-arm64': 1.2.15 + '@rolldown/binding-darwin-x64': 1.2.15 + '@rolldown/binding-freebsd-x64': 1.2.15 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.15 + '@rolldown/binding-linux-arm64-gnu': 1.2.15 + '@rolldown/binding-linux-arm64-musl': 1.2.15 + '@rolldown/binding-linux-ppc64-gnu': 1.2.15 + '@rolldown/binding-linux-s390x-gnu': 1.2.15 + '@rolldown/binding-linux-x64-gnu': 1.2.15 + '@rolldown/binding-linux-x64-musl': 1.2.15 + '@rolldown/binding-openharmony-arm64': 1.2.15 + '@rolldown/binding-win32-arm64-msvc': 1.2.15 + '@rolldown/binding-win32-x64-msvc': 1.2.15 + rollup@4.60.4: dependencies: '@types/estree': 1.0.8 @@ -31305,6 +32331,7 @@ snapshots: '@rollup/rollup-win32-x64-gnu': 4.60.4 '@rollup/rollup-win32-x64-msvc': 4.60.4 fsevents: 2.3.3 + optional: true rpc-websockets@9.3.9: dependencies: @@ -31344,6 +32371,10 @@ snapshots: rw@1.3.3: {} + rxjs@7.8.2: + dependencies: + tslib: 2.8.1 + safe-array-concat@1.1.4: dependencies: call-bind: 1.0.9 @@ -31375,10 +32406,6 @@ snapshots: dependencies: truncate-utf8-bytes: 1.0.2 - sass-lookup@5.0.1: - dependencies: - commander: 10.0.1 - sax@1.6.0: {} saxes@6.0.0: @@ -31424,13 +32451,11 @@ snapshots: semver@7.8.1: {} - semver@7.8.4: {} - semver@7.8.5: {} - send@0.19.2: + send@0.19.2(supports-color@10.2.2): dependencies: - debug: 2.6.9 + debug: 2.6.9(supports-color@10.2.2) depd: 2.0.0 destroy: 1.2.0 encodeurl: 2.0.0 @@ -31452,12 +32477,12 @@ snapshots: dependencies: type-fest: 0.20.2 - serve-static@1.16.3: + serve-static@1.16.3(supports-color@10.2.2): dependencies: encodeurl: 2.0.0 escape-html: 1.0.3 parseurl: 1.3.3 - send: 0.19.2 + send: 0.19.2(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -31504,7 +32529,7 @@ snapshots: dependencies: color: 4.2.3 detect-libc: 2.1.2 - semver: 7.8.1 + semver: 7.8.5 optionalDependencies: '@img/sharp-darwin-arm64': 0.33.5 '@img/sharp-darwin-x64': 0.33.5 @@ -31526,70 +32551,38 @@ snapshots: '@img/sharp-win32-ia32': 0.33.5 '@img/sharp-win32-x64': 0.33.5 - sharp@0.34.5: - dependencies: - '@img/colour': 1.1.0 - detect-libc: 2.1.2 - semver: 7.8.1 - optionalDependencies: - '@img/sharp-darwin-arm64': 0.34.5 - '@img/sharp-darwin-x64': 0.34.5 - '@img/sharp-libvips-darwin-arm64': 1.2.4 - '@img/sharp-libvips-darwin-x64': 1.2.4 - '@img/sharp-libvips-linux-arm': 1.2.4 - '@img/sharp-libvips-linux-arm64': 1.2.4 - '@img/sharp-libvips-linux-ppc64': 1.2.4 - '@img/sharp-libvips-linux-riscv64': 1.2.4 - '@img/sharp-libvips-linux-s390x': 1.2.4 - '@img/sharp-libvips-linux-x64': 1.2.4 - '@img/sharp-libvips-linuxmusl-arm64': 1.2.4 - '@img/sharp-libvips-linuxmusl-x64': 1.2.4 - '@img/sharp-linux-arm': 0.34.5 - '@img/sharp-linux-arm64': 0.34.5 - '@img/sharp-linux-ppc64': 0.34.5 - '@img/sharp-linux-riscv64': 0.34.5 - '@img/sharp-linux-s390x': 0.34.5 - '@img/sharp-linux-x64': 0.34.5 - '@img/sharp-linuxmusl-arm64': 0.34.5 - '@img/sharp-linuxmusl-x64': 0.34.5 - '@img/sharp-wasm32': 0.34.5 - '@img/sharp-win32-arm64': 0.34.5 - '@img/sharp-win32-ia32': 0.34.5 - '@img/sharp-win32-x64': 0.34.5 - optional: true - - sharp@0.35.3(@types/node@20.16.7): + sharp@0.35.5(@types/node@24.13.4): dependencies: '@img/colour': 1.1.0 detect-libc: 2.1.2 semver: 7.8.5 optionalDependencies: - '@img/sharp-darwin-arm64': 0.35.3 - '@img/sharp-darwin-x64': 0.35.3 - '@img/sharp-freebsd-wasm32': 0.35.3 - '@img/sharp-libvips-darwin-arm64': 1.3.2 - '@img/sharp-libvips-darwin-x64': 1.3.2 - '@img/sharp-libvips-linux-arm': 1.3.2 - '@img/sharp-libvips-linux-arm64': 1.3.2 - '@img/sharp-libvips-linux-ppc64': 1.3.2 - '@img/sharp-libvips-linux-riscv64': 1.3.2 - '@img/sharp-libvips-linux-s390x': 1.3.2 - '@img/sharp-libvips-linux-x64': 1.3.2 - '@img/sharp-libvips-linuxmusl-arm64': 1.3.2 - '@img/sharp-libvips-linuxmusl-x64': 1.3.2 - '@img/sharp-linux-arm': 0.35.3 - '@img/sharp-linux-arm64': 0.35.3 - '@img/sharp-linux-ppc64': 0.35.3 - '@img/sharp-linux-riscv64': 0.35.3 - '@img/sharp-linux-s390x': 0.35.3 - '@img/sharp-linux-x64': 0.35.3 - '@img/sharp-linuxmusl-arm64': 0.35.3 - '@img/sharp-linuxmusl-x64': 0.35.3 - '@img/sharp-webcontainers-wasm32': 0.35.3 - '@img/sharp-win32-arm64': 0.35.3 - '@img/sharp-win32-ia32': 0.35.3 - '@img/sharp-win32-x64': 0.35.3 - '@types/node': 20.16.7 + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 + '@types/node': 24.13.4 optional: true shebang-command@2.0.0: @@ -31634,14 +32627,6 @@ snapshots: signal-exit@4.1.0: {} - simple-concat@1.0.1: {} - - simple-get@4.0.1: - dependencies: - decompress-response: 6.0.0 - once: 1.4.0 - simple-concat: 1.0.1 - simple-swizzle@0.2.4: dependencies: is-arrayish: 0.3.4 @@ -31677,21 +32662,21 @@ snapshots: dot-case: 3.0.4 tslib: 2.8.1 - socket.io-client@4.8.3(bufferutil@4.1.0)(utf-8-validate@6.0.6): + socket.io-client@4.8.3(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6): dependencies: '@socket.io/component-emitter': 3.1.2 - debug: 4.4.3 - engine.io-client: 6.6.5(bufferutil@4.1.0)(utf-8-validate@6.0.6) - socket.io-parser: 4.2.6 + debug: 4.4.3(supports-color@10.2.2) + engine.io-client: 6.6.5(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) + socket.io-parser: 4.2.6(supports-color@10.2.2) transitivePeerDependencies: - bufferutil - supports-color - utf-8-validate - socket.io-parser@4.2.6: + socket.io-parser@4.2.6(supports-color@10.2.2): dependencies: '@socket.io/component-emitter': 3.1.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -31709,6 +32694,8 @@ snapshots: source-map-js@1.2.1: {} + source-map-js@1.2.2: {} + source-map-support@0.5.21: dependencies: buffer-from: 1.1.2 @@ -31718,6 +32705,8 @@ snapshots: source-map@0.6.1: {} + source-map@0.7.6: {} + space-separated-tokens@2.0.2: {} sparse-array@1.3.2: {} @@ -31728,7 +32717,8 @@ snapshots: sprintf-js@1.0.3: {} - stable-hash@0.0.5: {} + stable-hash@0.0.5: + optional: true stable@0.1.8: {} @@ -31746,7 +32736,7 @@ snapshots: statuses@2.0.2: {} - std-env@4.1.0: {} + std-env@4.2.0: {} stop-iteration-iterator@1.1.0: dependencies: @@ -31761,10 +32751,6 @@ snapshots: stream-shift@1.0.3: {} - stream-to-it@1.0.1: - dependencies: - it-stream-types: 2.0.4 - strict-uri-encode@2.0.0: {} string-argv@0.3.2: {} @@ -31773,6 +32759,8 @@ snapshots: string-template@0.2.1: {} + string-ts@2.3.1: {} + string-width@4.2.3: dependencies: emoji-regex: 8.0.0 @@ -31854,12 +32842,6 @@ snapshots: dependencies: safe-buffer: 5.2.1 - stringify-object@3.3.0: - dependencies: - get-own-enumerable-property-symbols: 3.0.2 - is-obj: 1.0.1 - is-regexp: 1.0.0 - strip-ansi@6.0.1: dependencies: ansi-regex: 5.0.1 @@ -31870,6 +32852,8 @@ snapshots: strip-bom@3.0.0: {} + strip-final-newline@4.0.0: {} + strip-hex-prefix@1.0.0: dependencies: is-hex-prefixed: 1.0.0 @@ -31882,24 +32866,29 @@ snapshots: dependencies: '@tokenizer/token': 0.3.0 - style-loader@3.3.4(webpack@5.107.2(esbuild@0.25.12)(postcss@8.5.15)): + style-loader@3.3.4(webpack@5.107.2(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3)): dependencies: - webpack: 5.107.2(esbuild@0.25.12)(postcss@8.5.15) + webpack: 5.107.2(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3) style-mod@4.1.3: {} - styled-jsx@5.1.6(@babel/core@7.29.7)(react@19.1.4): + styled-jsx@5.1.6(@babel/core@7.29.7(supports-color@10.2.2))(babel-plugin-macros@3.1.0)(react@19.1.4): dependencies: client-only: 0.0.1 react: 19.1.4 optionalDependencies: - '@babel/core': 7.29.7 - - stylis@4.2.0: {} + '@babel/core': 7.29.7(supports-color@10.2.2) + babel-plugin-macros: 3.1.0 - stylus-lookup@5.0.1: + styled-jsx@5.1.6(@babel/core@8.0.1)(babel-plugin-macros@3.1.0)(react@19.1.4): dependencies: - commander: 10.0.1 + client-only: 0.0.1 + react: 19.1.4 + optionalDependencies: + '@babel/core': 8.0.1 + babel-plugin-macros: 3.1.0 + + stylis@4.2.0: {} super-regex@0.2.0: dependencies: @@ -31956,7 +32945,7 @@ snapshots: picocolors: 1.1.1 sax: 1.6.0 - swagger-client@3.37.4: + swagger-client@3.37.4(debug@4.4.3(supports-color@10.2.2)): dependencies: '@babel/runtime-corejs3': 7.29.7 '@scarf/scarf': 1.4.0 @@ -31965,7 +32954,7 @@ snapshots: '@swagger-api/apidom-json-pointer': 1.11.1 '@swagger-api/apidom-ns-openapi-3-1': 1.11.1 '@swagger-api/apidom-ns-openapi-3-2': 1.11.1 - '@swagger-api/apidom-reference': 1.11.1 + '@swagger-api/apidom-reference': 1.11.1(debug@4.4.3(supports-color@10.2.2)) '@swaggerexpert/cookie': 2.0.2 deepmerge: 4.3.1 fast-json-patch: 3.1.1 @@ -31979,7 +32968,7 @@ snapshots: transitivePeerDependencies: - debug - swagger-ui-react@5.32.6(@types/react@19.1.7)(react-dom@19.1.4(react@19.1.4))(react@19.1.4): + swagger-ui-react@5.32.6(@types/react@19.1.7)(debug@4.4.3(supports-color@10.2.2))(react-dom@19.1.4(react@19.1.4))(react@19.1.4): dependencies: '@babel/runtime-corejs3': 7.29.7 '@scarf/scarf': 1.4.0 @@ -32012,7 +33001,7 @@ snapshots: reselect: 5.2.0 serialize-error: 8.1.0 sha.js: 2.4.12 - swagger-client: 3.37.4 + swagger-client: 3.37.4(debug@4.4.3(supports-color@10.2.2)) url-parse: 1.5.10 xml: 1.0.1 xml-but-prettier: 1.0.1 @@ -32037,35 +33026,23 @@ snapshots: tapable@2.3.3: {} - tar-fs@2.1.4: - dependencies: - chownr: 1.1.4 - mkdirp-classic: 0.5.3 - pump: 3.0.4 - tar-stream: 2.2.0 - - tar-stream@2.2.0: - dependencies: - bl: 4.1.0 - end-of-stream: 1.4.5 - fs-constants: 1.0.0 - inherits: 2.0.4 - readable-stream: 3.6.2 - tdigest@0.1.2: dependencies: bintrees: 1.0.2 - terser-webpack-plugin@5.6.1(esbuild@0.25.12)(postcss@8.5.15)(webpack@5.107.2(esbuild@0.25.12)(postcss@8.5.15)): + terser-webpack-plugin@5.6.1(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3)(webpack@5.107.2(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3)): dependencies: '@jridgewell/trace-mapping': 0.3.31 jest-worker: 27.5.1 schema-utils: 4.3.3 terser: 5.48.0 - webpack: 5.107.2(esbuild@0.25.12)(postcss@8.5.15) + webpack: 5.107.2(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3) optionalDependencies: - esbuild: 0.25.12 + csso: 5.0.5 + esbuild: 0.28.1 + lightningcss: 1.33.0 postcss: 8.5.15 + uglify-js: 3.19.3 terser@5.48.0: dependencies: @@ -32108,18 +33085,18 @@ snapshots: timestamp-nano@1.0.1: {} - tiny-case@1.0.3: {} - tiny-invariant@1.3.3: {} tiny-parse-argv@2.8.2: {} tiny-warning@1.0.3: {} - tinybench@2.9.0: {} + tinybench@6.1.4: {} tinyexec@1.2.2: {} + tinyexec@1.3.0: {} + tinyglobby@0.2.16: dependencies: fdir: 6.5.0(picomatch@4.0.4) @@ -32127,10 +33104,10 @@ snapshots: tinyglobby@0.2.17: dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 - tinyrainbow@3.1.0: {} + tinyrainbow@3.1.1: {} tldts-core@6.1.86: {} @@ -32140,10 +33117,6 @@ snapshots: dependencies: tldts-core: 6.1.86 - tldts@6.1.86: - dependencies: - tldts-core: 6.1.86 - tldts@7.4.0: dependencies: tldts-core: 7.4.0 @@ -32176,10 +33149,6 @@ snapshots: totalist@3.0.1: {} - tough-cookie@5.1.2: - dependencies: - tldts: 6.1.86 - tough-cookie@6.0.1: dependencies: tldts: 7.4.0 @@ -32190,6 +33159,8 @@ snapshots: dependencies: punycode: 2.3.1 + tree-kill@1.2.2: {} + tree-sitter-json@0.24.8(tree-sitter@0.21.1): dependencies: node-addon-api: 8.8.0 @@ -32226,30 +33197,10 @@ snapshots: ts-mixer@6.0.4: {} - ts-node@10.9.2(@types/node@20.16.7)(@typescript/typescript6@6.0.2): - dependencies: - '@cspotcode/source-map-support': 0.8.1 - '@tsconfig/node10': 1.0.12 - '@tsconfig/node12': 1.0.11 - '@tsconfig/node14': 1.0.3 - '@tsconfig/node16': 1.0.4 - '@types/node': 20.16.7 - acorn: 8.16.0 - acorn-walk: 8.3.5 - arg: 4.1.3 - create-require: 1.1.1 - diff: 4.0.4 - make-error: 1.3.6 - typescript: '@typescript/typescript6@6.0.2' - v8-compile-cache-lib: 3.0.1 - yn: 3.1.1 + ts-pattern@5.9.0: {} ts-toolbelt@9.6.0: {} - tsconfck@3.1.6(@typescript/typescript6@6.0.2): - optionalDependencies: - typescript: '@typescript/typescript6@6.0.2' - tsconfig-paths@3.15.0: dependencies: '@types/json5': 0.0.29 @@ -32257,12 +33208,6 @@ snapshots: minimist: 1.2.8 strip-bom: 3.0.0 - tsconfig-paths@4.2.0: - dependencies: - json5: 2.2.3 - minimist: 1.2.8 - strip-bom: 3.0.0 - tslib@1.14.1: {} tslib@2.4.1: {} @@ -32274,18 +33219,11 @@ snapshots: tslib: 1.14.1 typescript: '@typescript/typescript6@6.0.2' - tsutils@3.21.0(typescript@5.9.3): - dependencies: - tslib: 1.14.1 - typescript: 5.9.3 - tsyringe@4.10.0: dependencies: tslib: 1.14.1 - tunnel-agent@0.6.0: - dependencies: - safe-buffer: 5.2.1 + tunnel@0.0.6: {} type-check@0.4.0: dependencies: @@ -32295,8 +33233,6 @@ snapshots: type-fest@0.7.1: {} - type-fest@2.19.0: {} - type-fest@4.41.0: {} typed-array-buffer@1.0.3: @@ -32332,17 +33268,27 @@ snapshots: possible-typed-array-names: 1.1.0 reflect.getprototypeof: 1.0.10 + typed-inject@5.0.0: {} + + typed-rest-client@2.3.1: + dependencies: + des.js: 1.1.0 + js-md4: 0.3.2 + qs: 6.15.1 + tunnel: 0.0.6 + underscore: 1.13.8 + types-ramda@0.30.1: dependencies: ts-toolbelt: 9.6.0 - typescript-eslint@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2): + typescript-eslint@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2): dependencies: - '@typescript-eslint/eslint-plugin': 8.59.2(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2) - '@typescript-eslint/parser': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) - '@typescript-eslint/typescript-estree': 8.59.2(@typescript/typescript6@6.0.2) - '@typescript-eslint/utils': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2) - eslint: 9.39.2 + '@typescript-eslint/eslint-plugin': 8.59.2(@typescript-eslint/parser@8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2))(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/parser': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + '@typescript-eslint/typescript-estree': 8.59.2(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + '@typescript-eslint/utils': 8.59.2(@typescript/typescript6@6.0.2)(eslint@9.39.2(supports-color@10.2.2))(supports-color@10.2.2) + eslint: 9.39.2(supports-color@10.2.2) typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - supports-color @@ -32417,7 +33363,7 @@ snapshots: uint8arrays@6.1.1: dependencies: - multiformats: 14.0.0 + multiformats: 14.0.5 ulid@2.4.0: {} @@ -32430,19 +33376,18 @@ snapshots: uncrypto@0.1.3: {} - undici-types@6.19.8: {} + underscore@1.13.8: {} - undici-types@6.20.0: {} + undici-types@7.18.2: {} - undici-types@7.24.6: - optional: true + undici-types@7.24.6: {} undici-types@7.26.0: {} - undici@6.26.0: {} - undici@7.28.0: {} + undici@8.11.2: {} + unicode-canonical-property-names-ecmascript@2.0.1: {} unicode-match-property-ecmascript@2.0.0: @@ -32454,10 +33399,14 @@ snapshots: unicode-property-aliases-ecmascript@2.2.0: {} + unicorn-magic@0.3.0: {} + unicorn-magic@0.4.0: {} universalify@2.0.1: {} + unlimited-timeout@0.1.0: {} + unpipe@1.0.0: {} unraw@3.0.0: {} @@ -32488,6 +33437,7 @@ snapshots: '@unrs/resolver-binding-win32-arm64-msvc': 1.12.2 '@unrs/resolver-binding-win32-ia32-msvc': 1.12.2 '@unrs/resolver-binding-win32-x64-msvc': 1.12.2 + optional: true unstorage@1.17.5(idb-keyval@6.2.4): dependencies: @@ -32610,8 +33560,6 @@ snapshots: uuid@9.0.1: {} - v8-compile-cache-lib@3.0.1: {} - valibot@1.2.0(@typescript/typescript6@6.0.2): optionalDependencies: typescript: '@typescript/typescript6@6.0.2' @@ -32641,15 +33589,15 @@ snapshots: varint@6.0.0: {} - viem@2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76): + viem@2.23.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3): dependencies: '@noble/curves': 1.8.1 '@noble/hashes': 1.8.0 '@scure/bip32': 1.6.2 '@scure/bip39': 1.5.4 - abitype: 1.0.8(@typescript/typescript6@6.0.2)(zod@3.25.76) + abitype: 1.0.8(@typescript/typescript6@6.0.2)(zod@4.4.3) isows: 1.0.6(ws@8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - ox: 0.6.7(@typescript/typescript6@6.0.2)(zod@3.25.76) + ox: 0.6.7(@typescript/typescript6@6.0.2)(zod@4.4.3) ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) optionalDependencies: typescript: '@typescript/typescript6@6.0.2' @@ -32658,15 +33606,15 @@ snapshots: - utf-8-validate - zod - viem@2.31.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76): + viem@2.31.0(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3): dependencies: '@noble/curves': 1.9.1 '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 - abitype: 1.0.8(@typescript/typescript6@6.0.2)(zod@3.25.76) + abitype: 1.0.8(@typescript/typescript6@6.0.2)(zod@4.4.3) isows: 1.0.7(ws@8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - ox: 0.7.1(@typescript/typescript6@6.0.2)(zod@3.25.76) + ox: 0.7.1(@typescript/typescript6@6.0.2)(zod@4.4.3) ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) optionalDependencies: typescript: '@typescript/typescript6@6.0.2' @@ -32675,18 +33623,18 @@ snapshots: - utf-8-validate - zod - viem@2.38.6(bufferutil@4.1.0)(typescript@7.0.2)(utf-8-validate@6.0.6)(zod@4.4.3): + viem@2.38.6(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3): dependencies: '@noble/curves': 1.9.1 '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 - abitype: 1.1.0(typescript@7.0.2)(zod@4.4.3) + abitype: 1.1.0(@typescript/typescript6@6.0.2)(zod@4.4.3) isows: 1.0.7(ws@8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - ox: 0.9.6(typescript@7.0.2)(zod@4.4.3) + ox: 0.9.6(@typescript/typescript6@6.0.2)(zod@4.4.3) ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) optionalDependencies: - typescript: 7.0.2 + typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: - bufferutil - utf-8-validate @@ -32709,15 +33657,15 @@ snapshots: - utf-8-validate - zod - viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76): + viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3): dependencies: '@noble/curves': 1.9.1 '@noble/hashes': 1.8.0 '@scure/bip32': 1.7.0 '@scure/bip39': 1.6.0 - abitype: 1.1.0(@typescript/typescript6@6.0.2)(zod@3.25.76) + abitype: 1.1.0(@typescript/typescript6@6.0.2)(zod@4.4.3) isows: 1.0.7(ws@8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - ox: 0.9.6(@typescript/typescript6@6.0.2)(zod@3.25.76) + ox: 0.9.6(@typescript/typescript6@6.0.2)(zod@4.4.3) ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) optionalDependencies: typescript: '@typescript/typescript6@6.0.2' @@ -32743,132 +33691,94 @@ snapshots: - utf-8-validate - zod + viem@2.51.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3): + dependencies: + '@noble/curves': 1.9.1 + '@noble/hashes': 1.8.0 + '@scure/bip32': 1.7.0 + '@scure/bip39': 1.6.0 + abitype: 1.2.3(@typescript/typescript6@6.0.2)(zod@4.4.3) + isows: 1.0.7(ws@8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + ox: 0.14.25(@typescript/typescript6@6.0.2)(zod@4.4.3) + ws: 8.21.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) + optionalDependencies: + typescript: '@typescript/typescript6@6.0.2' + transitivePeerDependencies: + - bufferutil + - utf-8-validate + - zod + visit-values@2.0.0: {} - vite-plugin-dts@4.5.4(@types/node@20.16.7)(@typescript/typescript6@6.0.2)(rollup@4.60.4)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)): + vite-plugin-dts@4.5.4(@types/node@24.13.4)(@typescript/typescript6@6.0.2)(rollup@4.60.4)(supports-color@10.2.2)(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)): dependencies: - '@microsoft/api-extractor': 7.58.7(@types/node@20.16.7) + '@microsoft/api-extractor': 7.58.7(@types/node@24.13.4) '@rollup/pluginutils': 5.3.0(rollup@4.60.4) - '@volar/typescript': 2.4.28 + '@volar/typescript': 2.4.28(@typescript/typescript6@6.0.2) '@vue/language-core': 2.2.0(@typescript/typescript6@6.0.2) compare-versions: 6.1.1 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) kolorist: 1.8.0 local-pkg: 1.2.1 magic-string: 0.30.21 typescript: '@typescript/typescript6@6.0.2' optionalDependencies: - vite: 6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0) + vite: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) transitivePeerDependencies: - '@types/node' - rollup - supports-color - vite-plugin-svgr@4.5.0(@typescript/typescript6@6.0.2)(rollup@4.60.4)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)): - dependencies: - '@rollup/pluginutils': 5.3.0(rollup@4.60.4) - '@svgr/core': 8.1.0(@typescript/typescript6@6.0.2) - '@svgr/plugin-jsx': 8.1.0(@svgr/core@8.1.0(@typescript/typescript6@6.0.2)) - vite: 6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0) - transitivePeerDependencies: - - rollup - - supports-color - - typescript - - vite-plugin-svgr@5.2.0(@typescript/typescript6@6.0.2)(rollup@4.60.4)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)): + vite-plugin-svgr@5.2.0(@typescript/typescript6@6.0.2)(rollup@4.60.4)(supports-color@10.2.2)(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)): dependencies: '@rollup/pluginutils': 5.3.0(rollup@4.60.4) - '@svgr/core': 8.1.0(@typescript/typescript6@6.0.2) - '@svgr/plugin-jsx': 8.1.0(@svgr/core@8.1.0(@typescript/typescript6@6.0.2)) - vite: 6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0) + '@svgr/core': 8.1.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2) + '@svgr/plugin-jsx': 8.1.0(@svgr/core@8.1.0(@typescript/typescript6@6.0.2)(supports-color@10.2.2))(supports-color@10.2.2) + vite: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) transitivePeerDependencies: - rollup - supports-color - typescript - vite-tsconfig-paths@5.1.4(@typescript/typescript6@6.0.2)(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)): - dependencies: - debug: 4.4.3 - globrex: 0.1.2 - tsconfck: 3.1.6(@typescript/typescript6@6.0.2) - optionalDependencies: - vite: 6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0) - transitivePeerDependencies: - - supports-color - - typescript - - vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0): - dependencies: - esbuild: 0.25.12 - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - postcss: 8.5.15 - rollup: 4.60.4 - tinyglobby: 0.2.16 - optionalDependencies: - '@types/node': 20.16.7 - fsevents: 2.3.3 - terser: 5.48.0 - yaml: 2.9.0 - - vite@6.4.3(@types/node@22.12.0)(terser@5.48.0)(yaml@2.9.0): - dependencies: - esbuild: 0.25.12 - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - postcss: 8.5.15 - rollup: 4.60.4 - tinyglobby: 0.2.16 - optionalDependencies: - '@types/node': 22.12.0 - fsevents: 2.3.3 - terser: 5.48.0 - yaml: 2.9.0 - - vite@6.4.3(@types/node@25.9.2)(terser@5.48.0)(yaml@2.9.0): + vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0): dependencies: - esbuild: 0.25.12 - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - postcss: 8.5.15 - rollup: 4.60.4 - tinyglobby: 0.2.16 + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.31 + rolldown: 1.2.15 + tinyglobby: 0.2.17 optionalDependencies: - '@types/node': 25.9.2 + '@types/node': 24.13.4 + esbuild: 0.28.1 fsevents: 2.3.3 terser: 5.48.0 yaml: 2.9.0 - vitest-fetch-mock@0.4.5(vitest@4.1.7(@opentelemetry/api@1.9.1)(@types/node@20.16.7)(jsdom@27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6))(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0))): + vitest-fetch-mock@0.4.5(vitest@5.0.0): dependencies: - vitest: 4.1.7(@opentelemetry/api@1.9.1)(@types/node@20.16.7)(jsdom@27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6))(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) + vitest: 5.0.0(@opentelemetry/api@1.9.1)(@types/node@24.13.4)(@vitest/coverage-v8@5.0.0)(jsdom@27.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6))(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) - vitest@4.1.7(@opentelemetry/api@1.9.1)(@types/node@20.16.7)(jsdom@27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6))(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)): + vitest@5.0.0(@opentelemetry/api@1.9.1)(@types/node@24.13.4)(@vitest/coverage-v8@5.0.0)(jsdom@27.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6))(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)): dependencies: - '@vitest/expect': 4.1.7 - '@vitest/mocker': 4.1.7(vite@6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0)) - '@vitest/pretty-format': 4.1.7 - '@vitest/runner': 4.1.7 - '@vitest/snapshot': 4.1.7 - '@vitest/spy': 4.1.7 - '@vitest/utils': 4.1.7 - es-module-lexer: 2.1.0 - expect-type: 1.3.0 - magic-string: 0.30.21 - obug: 2.1.1 - pathe: 2.0.3 - picomatch: 4.0.4 - std-env: 4.1.0 - tinybench: 2.9.0 - tinyexec: 1.2.2 - tinyglobby: 0.2.16 - tinyrainbow: 3.1.0 - vite: 6.4.3(@types/node@20.16.7)(terser@5.48.0)(yaml@2.9.0) + '@types/chai': 5.2.3 + '@vitest/mocker': 5.0.0(vite@8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0)) + chai: 6.2.2 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.3.1 + obug: 2.2.1 + picomatch: 4.0.7 + std-env: 4.2.0 + tinybench: 6.1.4 + tinyexec: 1.3.0 + tinyglobby: 0.2.17 + vite: 8.3.5(@types/node@24.13.4)(esbuild@0.28.1)(terser@5.48.0)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: '@opentelemetry/api': 1.9.1 - '@types/node': 20.16.7 - jsdom: 27.3.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) + '@types/node': 24.13.4 + '@vitest/coverage-v8': 5.0.0(vitest@5.0.0) + jsdom: 27.3.0(bufferutil@4.1.0)(supports-color@10.2.2)(utf-8-validate@6.0.6) transitivePeerDependencies: - msw @@ -32888,14 +33798,14 @@ snapshots: dependencies: xml-name-validator: 5.0.0 - wagmi@2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7)(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(utf-8-validate@6.0.6))(react@19.1.4)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76))(zod@3.25.76): + wagmi@2.19.5(@tanstack/query-core@5.55.4)(@tanstack/react-query@5.55.4(react@19.1.4))(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(debug@4.4.3(supports-color@10.2.2))(fastestsmallesttextencoderdecoder@1.0.22)(react-native@0.85.3(@babel/core@7.29.7(supports-color@10.2.2))(@types/react@19.1.7)(bufferutil@4.1.0)(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6))(react@19.1.4)(supports-color@10.2.2)(utf-8-validate@6.0.6)(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3))(zod@4.4.3): dependencies: '@tanstack/react-query': 5.55.4(react@19.1.4) - '@wagmi/connectors': 6.2.0(09e58c13ebbf9932f0a56e13a5b340ff) - '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76)) + '@wagmi/connectors': 6.2.0(df3f0d3afef4414b7f4264d6db7d6a30) + '@wagmi/core': 2.22.1(@tanstack/query-core@5.55.4)(@types/react@19.1.7)(@typescript/typescript6@6.0.2)(react@19.1.4)(use-sync-external-store@1.4.0(react@19.1.4))(viem@2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3)) react: 19.1.4 use-sync-external-store: 1.4.0(react@19.1.4) - viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@3.25.76) + viem: 2.41.2(@typescript/typescript6@6.0.2)(bufferutil@4.1.0)(utf-8-validate@6.0.6)(zod@4.4.3) optionalDependencies: typescript: '@typescript/typescript6@6.0.2' transitivePeerDependencies: @@ -32927,6 +33837,7 @@ snapshots: - fastestsmallesttextencoderdecoder - immer - ioredis + - preact-render-to-string - react-native - supports-color - uploadthing @@ -32952,12 +33863,16 @@ snapshots: ms: 4.0.0-nightly.202508271359 supports-color: 10.2.2 + weapon-regex@2.0.4: {} + web-streams-polyfill@3.3.3: {} web-tree-sitter@0.24.5: optional: true - web-vitals@5.2.0: {} + web-vitals@6.2.1: {} + + web-vitals@6.2.2: {} web3-utils@1.10.4: dependencies: @@ -33013,7 +33928,7 @@ snapshots: webpack-sources@3.5.0: {} - webpack@5.107.2(esbuild@0.25.12)(postcss@8.5.15): + webpack@5.107.2(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3): dependencies: '@types/estree': 1.0.9 '@types/json-schema': 7.0.15 @@ -33025,7 +33940,7 @@ snapshots: browserslist: 4.28.2 chrome-trace-event: 1.0.4 enhanced-resolve: 5.23.0 - es-module-lexer: 2.1.0 + es-module-lexer: 2.3.2 eslint-scope: 5.1.1 events: 3.3.0 glob-to-regexp: 0.4.1 @@ -33035,7 +33950,7 @@ snapshots: neo-async: 2.6.2 schema-utils: 4.3.3 tapable: 2.3.3 - terser-webpack-plugin: 5.6.1(esbuild@0.25.12)(postcss@8.5.15)(webpack@5.107.2(esbuild@0.25.12)(postcss@8.5.15)) + terser-webpack-plugin: 5.6.1(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3)(webpack@5.107.2(csso@5.0.5)(esbuild@0.28.1)(lightningcss@1.33.0)(postcss@8.5.15)(uglify-js@3.19.3)) watchpack: 2.5.1 webpack-sources: 3.5.0 transitivePeerDependencies: @@ -33236,10 +34151,10 @@ snapshots: y18n: 5.0.8 yargs-parser: 21.1.1 - yn@3.1.1: {} - yocto-queue@0.1.0: {} + yoctocolors@2.2.0: {} + yup@0.32.11: dependencies: '@babel/runtime': 7.29.7 @@ -33250,19 +34165,8 @@ snapshots: property-expr: 2.0.6 toposort: 2.0.2 - yup@1.7.1: - dependencies: - property-expr: 2.0.6 - tiny-case: 1.0.3 - toposort: 2.0.2 - type-fest: 2.19.0 - zenscroll@4.0.2: {} - zod-validation-error@4.0.2(zod@4.4.3): - dependencies: - zod: 4.4.3 - zod@3.22.4: {} zod@3.25.76: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 8306071f981..c0c02181bcb 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -4,17 +4,26 @@ injectWorkspacePackages: true packages: - 'src/toolkit/package' + - 'deploy/tools/assets-downloader' - 'deploy/tools/envs-validator' - 'deploy/tools/feature-reporter' - 'deploy/tools/favicon-generator' - 'deploy/tools/sitemap-generator' + - 'deploy/tools/og-image-generator' - 'deploy/tools/multichain-config-generator' - 'deploy/tools/essential-dapps-chains-config-generator' - 'deploy/tools/llms-txt-generator' - - 'deploy/tools/affected-tests' verifyDepsBeforeRun: warn +# The widget-light EVM handler is patched for these wagmi v2 / viem versions. +# Resolve wallet clients per request; explicit chainId supports syncConnectedChain: false. +peerDependencyRules: + allowedVersions: + '@lifi/widget-light@4.3.2>wagmi': '2.19.5' + '@lifi/widget-light@4.3.2>@wagmi/core': '2.22.1' + '@lifi/widget-light@4.3.2>viem': '2.41.2' + overrides: '@wagmi/connectors': "6.2.0" ws: "8.21.0" @@ -23,8 +32,9 @@ overrides: node-forge: "1.3.2" brace-expansion: "1.1.12" js-yaml: "4.1.1" - "@noble/hashes": "1.8.0" + "@noble/hashes@1": "1.8.0" "vite-plugin-dts>brace-expansion": "2.0.2" + "minimatch@10>brace-expansion": "5.0.9" protobufjs: "7.5.5" # pnpm 11+: allowlisted dependency install scripts (required for native addons). @@ -33,7 +43,7 @@ allowBuilds: '@ipshipyard/node-datachannel': true '@reown/appkit': false '@scarf/scarf': false - '@specify-sh/sdk': false + '@specify-sh/publisher-sdk': false '@tree-sitter-grammars/tree-sitter-yaml': false bigint-buffer: false bufferutil: false @@ -64,3 +74,6 @@ minimumReleaseAgeExclude: - '@blockscout/tac-operation-lifecycle-types' - '@blockscout/visualizer-types' - '@blockscout/zetachain-cctx-types' + +patchedDependencies: + '@lifi/widget-light@4.3.2': patches/@lifi__widget-light@4.3.2.patch diff --git a/public/icons/name.d.ts b/public/icons/name.d.ts index e86e0f18072..fae25629167 100644 --- a/public/icons/name.d.ts +++ b/public/icons/name.d.ts @@ -89,7 +89,6 @@ | "lightning" | "link_external" | "link" - | "list_view" | "lock" | "merits_colored" | "merits_with_dot" @@ -105,6 +104,7 @@ | "monaco/vyper" | "moon-with-star" | "moon" + | "move" | "multisend" | "navigation/api_docs" | "navigation/api_keys" @@ -202,6 +202,7 @@ | "txn_batches" | "uniswap" | "user_op" + | "utilization" | "verification-steps/error" | "verification-steps/finalized" | "verification-steps/unfinalized" diff --git a/src/api/config.ts b/src/api/config.ts index 17cd051a6d7..43978a10368 100644 --- a/src/api/config.ts +++ b/src/api/config.ts @@ -2,7 +2,8 @@ import { pickBy } from 'es-toolkit'; -import type { ApiName } from 'src/api/types'; +import type { Apis } from 'src/api/types'; +// eslint-disable-next-line boundaries/element-types -- the list of stats resources with a refetch interval is owned by the chain-stats feature import { STATS_API_RESOURCES_REFETCH_INTERVAL } from 'src/features/chain-stats/types/config'; import type { StatsApiResourceNameRefetchInterval } from 'src/features/chain-stats/types/config'; @@ -10,23 +11,6 @@ import { getEnvValue, parseEnvJson } from 'src/config/utils/envs'; import { stripTrailingSlash } from 'src/toolkit/utils/url'; -import type { ResourceName } from './resources'; - -export interface ApiPropsBase { - endpoint: string; - basePath?: string; - socketEndpoint?: string; - instanceId?: string; - refetchInterval?: Partial<Record<ResourceName, number>>; -} - -export interface ApiPropsFull extends ApiPropsBase { - host: string; - protocol: string; - port?: string; - socketEndpoint: string; -} - const coreApi = (() => { const apiHost = getEnvValue('NEXT_PUBLIC_API_HOST'); if (!apiHost) { @@ -243,10 +227,6 @@ const zetachainApi = (() => { } })(); -export type Apis = { - core: ApiPropsFull | undefined; -} & Partial<Record<Exclude<ApiName, 'core'>, ApiPropsBase>>; - const apis: Apis = Object.freeze({ core: coreApi, admin: adminApi, diff --git a/src/api/hooks/useApiQuery.ts b/src/api/hooks/useApiQuery.ts index 8cd6710c029..ad5052abe80 100644 --- a/src/api/hooks/useApiQuery.ts +++ b/src/api/hooks/useApiQuery.ts @@ -5,6 +5,7 @@ import { useQuery } from '@tanstack/react-query'; import type { ExternalChainExtended } from 'src/shared/external-chains/types'; +// eslint-disable-next-line boundaries/element-types -- there is no better way to get chain value from multichain context in this global hook import { useMultichainContext } from 'src/features/multichain/context'; import type { ResourceError, ResourceName, ResourcePathParams, ResourcePayload } from '../resources'; diff --git a/src/api/resources/services/core/token.ts b/src/api/resources/services/core/token.ts index 86e152b4fb2..5c78da14199 100644 --- a/src/api/resources/services/core/token.ts +++ b/src/api/resources/services/core/token.ts @@ -26,6 +26,12 @@ export const CORE_API_TOKEN_RESOURCES = { filterFields: [], paginated: true, }, + token_ui_multiplier_changes: { + path: '/api/v2/tokens/:hash/ui-multiplier-changes', + pathParams: [ 'hash' as const ], + filterFields: [], + paginated: true, + }, token_transfers: { path: '/api/v2/tokens/:hash/transfers', pathParams: [ 'hash' as const ], @@ -96,6 +102,7 @@ R extends 'core:token' ? paths['/api/v2/tokens/{address_hash_param}']['get'] : R extends 'core:token_counters' ? paths['/api/v2/tokens/{address_hash_param}/counters']['get'] : R extends 'core:token_transfers' ? paths['/api/v2/tokens/{address_hash_param}/transfers']['get'] : R extends 'core:token_holders' ? paths['/api/v2/tokens/{address_hash_param}/holders']['get'] : +R extends 'core:token_ui_multiplier_changes' ? paths['/api/v2/tokens/{address_hash_param}/ui-multiplier-changes']['get'] : R extends 'core:token_instance' ? paths['/api/v2/tokens/{address_hash_param}/instances/{token_id_param}']['get'] : R extends 'core:token_instance_transfers_count' ? paths['/api/v2/tokens/{address_hash_param}/instances/{token_id_param}/transfers-count']['get'] : R extends 'core:token_instance_transfers' ? paths['/api/v2/tokens/{address_hash_param}/instances/{token_id_param}/transfers']['get'] : diff --git a/src/api/resources/services/interchain-indexer.ts b/src/api/resources/services/interchain-indexer.ts index 701550ee838..75f7ae0691a 100644 --- a/src/api/resources/services/interchain-indexer.ts +++ b/src/api/resources/services/interchain-indexer.ts @@ -9,12 +9,17 @@ import type { } from 'src/features/cross-chain-txs/types/api'; export const INTERCHAIN_INDEXER_API_RESOURCES = { + bridges: { + path: '/api/v1/interchain/bridges', + }, chains: { path: '/api/v1/interchain/chains', + scopeFilters: [ 'bridge_ids', 'include_unindexed_chains' ], }, messages: { path: '/api/v1/interchain/messages', - filterFields: [ 'q' as const ], + filterFields: [ 'q' as const, 'src_chain_ids' as const, 'dst_chain_ids' as const, 'bridge_ids' as const ], + scopeFilters: [ 'home_chain_id', 'bridge_ids', 'include_unindexed_chains' ], paginated: true, }, message: { @@ -25,50 +30,56 @@ export const INTERCHAIN_INDEXER_API_RESOURCES = { path: '/api/v1/interchain/messages\\:byTx/:hash', pathParams: [ 'hash' as const ], filterFields: [ 'q' as const ], + scopeFilters: [ 'home_chain_id', 'bridge_ids', 'include_unindexed_chains' ], paginated: true, }, address_messages: { path: '/api/v1/interchain/messages\\:byAddress/:hash', pathParams: [ 'hash' as const ], + filterFields: [ 'q' as const, 'src_chain_ids' as const, 'dst_chain_ids' as const, 'bridge_ids' as const ], + scopeFilters: [ 'home_chain_id', 'bridge_ids', 'include_unindexed_chains' ], paginated: true, }, transfers: { path: '/api/v1/interchain/transfers', - filterFields: [ 'q' as const ], + filterFields: [ 'q' as const, 'src_chain_ids' as const, 'dst_chain_ids' as const, 'bridge_ids' as const ], + scopeFilters: [ 'home_chain_id', 'bridge_ids', 'include_unindexed_chains' ], paginated: true, }, tx_transfers: { path: '/api/v1/interchain/transfers\\:byTx/:hash', pathParams: [ 'hash' as const ], - filterFields: [ 'q' as const ], + filterFields: [ 'q' as const, 'src_chain_ids' as const, 'dst_chain_ids' as const, 'bridge_ids' as const ], + scopeFilters: [ 'home_chain_id', 'bridge_ids', 'include_unindexed_chains' ], paginated: true, }, address_transfers: { path: '/api/v1/interchain/transfers\\:byAddress/:hash', pathParams: [ 'hash' as const ], + filterFields: [ 'q' as const, 'src_chain_ids' as const, 'dst_chain_ids' as const, 'bridge_ids' as const ], + scopeFilters: [ 'home_chain_id', 'bridge_ids', 'include_unindexed_chains' ], paginated: true, }, - stats_daily: { - path: '/api/v1/stats/daily', - }, - stats_common: { - path: '/api/v1/stats/common', - }, stats_chains: { path: '/api/v1/stats/chains', + scopeFilters: [ 'bridge_ids', 'include_unindexed_chains' ], paginated: true, }, stats_chain_messages_sent: { path: '/api/v1/stats/chain/:chainId/messages-paths/sent', pathParams: [ 'chainId' as const ], + scopeFilters: [ 'bridge_ids', 'include_unindexed_chains' ], }, stats_chain_messages_received: { path: '/api/v1/stats/chain/:chainId/messages-paths/received', pathParams: [ 'chainId' as const ], + scopeFilters: [ 'bridge_ids', 'include_unindexed_chains' ], }, bridged_tokens: { path: '/api/v1/stats/chain/:chainId/bridged-tokens', pathParams: [ 'chainId' as const ], + filterFields: [ 'q' as const ], + scopeFilters: [ 'bridge_ids', 'include_unindexed_chains' ], paginated: true, }, } satisfies Record<string, ApiResource>; @@ -77,6 +88,7 @@ export type InterchainIndexerApiResourceName = `interchainIndexer:${ keyof typeo /* eslint-disable @stylistic/indent */ export type InterchainIndexerApiResourcePayload<R extends InterchainIndexerApiResourceName> = +R extends 'interchainIndexer:bridges' ? interchainIndexer.GetBridgesResponse : R extends 'interchainIndexer:chains' ? interchainIndexer.GetChainsResponse : R extends 'interchainIndexer:messages' ? interchainIndexer.GetMessagesResponse : R extends 'interchainIndexer:message' ? interchainIndexer.InterchainMessage : @@ -85,8 +97,6 @@ R extends 'interchainIndexer:address_messages' ? interchainIndexer.GetMessagesRe R extends 'interchainIndexer:transfers' ? interchainIndexer.GetTransfersResponse : R extends 'interchainIndexer:tx_transfers' ? interchainIndexer.GetTransfersResponse : R extends 'interchainIndexer:address_transfers' ? interchainIndexer.GetTransfersResponse : -R extends 'interchainIndexer:stats_daily' ? interchainIndexer.GetDailyStatisticsResponse : -R extends 'interchainIndexer:stats_common' ? interchainIndexer.GetCommonStatisticsResponse : R extends 'interchainIndexer:stats_chains' ? interchainIndexer.GetChainsStatsResponse : R extends 'interchainIndexer:bridged_tokens' ? interchainIndexer.GetBridgedTokensResponse : R extends 'interchainIndexer:stats_chain_messages_sent' ? interchainIndexer.GetMessagePathsResponse : @@ -97,7 +107,10 @@ never; /* eslint-disable @stylistic/indent */ export type InterchainIndexerApiPaginationFilters<R extends InterchainIndexerApiResourceName> = R extends 'interchainIndexer:messages' ? CrossChainFilters : +R extends 'interchainIndexer:address_messages' ? CrossChainFilters : R extends 'interchainIndexer:transfers' ? CrossChainFilters : +R extends 'interchainIndexer:tx_transfers' ? CrossChainFilters : +R extends 'interchainIndexer:address_transfers' ? CrossChainFilters : R extends 'interchainIndexer:stats_chains' ? CrossChainFilters : R extends 'interchainIndexer:bridged_tokens' ? CrossChainFilters : never; diff --git a/src/api/resources/services/multichain-stats.ts b/src/api/resources/services/multichain-stats.ts index 350af7c6949..7f30bd7e87b 100644 --- a/src/api/resources/services/multichain-stats.ts +++ b/src/api/resources/services/multichain-stats.ts @@ -4,6 +4,9 @@ import type { ApiResource } from '../types'; import type * as stats from '@blockscout/stats-types'; export const MULTICHAIN_STATS_API_RESOURCES = { + counters: { + path: '/api/v1/counters', + }, pages_main: { path: '/api/v1/pages/multichain/main', }, @@ -13,6 +16,7 @@ export type MultichainStatsApiResourceName = `multichainStats:${ keyof typeof MU /* eslint-disable @stylistic/indent */ export type MultichainStatsApiResourcePayload<R extends MultichainStatsApiResourceName> = +R extends 'multichainStats:counters' ? stats.Counters : R extends 'multichainStats:pages_main' ? stats.MainPageMultichainStats : never; /* eslint-enable @stylistic/indent */ diff --git a/src/api/resources/types.ts b/src/api/resources/types.ts index 20152b85556..b528292affd 100644 --- a/src/api/resources/types.ts +++ b/src/api/resources/types.ts @@ -4,6 +4,7 @@ export interface ApiResource { path: string; pathParams?: Array<string>; filterFields?: Array<string>; + scopeFilters?: Array<string>; paginated?: boolean; headers?: RequestInit['headers']; } diff --git a/src/api/socket/SocketNewItemsNotice.tsx b/src/api/socket/SocketNewItemsNotice.tsx index 9c69e2d5106..ccca5802b1a 100644 --- a/src/api/socket/SocketNewItemsNotice.tsx +++ b/src/api/socket/SocketNewItemsNotice.tsx @@ -25,6 +25,7 @@ interface Props { num?: number; isLoading?: boolean; onLinkClick?: () => void; + colSpan?: number; } const SocketNewItemsNotice = chakra(({ children, className, url, num, showErrorAlert, type = 'transaction', isLoading, onLinkClick }: Props) => { @@ -98,7 +99,10 @@ const SocketNewItemsNotice = chakra(({ children, className, url, num, showErrorA export default SocketNewItemsNotice; -export const Desktop = ({ ...props }: Props) => { +// the notice row must span the whole table, so the fallback has to exceed any table's column count +const FALLBACK_COL_SPAN = 100; + +export const Desktop = ({ colSpan = FALLBACK_COL_SPAN, ...props }: Props) => { return ( <SocketNewItemsNotice borderRadius={ props.isLoading ? 'sm' : 0 } @@ -109,16 +113,7 @@ export const Desktop = ({ ...props }: Props) => { my={ props.isLoading ? '6px' : 0 } { ...props } > - { ({ content }) => <TableRow><TableCell colSpan={ 100 } p={ 0 } _first={{ p: 0 }} _last={{ p: 0 }}>{ content }</TableCell></TableRow> } + { ({ content }) => <TableRow><TableCell colSpan={ colSpan } p={ 0 } _first={{ p: 0 }} _last={{ p: 0 }}>{ content }</TableCell></TableRow> } </SocketNewItemsNotice> ); }; - -export const Mobile = ({ ...props }: Props) => { - return ( - <SocketNewItemsNotice - borderBottomRadius={ 0 } - { ...props } - /> - ); -}; diff --git a/src/api/socket/useSocketChannel.ts b/src/api/socket/useSocketChannel.ts index 5d161ffb65e..ae60012ff9a 100644 --- a/src/api/socket/useSocketChannel.ts +++ b/src/api/socket/useSocketChannel.ts @@ -40,13 +40,6 @@ export default function useSocketChannel({ topic, params, isDisabled, onJoin, on return cleanUpRefs; }, [ onSocketClose, onSocketError, socket, isDisabled ]); - useEffect(() => { - if (isDisabled && channel) { - channel.leave(); - setChannel(undefined); - } - }, [ channel, isDisabled ]); - useEffect(() => { if (!socket || isDisabled || !topic || !channelRegistry) { return; diff --git a/src/api/types.ts b/src/api/types.ts index 3a747e9669c..3aa5d883b70 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -1,6 +1,27 @@ // SPDX-License-Identifier: LicenseRef-Blockscout +import type { ResourceName } from './resources'; + export type ApiName = 'core' | 'admin' | 'bens' | 'contractInfo' | 'clusters' | 'external' | 'interchainIndexer' | 'metadata' | 'multichainAggregator' | 'multichainStats' | 'rewards' | 'stats' | 'tac' | 'userOps' | 'visualize' | 'zetachain'; + +export interface ApiPropsBase { + endpoint: string; + basePath?: string; + socketEndpoint?: string; + instanceId?: string; + refetchInterval?: Partial<Record<ResourceName, number>>; +} + +export interface ApiPropsFull extends ApiPropsBase { + host: string; + protocol: string; + port?: string; + socketEndpoint: string; +} + +export type Apis = { + core: ApiPropsFull | undefined; +} & Partial<Record<Exclude<ApiName, 'core'>, ApiPropsBase>>; diff --git a/src/api/utils/build-url.ts b/src/api/utils/build-url.ts index d2b87255255..e6b66168b21 100644 --- a/src/api/utils/build-url.ts +++ b/src/api/utils/build-url.ts @@ -9,6 +9,7 @@ import config from 'src/config'; import type { ResourceName, ResourcePathParams } from '../resources'; import getResourceParams from './get-resource-params'; import isNeedProxy from './is-need-proxy'; +import { resolveScopeFilters } from './scope-filters'; export default function buildUrl<R extends ResourceName>( resourceFullName: R, @@ -17,13 +18,14 @@ export default function buildUrl<R extends ResourceName>( noProxy?: boolean, chain?: ExternalChainExtended, ): string { - const { api, resource } = getResourceParams(resourceFullName, chain); + const { api, apiName, resource } = getResourceParams(resourceFullName, chain); const baseUrl = !noProxy && isNeedProxy() ? config.app.baseUrl : api.endpoint; const basePath = api.basePath ?? ''; const path = !noProxy && isNeedProxy() ? '/node-api/proxy' + basePath + resource.path : basePath + resource.path; const url = new URL(compile(path)(pathParams), baseUrl); + const params = { ...queryParams, ...resolveScopeFilters(apiName, resource.scopeFilters, chain, queryParams) }; - queryParams && Object.entries(queryParams).forEach(([ key, value ]) => { + Object.entries(params).forEach(([ key, value ]) => { // there are some pagination params that can be null or false for the next page value !== undefined && value !== '' && url.searchParams.append(key, String(value)); }); diff --git a/src/api/utils/get-resource-params.ts b/src/api/utils/get-resource-params.ts index bfa8f4cd89e..c53a92f96bc 100644 --- a/src/api/utils/get-resource-params.ts +++ b/src/api/utils/get-resource-params.ts @@ -1,16 +1,15 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { ApiResource } from '../resources/types'; import type { ApiName } from '../types'; import type { ExternalChainExtended } from 'src/shared/external-chains/types'; import config from 'src/config'; import type { ResourceName } from '../resources'; -import { RESOURCES } from '../resources'; +import { getResource } from './get-resource'; export default function getResourceParams(resourceFullName: ResourceName, chain?: ExternalChainExtended) { - const [ apiName, resourceName ] = resourceFullName.split(':') as [ ApiName, string ]; + const [ apiName ] = resourceFullName.split(':') as [ ApiName, string ]; const apiConfig = (() => { if (chain?.app_config?.apis) { @@ -27,6 +26,6 @@ export default function getResourceParams(resourceFullName: ResourceName, chain? return { api: apiConfig, apiName, - resource: RESOURCES[apiName][resourceName as keyof typeof RESOURCES[ApiName]] as ApiResource, + resource: getResource(resourceFullName), }; } diff --git a/src/api/utils/get-resource.spec.ts b/src/api/utils/get-resource.spec.ts new file mode 100644 index 00000000000..4dc1d8e5ff2 --- /dev/null +++ b/src/api/utils/get-resource.spec.ts @@ -0,0 +1,18 @@ +import { describe, it, expect } from 'vitest'; + +import { getResource } from './get-resource'; + +describe('getResource', () => { + it('returns the registry definition of a resource', () => { + expect(getResource('core:address_txs')).toEqual({ + path: '/api/v2/addresses/:hash/transactions', + pathParams: [ 'hash' ], + filterFields: [ 'filter' ], + paginated: true, + }); + }); + + it('does not depend on the API being configured', () => { + expect(getResource('interchainIndexer:bridged_tokens').path).toEqual(expect.any(String)); + }); +}); diff --git a/src/api/utils/get-resource.ts b/src/api/utils/get-resource.ts new file mode 100644 index 00000000000..e0354f78d86 --- /dev/null +++ b/src/api/utils/get-resource.ts @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { ApiResource } from '../resources/types'; +import type { ApiName } from '../types'; + +import type { ResourceName } from '../resources'; +import { RESOURCES } from '../resources'; + +export function getResource(resourceFullName: ResourceName): ApiResource { + const [ apiName, resourceName ] = resourceFullName.split(':') as [ ApiName, keyof typeof RESOURCES[ApiName] ]; + return RESOURCES[apiName][resourceName]; +} diff --git a/src/api/utils/scope-filters.spec.ts b/src/api/utils/scope-filters.spec.ts new file mode 100644 index 00000000000..44a3a7ff695 --- /dev/null +++ b/src/api/utils/scope-filters.spec.ts @@ -0,0 +1,264 @@ +import type { ApiResource } from '../resources/types'; +import type { ExternalChainExtended } from 'src/shared/external-chains/types'; + +// eslint-disable-next-line boundaries/element-types -- the spec needs a real multichain fixture; the api → features ban targets runtime code +import { chainA } from 'src/features/multichain/mocks/chains'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { describe, expect, test, vi } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import type { ResourceName } from '../resources'; +import { RESOURCES } from '../resources'; +import { SCOPE_FILTER_RESOLVERS } from './scope-filters'; + +const INTERCHAIN_HOST = 'http://localhost:3014'; +// NEXT_PUBLIC_NETWORK_ID in vitest/.env.vitest +const DEPLOYMENT_CHAIN_ID = '1'; +const BRIDGE_IDS = '1,2'; +const BRIDGE_IDS_ENCODED = encodeURIComponent(BRIDGE_IDS); +const PATH_PARAM_STUB = 'stub'; +const NO_SCOPE_FILTERS: Array<string> = []; + +const CROSS_CHAIN_ENVS = ENVS_MAP.crossChainTxs; +const MULTICHAIN_ENVS = [ ...ENVS_MAP.crossChainTxs, ...ENVS_MAP.multichain ]; + +// a cluster chain always carries `app_config.apis`, and `getResourceParams` prefers the host declared +// there over the deployment's own — so the fixture has to name the indexer it points at +const CHAIN_IN_SCOPE = { + ...chainA, + app_config: { + ...chainA.app_config, + apis: { + ...chainA.app_config.apis, + interchainIndexer: { endpoint: INTERCHAIN_HOST }, + }, + }, +}; + +type BuildUrl = ( + resource: ResourceName, + pathParams?: Record<string, string>, + queryParams?: Record<string, string>, + noProxy?: boolean, + chain?: ExternalChainExtended, +) => string; + +// the resource name and its path params are only known at runtime here, so buildUrl's per-resource +// generics cannot be satisfied — the registry walk below is the whole point of the test +const importBuildUrl = async() => (await import('./build-url')).default as unknown as BuildUrl; + +function buildUrlWithEnvs( + envs: Array<[ string, string ]>, + resource: ResourceName, + { pathParams, queryParams, chain }: { + pathParams?: Record<string, string>; + queryParams?: Record<string, string>; + chain?: ExternalChainExtended; + } = {}, +) { + return withEnvs(envs, async() => { + const buildUrl = await importBuildUrl(); + return buildUrl(resource, pathParams, queryParams, undefined, chain); + }); +} + +describe('scope filter derivation', () => { + test('multichain off — the deployment chain is the focal chain', async() => { + const url = await buildUrlWithEnvs(CROSS_CHAIN_ENVS, 'interchainIndexer:messages'); + + expect(url).toBe(`${ INTERCHAIN_HOST }/api/v1/interchain/messages?home_chain_id=1&include_unindexed_chains=false`); + }); + + test('multichain with a chain in scope — that chain is the focal chain, and no bridge_ids narrows it', async() => { + const url = await buildUrlWithEnvs(MULTICHAIN_ENVS, 'interchainIndexer:messages', { chain: CHAIN_IN_SCOPE }); + + expect(url).toBe(`${ INTERCHAIN_HOST }/api/v1/interchain/messages?home_chain_id=${ CHAIN_IN_SCOPE.id }&include_unindexed_chains=false`); + }); + + test('multichain aggregated — the deployment bridges scope the request', async() => { + const url = await buildUrlWithEnvs(MULTICHAIN_ENVS, 'interchainIndexer:messages'); + + expect(url).toBe( + `${ INTERCHAIN_HOST }/api/v1/interchain/messages?bridge_ids=${ BRIDGE_IDS_ENCODED }&include_unindexed_chains=false`, + ); + }); + + test('include_unindexed_chains comes from its own env', async() => { + const url = await buildUrlWithEnvs( + [ ...CROSS_CHAIN_ENVS, [ 'NEXT_PUBLIC_CROSS_CHAIN_TXS_INCLUDE_UNINDEXED_CHAINS', 'true' ] ], + 'interchainIndexer:messages', + ); + + expect(url).toBe(`${ INTERCHAIN_HOST }/api/v1/interchain/messages?home_chain_id=1&include_unindexed_chains=true`); + }); + + test('message details declares no scope filter and carries none', async() => { + const url = await buildUrlWithEnvs(CROSS_CHAIN_ENVS, 'interchainIndexer:message', { pathParams: { id: '0x123' } }); + + expect(url).toBe(`${ INTERCHAIN_HOST }/api/v1/interchain/messages/0x123`); + }); + + test('the caller query params keep their place in front of the profile', async() => { + const url = await buildUrlWithEnvs(CROSS_CHAIN_ENVS, 'interchainIndexer:messages', { + queryParams: { q: 'duck', page_token: 'token' }, + }); + + expect(url).toBe( + `${ INTERCHAIN_HOST }/api/v1/interchain/messages?q=duck&page_token=token&home_chain_id=1&include_unindexed_chains=false`, + ); + }); + + test('a user bridge_ids value replaces the deployment bridges', async() => { + const url = await buildUrlWithEnvs(MULTICHAIN_ENVS, 'interchainIndexer:messages', { + queryParams: { bridge_ids: '3' }, + }); + + expect(url).toBe(`${ INTERCHAIN_HOST }/api/v1/interchain/messages?bridge_ids=3&include_unindexed_chains=false`); + }); + + test('an empty user bridge_ids falls back to the deployment bridges', async() => { + const url = await buildUrlWithEnvs(MULTICHAIN_ENVS, 'interchainIndexer:messages', { + queryParams: { bridge_ids: '' }, + }); + + expect(url).toBe( + `${ INTERCHAIN_HOST }/api/v1/interchain/messages?bridge_ids=${ BRIDGE_IDS_ENCODED }&include_unindexed_chains=false`, + ); + }); + + test('user chain filters pass through untouched next to the profile', async() => { + const url = await buildUrlWithEnvs(CROSS_CHAIN_ENVS, 'interchainIndexer:transfers', { + queryParams: { src_chain_ids: '100', dst_chain_ids: '1' }, + }); + + expect(url).toBe( + `${ INTERCHAIN_HOST }/api/v1/interchain/transfers?src_chain_ids=100&dst_chain_ids=1&home_chain_id=1&include_unindexed_chains=false`, + ); + }); + + test('a resource declaring bridge_ids only never sends home_chain_id', async() => { + const url = await buildUrlWithEnvs(CROSS_CHAIN_ENVS, 'interchainIndexer:chains'); + + expect(url).toBe( + `${ INTERCHAIN_HOST }/api/v1/interchain/chains?bridge_ids=${ BRIDGE_IDS_ENCODED }&include_unindexed_chains=false`, + ); + }); +}); + +const INTERCHAIN_RESOURCES = Object.entries(RESOURCES.interchainIndexer) as Array<[ string, ApiResource ]>; + +// message details deliberately takes no profile, so a link to it resolves even for a row the lists hide; +// the bridges directory is narrowed to the deployment scope client-side, where bridge names are needed +const UNSCOPED_BY_DESIGN = [ 'message', 'bridges' ]; + +const KNOWN_SCOPE_FILTERS = Object.keys(SCOPE_FILTER_RESOLVERS.interchainIndexer ?? {}); + +function pathParamsStub(resource: ApiResource) { + return Object.fromEntries((resource.pathParams ?? []).map((param) => [ param, PATH_PARAM_STUB ])); +} + +function expectedFocalChainProfile(scopeFilters: Array<string> = NO_SCOPE_FILTERS) { + const chainPredicate = (() => { + if (scopeFilters.includes('home_chain_id')) { + return { home_chain_id: DEPLOYMENT_CHAIN_ID }; + } + return scopeFilters.includes('bridge_ids') ? { bridge_ids: BRIDGE_IDS } : {}; + })(); + + return { + ...chainPredicate, + ...(scopeFilters.includes('include_unindexed_chains') ? { include_unindexed_chains: 'false' } : {}), + }; +} + +function expectedAggregatedProfile(scopeFilters: Array<string> = NO_SCOPE_FILTERS) { + return { + ...(scopeFilters.includes('bridge_ids') ? { bridge_ids: BRIDGE_IDS } : {}), + ...(scopeFilters.includes('include_unindexed_chains') ? { include_unindexed_chains: 'false' } : {}), + }; +} + +describe('every registered resource answers how it is scoped', () => { + test.each(INTERCHAIN_RESOURCES)('interchainIndexer:%s declares a scope', (name, resource) => { + const declared = resource.scopeFilters ?? NO_SCOPE_FILTERS; + + expect(declared.length > 0).toBe(!UNSCOPED_BY_DESIGN.includes(name)); + }); + + test.each(INTERCHAIN_RESOURCES)('interchainIndexer:%s declares only resolvable filters', (name, resource) => { + expect(KNOWN_SCOPE_FILTERS).toEqual(expect.arrayContaining(resource.scopeFilters ?? NO_SCOPE_FILTERS)); + }); +}); + +describe('every declared scope filter reaches the URL of every registered resource', () => { + test.each(INTERCHAIN_RESOURCES)('interchainIndexer:%s on a focal-chain deployment', async(name, resource) => { + const url = await buildUrlWithEnvs(CROSS_CHAIN_ENVS, `interchainIndexer:${ name }` as ResourceName, { + pathParams: pathParamsStub(resource), + }); + + expect(Object.fromEntries(new URL(url).searchParams)).toEqual(expectedFocalChainProfile(resource.scopeFilters)); + }); + + test.each(INTERCHAIN_RESOURCES)('interchainIndexer:%s on an aggregated multichain view', async(name, resource) => { + const url = await buildUrlWithEnvs(MULTICHAIN_ENVS, `interchainIndexer:${ name }` as ResourceName, { + pathParams: pathParamsStub(resource), + }); + + expect(Object.fromEntries(new URL(url).searchParams)).toEqual(expectedAggregatedProfile(resource.scopeFilters)); + }); +}); + +describe('a declared scope filter with no resolver for its own service', () => { + const FIXTURE_RESOURCE_NAME = 'scope_filter_fixture'; + const MISSPELLED_FILTER = 'bridge_id'; + + const FIXTURE_RESOURCES = { + interchainIndexer: { + path: '/api/v1/interchain/fixture', + scopeFilters: [ 'home_chain_id', MISSPELLED_FILTER ], + }, + core: { + path: '/api/v2/fixture', + scopeFilters: [ 'home_chain_id', 'bridge_ids', 'include_unindexed_chains' ], + }, + } satisfies Record<string, ApiResource>; + + type FixtureApiName = keyof typeof FIXTURE_RESOURCES; + + function buildUrlForFixtureResource(envs: Array<[ string, string ]>, apiName: FixtureApiName) { + return withEnvs(envs, async() => { + vi.doMock('../resources', async() => { + const actual = await vi.importActual<{ RESOURCES: typeof RESOURCES }>('../resources'); + + return { + ...actual, + RESOURCES: { + ...actual.RESOURCES, + [apiName]: { ...actual.RESOURCES[apiName], [FIXTURE_RESOURCE_NAME]: FIXTURE_RESOURCES[apiName] }, + }, + }; + }); + + try { + const buildUrl = await importBuildUrl(); + return buildUrl(`${ apiName }:${ FIXTURE_RESOURCE_NAME }` as ResourceName); + } finally { + vi.doUnmock('../resources'); + } + }); + } + + test('is left out of the query string instead of failing the request', async() => { + const url = await buildUrlForFixtureResource(CROSS_CHAIN_ENVS, 'interchainIndexer'); + + expect(url).toBe(`${ INTERCHAIN_HOST }/api/v1/interchain/fixture?home_chain_id=${ DEPLOYMENT_CHAIN_ID }`); + }); + + test('does not inherit the interchain resolver of the same name', async() => { + const url = await buildUrlForFixtureResource(CROSS_CHAIN_ENVS, 'core'); + + expect(Object.fromEntries(new URL(url).searchParams)).toEqual({}); + }); +}); diff --git a/src/api/utils/scope-filters.ts b/src/api/utils/scope-filters.ts new file mode 100644 index 00000000000..040fc548921 --- /dev/null +++ b/src/api/utils/scope-filters.ts @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { ApiName } from '../types'; +import type { ExternalChainExtended } from 'src/shared/external-chains/types'; + +import config from 'src/config'; + +const crossChainTxsFeature = config.features.crossChainTxs; + +type QueryParams = Record<string, unknown>; + +interface ScopeFilterContext { + readonly declaredFilters: ReadonlyArray<string>; + readonly chain: ExternalChainExtended | undefined; + readonly queryParams: QueryParams; +} + +type ScopeFilterResolver = (context: ScopeFilterContext) => string | undefined; + +const resolveFocalChainId: ScopeFilterResolver = ({ chain }) => { + return config.features.multichain.isEnabled ? chain?.id : config.chain.id; +}; + +const hasUserBridgeIds = (queryParams: QueryParams): boolean => { + const value = queryParams.bridge_ids; + return value !== undefined && value !== ''; +}; + +const resolveBridgeIds: ScopeFilterResolver = (context) => { + if (crossChainTxsFeature.isEnabled) { + if (hasUserBridgeIds(context.queryParams)) { + return; + } + + const hasFocalChain = context.declaredFilters.includes('home_chain_id') && Boolean(resolveFocalChainId(context)); + + if (hasFocalChain || crossChainTxsFeature.bridgeIds.length === 0) { + return; + } + + return crossChainTxsFeature.bridgeIds.join(','); + } +}; + +const resolveIncludeUnindexedChains: ScopeFilterResolver = () => { + if (crossChainTxsFeature.isEnabled) { + return String(crossChainTxsFeature.includeUnindexedChains); + } +}; + +export const SCOPE_FILTER_RESOLVERS: Partial<Record<ApiName, Record<string, ScopeFilterResolver>>> = { + interchainIndexer: { + home_chain_id: resolveFocalChainId, + bridge_ids: resolveBridgeIds, + include_unindexed_chains: resolveIncludeUnindexedChains, + }, +}; + +const NO_SCOPE_FILTERS: ReadonlyArray<string> = []; +const NO_RESOLVERS: Record<string, ScopeFilterResolver> = {}; +const NO_QUERY_PARAMS: QueryParams = {}; + +export function resolveScopeFilters( + apiName: ApiName, + scopeFilters: ReadonlyArray<string> | undefined, + chain: ExternalChainExtended | undefined, + queryParams: QueryParams | undefined, +): Record<string, string> { + const resolvers = SCOPE_FILTER_RESOLVERS[apiName] ?? NO_RESOLVERS; + const declaredFilters = scopeFilters ?? NO_SCOPE_FILTERS; + const context: ScopeFilterContext = { declaredFilters, chain, queryParams: queryParams ?? NO_QUERY_PARAMS }; + + const entries = declaredFilters + .map((name) => [ name, resolvers[name]?.(context) ] as const) + .filter((entry): entry is [ string, string ] => entry[1] !== undefined); + + return Object.fromEntries(entries); +} diff --git a/src/config/CONTEXT.md b/src/config/CONTEXT.md new file mode 100644 index 00000000000..c57bb539dc4 --- /dev/null +++ b/src/config/CONTEXT.md @@ -0,0 +1,39 @@ +# App config — context + +`src/config/index.ts` assembles the app config from the co-located config modules: `src/api/config.ts`, +`src/features/**/config.ts`, `src/slices/*/config.ts`, `src/shell/*/config.ts`, `src/services/*/config.ts`. +Each module turns raw env values into typed, validated data. The aggregator is the only place the app reads +that data from. + +## The convention + +Three rules. ESLint enforces all of them (`eslint.config.mjs`, the "App config convention" blocks), so a +violation fails before review. + +1. **A config module has no export besides its default.** Everything the feature owns lives inside the + config object, widening its `Feature<Payload>`. `Feature<>` hides the payload when `isEnabled` is + `false`. A value exported beside the object stays readable while the feature is off, which is the state + the type exists to rule out. Types and constant lists go to a sibling role file — `types/config.ts`, + `types.ts`, `consts.ts` — never the config module. +2. **Only `src/config` is imported.** App code reads `config.<section>.<name>` (the sections: + `.agents/rules/env-vars.md`). It never imports the module itself. +3. **Only config modules read envs.** `src/config/utils/envs.ts` is importable from a `config.ts` or + `src/config/**`, nowhere else, and the raw `window.__envs` map is read inside that file only. A value + read elsewhere is untyped, unvalidated and invisible to the aggregator. It can also differ between the + browser and Node. A util that called `getEnvValue` directly read one value in the browser and another + under Node, and broke an unrelated test suite in a way that showed up only as a visual diff. + +## Exemptions the rules allow + +- **Config-to-config imports.** A config module may import another config module directly, for example a + feature gated on whether another one is enabled. The aggregator cannot be used from inside a module it + aggregates. +- **A `config.spec.ts`** imports the module under test directly and dynamically, under `withEnvs`, because + the config is a frozen module-level singleton. The exemption is by file name, not by neighbourhood. +- **Type-only imports** of a config module carry no runtime payload and pass. +- **Companions.** `<feature>/types/config.ts` and `<feature>/mocks/config.ts` are not config modules and + export freely. +- **Outside `src/`.** `playwright/`, `vitest/`, `deploy/` and `tools/` are not checked. + +The Node env-validator constraint on these files (no React, browser APIs, or code from other slices and +features) lives in `.agents/rules/architecture.md`. diff --git a/src/config/features.ts b/src/config/features.ts index 72d31b769af..1db6277ea5f 100644 --- a/src/config/features.ts +++ b/src/config/features.ts @@ -10,6 +10,7 @@ export { default as alternativeExplorers } from 'src/features/alternative-explor export { default as apiDocs } from 'src/features/api-docs/config'; export { default as beaconChain } from 'src/features/chain-variants/beacon-chain/config'; export { default as bridgedTokens } from 'src/features/bridged-tokens/config'; +export { default as bubblemaps } from 'src/features/bubblemaps/config'; export { default as connectWallet } from 'src/features/connect-wallet/config'; export { default as celo } from 'src/features/chain-variants/celo/config'; export { default as crossChainTxs } from 'src/features/cross-chain-txs/config'; diff --git a/src/config/services.ts b/src/config/services.ts index 563efe8f512..105b01a4edb 100644 --- a/src/config/services.ts +++ b/src/config/services.ts @@ -3,6 +3,7 @@ export { default as googleAnalytics } from 'src/services/google-analytics/config'; export { default as growthBook } from 'src/services/growthbook/config'; export { default as mixpanel } from 'src/services/mixpanel/config'; +export { default as posthog } from 'src/services/posthog/config'; export { default as reCaptcha } from 'src/services/re-captcha/config'; export { default as rollbar } from 'src/services/rollbar/config'; export { default as usercentrics } from 'src/services/usercentrics/config'; diff --git a/src/config/test-utils/env-presets.ts b/src/config/test-utils/env-presets.ts index e7e726707f9..bcc9b499ce1 100644 --- a/src/config/test-utils/env-presets.ts +++ b/src/config/test-utils/env-presets.ts @@ -46,12 +46,19 @@ export const ENVS_MAP: Record<string, Array<[string, string]>> = { xStarScore: [ [ 'NEXT_PUBLIC_XSTAR_SCORE_URL', 'https://localhost:3115' ], ], + bubblemaps: [ + [ 'NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG', 'eth' ], + [ 'NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID', 'demo' ], + ], hasContractAuditReports: [ [ 'NEXT_PUBLIC_HAS_CONTRACT_AUDIT_REPORTS', 'true' ], ], blockHiddenFields: [ [ 'NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_FIELDS', '["burnt_fees", "total_reward", "nonce"]' ], ], + blockHiddenViews: [ + [ 'NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_VIEWS', '["reorgs", "uncles"]' ], + ], stabilityEnvs: [ [ 'NEXT_PUBLIC_VIEWS_ADDRESS_HIDDEN_VIEWS', '["top_accounts"]' ], [ 'NEXT_PUBLIC_VIEWS_TX_HIDDEN_FIELDS', '["value","fee_currency","gas_price","gas_fees","burnt_fees"]' ], @@ -100,7 +107,7 @@ export const ENVS_MAP: Record<string, Array<[string, string]>> = { [ 'NEXT_PUBLIC_INTEROP_ENABLED', 'true' ], ], tac: [ - [ 'NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST', 'http://localhost:3100' ], + [ 'NEXT_PUBLIC_TAC_OPERATION_LIFECYCLE_API_HOST', 'http://localhost:3010' ], [ 'NEXT_PUBLIC_TAC_TON_EXPLORER_URL', 'https://testnet.tonviewer.com' ], ], celo: [ @@ -132,6 +139,7 @@ export const ENVS_MAP: Record<string, Array<[string, string]>> = { crossChainTxs: [ [ 'NEXT_PUBLIC_INTERCHAIN_INDEXER_API_HOST', 'http://localhost:3014' ], [ 'NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED', 'true' ], + [ 'NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS', '[1,2]' ], ], proApi: [ [ 'NEXT_PUBLIC_PRO_API_SUPPORTED', 'true' ], @@ -139,6 +147,12 @@ export const ENVS_MAP: Record<string, Array<[string, string]>> = { flashblocks: [ [ 'NEXT_PUBLIC_FLASHBLOCKS_SOCKET_URL', 'wss://localhost:3120/ws' ], ], +<<<<<<< HEAD +======= + additionalTokenTypes: [ + [ 'NEXT_PUBLIC_NETWORK_ADDITIONAL_TOKEN_TYPES', '[{"id":"ERC-7984","name":"ERC-7984"},{"id":"ERC-8056","name":"ERC-8056"}]' ], + ], +>>>>>>> v2.13.0 tokenActionButton: [ [ 'NEXT_PUBLIC_TOKEN_ACTION_BUTTON_CONFIG', diff --git a/src/config/utils/envs.spec.ts b/src/config/utils/envs.spec.ts new file mode 100644 index 00000000000..e94e6a5aef2 --- /dev/null +++ b/src/config/utils/envs.spec.ts @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { buildExternalAssetFilePath, parseEnvHtmlList } from './envs'; + +describe('parseEnvHtmlList', () => { + it('returns no items for an unset or empty value', () => { + expect(parseEnvHtmlList(undefined)).toEqual([]); + expect(parseEnvHtmlList('')).toEqual([]); + }); + + it('treats a plain string as one item, quotes as set', () => { + expect(parseEnvHtmlList(`Don't <a href='https://example.com'>miss</a>`)).toEqual([ `Don't <a href='https://example.com'>miss</a>` ]); + }); + + it('parses a double-quoted list as set, keeping apostrophes and single-quoted attributes', () => { + expect(parseEnvHtmlList(`["It's down", "<a href='https://example.com'>Link</a>"]`)).toEqual([ + `It's down`, + `<a href='https://example.com'>Link</a>`, + ]); + }); + + it('parses a single-quoted list through the quote rewrite', () => { + expect(parseEnvHtmlList(`['Hello', '<b>World</b>']`)).toEqual([ 'Hello', '<b>World</b>' ]); + }); + + it('keeps only the string items of a list', () => { + expect(parseEnvHtmlList('["Hello", 1, null]')).toEqual([ 'Hello' ]); + }); + + it('treats JSON that is not a list as one item', () => { + expect(parseEnvHtmlList('"Hello"')).toEqual([ '"Hello"' ]); + }); +}); + +describe('buildExternalAssetFilePath', () => { + it('derives the file name from the env name and the extension from the URL path', () => { + expect(buildExternalAssetFilePath('NEXT_PUBLIC_NETWORK_LOGO', 'https://example.com/images/logo.svg')) + .toBe('/assets/configs/network_logo.svg'); + expect(buildExternalAssetFilePath('NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', 'https://example.com/config.json?v=2')) + .toBe('/assets/configs/marketplace_config.json'); + }); + + it('uses the bare file name when the URL path has no extension', () => { + expect(buildExternalAssetFilePath('NEXT_PUBLIC_NETWORK_LOGO', 'https://imagedelivery.net/abc/390b3c31-7286/public')) + .toBe('/assets/configs/network_logo'); + expect(buildExternalAssetFilePath('NEXT_PUBLIC_OG_IMAGE_URL', 'https://example.com/v1.2/og')) + .toBe('/assets/configs/og_image'); + expect(buildExternalAssetFilePath('NEXT_PUBLIC_NETWORK_LOGO', 'https://example.com/logo.svg/')) + .toBe('/assets/configs/network_logo'); + expect(buildExternalAssetFilePath('NEXT_PUBLIC_NETWORK_LOGO', 'https://example.com')) + .toBe('/assets/configs/network_logo'); + expect(buildExternalAssetFilePath('NEXT_PUBLIC_NETWORK_LOGO', 'https://example.com/file.foo-bar')) + .toBe('/assets/configs/network_logo'); + }); + + it('lowercases the extension', () => { + expect(buildExternalAssetFilePath('NEXT_PUBLIC_NETWORK_ICON', 'https://example.com/Icon.PNG')) + .toBe('/assets/configs/network_icon.png'); + }); + + it('supports file:// URLs and an uppercase scheme', () => { + expect(buildExternalAssetFilePath('NEXT_PUBLIC_FOOTER_LINKS', 'file:///opt/links.json')) + .toBe('/assets/configs/footer_links.json'); + expect(buildExternalAssetFilePath('NEXT_PUBLIC_NETWORK_LOGO', 'HTTPS://example.com/logo.svg')) + .toBe('/assets/configs/network_logo.svg'); + }); + + it('treats a raw JSON value as a json file', () => { + expect(buildExternalAssetFilePath('NEXT_PUBLIC_FEATURED_NETWORKS', '[{"title":"Foo"}]')) + .toBe('/assets/configs/featured_networks.json'); + }); + + it('returns undefined for a value that is neither a URL nor JSON', () => { + expect(buildExternalAssetFilePath('NEXT_PUBLIC_FEATURED_NETWORKS', 'not a url')).toBeUndefined(); + }); +}); diff --git a/src/config/utils/envs.ts b/src/config/utils/envs.ts index 70549295a98..66768648fdf 100644 --- a/src/config/utils/envs.ts +++ b/src/config/utils/envs.ts @@ -5,7 +5,9 @@ import * as regexp from 'src/toolkit/utils/regexp'; export const replaceQuotes = (value: string | undefined) => value?.replaceAll('\'', '"'); -export const getEnvValue = (envName: string) => { +type EnvRead = { readonly value: string | undefined; readonly isFromTestStorage: boolean }; + +const readEnv = (envName: string): EnvRead => { // eslint-disable-next-line no-restricted-properties const envs = (isBrowser() ? window.__envs : process.env) ?? {}; @@ -13,13 +15,20 @@ export const getEnvValue = (envName: string) => { const storageValue = localStorage.getItem(envName); if (typeof storageValue === 'string') { - return storageValue; + return { value: storageValue, isFromTestStorage: true }; } } - return replaceQuotes(envs[envName]); + return { value: envs[envName], isFromTestStorage: false }; +}; + +export const getEnvValue = (envName: string): string | undefined => { + const { value, isFromTestStorage } = readEnv(envName); + return isFromTestStorage ? value : replaceQuotes(value); }; +export const getRawEnvValue = (envName: string): string | undefined => readEnv(envName).value; + export const parseEnvJson = <DataType>(env: string | undefined): DataType | null => { try { return JSON.parse(env || 'null') as DataType | null; @@ -28,6 +37,22 @@ export const parseEnvJson = <DataType>(env: string | undefined): DataType | null } }; +// HTML is rendered as set: the quote rewrite of getEnvValue would turn an apostrophe or a single-quoted +// attribute value into a double quote. +export const getEnvHtmlValue = (envName: string): string | undefined => getRawEnvValue(envName); + +// A JSON list of HTML items is parsed as set first, since the quote rewrite breaks an item with an apostrophe +// or a single-quoted attribute; the rewritten form keeps the `['a','b']` syntax working. Anything else is one item. +export const parseEnvHtmlList = (value: string | undefined): Array<string> => { + if (!value) { + return []; + } + + const parsed = parseEnvJson<unknown>(value) ?? parseEnvJson<unknown>(replaceQuotes(value)); + + return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === 'string') : [ value ]; +}; + export const getExternalAssetFilePath = (envName: string) => { const parsedValue = getEnvValue(envName); @@ -39,24 +64,23 @@ export const getExternalAssetFilePath = (envName: string) => { }; export const buildExternalAssetFilePath = (name: string, value: string) => { - try { - const fileName = name.replace(/^NEXT_PUBLIC_/, '').replace(/_URL$/, '').toLowerCase(); + const fileName = name.replace(/^NEXT_PUBLIC_/, '').replace(/_URL$/, '').toLowerCase(); + const url = parseUrl(value); - const fileExtension = getAssetFileExtension(value); - if (!fileExtension) { - throw new Error('Cannot get file path'); - } - return `/assets/configs/${ fileName }.${ fileExtension }`; - } catch (error) { - return; + if (!url) { + return parseEnvJson(value) ? `/assets/configs/${ fileName }.json` : undefined; } + + // deploy/tools/assets-downloader saves the file under this same name; a URL whose path has no + // file extension (e.g. Cloudflare Images "…/<id>/public") is saved under the bare file name. + const fileExtension = url.pathname.match(regexp.FILE_EXTENSION)?.[1]?.toLowerCase(); + return fileExtension ? `/assets/configs/${ fileName }.${ fileExtension }` : `/assets/configs/${ fileName }`; }; -function getAssetFileExtension(value: string) { +function parseUrl(value: string): URL | undefined { try { - const url = new URL(value); - return url.pathname.match(regexp.FILE_EXTENSION)?.[1]; + return new URL(value); } catch (error) { - return parseEnvJson(value) ? 'json' : undefined; + return; } } diff --git a/src/features/account/components/auth-modal/AuthModal.pw.tsx b/src/features/account/components/auth-modal/AuthModal.pw.tsx index f72db3f7397..cf653e6207e 100644 --- a/src/features/account/components/auth-modal/AuthModal.pw.tsx +++ b/src/features/account/components/auth-modal/AuthModal.pw.tsx @@ -9,7 +9,7 @@ import { test, expect } from 'playwright/lib'; import AuthModalStory from './AuthModal.pwstory'; test('email login', async({ render, page, mockApiResponse }) => { - + await mockApiResponse('core:csrf', {} as never); await render(<AuthModalStory flow="email_login"/>); await expect(page.getByText('Status: Not authenticated')).toBeVisible(); @@ -54,6 +54,7 @@ const linkEmailTest = test.extend<{ context: BrowserContext }>({ linkEmailTest('link email to account', async({ render, page, mockApiResponse }) => { await mockApiResponse('core:user_info', profileMock.base); + await mockApiResponse('core:csrf', {} as never); await render(<AuthModalStory flow="email_link"/>); await expect(page.getByText('Status: Authenticated')).toBeVisible(); diff --git a/src/features/account/components/auth-modal/AuthModal.tsx b/src/features/account/components/auth-modal/AuthModal.tsx index d414acaa396..bf48ae7c2a9 100644 --- a/src/features/account/components/auth-modal/AuthModal.tsx +++ b/src/features/account/components/auth-modal/AuthModal.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React from 'react'; import type { Screen, ScreenSuccess } from './types'; @@ -12,7 +11,8 @@ import useGetCsrfToken from 'src/features/account/hooks/useGetCsrfToken'; import { useRewardsContext } from 'src/features/rewards/context'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; +import { useRouter } from 'src/shared/router/useRouter'; import { DialogBody, DialogContent, DialogHeader, DialogRoot } from 'src/toolkit/chakra/dialog'; @@ -28,18 +28,18 @@ const feature = config.features.account; interface Props { initialScreen: Screen; onClose: (isSuccess?: boolean, rewardsApiToken?: string) => void; - mixpanelConfig?: { + analyticsConfig?: { wallet_connect?: { - source: mixpanel.EventPayload<mixpanel.EventTypes.WALLET_CONNECT>['Source']; + source: analytics.EventPayload<analytics.EventTypes.WALLET_CONNECT>['Source']; }; account_link_info: { - source: mixpanel.EventPayload<mixpanel.EventTypes.ACCOUNT_LINK_INFO>['Source']; + source: analytics.EventPayload<analytics.EventTypes.ACCOUNT_LINK_INFO>['Source']; }; }; closeOnError?: boolean; } -const AuthModal = ({ initialScreen, onClose, mixpanelConfig, closeOnError }: Props) => { +const AuthModal = ({ initialScreen, onClose, analyticsConfig, closeOnError }: Props) => { const [ steps, setSteps ] = React.useState<Array<Screen>>([ initialScreen ]); const [ isSuccess, setIsSuccess ] = React.useState(false); const [ rewardsApiToken, setRewardsApiToken ] = React.useState<string | undefined>(undefined); @@ -51,18 +51,18 @@ const AuthModal = ({ initialScreen, onClose, mixpanelConfig, closeOnError }: Pro React.useEffect(() => { if ('isAuth' in initialScreen && initialScreen.isAuth) { - mixpanel.logEvent(mixpanel.EventTypes.ACCOUNT_LINK_INFO, { + analytics.logEvent(analytics.EventTypes.ACCOUNT_LINK_INFO, { Status: 'Started', Type: initialScreen.type === 'connect_wallet' ? 'Wallet' : 'Email', - Source: mixpanelConfig?.account_link_info.source ?? 'Profile dropdown', + Source: analyticsConfig?.account_link_info.source ?? 'Profile dropdown', }); } else { - mixpanel.logEvent(mixpanel.EventTypes.LOGIN, { + analytics.logEvent(analytics.EventTypes.LOGIN, { Action: 'Started', - Source: mixpanel.getPageType(router.pathname), + Source: analytics.getPageType(router.pathname), }); } - }, [ initialScreen, mixpanelConfig, router.pathname ]); + }, [ initialScreen, analyticsConfig, router.pathname ]); const onNextStep = React.useCallback((screen: Screen) => { setSteps((prev) => [ ...prev, screen ]); @@ -80,13 +80,13 @@ const AuthModal = ({ initialScreen, onClose, mixpanelConfig, closeOnError }: Pro setIsSuccess(true); if ('isAuth' in initialScreen && initialScreen.isAuth) { - mixpanel.logEvent(mixpanel.EventTypes.ACCOUNT_LINK_INFO, { + analytics.logEvent(analytics.EventTypes.ACCOUNT_LINK_INFO, { Status: 'Finished', Type: screen.type === 'success_wallet' ? 'Wallet' : 'Email', - Source: mixpanelConfig?.account_link_info.source ?? 'Profile dropdown', + Source: analyticsConfig?.account_link_info.source ?? 'Profile dropdown', }); } else { - mixpanel.logEvent(mixpanel.EventTypes.LOGIN, { + analytics.logEvent(analytics.EventTypes.LOGIN, { Action: 'Success', Source: screen.type === 'success_wallet' ? 'Wallet' : 'Email', }); @@ -101,7 +101,7 @@ const AuthModal = ({ initialScreen, onClose, mixpanelConfig, closeOnError }: Pro } onNextStep(screen); - }, [ initialScreen, mixpanelConfig?.account_link_info.source, onNextStep, csrfQuery, queryClient, onRewardsLoginSuccess ]); + }, [ initialScreen, analyticsConfig?.account_link_info.source, onNextStep, csrfQuery, queryClient, onRewardsLoginSuccess ]); const onModalClose = React.useCallback(() => { onClose(isSuccess, rewardsApiToken); @@ -140,7 +140,7 @@ const AuthModal = ({ initialScreen, onClose, mixpanelConfig, closeOnError }: Pro onError={ onReset } isAuth={ currentStep.isAuth } loginToRewards={ currentStep.loginToRewards } - source={ mixpanelConfig?.wallet_connect?.source } + source={ analyticsConfig?.wallet_connect?.source } /> ); case 'email': @@ -148,7 +148,7 @@ const AuthModal = ({ initialScreen, onClose, mixpanelConfig, closeOnError }: Pro <AuthModalScreenEmail onSubmit={ onNextStep } isAuth={ currentStep.isAuth } - mixpanelConfig={ mixpanelConfig } + analyticsConfig={ analyticsConfig } /> ); case 'otp_code': diff --git a/src/features/account/components/auth-modal/guard/AuthGuard.tsx b/src/features/account/components/auth-modal/guard/AuthGuard.ts similarity index 100% rename from src/features/account/components/auth-modal/guard/AuthGuard.tsx rename to src/features/account/components/auth-modal/guard/AuthGuard.ts diff --git a/src/features/account/components/auth-modal/guard/AuthGuardDynamic.tsx b/src/features/account/components/auth-modal/guard/AuthGuardDynamic.ts similarity index 100% rename from src/features/account/components/auth-modal/guard/AuthGuardDynamic.tsx rename to src/features/account/components/auth-modal/guard/AuthGuardDynamic.ts diff --git a/src/features/account/components/auth-modal/screens/AuthModalScreenConnectWallet.tsx b/src/features/account/components/auth-modal/screens/AuthModalScreenConnectWallet.tsx index c0a2f010ee6..cc12731281a 100644 --- a/src/features/account/components/auth-modal/screens/AuthModalScreenConnectWallet.tsx +++ b/src/features/account/components/auth-modal/screens/AuthModalScreenConnectWallet.tsx @@ -8,15 +8,15 @@ import type { UserInfo } from 'src/features/account/types/api'; import useSignInWithWallet from 'src/features/account/hooks/useSignInWithWallet'; -import type * as mixpanel from 'src/services/mixpanel'; import ReCaptcha from 'src/services/re-captcha/ReCaptcha'; import useReCaptcha from 'src/services/re-captcha/useReCaptcha'; +import type * as analytics from 'src/shared/analytics'; interface Props { onSuccess: (screen: ScreenSuccess) => void; onError: (isAuth?: boolean) => void; isAuth?: boolean; - source?: mixpanel.EventPayload<mixpanel.EventTypes.WALLET_CONNECT>['Source']; + source?: analytics.EventPayload<analytics.EventTypes.WALLET_CONNECT>['Source']; loginToRewards?: boolean; } diff --git a/src/features/account/components/auth-modal/screens/AuthModalScreenEmail.tsx b/src/features/account/components/auth-modal/screens/AuthModalScreenEmail.tsx index 24b5f1f30f4..2d7285f092a 100644 --- a/src/features/account/components/auth-modal/screens/AuthModalScreenEmail.tsx +++ b/src/features/account/components/auth-modal/screens/AuthModalScreenEmail.tsx @@ -9,9 +9,9 @@ import type { EmailFormFields, Screen } from '../types'; import useApiFetch from 'src/api/hooks/useApiFetch'; -import * as mixpanel from 'src/services/mixpanel'; import ReCaptcha from 'src/services/re-captcha/ReCaptcha'; import useReCaptcha from 'src/services/re-captcha/useReCaptcha'; +import * as analytics from 'src/shared/analytics'; import getErrorMessage from 'src/shared/errors/get-error-message'; import getErrorObjPayload from 'src/shared/errors/get-error-obj-payload'; @@ -22,14 +22,14 @@ import { FormFieldEmail } from 'src/toolkit/components/forms/fields/FormFieldEma interface Props { onSubmit: (screen: Screen) => void; isAuth?: boolean; - mixpanelConfig?: { + analyticsConfig?: { account_link_info: { - source: mixpanel.EventPayload<mixpanel.EventTypes.ACCOUNT_LINK_INFO>['Source']; + source: analytics.EventPayload<analytics.EventTypes.ACCOUNT_LINK_INFO>['Source']; }; }; } -const AuthModalScreenEmail = ({ onSubmit, isAuth, mixpanelConfig }: Props) => { +const AuthModalScreenEmail = ({ onSubmit, isAuth, analyticsConfig }: Props) => { const apiFetch = useApiFetch(); const recaptcha = useReCaptcha(); @@ -58,13 +58,13 @@ const AuthModalScreenEmail = ({ onSubmit, isAuth, mixpanelConfig }: Props) => { await recaptcha.fetchProtectedResource(sendCodeFetchFactory(formData.email)); if (isAuth) { - mixpanelConfig?.account_link_info.source !== 'Profile' && mixpanel.logEvent(mixpanel.EventTypes.ACCOUNT_LINK_INFO, { - Source: mixpanelConfig?.account_link_info.source ?? 'Profile dropdown', + analyticsConfig?.account_link_info.source !== 'Profile' && analytics.logEvent(analytics.EventTypes.ACCOUNT_LINK_INFO, { + Source: analyticsConfig?.account_link_info.source ?? 'Profile dropdown', Status: 'OTP sent', Type: 'Email', }); } else { - mixpanel.logEvent(mixpanel.EventTypes.LOGIN, { + analytics.logEvent(analytics.EventTypes.LOGIN, { Action: 'OTP sent', Source: 'Email', }); @@ -76,7 +76,7 @@ const AuthModalScreenEmail = ({ onSubmit, isAuth, mixpanelConfig }: Props) => { description: getErrorObjPayload<{ message: string }>(error)?.message || getErrorMessage(error) || 'Something went wrong', }); } - }, [ recaptcha, sendCodeFetchFactory, isAuth, onSubmit, mixpanelConfig?.account_link_info.source ]); + }, [ recaptcha, sendCodeFetchFactory, isAuth, onSubmit, analyticsConfig?.account_link_info.source ]); return ( <FormProvider { ...formApi }> diff --git a/src/features/account/components/auth-modal/screens/AuthModalScreenSelectMethod.tsx b/src/features/account/components/auth-modal/screens/AuthModalScreenSelectMethod.tsx index 1f841a437a3..a1d04e5ce2c 100644 --- a/src/features/account/components/auth-modal/screens/AuthModalScreenSelectMethod.tsx +++ b/src/features/account/components/auth-modal/screens/AuthModalScreenSelectMethod.tsx @@ -5,7 +5,7 @@ import React from 'react'; import type { Screen } from '../types'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { Button } from 'src/toolkit/chakra/button'; @@ -16,7 +16,7 @@ interface Props { const AuthModalScreenSelectMethod = ({ onSelectMethod }: Props) => { const handleEmailClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.LOGIN, { + analytics.logEvent(analytics.EventTypes.LOGIN, { Action: 'Email', Source: 'Options selector', }); @@ -24,7 +24,7 @@ const AuthModalScreenSelectMethod = ({ onSelectMethod }: Props) => { }, [ onSelectMethod ]); const handleConnectWalletClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.LOGIN, { + analytics.logEvent(analytics.EventTypes.LOGIN, { Action: 'Wallet', Source: 'Options selector', }); diff --git a/src/features/account/components/auth-modal/screens/AuthModalScreenSuccessWallet.tsx b/src/features/account/components/auth-modal/screens/AuthModalScreenSuccessWallet.tsx index e9cdae22541..d958324a3a1 100644 --- a/src/features/account/components/auth-modal/screens/AuthModalScreenSuccessWallet.tsx +++ b/src/features/account/components/auth-modal/screens/AuthModalScreenSuccessWallet.tsx @@ -7,10 +7,10 @@ import type { Screen } from '../types'; import type { UserInfo } from 'src/features/account/types/api'; import config from 'src/config'; -import shortenString from 'src/shared/texts/shorten-string'; import { Button } from 'src/toolkit/chakra/button'; import { apos } from 'src/toolkit/utils/htmlEntities'; +import { shortenString } from 'src/toolkit/utils/texts'; interface Props { address: string; diff --git a/src/features/account/components/user-profile/auth0/UserProfileButton.tsx b/src/features/account/components/user-profile/auth0/UserProfileButton.tsx index 5929cf7fc41..bc086e53946 100644 --- a/src/features/account/components/user-profile/auth0/UserProfileButton.tsx +++ b/src/features/account/components/user-profile/auth0/UserProfileButton.tsx @@ -12,11 +12,11 @@ import useWeb3AccountWithDomain from 'src/features/connect-wallet/hooks/useAccou import { useMarketplaceContext } from 'src/features/marketplace/context'; import useIsMobile from 'src/shared/hooks/useIsMobile'; -import shortenString from 'src/shared/texts/shorten-string'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { shortenString } from 'src/toolkit/utils/texts'; import UserIdenticon from '../UserIdenticon'; diff --git a/src/features/account/components/user-profile/auth0/UserProfileContent.tsx b/src/features/account/components/user-profile/auth0/UserProfileContent.tsx index f642e2e6e8f..ddfc177297b 100644 --- a/src/features/account/components/user-profile/auth0/UserProfileContent.tsx +++ b/src/features/account/components/user-profile/auth0/UserProfileContent.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Separator, Flex, VStack } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { NavLink } from '../types'; @@ -12,12 +11,13 @@ import { useMarketplaceContext } from 'src/features/marketplace/context'; import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; -import shortenString from 'src/shared/texts/shorten-string'; +import { route } from 'src/shared/router/routes'; import { Button } from 'src/toolkit/chakra/button'; import { Link } from 'src/toolkit/chakra/link'; import { Hint } from 'src/toolkit/components/Hint/Hint'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; +import { shortenString } from 'src/toolkit/utils/texts'; import UserProfileContentWallet from '../common/UserProfileContentWallet'; import UserWalletAutoConnectAlert from '../UserWalletAutoConnectAlert'; @@ -111,7 +111,7 @@ const UserProfileContent = ({ data, onClose, onLogin, onAddEmail, onAddAddress } <Flex p={ 2 } columnGap={ 4 }> <Box mr="auto">Email</Box> { data?.email ? - <TruncatedText text={ data.email }/> : <Link onClick={ onAddEmail }>Add email</Link> } + <Truncate value={ data.email } type="end"/> : <Link onClick={ onAddEmail }>Add email</Link> } </Flex> </Box> diff --git a/src/features/account/components/user-profile/auth0/UserProfileDesktop.tsx b/src/features/account/components/user-profile/auth0/UserProfileDesktop.tsx index 80f3651d5ab..13bd862f1fb 100644 --- a/src/features/account/components/user-profile/auth0/UserProfileDesktop.tsx +++ b/src/features/account/components/user-profile/auth0/UserProfileDesktop.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { type ButtonProps } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { Screen } from 'src/features/account/components/auth-modal/types'; @@ -11,7 +10,8 @@ import useProfileQuery from 'src/features/account/hooks/useProfileQuery'; import useAccount from 'src/features/connect-wallet/hooks/useAccount'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; +import { useRouter } from 'src/shared/router/useRouter'; import { PopoverBody, PopoverContent, PopoverRoot, PopoverTrigger } from 'src/toolkit/chakra/popover'; import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; @@ -40,7 +40,7 @@ const UserProfileDesktop = ({ buttonSize, buttonVariant = 'header' }: Props) => const handleProfileButtonClick = React.useCallback(() => { if (profileQuery.data || web3Address) { - mixpanel.logEvent(mixpanel.EventTypes.ACCOUNT_ACCESS, { Action: 'Dropdown open' }); + analytics.logEvent(analytics.EventTypes.ACCOUNT_ACCESS, { Action: 'Dropdown open' }); profileMenu.onOpen(); return; } diff --git a/src/features/account/components/user-profile/auth0/UserProfileMobile.tsx b/src/features/account/components/user-profile/auth0/UserProfileMobile.tsx index 164d0af9941..8f71ee5e964 100644 --- a/src/features/account/components/user-profile/auth0/UserProfileMobile.tsx +++ b/src/features/account/components/user-profile/auth0/UserProfileMobile.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { Screen } from 'src/features/account/components/auth-modal/types'; @@ -10,7 +9,8 @@ import useProfileQuery from 'src/features/account/hooks/useProfileQuery'; import useAccount from 'src/features/connect-wallet/hooks/useAccount'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; +import { useRouter } from 'src/shared/router/useRouter'; import { DrawerBody, DrawerContent, DrawerRoot, DrawerTrigger } from 'src/toolkit/chakra/drawer'; import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; @@ -34,7 +34,7 @@ const UserProfileMobile = () => { const handleProfileButtonClick = React.useCallback(() => { if (profileQuery.data || web3Address) { - mixpanel.logEvent(mixpanel.EventTypes.ACCOUNT_ACCESS, { Action: 'Dropdown open' }); + analytics.logEvent(analytics.EventTypes.ACCOUNT_ACCESS, { Action: 'Dropdown open' }); profileMenu.onOpen(); return; } diff --git a/src/features/account/components/user-profile/dynamic/UserProfileButton.tsx b/src/features/account/components/user-profile/dynamic/UserProfileButton.tsx index ae8065707e4..4e3f96dca2d 100644 --- a/src/features/account/components/user-profile/dynamic/UserProfileButton.tsx +++ b/src/features/account/components/user-profile/dynamic/UserProfileButton.tsx @@ -7,10 +7,10 @@ import { getUserHandle } from 'src/features/account/utils/user-handle'; import useAccountWithDomain from 'src/features/connect-wallet/hooks/useAccountWithDomain'; import { useMarketplaceContext } from 'src/features/marketplace/context'; -import shortenString from 'src/shared/texts/shorten-string'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button, type ButtonProps } from 'src/toolkit/chakra/button'; +import { shortenString } from 'src/toolkit/utils/texts'; import UserIdenticon from '../UserIdenticon'; diff --git a/src/features/account/components/user-profile/wallet/UserWalletButton.tsx b/src/features/account/components/user-profile/wallet/UserWalletButton.tsx index a8d89cb25c4..40ddc3c8616 100644 --- a/src/features/account/components/user-profile/wallet/UserWalletButton.tsx +++ b/src/features/account/components/user-profile/wallet/UserWalletButton.tsx @@ -5,10 +5,10 @@ import { Box, HStack } from '@chakra-ui/react'; import React from 'react'; import useIsMobile from 'src/shared/hooks/useIsMobile'; -import shortenString from 'src/shared/texts/shorten-string'; import { Button } from 'src/toolkit/chakra/button'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { shortenString } from 'src/toolkit/utils/texts'; import UserIdenticon from '../UserIdenticon'; diff --git a/src/features/account/config.spec.ts b/src/features/account/config.spec.ts new file mode 100644 index 00000000000..590e436c756 --- /dev/null +++ b/src/features/account/config.spec.ts @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import type accountConfig from './config'; + +async function loadConfig(envs: Array<[ string, string ]>): Promise<typeof accountConfig> { + return withEnvs(envs, async() => { + // `src/config` has to be imported first: reaching it through `./config` instead enters the + // graph mid-cycle, and `src/shell/metadata/config` then reads `app.baseUrl` off an + // uninitialised module + await import('src/config'); + return (await import('./config')).default; + }); +} + +const HTML_AS_SET = `Don't miss <a href='https://example.com'>this</a>`; + +describe('account feature config', () => { + it('is disabled when the account is not supported', async() => { + expect((await loadConfig([ [ 'NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED', '' ] ])).isEnabled).toBe(false); + }); + + it('is disabled without a dynamic environment id or a reCaptcha site key', async() => { + expect((await loadConfig([ [ 'NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY', '' ] ])).isEnabled).toBe(false); + }); + + it('signs in through auth0 with the reCaptcha site key', async() => { + expect(await loadConfig([])).toMatchObject({ + isEnabled: true, + authProvider: 'auth0', + verifiedAddresses: { isEnabled: true }, + }); + }); + + it('signs in through dynamic with its environment id', async() => { + expect(await loadConfig([ + [ 'NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER', 'dynamic' ], + [ 'NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID', 'env-1' ], + ])).toMatchObject({ + isEnabled: true, + authProvider: 'dynamic', + dynamic: { environmentId: 'env-1' }, + }); + }); + + it('has no verified addresses without the admin service API', async() => { + expect(await loadConfig([ [ 'NEXT_PUBLIC_ADMIN_SERVICE_API_HOST', '' ] ])).toMatchObject({ + isEnabled: true, + verifiedAddresses: undefined, + }); + }); + + it('keeps the HTML values as set, apostrophes and single quotes included', async() => { + expect(await loadConfig([ + [ 'NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE', HTML_AS_SET ], + [ 'NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML', HTML_AS_SET ], + ])).toMatchObject({ + apiKeys: { alertMessage: HTML_AS_SET }, + verifiedAddresses: { expeditedReviewHtml: HTML_AS_SET }, + }); + }); + + it('shows the built-in API keys notice on chains with the Blockscout API unless the value is set empty', async() => { + const withNotice = await loadConfig([ [ 'NEXT_PUBLIC_PRO_API_SUPPORTED', 'true' ] ]); + expect(withNotice.isEnabled && withNotice.apiKeys.alertMessage).toContain('Deprecation Notice'); + + const optedOut = await loadConfig([ [ 'NEXT_PUBLIC_PRO_API_SUPPORTED', 'true' ], [ 'NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE', '' ] ]); + expect(optedOut.isEnabled && optedOut.apiKeys.alertMessage).toBe(''); + + const otherChain = await loadConfig([ [ 'NEXT_PUBLIC_PRO_API_SUPPORTED', '' ] ]); + expect(otherChain.isEnabled && otherChain.apiKeys.alertMessage).toBeUndefined(); + }); +}); diff --git a/src/features/account/config.ts b/src/features/account/config.ts index 794cfbc4332..0d60d39817a 100644 --- a/src/features/account/config.ts +++ b/src/features/account/config.ts @@ -10,18 +10,18 @@ import verifiedTokens from 'src/features/verified-tokens/config'; import app from 'src/config/app'; import * as services from 'src/config/services'; -import { getEnvValue } from 'src/config/utils/envs'; +import { getEnvHtmlValue, getEnvValue } from 'src/config/utils/envs'; import type { Feature } from 'src/config/utils/features'; const title = 'My account'; const API_KEYS_ALERT_MESSAGE_DEFAULT = '<b>Deprecation Notice:</b> Chain-specific API keys are deprecated.<br>' + - 'Please migrate to the <a href="https://dev.blockscout.com/?utm_source=blockscout_account" target="_blank">Blockscout PRO API</a> ' + + 'Please migrate to the <a href="https://dev.blockscout.com/?utm_source=blockscout_account" target="_blank">Blockscout API</a> ' + 'for multichain access.'; -// Chains served by the Pro API get the deprecation notice out of the box; an explicitly +// Chains served by the Blockscout API get the deprecation notice out of the box; an explicitly // empty value is how an instance opts out of it. -const apiKeysAlertMessage = getEnvValue('NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE') ?? +const apiKeysAlertMessage = getEnvHtmlValue('NEXT_PUBLIC_API_KEYS_ALERT_MESSAGE') ?? (chain.isProApiSupported ? API_KEYS_ALERT_MESSAGE_DEFAULT : undefined); const config: Feature<{ @@ -47,7 +47,7 @@ const config: Feature<{ const dynamicEnvironmentId = getEnvValue('NEXT_PUBLIC_ACCOUNT_DYNAMIC_ENVIRONMENT_ID'); const addressVerificationEnabled = !app.isPrivateMode && verifiedTokens.isEnabled && apis.admin !== undefined; - const expeditedReviewHtml = getEnvValue('NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML'); + const expeditedReviewHtml = getEnvHtmlValue('NEXT_PUBLIC_TOKEN_INFO_EXPEDITED_REVIEW_HTML'); const verifiedAddresses = addressVerificationEnabled ? { isEnabled: true, expeditedReviewHtml, diff --git a/src/features/account/hooks/useGetCsrfToken.tsx b/src/features/account/hooks/useGetCsrfToken.ts similarity index 100% rename from src/features/account/hooks/useGetCsrfToken.tsx rename to src/features/account/hooks/useGetCsrfToken.ts diff --git a/src/features/account/hooks/useLinkEmailDynamic.ts b/src/features/account/hooks/useLinkEmailDynamic.ts index 81765301ecb..bea5288f6d9 100644 --- a/src/features/account/hooks/useLinkEmailDynamic.ts +++ b/src/features/account/hooks/useLinkEmailDynamic.ts @@ -8,14 +8,14 @@ import type { UserInfo } from 'src/features/account/types/api'; import { getResourceKey } from 'src/api/hooks/useApiQuery'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; export default function useLinkEmailDynamic(): () => void { const { updateUserWithModal } = useUserUpdateRequest(); const queryClient = useQueryClient(); return React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.ACCOUNT_LINK_INFO, { + analytics.logEvent(analytics.EventTypes.ACCOUNT_LINK_INFO, { Status: 'Started', Type: 'Email', Source: 'Profile dropdown', @@ -24,7 +24,7 @@ export default function useLinkEmailDynamic(): () => void { queryClient.setQueryData(getResourceKey('core:user_info'), (prevData: UserInfo | undefined) => { return { ...prevData, email: fields.email }; }); - mixpanel.logEvent(mixpanel.EventTypes.ACCOUNT_LINK_INFO, { + analytics.logEvent(analytics.EventTypes.ACCOUNT_LINK_INFO, { Status: 'Finished', Type: 'Email', Source: 'Profile dropdown', diff --git a/src/features/account/hooks/useLogout.ts b/src/features/account/hooks/useLogout.ts index 86c0ca4e178..8a67bc1255d 100644 --- a/src/features/account/hooks/useLogout.ts +++ b/src/features/account/hooks/useLogout.ts @@ -1,8 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import useApiFetch from 'src/api/hooks/useApiFetch'; @@ -12,7 +10,9 @@ import useWalletReown from 'src/features/connect-wallet/hooks/wallet/useWalletRe import { useRewardsContext } from 'src/features/rewards/context'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; +import type { Route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import * as cookies from 'src/shared/storage/cookies'; import { toaster } from 'src/toolkit/chakra/toaster'; @@ -44,14 +44,14 @@ export default function useLogout() { rewardsLogout(); } - mixpanel.logEvent(mixpanel.EventTypes.ACCOUNT_ACCESS, { Action: 'Logged out' }, { send_immediately: true }); - mixpanel.reset(); + analytics.logEvent(analytics.EventTypes.ACCOUNT_ACCESS, { Action: 'Logged out' }, { sendImmediately: true }); + analytics.reset(); if ( PROTECTED_ROUTES.includes(router.pathname) || (router.pathname === '/txs' && router.query.tab === 'watchlist') ) { - await router.push({ pathname: '/' }, undefined, { shallow: true }); + await router.push({ pathname: '/' }, { shallow: true }); } queryClient.resetQueries({ diff --git a/src/features/account/hooks/useSignInWithWallet.ts b/src/features/account/hooks/useSignInWithWallet.ts index 5300a3d80da..26587488215 100644 --- a/src/features/account/hooks/useSignInWithWallet.ts +++ b/src/features/account/hooks/useSignInWithWallet.ts @@ -12,7 +12,7 @@ import useWalletReown from 'src/features/connect-wallet/hooks/wallet/useWalletRe import { getWeb3Runtime } from 'src/features/connect-wallet/utils/runtime'; import config from 'src/config'; -import type * as mixpanel from 'src/services/mixpanel'; +import type * as analytics from 'src/shared/analytics'; import getErrorMessage from 'src/shared/errors/get-error-message'; import getErrorObj from 'src/shared/errors/get-error-obj'; import getErrorObjPayload from 'src/shared/errors/get-error-obj-payload'; @@ -44,7 +44,7 @@ function composeMessage(address: string, nonceBlockscout: string, nonceRewards: interface Props { onSuccess?: ({ address, profile, rewardsToken }: { address: string; profile: UserInfo; rewardsToken?: string }) => void; onError?: () => void; - source?: mixpanel.EventPayload<mixpanel.EventTypes.WALLET_CONNECT>['Source']; + source?: analytics.EventPayload<analytics.EventTypes.WALLET_CONNECT>['Source']; isAuth?: boolean; loginToRewards?: boolean; fetchProtectedResource: <T>(fetcher: (token?: string) => Promise<T>, token?: string) => Promise<T>; diff --git a/src/features/account/pages/address/AddressFavoriteButton.tsx b/src/features/account/pages/address/AddressFavoriteButton.tsx index 20b650329b8..4c4afb3f277 100644 --- a/src/features/account/pages/address/AddressFavoriteButton.tsx +++ b/src/features/account/pages/address/AddressFavoriteButton.tsx @@ -2,7 +2,6 @@ import { chakra } from '@chakra-ui/react'; import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React from 'react'; import { getResourceKey } from 'src/api/hooks/useApiQuery'; @@ -13,8 +12,9 @@ import WatchlistAddModal from 'src/features/account/pages/watchlist/AddressModal import DeleteAddressModal from 'src/features/account/pages/watchlist/DeleteAddressModal'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import usePreventFocusAfterModalClosing from 'src/shared/hooks/usePreventFocusAfterModalClosing'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { IconButton } from 'src/toolkit/chakra/icon-button'; @@ -37,7 +37,7 @@ const AddressFavoriteButton = ({ className, hash, watchListId }: Props) => { const handleAddToFavorite = React.useCallback(() => { watchListId ? deleteModalProps.onOpen() : addModalProps.onOpen(); - !watchListId && mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { Type: 'Add to watchlist' }); + !watchListId && analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Add to watchlist' }); }, [ watchListId, deleteModalProps, addModalProps ]); const handleAddOrDeleteSuccess = React.useCallback(async() => { @@ -88,7 +88,7 @@ const AddressFavoriteButton = ({ className, hash, watchListId }: Props) => { hasEmail={ Boolean(profileQuery.data?.email) } showEmailAlert /> - { formData.id && ( + { formData.id !== undefined && ( <DeleteAddressModal { ...deleteModalProps } data={ formData } diff --git a/src/features/account/pages/api-keys/ApiKeyTable/ApiKeyListItem.tsx b/src/features/account/pages/api-keys/ApiKeyTable/ApiKeyListItem.tsx deleted file mode 100644 index a307e3f3a1d..00000000000 --- a/src/features/account/pages/api-keys/ApiKeyTable/ApiKeyListItem.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React, { useCallback } from 'react'; - -import type { ApiKey } from 'src/features/account/types/api'; - -import TableItemActionButtons from 'src/features/account/components/TableItemActionButtons'; -import ApiKeySnippet from 'src/features/account/pages/api-keys/ApiKeySnippet'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -interface Props { - item: ApiKey; - isLoading?: boolean; - onEditClick: (item: ApiKey) => void; - onDeleteClick: (item: ApiKey) => void; -} - -const ApiKeyListItem = ({ item, isLoading, onEditClick, onDeleteClick }: Props) => { - - const onItemEditClick = useCallback(() => { - return onEditClick(item); - }, [ item, onEditClick ]); - - const onItemDeleteClick = useCallback(() => { - return onDeleteClick(item); - }, [ item, onDeleteClick ]); - - return ( - <ListItemMobile> - <ApiKeySnippet apiKey={ item.api_key } name={ item.name } isLoading={ isLoading }/> - <TableItemActionButtons onDeleteClick={ onItemDeleteClick } onEditClick={ onItemEditClick } isLoading={ isLoading }/> - </ListItemMobile> - ); -}; - -export default ApiKeyListItem; diff --git a/src/features/account/pages/api-keys/ApiKeyTable/ApiKeyTable.tsx b/src/features/account/pages/api-keys/ApiKeyTable/ApiKeyTable.tsx index 7d240acac5c..40f504e55d8 100644 --- a/src/features/account/pages/api-keys/ApiKeyTable/ApiKeyTable.tsx +++ b/src/features/account/pages/api-keys/ApiKeyTable/ApiKeyTable.tsx @@ -4,6 +4,8 @@ import React from 'react'; import type { ApiKeys, ApiKey } from 'src/features/account/types/api'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; + import { TableBody, TableColumnHeader, TableHeader, TableRoot, TableRow } from 'src/toolkit/chakra/table'; import ApiKeyTableItem from './ApiKeyTableItem'; @@ -16,7 +18,11 @@ interface Props { limit: number; } +const getBaseKey = (item: ApiKey): string => item.api_key; + const ApiKeyTable = ({ data, isLoading, onDeleteClick, onEditClick, limit }: Props) => { + const keys = useUniqueKeys(data, getBaseKey); + return ( <TableRoot minWidth="600px"> <TableHeader> @@ -28,7 +34,7 @@ const ApiKeyTable = ({ data, isLoading, onDeleteClick, onEditClick, limit }: Pro <TableBody> { data?.map((item, index) => ( <ApiKeyTableItem - key={ item.api_key + (isLoading ? index : '') } + key={ keys[index] } item={ item } isLoading={ isLoading } onDeleteClick={ onDeleteClick } diff --git a/src/features/account/pages/api-keys/ApiKeys.tsx b/src/features/account/pages/api-keys/ApiKeys.tsx index bb732be36bc..8a78fea1202 100644 --- a/src/features/account/pages/api-keys/ApiKeys.tsx +++ b/src/features/account/pages/api-keys/ApiKeys.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Text } from '@chakra-ui/react'; import React, { useCallback, useState } from 'react'; import type { ApiKey } from 'src/features/account/types/api'; @@ -15,23 +15,25 @@ import { API_KEY } from 'src/features/account/stubs'; import config from 'src/config'; import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; +import { sanitizeHtml } from 'src/shared/texts/sanitize-html'; import { Alert } from 'src/toolkit/chakra/alert'; import { BoxHtml } from 'src/toolkit/chakra/box'; import { Button } from 'src/toolkit/chakra/button'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; import { space } from 'src/toolkit/utils/htmlEntities'; import ApiKeyModal from './ApiKeyModal/ApiKeyModal'; -import ApiKeyListItem from './ApiKeyTable/ApiKeyListItem'; import ApiKeyTable from './ApiKeyTable/ApiKeyTable'; import DeleteApiKeyModal from './DeleteApiKeyModal'; const DATA_LIMIT = 3; const feature = config.features.account; +const alertHtml = feature.isEnabled ? sanitizeHtml(feature.apiKeys.alertMessage || '') : ''; const ApiKeysPage: React.FC = () => { const apiKeyModalProps = useDisclosure(); @@ -69,8 +71,7 @@ const ApiKeysPage: React.FC = () => { const description = config.chain.isProApiSupported ? ( <AccountPageDescription> - Blockscout APIs require a key. Create a <Link href="https://dev.blockscout.com" external noIcon> - free PRO API key</Link> to access all multichain endpoints. + Create a <Link href="https://dev.blockscout.com" external noIcon>free Blockscout API key</Link> to access all multichain endpoints. </AccountPageDescription> ) : ( <AccountPageDescription> @@ -85,35 +86,22 @@ const ApiKeysPage: React.FC = () => { } const list = ( - <> - <Box display={{ base: 'block', lg: 'none' }}> - { data?.map((item, index) => ( - <ApiKeyListItem - key={ item.api_key + (isPlaceholderData ? index : '') } - item={ item } - isLoading={ isPlaceholderData } - onDeleteClick={ onDeleteClick } - onEditClick={ onEditClick } - /> - )) } - </Box> - <Box display={{ base: 'none', lg: 'block' }}> - <ApiKeyTable - data={ data } - isLoading={ isPlaceholderData } - onDeleteClick={ onDeleteClick } - onEditClick={ onEditClick } - limit={ DATA_LIMIT } - /> - </Box> - </> + <TableContainerScrollable> + <ApiKeyTable + data={ data } + isLoading={ isPlaceholderData } + onDeleteClick={ onDeleteClick } + onEditClick={ onEditClick } + limit={ DATA_LIMIT } + /> + </TableContainerScrollable> ); const canAdd = !isPlaceholderData ? (data?.length || 0) < DATA_LIMIT : true; - const alert = feature.isEnabled && feature.apiKeys.alertMessage ? ( + const alert = alertHtml ? ( <Alert status="warning" mb={ 6 }> - <BoxHtml html={ feature.apiKeys.alertMessage }/> + <BoxHtml html={ alertHtml }/> </Alert> ) : null; diff --git a/src/features/account/pages/custom-abi/CustomAbi.tsx b/src/features/account/pages/custom-abi/CustomAbi.tsx index 7b19ab3763f..a8120226dce 100644 --- a/src/features/account/pages/custom-abi/CustomAbi.tsx +++ b/src/features/account/pages/custom-abi/CustomAbi.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React, { useCallback, useState } from 'react'; import type { CustomAbi } from 'src/features/account/types/api'; @@ -17,10 +16,10 @@ import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; import { Button } from 'src/toolkit/chakra/button'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; import CustomAbiModal from './CustomAbiModal/CustomAbiModal'; -import CustomAbiListItem from './CustomAbiTable/CustomAbiListItem'; import CustomAbiTable from './CustomAbiTable/CustomAbiTable'; import DeleteCustomAbiModal from './DeleteCustomAbiModal'; @@ -70,27 +69,14 @@ const CustomAbiPage: React.FC = () => { } const list = ( - <> - <Box display={{ base: 'block', lg: 'none' }}> - { data?.map((item, index) => ( - <CustomAbiListItem - key={ item.id + (isPlaceholderData ? String(index) : '') } - item={ item } - isLoading={ isPlaceholderData } - onDeleteClick={ onDeleteClick } - onEditClick={ onEditClick } - /> - )) } - </Box> - <Box display={{ base: 'none', lg: 'block' }}> - <CustomAbiTable - data={ data } - isLoading={ isPlaceholderData } - onDeleteClick={ onDeleteClick } - onEditClick={ onEditClick } - /> - </Box> - </> + <TableContainerScrollable> + <CustomAbiTable + data={ data } + isLoading={ isPlaceholderData } + onDeleteClick={ onDeleteClick } + onEditClick={ onEditClick } + /> + </TableContainerScrollable> ); return ( diff --git a/src/features/account/pages/custom-abi/CustomAbiTable/CustomAbiListItem.tsx b/src/features/account/pages/custom-abi/CustomAbiTable/CustomAbiListItem.tsx deleted file mode 100644 index 1edaf0c03f5..00000000000 --- a/src/features/account/pages/custom-abi/CustomAbiTable/CustomAbiListItem.tsx +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React, { useCallback } from 'react'; - -import type { CustomAbi } from 'src/features/account/types/api'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import TableItemActionButtons from 'src/features/account/components/TableItemActionButtons'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - item: CustomAbi; - isLoading?: boolean; - onEditClick: (item: CustomAbi) => void; - onDeleteClick: (item: CustomAbi) => void; -} - -const CustomAbiListItem = ({ item, isLoading, onEditClick, onDeleteClick }: Props) => { - - const onItemEditClick = useCallback(() => { - return onEditClick(item); - }, [ item, onEditClick ]); - - const onItemDeleteClick = useCallback(() => { - return onDeleteClick(item); - }, [ item, onDeleteClick ]); - - return ( - <ListItemMobile> - <Box maxW="100%"> - <AddressEntity - address={ item.contract_address } - fontWeight="600" - isLoading={ isLoading } - /> - <Skeleton textStyle="sm" color="text.secondary" mt={ 0.5 } ml={ 8 } display="inline-block" loading={ isLoading }> - <span>{ item.name }</span> - </Skeleton> - </Box> - <TableItemActionButtons onDeleteClick={ onItemDeleteClick } onEditClick={ onItemEditClick } isLoading={ isLoading }/> - </ListItemMobile> - ); -}; - -export default React.memo(CustomAbiListItem); diff --git a/src/features/account/pages/home/LatestWatchlistTxs.tsx b/src/features/account/pages/home/LatestWatchlistTxs.tsx index 945b5fd3c3c..8a76bba5c02 100644 --- a/src/features/account/pages/home/LatestWatchlistTxs.tsx +++ b/src/features/account/pages/home/LatestWatchlistTxs.tsx @@ -1,26 +1,24 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; import LatestTxsFallback from 'src/slices/home/pages/index/txs/LatestTxsFallback'; -import LatestTxsItem from 'src/slices/home/pages/index/txs/LatestTxsItem'; -import LatestTxsItemMobile from 'src/slices/home/pages/index/txs/LatestTxsItemMobile'; +import LatestTxsItem, { LATEST_TXS_TABLE_MIN_WIDTH } from 'src/slices/home/pages/index/txs/LatestTxsItem'; import { TX } from 'src/slices/tx/stubs/tx'; import useRedirectForInvalidAuthToken from 'src/features/account/hooks/useRedirectForInvalidAuthToken'; -import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; +import { TableBody, TableContainerScrollable, TableRoot } from 'src/toolkit/chakra/table'; const LatestWatchlistTxs = () => { useRedirectForInvalidAuthToken(); - const isMobile = useIsMobile(); - const txsCount = isMobile ? 2 : 5; + const txsCount = 5; const { data, isPlaceholderData, isError } = useApiQuery('core:homepage_txs_watchlist', { queryOptions: { placeholderData: Array(txsCount).fill(TX), @@ -39,23 +37,20 @@ const LatestWatchlistTxs = () => { const txsUrl = route({ pathname: '/txs', query: { tab: 'watchlist' } }); return ( <> - <Box mb={ 3 } display={{ base: 'block', lg: 'none' }} textStyle="sm"> - { data.slice(0, txsCount).map(((tx, index) => ( - <LatestTxsItemMobile - key={ tx.hash + (isPlaceholderData ? index : '') } - tx={ tx } - isLoading={ isPlaceholderData } - /> - ))) } - </Box> - <Box mb={ 4 } display={{ base: 'none', lg: 'block' }} textStyle="sm"> - { data.slice(0, txsCount).map(((tx, index) => ( - <LatestTxsItem - key={ tx.hash + (isPlaceholderData ? index : '') } - tx={ tx } - isLoading={ isPlaceholderData } - /> - ))) } + <Box mb={ 4 } textStyle="sm"> + <TableContainerScrollable> + <TableRoot minW={ LATEST_TXS_TABLE_MIN_WIDTH }> + <TableBody> + { data.slice(0, txsCount).map(((tx, index) => ( + <LatestTxsItem + key={ tx.hash + (isPlaceholderData ? index : '') } + tx={ tx } + isLoading={ isPlaceholderData } + /> + ))) } + </TableBody> + </TableRoot> + </TableContainerScrollable> </Box> <Flex justifyContent="center"> <Link textStyle="sm" href={ txsUrl }>View all watch list transactions</Link> diff --git a/src/features/account/pages/login/Login.tsx b/src/features/account/pages/login/Login.tsx index 923b5885efa..26817b0090c 100644 --- a/src/features/account/pages/login/Login.tsx +++ b/src/features/account/pages/login/Login.tsx @@ -8,8 +8,8 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import config from 'src/config'; import useFeatureValue from 'src/services/growthbook/useFeatureValue'; -import { track } from 'src/services/mixpanel/queue'; import { useRollbar } from 'src/services/rollbar'; +import * as analytics from 'src/shared/analytics'; import useGradualIncrement from 'src/shared/numbers/useGradualIncrement'; import * as cookies from 'src/shared/storage/cookies'; @@ -36,8 +36,8 @@ const Login = () => { rollbar?.error('Test error', { payload: 'foo' }); }, [ rollbar ]); - const checkMixpanel = React.useCallback(() => { - track('Test event', { my_prop: 'foo bar' }); + const checkAnalytics = React.useCallback(() => { + analytics.logEvent(analytics.EventTypes.BUTTON_CLICK, { Content: 'Check analytics', Source: 'Login page' }); }, []); const handleTokenChange = React.useCallback((event: ChangeEvent<HTMLTextAreaElement>) => { @@ -85,7 +85,7 @@ const Login = () => { ) } <Flex columnGap={ 2 }> <Button colorScheme="red" onClick={ checkRollbar }>Check Rollbar</Button> - <Button colorScheme="teal" onClick={ checkMixpanel }>Check Mixpanel</Button> + <Button colorScheme="teal" onClick={ checkAnalytics }>Check analytics</Button> </Flex> <Flex columnGap={ 2 } alignItems="center"> <Box w="50px" textAlign="center">{ num }</Box> diff --git a/src/features/account/pages/private-tags/AddressModal/AddressModal.tsx b/src/features/account/pages/private-tags/AddressModal/AddressModal.tsx index 17cfb919c22..81ef14d5eea 100644 --- a/src/features/account/pages/private-tags/AddressModal/AddressModal.tsx +++ b/src/features/account/pages/private-tags/AddressModal/AddressModal.tsx @@ -4,7 +4,7 @@ import React, { useCallback, useState } from 'react'; import type { AddressTag } from 'src/features/account/types/api'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import FormModal from 'src/shared/forms/FormModal'; import AddressForm from './AddressForm'; @@ -24,16 +24,16 @@ const AddressModal: React.FC<Props> = ({ open, onOpenChange, onSuccess, data, pa const [ isAlertVisible, setAlertVisible ] = useState(false); React.useEffect(() => { - open && !data?.id && mixpanel.logEvent( - mixpanel.EventTypes.PRIVATE_TAG, + open && !data?.id && analytics.logEvent( + analytics.EventTypes.PRIVATE_TAG, { Action: 'Form opened', 'Page type': pageType, 'Tag type': 'Address' }, ); }, [ data?.id, open, pageType ]); const handleSuccess = React.useCallback(() => { if (!data?.id) { - mixpanel.logEvent( - mixpanel.EventTypes.PRIVATE_TAG, + analytics.logEvent( + analytics.EventTypes.PRIVATE_TAG, { Action: 'Submit', 'Page type': pageType, 'Tag type': 'Address' }, ); } diff --git a/src/features/account/pages/private-tags/AddressTagTable/AddressTagListItem.tsx b/src/features/account/pages/private-tags/AddressTagTable/AddressTagListItem.tsx deleted file mode 100644 index a9bfa91d010..00000000000 --- a/src/features/account/pages/private-tags/AddressTagTable/AddressTagListItem.tsx +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, HStack, Text } from '@chakra-ui/react'; -import React, { useCallback } from 'react'; - -import type { AddressTag } from 'src/features/account/types/api'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import TableItemActionButtons from 'src/features/account/components/TableItemActionButtons'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Tag } from 'src/toolkit/chakra/tag'; - -interface Props { - item: AddressTag; - onEditClick: (data: AddressTag) => void; - onDeleteClick: (data: AddressTag) => void; - isLoading?: boolean; -} - -const AddressTagListItem = ({ item, onEditClick, onDeleteClick, isLoading }: Props) => { - const onItemEditClick = useCallback(() => { - return onEditClick(item); - }, [ item, onEditClick ]); - - const onItemDeleteClick = useCallback(() => { - return onDeleteClick(item); - }, [ item, onDeleteClick ]); - - return ( - <ListItemMobile> - <Flex alignItems="flex-start" flexDirection="column" maxW="100%"> - <AddressEntity - address={ item.address } - isLoading={ isLoading } - fontWeight="600" - w="100%" - /> - <HStack gap={ 3 } mt={ 4 }> - <Text textStyle="sm" fontWeight="medium">Private tag</Text> - <Skeleton loading={ isLoading } display="inline-block" borderRadius="sm"> - <Tag> - { item.name } - </Tag> - </Skeleton> - </HStack> - </Flex> - <TableItemActionButtons onDeleteClick={ onItemDeleteClick } onEditClick={ onItemEditClick } isLoading={ isLoading }/> - </ListItemMobile> - ); -}; - -export default React.memo(AddressTagListItem); diff --git a/src/features/account/pages/private-tags/PrivateAddressTags.tsx b/src/features/account/pages/private-tags/PrivateAddressTags.tsx index 3bde7b17c42..a5e1ad2e842 100644 --- a/src/features/account/pages/private-tags/PrivateAddressTags.tsx +++ b/src/features/account/pages/private-tags/PrivateAddressTags.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React, { useCallback, useState } from 'react'; import type { AddressTag } from 'src/features/account/types/api'; @@ -10,22 +9,22 @@ import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ import AccountPageDescription from 'src/features/account/components/AccountPageDescription'; import { PRIVATE_TAG_ADDRESS } from 'src/features/account/stubs'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { Button } from 'src/toolkit/chakra/button'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; import AddressModal from './AddressModal/AddressModal'; -import AddressTagListItem from './AddressTagTable/AddressTagListItem'; import AddressTagTable from './AddressTagTable/AddressTagTable'; import DeletePrivateTagModal from './DeletePrivateTagModal'; const PrivateAddressTags = () => { - const { data: addressTagsData, isError, isPlaceholderData, refetch, pagination } = useQueryWithPages({ + const { data: addressTagsData, isError, isInitialLoading, isTransitioning, refetch, pagination } = useApiPaginatedQuery({ resourceName: 'core:private_tags_address', options: { refetchOnMount: false, @@ -80,29 +79,19 @@ const PrivateAddressTags = () => { itemsNum={ addressTagsData?.items.length } emptyText="" actionBar={ actionBar } + isTransitioning={ isTransitioning } > - <Box display={{ base: 'block', lg: 'none' }}> - { addressTagsData?.items.map((item: AddressTag, index: number) => ( - <AddressTagListItem - item={ item } - key={ item.id + (isPlaceholderData ? String(index) : '') } - onDeleteClick={ onDeleteClick } - onEditClick={ onEditClick } - isLoading={ isPlaceholderData } - /> - )) } - </Box> - <Box display={{ base: 'none', lg: 'block' }}> + <TableContainerScrollable> <AddressTagTable - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } data={ addressTagsData?.items } onDeleteClick={ onDeleteClick } onEditClick={ onEditClick } top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } /> - </Box> + </TableContainerScrollable> </DataList> - <Skeleton mt={ 8 } loading={ isPlaceholderData } display="inline-block"> + <Skeleton mt={ 8 } loading={ isInitialLoading } display="inline-block"> <Button onClick={ addressModalProps.onOpen } > @@ -112,7 +101,7 @@ const PrivateAddressTags = () => { <AddressModal { ...addressModalProps } data={ addressModalData } - pageType={ mixpanel.getPageType('/account/tag-address') } + pageType={ analytics.getPageType('/account/tag-address') } onOpenChange={ onAddressModalOpenChange } onSuccess={ onAddOrEditSuccess } /> diff --git a/src/features/account/pages/private-tags/PrivateTransactionTags.tsx b/src/features/account/pages/private-tags/PrivateTransactionTags.tsx index 01776d1fc3f..430424898d6 100644 --- a/src/features/account/pages/private-tags/PrivateTransactionTags.tsx +++ b/src/features/account/pages/private-tags/PrivateTransactionTags.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React, { useCallback, useState } from 'react'; import type { TransactionTag } from 'src/features/account/types/api'; @@ -12,19 +11,19 @@ import { PRIVATE_TAG_TX } from 'src/features/account/stubs'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { Button } from 'src/toolkit/chakra/button'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; import DeletePrivateTagModal from './DeletePrivateTagModal'; import TransactionModal from './TransactionModal/TransactionModal'; -import TransactionTagListItem from './TransactionTagTable/TransactionTagListItem'; import TransactionTagTable from './TransactionTagTable/TransactionTagTable'; const PrivateTransactionTags = () => { - const { data: transactionTagsData, isPlaceholderData, isError, pagination } = useQueryWithPages({ + const { data: transactionTagsData, isInitialLoading, isTransitioning, isError, pagination } = useApiPaginatedQuery({ resourceName: 'core:private_tags_tx', options: { refetchOnMount: false, @@ -79,29 +78,19 @@ const PrivateTransactionTags = () => { itemsNum={ transactionTagsData?.items.length } emptyText="" actionBar={ actionBar } + isTransitioning={ isTransitioning } > - <Box display={{ base: 'block', lg: 'none' }}> - { transactionTagsData?.items.map((item, index) => ( - <TransactionTagListItem - key={ item.id + (isPlaceholderData ? String(index) : '') } - item={ item } - isLoading={ isPlaceholderData } - onDeleteClick={ onDeleteClick } - onEditClick={ onEditClick } - /> - )) } - </Box> - <Box display={{ base: 'none', lg: 'block' }}> + <TableContainerScrollable> <TransactionTagTable data={ transactionTagsData?.items } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } onDeleteClick={ onDeleteClick } onEditClick={ onEditClick } top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } /> - </Box> + </TableContainerScrollable> </DataList> - <Skeleton mt={ 8 } loading={ isPlaceholderData } display="inline-block"> + <Skeleton mt={ 8 } loading={ isInitialLoading } display="inline-block"> <Button onClick={ transactionModalProps.onOpen } > diff --git a/src/features/account/pages/private-tags/TransactionModal/TransactionModal.tsx b/src/features/account/pages/private-tags/TransactionModal/TransactionModal.tsx index 424f1b7c1b2..fce66faf267 100644 --- a/src/features/account/pages/private-tags/TransactionModal/TransactionModal.tsx +++ b/src/features/account/pages/private-tags/TransactionModal/TransactionModal.tsx @@ -4,7 +4,7 @@ import React, { useCallback, useState } from 'react'; import type { TransactionTag } from 'src/features/account/types/api'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import FormModal from 'src/shared/forms/FormModal'; import TransactionForm from './TransactionForm'; @@ -23,18 +23,18 @@ const TransactionModal: React.FC<Props> = ({ open, onOpenChange, onSuccess, data const [ isAlertVisible, setAlertVisible ] = useState(false); React.useEffect(() => { - open && !data?.id && mixpanel.logEvent( - mixpanel.EventTypes.PRIVATE_TAG, - { Action: 'Form opened', 'Page type': mixpanel.getPageType('/account/tag-address'), 'Tag type': 'Tx' }, + open && !data?.id && analytics.logEvent( + analytics.EventTypes.PRIVATE_TAG, + { Action: 'Form opened', 'Page type': analytics.getPageType('/account/tag-address'), 'Tag type': 'Tx' }, ); }, [ data?.id, open ]); const handleSuccess = React.useCallback(async() => { onSuccess?.(); if (!data?.id) { - mixpanel.logEvent( - mixpanel.EventTypes.PRIVATE_TAG, - { Action: 'Submit', 'Page type': mixpanel.getPageType('/account/tag-address'), 'Tag type': 'Tx' }, + analytics.logEvent( + analytics.EventTypes.PRIVATE_TAG, + { Action: 'Submit', 'Page type': analytics.getPageType('/account/tag-address'), 'Tag type': 'Tx' }, ); } }, [ data?.id, onSuccess ]); diff --git a/src/features/account/pages/private-tags/TransactionTagTable/TransactionTagListItem.tsx b/src/features/account/pages/private-tags/TransactionTagTable/TransactionTagListItem.tsx deleted file mode 100644 index 923c4831a00..00000000000 --- a/src/features/account/pages/private-tags/TransactionTagTable/TransactionTagListItem.tsx +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { HStack, Text, Flex } from '@chakra-ui/react'; -import React, { useCallback } from 'react'; - -import type { TransactionTag } from 'src/features/account/types/api'; - -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import TableItemActionButtons from 'src/features/account/components/TableItemActionButtons'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Tag } from 'src/toolkit/chakra/tag'; - -interface Props { - item: TransactionTag; - isLoading?: boolean; - onEditClick: (data: TransactionTag) => void; - onDeleteClick: (data: TransactionTag) => void; -} - -const TransactionTagListItem = ({ item, isLoading, onEditClick, onDeleteClick }: Props) => { - const onItemEditClick = useCallback(() => { - return onEditClick(item); - }, [ item, onEditClick ]); - - const onItemDeleteClick = useCallback(() => { - return onDeleteClick(item); - }, [ item, onDeleteClick ]); - - return ( - <ListItemMobile> - <Flex alignItems="flex-start" flexDirection="column" maxW="100%"> - <TxEntity - hash={ item.transaction_hash } - isLoading={ isLoading } - fontWeight={ 600 } - maxW="100%" - /> - <HStack gap={ 3 } mt={ 4 }> - <Text textStyle="sm" fontWeight={ 500 }>Private tag</Text> - <Tag loading={ isLoading } truncated>{ item.name }</Tag> - </HStack> - </Flex> - <TableItemActionButtons onDeleteClick={ onItemDeleteClick } onEditClick={ onItemEditClick } isLoading={ isLoading }/> - </ListItemMobile> - ); -}; - -export default React.memo(TransactionTagListItem); diff --git a/src/features/account/pages/profile/MyProfile.tsx b/src/features/account/pages/profile/MyProfile.tsx index bacf3ae822f..6935db90644 100644 --- a/src/features/account/pages/profile/MyProfile.tsx +++ b/src/features/account/pages/profile/MyProfile.tsx @@ -21,7 +21,7 @@ import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; import MyProfileEmail from './MyProfileEmail'; import MyProfileWallet from './MyProfileWallet'; -const MIXPANEL_CONFIG = { +const ANALYTICS_CONFIG = { wallet_connect: { source: 'Profile' as const, }, @@ -63,7 +63,7 @@ const MyProfile = () => { <MyProfileWallet profileQuery={ profileQuery } onAddWallet={ handleAddWalletClick }/> } </Flex> { authModal.open && authInitialScreen && - <AuthModal initialScreen={ authInitialScreen } onClose={ authModal.onClose } mixpanelConfig={ MIXPANEL_CONFIG }/> } + <AuthModal initialScreen={ authInitialScreen } onClose={ authModal.onClose } analyticsConfig={ ANALYTICS_CONFIG }/> } </> ); })(); diff --git a/src/features/account/pages/profile/MyProfileEmail.tsx b/src/features/account/pages/profile/MyProfileEmail.tsx index f7caf211470..ac26c6ab399 100644 --- a/src/features/account/pages/profile/MyProfileEmail.tsx +++ b/src/features/account/pages/profile/MyProfileEmail.tsx @@ -14,9 +14,9 @@ import useApiFetch from 'src/api/hooks/useApiFetch'; import AuthModal from 'src/features/account/components/auth-modal/AuthModal'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; import ReCaptcha from 'src/services/re-captcha/ReCaptcha'; import useReCaptcha from 'src/services/re-captcha/useReCaptcha'; +import * as analytics from 'src/shared/analytics'; import getErrorMessage from 'src/shared/errors/get-error-message'; import getErrorObjPayload from 'src/shared/errors/get-error-obj-payload'; @@ -28,7 +28,7 @@ import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; import MyProfileFieldsEmail from './fields/MyProfileFieldsEmail'; -const MIXPANEL_CONFIG = { +const ANALYTICS_CONFIG = { account_link_info: { source: 'Profile' as const, }, @@ -66,7 +66,7 @@ const MyProfileEmail = ({ profileQuery }: Props) => { const onFormSubmit: SubmitHandler<FormFields> = React.useCallback(async(formData) => { try { await recaptcha.fetchProtectedResource(authFetchFactory(formData.email)); - mixpanel.logEvent(mixpanel.EventTypes.ACCOUNT_LINK_INFO, { + analytics.logEvent(analytics.EventTypes.ACCOUNT_LINK_INFO, { Source: 'Profile', Status: 'OTP sent', Type: 'Email', @@ -116,7 +116,7 @@ const MyProfileEmail = ({ profileQuery }: Props) => { <AuthModal initialScreen={{ type: 'otp_code', isAuth: true, email: formApi.getValues('email') }} onClose={ authModal.onClose } - mixpanelConfig={ MIXPANEL_CONFIG } + analyticsConfig={ ANALYTICS_CONFIG } /> ) } </section> diff --git a/src/features/account/pages/profile/__screenshots__/MyProfile.pw.tsx_default_without-address-1.png b/src/features/account/pages/profile/__screenshots__/MyProfile.pw.tsx_default_without-address-1.png index 34fca2b4215..49871c1dcba 100644 Binary files a/src/features/account/pages/profile/__screenshots__/MyProfile.pw.tsx_default_without-address-1.png and b/src/features/account/pages/profile/__screenshots__/MyProfile.pw.tsx_default_without-address-1.png differ diff --git a/src/features/account/pages/profile/__screenshots__/MyProfile.pw.tsx_default_without-email-1.png b/src/features/account/pages/profile/__screenshots__/MyProfile.pw.tsx_default_without-email-1.png index e2d4b08634d..0024fea2503 100644 Binary files a/src/features/account/pages/profile/__screenshots__/MyProfile.pw.tsx_default_without-email-1.png and b/src/features/account/pages/profile/__screenshots__/MyProfile.pw.tsx_default_without-email-1.png differ diff --git a/src/features/account/pages/tx-index-watchlist/TxsWatchlist.tsx b/src/features/account/pages/tx-index-watchlist/TxsWatchlist.tsx index 09848a21750..29ce2b35346 100644 --- a/src/features/account/pages/tx-index-watchlist/TxsWatchlist.tsx +++ b/src/features/account/pages/tx-index-watchlist/TxsWatchlist.tsx @@ -6,10 +6,10 @@ import TxsWithFrontendSorting from 'src/slices/tx/pages/index/list/TxsWithFronte import useRedirectForInvalidAuthToken from 'src/features/account/hooks/useRedirectForInvalidAuthToken'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; type Props = { - query: QueryWithPagesResult<'core:txs_watchlist'>; + query: ApiPaginatedQueryResult<'core:txs_watchlist'>; top?: number; }; diff --git a/src/features/account/pages/verified-addresses/VerifiedAddresses.pw.tsx b/src/features/account/pages/verified-addresses/VerifiedAddresses.pw.tsx index ce2e53da077..4432857b034 100644 --- a/src/features/account/pages/verified-addresses/VerifiedAddresses.pw.tsx +++ b/src/features/account/pages/verified-addresses/VerifiedAddresses.pw.tsx @@ -17,7 +17,7 @@ test.beforeEach(async({ mockAssetResponse }) => { await mockAssetResponse(mocks.TOKEN_INFO_APPLICATION_BASE.iconUrl, './playwright/mocks/image_s.jpg'); }); -test('base view +@mobile', async({ render, mockApiResponse }) => { +test('base view', async({ render, mockApiResponse }) => { await mockApiResponse('contractInfo:verified_addresses', mocks.VERIFIED_ADDRESS_RESPONSE.DEFAULT, { pathParams: { instanceId: '1' } }); await mockApiResponse('admin:token_info_applications', mocks.TOKEN_INFO_APPLICATIONS_RESPONSE.DEFAULT, { pathParams: { instanceId: '1', id: undefined } }); await mockApiResponse('core:user_info', profileMock.base); diff --git a/src/features/account/pages/verified-addresses/VerifiedAddresses.tsx b/src/features/account/pages/verified-addresses/VerifiedAddresses.tsx index fdb54762cec..6432d34bc78 100644 --- a/src/features/account/pages/verified-addresses/VerifiedAddresses.tsx +++ b/src/features/account/pages/verified-addresses/VerifiedAddresses.tsx @@ -1,8 +1,7 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { List, chakra, Box } from '@chakra-ui/react'; +import { List, chakra } from '@chakra-ui/react'; import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React from 'react'; import type * as adminRs from '@blockscout/admin-rs-types'; @@ -17,19 +16,20 @@ import useProfileQuery from 'src/features/account/hooks/useProfileQuery'; import useRedirectForInvalidAuthToken from 'src/features/account/hooks/useRedirectForInvalidAuthToken'; import AddressVerificationModal from 'src/features/account/pages/verified-addresses/address-verification/AddressVerificationModal'; import VerifiedAddressesEmailAlert from 'src/features/account/pages/verified-addresses/index/VerifiedAddressesEmailAlert'; -import VerifiedAddressesListItem from 'src/features/account/pages/verified-addresses/index/VerifiedAddressesListItem'; import VerifiedAddressesTable from 'src/features/account/pages/verified-addresses/index/VerifiedAddressesTable'; import TokenInfoForm from 'src/features/account/pages/verified-addresses/token-info/TokenInfoForm'; import { TOKEN_INFO_APPLICATION, VERIFIED_ADDRESS } from 'src/features/account/stubs'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import DataList from 'src/shared/lists/DataList'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { collator } from 'src/shared/texts/collator'; import { Button } from 'src/toolkit/chakra/button'; import { Link } from 'src/toolkit/chakra/link'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { BackToButton } from 'src/toolkit/components/buttons/BackToButton'; import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; @@ -161,32 +161,15 @@ const VerifiedAddresses = () => { if (addressesQuery.data?.verifiedAddresses) { return ( - <> - <Box hideFrom="lg" key="content-mobile"> - { addressesQuery.data.verifiedAddresses.map((item, index) => ( - <VerifiedAddressesListItem - key={ item.contractAddress + (isLoading ? index : '') } - item={ item } - application={ - applicationsQuery.data?.submissions - ?.find(({ tokenAddress }) => tokenAddress.toLowerCase() === item.contractAddress.toLowerCase()) - } - onAdd={ handleItemAdd } - onEdit={ handleItemEdit } - isLoading={ isLoading } - /> - )) } - </Box> - <Box hideBelow="lg" key="content-desktop"> - <VerifiedAddressesTable - data={ addressesQuery.data.verifiedAddresses } - applications={ applicationsQuery.data?.submissions } - onItemEdit={ handleItemEdit } - onItemAdd={ handleItemAdd } - isLoading={ isLoading } - /> - </Box> - </> + <TableContainerScrollable> + <VerifiedAddressesTable + data={ addressesQuery.data.verifiedAddresses } + applications={ applicationsQuery.data?.submissions } + onItemEdit={ handleItemEdit } + onItemAdd={ handleItemAdd } + isLoading={ isLoading } + /> + </TableContainerScrollable> ); } @@ -229,7 +212,7 @@ const VerifiedAddresses = () => { </DataList> { addButton } <AddressVerificationModal - pageType={ mixpanel.getPageType('/account/verified-addresses') } + pageType={ analytics.getPageType('/account/verified-addresses') } open={ modalProps.open } onOpenChange={ modalProps.onOpenChange } onSubmit={ handleAddressSubmit } diff --git a/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_default_address-verification-flow-1.png b/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_default_address-verification-flow-1.png index 7f0e77a6ec2..59cef2b7c7c 100644 Binary files a/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_default_address-verification-flow-1.png and b/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_default_address-verification-flow-1.png differ diff --git a/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_default_base-view-1.png b/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..da89a333f9a Binary files /dev/null and b/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_default_base-view-1.png differ diff --git a/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_default_base-view-mobile-1.png b/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 408636d0ec0..00000000000 Binary files a/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_mobile_base-view-mobile-1.png b/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 0296c06047c..00000000000 Binary files a/src/features/account/pages/verified-addresses/__screenshots__/VerifiedAddresses.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/account/pages/verified-addresses/address-verification/AddressVerificationModal.tsx b/src/features/account/pages/verified-addresses/address-verification/AddressVerificationModal.tsx index 1db149220e2..d8cfef94d7f 100644 --- a/src/features/account/pages/verified-addresses/address-verification/AddressVerificationModal.tsx +++ b/src/features/account/pages/verified-addresses/address-verification/AddressVerificationModal.tsx @@ -6,7 +6,7 @@ import type { AddressVerificationFormFirstStepFields } from './types'; import type * as contractsInfo from '@blockscout/contracts-info-types'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { DialogBody, DialogContent, DialogHeader, DialogRoot } from 'src/toolkit/chakra/dialog'; @@ -31,8 +31,8 @@ const AddressVerificationModal = ({ defaultAddress, open, onOpenChange, onSubmit const [ data, setData ] = React.useState<StateData>({ address: '', signingMessage: '', contractCreator: '' }); React.useEffect(() => { - open && mixpanel.logEvent( - mixpanel.EventTypes.VERIFY_ADDRESS, + open && analytics.logEvent( + analytics.EventTypes.VERIFY_ADDRESS, { Action: 'Form opened', 'Page type': pageType }, ); }, [ open, pageType ]); @@ -40,8 +40,8 @@ const AddressVerificationModal = ({ defaultAddress, open, onOpenChange, onSubmit const handleGoToSecondStep = React.useCallback((firstStepResult: typeof data) => { setData(firstStepResult); setStepIndex((prev) => prev + 1); - mixpanel.logEvent( - mixpanel.EventTypes.VERIFY_ADDRESS, + analytics.logEvent( + analytics.EventTypes.VERIFY_ADDRESS, { Action: 'Address entered', 'Page type': pageType }, ); }, [ pageType ]); @@ -50,8 +50,8 @@ const AddressVerificationModal = ({ defaultAddress, open, onOpenChange, onSubmit onSubmit(address); setStepIndex((prev) => prev + 1); setData((prev) => ({ ...prev, isToken: Boolean(address.metadata?.tokenName) })); - mixpanel.logEvent( - mixpanel.EventTypes.VERIFY_ADDRESS, + analytics.logEvent( + analytics.EventTypes.VERIFY_ADDRESS, { Action: 'Sign ownership', 'Page type': pageType, 'Sign method': signMethod }, ); }, [ onSubmit, pageType ]); diff --git a/src/features/account/pages/verified-addresses/address-verification/steps/AddressVerificationStepAddress.tsx b/src/features/account/pages/verified-addresses/address-verification/steps/AddressVerificationStepAddress.tsx index 2bbbda32c0e..23079e8f014 100644 --- a/src/features/account/pages/verified-addresses/address-verification/steps/AddressVerificationStepAddress.tsx +++ b/src/features/account/pages/verified-addresses/address-verification/steps/AddressVerificationStepAddress.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { SubmitHandler } from 'react-hook-form'; import { FormProvider, useForm } from 'react-hook-form'; @@ -17,6 +16,7 @@ import useApiFetch from 'src/api/hooks/useApiFetch'; import type { ResourceError } from 'src/api/resources'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; import { Alert } from 'src/toolkit/chakra/alert'; import { Button } from 'src/toolkit/chakra/button'; diff --git a/src/features/account/pages/verified-addresses/address-verification/steps/AddressVerificationStepSignature.tsx b/src/features/account/pages/verified-addresses/address-verification/steps/AddressVerificationStepSignature.tsx index 31530fe8802..599942d12de 100644 --- a/src/features/account/pages/verified-addresses/address-verification/steps/AddressVerificationStepSignature.tsx +++ b/src/features/account/pages/verified-addresses/address-verification/steps/AddressVerificationStepSignature.tsx @@ -21,7 +21,6 @@ import { getWeb3Runtime } from 'src/features/connect-wallet/utils/runtime'; import config from 'src/config'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import shortenString from 'src/shared/texts/shorten-string'; import { Alert } from 'src/toolkit/chakra/alert'; import { Button } from 'src/toolkit/chakra/button'; @@ -29,6 +28,7 @@ import { Link } from 'src/toolkit/chakra/link'; import { Radio, RadioGroup } from 'src/toolkit/chakra/radio'; import { FormFieldText } from 'src/toolkit/components/forms/fields/FormFieldText'; import { SIGNATURE_REGEXP } from 'src/toolkit/components/forms/validators/signature'; +import { shortenString } from 'src/toolkit/utils/texts'; import AdminSupportText from '../../AdminSupportText'; diff --git a/src/features/account/pages/verified-addresses/address-verification/steps/__screenshots__/AddressVerificationStepAddress.pw.tsx_mobile_SOURCE-CODE-NOT-VERIFIED-ERROR-view-mobile-1.png b/src/features/account/pages/verified-addresses/address-verification/steps/__screenshots__/AddressVerificationStepAddress.pw.tsx_mobile_SOURCE-CODE-NOT-VERIFIED-ERROR-view-mobile-1.png index 6c77bf1962a..67f0d437071 100644 Binary files a/src/features/account/pages/verified-addresses/address-verification/steps/__screenshots__/AddressVerificationStepAddress.pw.tsx_mobile_SOURCE-CODE-NOT-VERIFIED-ERROR-view-mobile-1.png and b/src/features/account/pages/verified-addresses/address-verification/steps/__screenshots__/AddressVerificationStepAddress.pw.tsx_mobile_SOURCE-CODE-NOT-VERIFIED-ERROR-view-mobile-1.png differ diff --git a/src/features/account/pages/verified-addresses/address-verification/steps/__screenshots__/AddressVerificationStepSignature.pw.tsx_mobile_INVALID-SIGNER-ERROR-view-mobile-1.png b/src/features/account/pages/verified-addresses/address-verification/steps/__screenshots__/AddressVerificationStepSignature.pw.tsx_mobile_INVALID-SIGNER-ERROR-view-mobile-1.png index cab77c1f061..b126dafd6a9 100644 Binary files a/src/features/account/pages/verified-addresses/address-verification/steps/__screenshots__/AddressVerificationStepSignature.pw.tsx_mobile_INVALID-SIGNER-ERROR-view-mobile-1.png and b/src/features/account/pages/verified-addresses/address-verification/steps/__screenshots__/AddressVerificationStepSignature.pw.tsx_mobile_INVALID-SIGNER-ERROR-view-mobile-1.png differ diff --git a/src/features/account/pages/verified-addresses/index/VerifiedAddressesListItem.tsx b/src/features/account/pages/verified-addresses/index/VerifiedAddressesListItem.tsx deleted file mode 100644 index 1947ca6ef1b..00000000000 --- a/src/features/account/pages/verified-addresses/index/VerifiedAddressesListItem.tsx +++ /dev/null @@ -1,135 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type * as adminRs from '@blockscout/admin-rs-types'; -import type * as contractsInfo from '@blockscout/contracts-info-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; - -import dayjs from 'src/shared/date-and-time/dayjs'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import { IconButton } from 'src/toolkit/chakra/icon-button'; -import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Tooltip } from 'src/toolkit/chakra/tooltip'; - -import VerifiedAddressesStatus from './VerifiedAddressesStatus'; - -interface Props { - item: contractsInfo.VerifiedAddress; - application: adminRs.TokenInfoSubmission | undefined; - onAdd: (address: string) => void; - onEdit: (address: string) => void; - isLoading: boolean; -} - -const VerifiedAddressesListItem = ({ item, application, onAdd, onEdit, isLoading }: Props) => { - const handleAddClick = React.useCallback(() => { - if (isLoading) { - return; - } - onAdd(item.contractAddress); - }, [ isLoading, item.contractAddress, onAdd ]); - - const handleEditClick = React.useCallback(() => { - if (isLoading) { - return; - } - onEdit(item.contractAddress); - }, [ isLoading, item.contractAddress, onEdit ]); - - const tokenInfo = (() => { - if (isLoading) { - return <Skeleton loading height={ 6 } width="140px"/>; - } - - if (!item.metadata?.tokenName) { - return <span>Not a token</span>; - } - - if (!application) { - return <Link onClick={ handleAddClick }>Add details</Link>; - } - - const token = { - type: 'ERC-20' as const, - icon_url: application.iconUrl, - address_hash: application.tokenAddress, - name: item.metadata.tokenName, - symbol: '', - reputation: null, - }; - - return ( - <> - <TokenEntity - token={ token } - noLink={ application.status === 'IN_PROCESS' } - noCopy - noSymbol - /> - <Tooltip content="Edit" disabled={ isLoading } disableOnMobile> - <IconButton - aria-label="edit" - variant="link" - size="2xs" - borderRadius="none" - onClick={ handleEditClick } - > - <SpriteIcon name="edit"/> - </IconButton> - </Tooltip> - </> - ); - })(); - - return ( - <ListItemMobileGrid.Container> - <ListItemMobileGrid.Label isLoading={ isLoading }>Address</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity - address={{ hash: item.contractAddress, is_contract: true }} - isLoading={ isLoading } - w="100%" - /> - </ListItemMobileGrid.Value> - - { item.metadata?.tokenName && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Token Info</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value display="flex" alignItems="center"> - { tokenInfo } - </ListItemMobileGrid.Value> - </> - ) } - - { item.metadata?.tokenName && application && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block"> - <VerifiedAddressesStatus status={ application.status }/> - </Skeleton> - </ListItemMobileGrid.Value> - </> - ) } - - { item.metadata?.tokenName && application && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Date</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block"> - { dayjs(application.updatedAt).format('MMM DD, YYYY') } - </Skeleton> - </ListItemMobileGrid.Value> - </> - ) } - </ListItemMobileGrid.Container> - ); -}; - -export default React.memo(VerifiedAddressesListItem); diff --git a/src/features/account/pages/verified-addresses/index/VerifiedAddressesTable.tsx b/src/features/account/pages/verified-addresses/index/VerifiedAddressesTable.tsx index 2cceae1fe51..d9280d4b1ea 100644 --- a/src/features/account/pages/verified-addresses/index/VerifiedAddressesTable.tsx +++ b/src/features/account/pages/verified-addresses/index/VerifiedAddressesTable.tsx @@ -5,6 +5,8 @@ import React from 'react'; import type * as adminRs from '@blockscout/admin-rs-types'; import type * as contractsInfo from '@blockscout/contracts-info-types'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; + import { TableBody, TableColumnHeader, TableHeader, TableRoot, TableRow } from 'src/toolkit/chakra/table'; import VerifiedAddressesTableItem from './VerifiedAddressesTableItem'; @@ -17,9 +19,13 @@ interface Props { isLoading: boolean; } +const getBaseKey = (item: contractsInfo.VerifiedAddress): string => item.contractAddress; + const VerifiedAddressesTable = ({ data, applications, onItemEdit, onItemAdd, isLoading }: Props) => { + const keys = useUniqueKeys(data, getBaseKey); + return ( - <TableRoot> + <TableRoot minW="800px"> <TableHeader> <TableRow> <TableColumnHeader>Address</TableColumnHeader> @@ -32,7 +38,7 @@ const VerifiedAddressesTable = ({ data, applications, onItemEdit, onItemAdd, isL <TableBody> { data.map((item, index) => ( <VerifiedAddressesTableItem - key={ item.contractAddress + (isLoading ? index : '') } + key={ keys[index] } item={ item } application={ applications?.find(({ tokenAddress }) => tokenAddress.toLowerCase() === item.contractAddress.toLowerCase()) } onAdd={ onItemAdd } diff --git a/src/features/account/pages/verified-addresses/token-info/TokenInfoExpeditedReview.tsx b/src/features/account/pages/verified-addresses/token-info/TokenInfoExpeditedReview.tsx index ce7c7a47fa6..7b79bce493f 100644 --- a/src/features/account/pages/verified-addresses/token-info/TokenInfoExpeditedReview.tsx +++ b/src/features/account/pages/verified-addresses/token-info/TokenInfoExpeditedReview.tsx @@ -5,6 +5,7 @@ import React from 'react'; import type { Fields } from './types'; +import { sanitizeHtml } from 'src/shared/texts/sanitize-html'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { BoxHtml } from 'src/toolkit/chakra/box'; @@ -22,6 +23,8 @@ interface Props { const TokenInfoExpeditedReview = ({ html, readOnly }: Props) => { + const safeHtml = React.useMemo(() => sanitizeHtml(html), [ html ]); + const rules = React.useMemo(() => ({ validate: { tx_hash: transactionHashValidator, @@ -45,7 +48,7 @@ const TokenInfoExpeditedReview = ({ html, readOnly }: Props) => { </Flex> <List.Root as="ol" listStyleType="decimal" gap={ 6 } mt={ 6 } pl={ 5 }> <List.Item _marker={{ fontWeight: 600 }} pl={ 3 }> - <BoxHtml html={ html }/> + <BoxHtml html={ safeHtml }/> </List.Item> <List.Item _marker={{ fontWeight: 600 }} pl={ 3 }> Once payment is completed, enter the <chakra.span fontWeight={ 600 }>transaction hash</chakra.span> diff --git a/src/features/account/pages/verified-addresses/token-info/TokenInfoForm.pw.tsx b/src/features/account/pages/verified-addresses/token-info/TokenInfoForm.pw.tsx index 39e58d6d6d6..1ab624a719e 100644 --- a/src/features/account/pages/verified-addresses/token-info/TokenInfoForm.pw.tsx +++ b/src/features/account/pages/verified-addresses/token-info/TokenInfoForm.pw.tsx @@ -3,19 +3,21 @@ import React from 'react'; import * as mocks from 'src/features/account/mocks/verified-addresses'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; +import type { TestFnArgs } from 'playwright/lib'; import { test, expect } from 'playwright/lib'; import TokenInfoForm from './TokenInfoForm'; -test.beforeEach(async({ mockApiResponse, mockAssetResponse }) => { +const mockFormData = async({ mockApiResponse, mockAssetResponse }: Pick<TestFnArgs, 'mockApiResponse' | 'mockAssetResponse'>) => { await mockApiResponse('admin:token_info_applications_config', mocks.TOKEN_INFO_FORM_CONFIG, { pathParams: { instanceId: '1' } }); await mockAssetResponse(mocks.TOKEN_INFO_APPLICATION_BASE.iconUrl, './playwright/mocks/image_md.jpg'); -}); +}; -test('base view +@mobile +@dark-mode', async({ render, mockEnvs }) => { +test('base view +@mobile +@dark-mode', async({ render, mockEnvs, mockApiResponse, mockAssetResponse }) => { await mockEnvs([ ...ENVS_MAP.verifiedAddresses, ]); + await mockFormData({ mockApiResponse, mockAssetResponse }); const props = { address: mocks.VERIFIED_ADDRESS.ITEM_1.contractAddress, tokenName: 'Test Token (TT)', @@ -26,7 +28,8 @@ test('base view +@mobile +@dark-mode', async({ render, mockEnvs }) => { await expect(component).toHaveScreenshot(); }); -test('status IN_PROCESS', async({ render }) => { +test('status IN_PROCESS', async({ render, mockApiResponse, mockAssetResponse }) => { + await mockFormData({ mockApiResponse, mockAssetResponse }); const props = { address: mocks.VERIFIED_ADDRESS.ITEM_1.contractAddress, tokenName: 'Test Token (TT)', diff --git a/src/features/account/pages/verified-addresses/token-info/TokenInfoForm.tsx b/src/features/account/pages/verified-addresses/token-info/TokenInfoForm.tsx index 3ddd4e6f892..f53ac3c36d2 100644 --- a/src/features/account/pages/verified-addresses/token-info/TokenInfoForm.tsx +++ b/src/features/account/pages/verified-addresses/token-info/TokenInfoForm.tsx @@ -14,8 +14,8 @@ import type { ResourceError } from 'src/api/resources'; import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; -import * as mixpanel from 'src/services/mixpanel'; import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; +import * as analytics from 'src/shared/analytics'; import { Button } from 'src/toolkit/chakra/button'; import { toaster } from 'src/toolkit/chakra/toaster'; @@ -62,7 +62,7 @@ const TokenInfoForm = ({ address, tokenName, application, onSubmit }: Props) => React.useEffect(() => { if (!application?.id && !openEventSent.current) { - mixpanel.logEvent(mixpanel.EventTypes.VERIFY_TOKEN, { Action: 'Form opened' }); + analytics.logEvent(analytics.EventTypes.VERIFY_TOKEN, { Action: 'Form opened' }); openEventSent.current = true; } }, [ application?.id ]); @@ -87,7 +87,7 @@ const TokenInfoForm = ({ address, tokenName, application, onSubmit }: Props) => onSubmit(result); if (!application?.id) { - mixpanel.logEvent(mixpanel.EventTypes.VERIFY_TOKEN, { Action: 'Submit' }); + analytics.logEvent(analytics.EventTypes.VERIFY_TOKEN, { Action: 'Submit' }); } } else { diff --git a/src/features/account/pages/verified-addresses/token-info/__screenshots__/TokenInfoForm.pw.tsx_mobile_base-view-mobile-dark-mode-1.png b/src/features/account/pages/verified-addresses/token-info/__screenshots__/TokenInfoForm.pw.tsx_mobile_base-view-mobile-dark-mode-1.png index 818c5c93a2a..5157b3fbb10 100644 Binary files a/src/features/account/pages/verified-addresses/token-info/__screenshots__/TokenInfoForm.pw.tsx_mobile_base-view-mobile-dark-mode-1.png and b/src/features/account/pages/verified-addresses/token-info/__screenshots__/TokenInfoForm.pw.tsx_mobile_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/account/pages/watchlist/Watchlist.tsx b/src/features/account/pages/watchlist/Watchlist.tsx index 0833078a577..a4dd05ca3d6 100644 --- a/src/features/account/pages/watchlist/Watchlist.tsx +++ b/src/features/account/pages/watchlist/Watchlist.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import { useQueryClient } from '@tanstack/react-query'; import React, { useCallback, useState } from 'react'; @@ -19,21 +18,21 @@ import { WATCH_LIST_ITEM_WITH_TOKEN_INFO } from 'src/features/account/stubs'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { Button } from 'src/toolkit/chakra/button'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; import AddressModal from './AddressModal/AddressModal'; import DeleteAddressModal from './DeleteAddressModal'; import WatchlistEmailAlert from './WatchlistEmailAlert'; -import WatchListItem from './WatchlistTable/WatchListItem'; import WatchlistTable from './WatchlistTable/WatchlistTable'; const WatchList: React.FC = () => { - const { data, isPlaceholderData, isError, pagination } = useQueryWithPages({ + const { data, isInitialLoading, isTransitioning, isError, pagination } = useApiPaginatedQuery({ resourceName: 'core:watchlist', options: { placeholderData: { items: Array(5).fill(WATCH_LIST_ITEM_WITH_TOKEN_INFO), next_page_params: null }, @@ -103,31 +102,20 @@ const WatchList: React.FC = () => { itemsNum={ data?.items.length } emptyText="" actionBar={ actionBar } + isTransitioning={ isTransitioning } > - <Box display={{ base: 'block', lg: 'none' }}> - { data?.items.map((item, index) => ( - <WatchListItem - key={ item.address_hash + (isPlaceholderData ? index : '') } - item={ item } - isLoading={ isPlaceholderData } - onDeleteClick={ onDeleteClick } - onEditClick={ onEditClick } - hasEmail={ hasEmail } - /> - )) } - </Box> - <Box display={{ base: 'none', lg: 'block' }}> + <TableContainerScrollable> <WatchlistTable data={ data?.items } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } onDeleteClick={ onDeleteClick } onEditClick={ onEditClick } top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } hasEmail={ hasEmail } /> - </Box> + </TableContainerScrollable> </DataList> - <Skeleton mt={ 8 } loading={ isPlaceholderData } display="inline-block"> + <Skeleton mt={ 8 } loading={ isInitialLoading } display="inline-block"> <Button onClick={ addressModalProps.onOpen } > diff --git a/src/features/account/pages/watchlist/WatchlistTable/WatchListItem.tsx b/src/features/account/pages/watchlist/WatchlistTable/WatchListItem.tsx deleted file mode 100644 index 1592091e54c..00000000000 --- a/src/features/account/pages/watchlist/WatchlistTable/WatchListItem.tsx +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box, Text, HStack, Flex } from '@chakra-ui/react'; -import { useMutation } from '@tanstack/react-query'; -import React, { useCallback, useState } from 'react'; - -import type { WatchlistAddress } from 'src/features/account/types/api'; - -import useApiFetch from 'src/api/hooks/useApiFetch'; - -import TableItemActionButtons from 'src/features/account/components/TableItemActionButtons'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Switch } from 'src/toolkit/chakra/switch'; -import { Tag } from 'src/toolkit/chakra/tag'; -import { toaster } from 'src/toolkit/chakra/toaster'; - -import WatchListAddressItem from './WatchListAddressItem'; - -interface Props { - item: WatchlistAddress; - isLoading?: boolean; - onEditClick: (data: WatchlistAddress) => void; - onDeleteClick: (data: WatchlistAddress) => void; - hasEmail: boolean; -} - -const WatchListItem = ({ item, isLoading, onEditClick, onDeleteClick, hasEmail }: Props) => { - const [ notificationEnabled, setNotificationEnabled ] = useState(item.notification_methods.email); - const [ switchDisabled, setSwitchDisabled ] = useState(false); - const onItemEditClick = useCallback(() => { - return onEditClick(item); - }, [ item, onEditClick ]); - - const onItemDeleteClick = useCallback(() => { - return onDeleteClick(item); - }, [ item, onDeleteClick ]); - - const apiFetch = useApiFetch(); - - const showErrorToast = useCallback(() => { - toaster.error({ - title: 'Error', - description: 'There has been an error processing your request', - }); - }, [ ]); - - const showNotificationToast = useCallback((isOn: boolean) => { - toaster.success({ - title: 'Success', - description: isOn ? 'Email notification is ON' : 'Email notification is OFF', - }); - }, [ ]); - - const { mutate } = useMutation<WatchlistAddress>({ - mutationFn: () => { - setSwitchDisabled(true); - const body = { ...item, notification_methods: { email: !notificationEnabled } }; - setNotificationEnabled(prevState => !prevState); - return apiFetch('core:watchlist', { - pathParams: { id: String(item.id) }, - fetchParams: { method: 'PUT', body }, - }) as Promise<WatchlistAddress>; - }, - onError: () => { - showErrorToast(); - setNotificationEnabled(prevState => !prevState); - setSwitchDisabled(false); - }, - onSuccess: (data) => { - setSwitchDisabled(false); - showNotificationToast(data.notification_methods.email); - }, - }); - - const onSwitch = useCallback(() => { - return mutate(); - }, [ mutate ]); - - return ( - <ListItemMobile> - <Box maxW="100%"> - <WatchListAddressItem item={ item } isLoading={ isLoading }/> - <HStack gap={ 3 } mt={ 6 }> - <Text textStyle="sm" fontWeight={ 500 }>Private tag</Text> - <Tag loading={ isLoading } truncated>{ item.name }</Tag> - </HStack> - </Box> - <Flex alignItems="center" justifyContent="space-between" mt={ 6 } w="100%"> - <HStack gap={ 3 }> - <Text textStyle="sm" fontWeight={ 500 }>Email notification</Text> - <Skeleton loading={ isLoading } display="inline-block"> - <Switch - checked={ notificationEnabled } - onCheckedChange={ onSwitch } - aria-label="Email notification" - disabled={ !hasEmail || switchDisabled } - /> - </Skeleton> - </HStack> - <TableItemActionButtons onDeleteClick={ onItemDeleteClick } onEditClick={ onItemEditClick } isLoading={ isLoading }/> - </Flex> - </ListItemMobile> - ); -}; - -export default WatchListItem; diff --git a/src/features/account/pages/watchlist/WatchlistTable/WatchlistTable.tsx b/src/features/account/pages/watchlist/WatchlistTable/WatchlistTable.tsx index 2e9f6e98799..23dd247be5d 100644 --- a/src/features/account/pages/watchlist/WatchlistTable/WatchlistTable.tsx +++ b/src/features/account/pages/watchlist/WatchlistTable/WatchlistTable.tsx @@ -4,6 +4,8 @@ import React from 'react'; import type { WatchlistAddress } from 'src/features/account/types/api'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; + import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; import WatchlistTableItem from './WatchListTableItem'; @@ -17,9 +19,13 @@ interface Props { hasEmail: boolean; } +const getBaseKey = (item: WatchlistAddress): string => item.address_hash; + const WatchlistTable = ({ data, isLoading, onDeleteClick, onEditClick, top, hasEmail }: Props) => { + const keys = useUniqueKeys(data, getBaseKey); + return ( - <TableRoot minWidth="600px"> + <TableRoot minWidth="800px"> <TableHeaderSticky top={ top }> <TableRow> <TableColumnHeader width="70%">Address</TableColumnHeader> @@ -31,7 +37,7 @@ const WatchlistTable = ({ data, isLoading, onDeleteClick, onEditClick, top, hasE <TableBody> { data?.map((item, index) => ( <WatchlistTableItem - key={ item.address_hash + (isLoading ? index : '') } + key={ keys[index] } item={ item } isLoading={ isLoading } onDeleteClick={ onDeleteClick } diff --git a/src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgetCard.tsx b/src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgetCard.tsx index 47043716d07..ab361d2a662 100644 --- a/src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgetCard.tsx +++ b/src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgetCard.tsx @@ -6,7 +6,7 @@ import { useCallback } from 'react'; import type { Address3rdPartyWidget } from 'src/features/address-3rd-party-widgets/types/view'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Image } from 'src/toolkit/chakra/image'; @@ -40,7 +40,7 @@ const Address3rdPartyWidgetCard = ({ name, config, address, isLoading }: Props) }); const handleClick = useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.ADDRESS_WIDGET, { Name: name }); + analytics.logEvent(analytics.EventTypes.ADDRESS_WIDGET, { Name: name }); }, [ name ]); if (!config) { diff --git a/src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgets.tsx b/src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgets.tsx index 50379f369cc..529dcc947a7 100644 --- a/src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgets.tsx +++ b/src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgets.tsx @@ -1,14 +1,14 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Grid, Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; -import { route } from 'nextjs-routes'; import { useMemo } from 'react'; import type { Address3rdPartyWidget } from 'src/features/address-3rd-party-widgets/types/view'; import useIsMounted from 'src/shared/hooks/useIsMounted'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/features/address-3rd-party-widgets/pages/address/useAddress3rdPartyWidgets.tsx b/src/features/address-3rd-party-widgets/pages/address/useAddress3rdPartyWidgets.ts similarity index 100% rename from src/features/address-3rd-party-widgets/pages/address/useAddress3rdPartyWidgets.tsx rename to src/features/address-3rd-party-widgets/pages/address/useAddress3rdPartyWidgets.ts diff --git a/src/features/address-3rd-party-widgets/pages/address/useWidgetsConfigQuery.tsx b/src/features/address-3rd-party-widgets/pages/address/useWidgetsConfigQuery.ts similarity index 100% rename from src/features/address-3rd-party-widgets/pages/address/useWidgetsConfigQuery.tsx rename to src/features/address-3rd-party-widgets/pages/address/useWidgetsConfigQuery.ts diff --git a/src/features/address-metadata/components/AppActionButton.tsx b/src/features/address-metadata/components/AppActionButton.tsx index 80c58df0ee5..80bfa2a8baa 100644 --- a/src/features/address-metadata/components/AppActionButton.tsx +++ b/src/features/address-metadata/components/AppActionButton.tsx @@ -1,33 +1,42 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Text, chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; -import type { AddressMetadataTagFormatted } from 'src/features/address-metadata/types/client'; +import type { AppActionSource } from 'src/features/address-metadata/utils/build-app-action-url'; +import { buildAppActionUrl } from 'src/features/address-metadata/utils/build-app-action-url'; +import type { AppActionData } from 'src/features/address-metadata/utils/get-app-action-data'; +import { useMultichainContext } from 'src/features/multichain/context'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; +import { route } from 'src/shared/router/routes'; import { Image } from 'src/toolkit/chakra/image'; import { Link } from 'src/toolkit/chakra/link'; type Props = { - data: NonNullable<AddressMetadataTagFormatted['meta']>; + data: AppActionData; className?: string; + addressHash?: string; txHash?: string; - source: 'Txn' | 'NFT collection' | 'NFT item'; + source: AppActionSource; }; -const AppActionButton = ({ data, className, txHash, source }: Props) => { +const AppActionButton = ({ data, className, addressHash, txHash, source }: Props) => { const { appID, textColor, bgColor, appActionButtonText, appLogoURL, appMarketplaceURL } = data; - const actionURL = appMarketplaceURL?.replace('{chainId}', config.chain.id || '').replace('{txHash}', txHash || ''); + const multichainContext = useMultichainContext(); + const chainId = multichainContext?.chain?.app_config.chain.id || config.chain.id; + + const actionURL = appMarketplaceURL ? + buildAppActionUrl(appMarketplaceURL, { address: addressHash, chainId, txHash }, source) : + undefined; const handleClick = React.useCallback(() => { const info = appID || actionURL; if (info) { - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { Type: 'Action button', Info: info, Source: source }); + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Action button', Info: info, Source: source }); } }, [ source, appID, actionURL ]); diff --git a/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_dark-color-mode_button-without-styles-dark-mode-1.png b/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_dark-color-mode_button-without-styles-dark-mode-1.png index 81ce9396e87..27eab94a44b 100644 Binary files a/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_dark-color-mode_button-without-styles-dark-mode-1.png and b/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_dark-color-mode_button-without-styles-dark-mode-1.png differ diff --git a/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_dark-color-mode_link-without-styles-dark-mode-1.png b/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_dark-color-mode_link-without-styles-dark-mode-1.png index e227c626ae6..be6ec202290 100644 Binary files a/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_dark-color-mode_link-without-styles-dark-mode-1.png and b/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_dark-color-mode_link-without-styles-dark-mode-1.png differ diff --git a/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_default_button-without-styles-dark-mode-1.png b/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_default_button-without-styles-dark-mode-1.png index ee56c6252d9..d38df5fd862 100644 Binary files a/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_default_button-without-styles-dark-mode-1.png and b/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_default_button-without-styles-dark-mode-1.png differ diff --git a/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_default_link-without-styles-dark-mode-1.png b/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_default_link-without-styles-dark-mode-1.png index d1c94624a3b..1845b9d6126 100644 Binary files a/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_default_link-without-styles-dark-mode-1.png and b/src/features/address-metadata/components/__screenshots__/AppActionButton.pw.tsx_default_link-without-styles-dark-mode-1.png differ diff --git a/src/features/address-metadata/components/tag/MetadataTag.pw.tsx b/src/features/address-metadata/components/tag/MetadataTag.pw.tsx index 4e2c362e316..f44fc60fe68 100644 --- a/src/features/address-metadata/components/tag/MetadataTag.pw.tsx +++ b/src/features/address-metadata/components/tag/MetadataTag.pw.tsx @@ -43,6 +43,15 @@ test('tag with link and long name +@dark-mode', async({ render }) => { await expect(component).toHaveScreenshot(); }); +test('truncated tag with tooltip shows one tooltip on hover', async({ render, page, mockAssetResponse }) => { + await mockAssetResponse(addressMetadataMock.tagWithTooltip.meta?.tooltipIcon as string, './playwright/mocks/image_s.jpg'); + await mockAssetResponse(addressMetadataMock.tagWithTooltip.meta?.tooltipAttributionIcon as string, './playwright/mocks/image_md.jpg'); + const component = await render(<MetadataTag data={ addressMetadataMock.tagWithTooltip } maxW="80px"/>); + await component.getByText('BlockscoutHeroes').hover(); + await expect(page.getByText('Blockscout team member')).toBeVisible(); + await expect(page.getByRole('tooltip')).toHaveCount(1); +}); + test('tag with tooltip +@dark-mode', async({ render, page, mockAssetResponse }) => { await mockAssetResponse(addressMetadataMock.tagWithTooltip.meta?.tooltipIcon as string, './playwright/mocks/image_s.jpg'); await mockAssetResponse(addressMetadataMock.tagWithTooltip.meta?.tooltipAttributionIcon as string, './playwright/mocks/image_md.jpg'); diff --git a/src/features/address-metadata/components/tag/MetadataTag.tsx b/src/features/address-metadata/components/tag/MetadataTag.tsx index 6339e86187e..0680416c6e9 100644 --- a/src/features/address-metadata/components/tag/MetadataTag.tsx +++ b/src/features/address-metadata/components/tag/MetadataTag.tsx @@ -7,7 +7,7 @@ import type { MetadataTag as TMetadataTag } from './types'; import { useMultichainContext } from 'src/features/multichain/context'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { Link, LinkExternalIcon } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; @@ -15,7 +15,7 @@ import { Tag } from 'src/toolkit/chakra/tag'; import MetadataTagIcon from './MetadataTagIcon'; import MetadataTagTooltip from './MetadataTagTooltip'; -import { getTagName, getTagLinkParams } from './utils'; +import { getTagName, getTagLinkParams, hasTagTooltip } from './utils'; interface Props extends HTMLChakraProps<'span'> { data: TMetadataTag; @@ -37,7 +37,7 @@ const MetadataTag = ({ data, addressHash, isLoading, noLink, noColors, ...rest } return; } - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Address tag', Info: data.slug, URL: linkParams.href, @@ -70,7 +70,8 @@ const MetadataTag = ({ data, addressHash, isLoading, noLink, noColors, ...rest } bg={ !noColors ? data.meta?.bgColor : undefined } color={ !noColors ? data.meta?.textColor : undefined } startElement={ <MetadataTagIcon data={ data } noColors={ noColors }/> } - truncated + // the tag tooltip and the overflow tooltip would open together on hover + truncated={ !hasTagTooltip(data) } endElement={ linkParams?.type === 'external' ? <LinkExternalIcon color={ iconColor }/> : null } endElementProps={ linkParams?.type === 'external' ? { ml: -1 } : undefined } _hover={ hasLink ? { opacity: 0.76 } : undefined } diff --git a/src/features/address-metadata/components/tag/MetadataTagTooltip.tsx b/src/features/address-metadata/components/tag/MetadataTagTooltip.tsx index 108111645e4..7fd58c39c50 100644 --- a/src/features/address-metadata/components/tag/MetadataTagTooltip.tsx +++ b/src/features/address-metadata/components/tag/MetadataTagTooltip.tsx @@ -5,27 +5,21 @@ import React from 'react'; import type { MetadataTag } from './types'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { Image } from 'src/toolkit/chakra/image'; import { Link } from 'src/toolkit/chakra/link'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; import { makePrettyLink } from 'src/toolkit/utils/url'; +import { hasTagTooltip } from './utils'; + interface Props { data: MetadataTag; children: React.ReactNode; } const EntityTagTooltip = ({ data, children }: Props) => { - const hasPopover = Boolean( - data.meta?.tooltipIcon || - data.meta?.tooltipTitle || - data.meta?.tooltipDescription || - data.meta?.tooltipUrl || - data.meta?.tooltipAttribution, - ); - const link = makePrettyLink(data.meta?.tooltipUrl); const attribution = React.useMemo(() => { @@ -41,14 +35,14 @@ const EntityTagTooltip = ({ data, children }: Props) => { return; } - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Address tag', Info: data.slug, URL: data.meta.tooltipUrl, }); }, [ data.meta?.tooltipUrl, data.slug ]); - if (!hasPopover) { + if (!hasTagTooltip(data)) { // eslint-disable-next-line react/jsx-no-useless-fragment return <>{ children }</>; } diff --git a/src/features/address-metadata/components/tag/MetadataTags.tsx b/src/features/address-metadata/components/tag/MetadataTags.tsx index 490ef7a6cb0..6f26479353a 100644 --- a/src/features/address-metadata/components/tag/MetadataTags.tsx +++ b/src/features/address-metadata/components/tag/MetadataTags.tsx @@ -5,6 +5,8 @@ import React from 'react'; import type { MetadataTag as TMetadataTag } from './types'; +import { isHiddenTag } from 'src/features/address-metadata/utils/is-hidden-tag'; + import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; @@ -21,8 +23,9 @@ interface Props { noColors?: boolean; } -const MetadataTags = ({ tags, addressHash, className, isLoading, noColors }: Props) => { +const MetadataTags = ({ tags: allTags, addressHash, className, isLoading, noColors }: Props) => { const isMobile = useIsMobile(); + const tags = React.useMemo(() => allTags.filter((tag) => !isHiddenTag(tag)), [ allTags ]); const visibleNum = isMobile ? 2 : 3; const metaSuitesPlaceholder = config.features.metasuites.isEnabled ? diff --git a/src/features/address-metadata/components/tag/__screenshots__/MetadataTags.pw.tsx_mobile_mixed-name-length-mobile-1.png b/src/features/address-metadata/components/tag/__screenshots__/MetadataTags.pw.tsx_mobile_mixed-name-length-mobile-1.png index a2f719b7a1b..877b2ccde76 100644 Binary files a/src/features/address-metadata/components/tag/__screenshots__/MetadataTags.pw.tsx_mobile_mixed-name-length-mobile-1.png and b/src/features/address-metadata/components/tag/__screenshots__/MetadataTags.pw.tsx_mobile_mixed-name-length-mobile-1.png differ diff --git a/src/features/address-metadata/components/tag/__screenshots__/MetadataTags.pw.tsx_mobile_one-tag-with-long-name-mobile---default-1.png b/src/features/address-metadata/components/tag/__screenshots__/MetadataTags.pw.tsx_mobile_one-tag-with-long-name-mobile---default-1.png index f69f93c9977..055b2668f8f 100644 Binary files a/src/features/address-metadata/components/tag/__screenshots__/MetadataTags.pw.tsx_mobile_one-tag-with-long-name-mobile---default-1.png and b/src/features/address-metadata/components/tag/__screenshots__/MetadataTags.pw.tsx_mobile_one-tag-with-long-name-mobile---default-1.png differ diff --git a/src/features/address-metadata/components/tag/utils.ts b/src/features/address-metadata/components/tag/utils.ts index c2c5db22c91..b646a1d9bd3 100644 --- a/src/features/address-metadata/components/tag/utils.ts +++ b/src/features/address-metadata/components/tag/utils.ts @@ -32,6 +32,16 @@ export function getTagLinkParams( } } +export function hasTagTooltip(data: MetadataTag): boolean { + return Boolean( + data.meta?.tooltipIcon || + data.meta?.tooltipTitle || + data.meta?.tooltipDescription || + data.meta?.tooltipUrl || + data.meta?.tooltipAttribution, + ); +} + export function getTagName(data: MetadataTag, addressHash?: string) { if (data.tagType === 'name' && data.meta?.cexDeposit === 'true' && addressHash) { return `${ data.name } (${ addressHash.slice(0, 2 + 5) })`; diff --git a/src/features/address-metadata/hooks/useAppActionData.ts b/src/features/address-metadata/hooks/useAppActionData.ts new file mode 100644 index 00000000000..562f3f77367 --- /dev/null +++ b/src/features/address-metadata/hooks/useAppActionData.ts @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { useMemo } from 'react'; + +import type { AppActionData } from '../utils/get-app-action-data'; +import { getAppActionData } from '../utils/get-app-action-data'; +import useAddressMetadataInfoQuery from './useAddressMetadataInfoQuery'; + +export default function useAppActionData(address: string | undefined = '', isEnabled = true): AppActionData | null { + const memoizedArray = useMemo(() => address ? [ address ] : [], [ address ]); + const { data } = useAddressMetadataInfoQuery(memoizedArray, isEnabled); + return getAppActionData(data?.addresses[address?.toLowerCase()]?.tags); +} diff --git a/src/features/address-metadata/hooks/useAppActionData.tsx b/src/features/address-metadata/hooks/useAppActionData.tsx deleted file mode 100644 index e5f75ec4aa3..00000000000 --- a/src/features/address-metadata/hooks/useAppActionData.tsx +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useMemo } from 'react'; - -import config from 'src/config'; - -import useAddressMetadataInfoQuery from './useAddressMetadataInfoQuery'; - -export default function useAppActionData(address: string | undefined = '', isEnabled = true) { - const memoizedArray = useMemo(() => address ? [ address ] : [], [ address ]); - const { data } = useAddressMetadataInfoQuery(memoizedArray, isEnabled); - const metadata = data?.addresses[address?.toLowerCase()]; - const tag = metadata?.tags?.find(({ tagType }) => tagType === 'protocol'); - if (tag?.meta?.appMarketplaceURL || (config.features.marketplace.isEnabled && tag?.meta?.appID)) { - return tag.meta; - } - return null; -} diff --git a/src/features/address-metadata/mocks/tags.ts b/src/features/address-metadata/mocks/tags.ts index fddc7d1b5f3..51b9adfdbdb 100644 --- a/src/features/address-metadata/mocks/tags.ts +++ b/src/features/address-metadata/mocks/tags.ts @@ -1,5 +1,7 @@ /* eslint-disable max-len */ -import type { AddressMetadataTagApi } from 'src/features/address-metadata/types/api'; +import type { AddressMetadataInfo, AddressMetadataTagApi } from 'src/features/address-metadata/types/api'; + +import { TOKEN_ACTION_BUTTON_HIDDEN_TAG_SLUG } from 'src/features/token-action-button/utils/is-token-action-button-hidden'; export const nameTag: AddressMetadataTagApi = { slug: 'quack-quack', @@ -128,3 +130,37 @@ export const noteTag2: AddressMetadataTagApi = { data: 'The token MILF was launched on May 13, 2021. The maximum total supply of the token is 100 billion.', }, }; + +export const hiddenProtocolTagWithMeta: AddressMetadataTagApi = { + slug: 'buy-on-duck-portal', + name: 'Buy on Duck portal', + tagType: 'protocol', + ordinal: 0, + meta: { + appActionButtonText: 'Buy on Duck portal', + appLogoURL: 'https://localhost:3100/icon.svg', + appMarketplaceURL: 'https://portal.duck.io/swap?chainId={chainId}&token={address}', + bgColor: '#3A3B54', + textColor: '#FFFFFF', + hidden: 'true', + }, +}; + +export const tokenActionButtonHiddenServiceTag: AddressMetadataTagApi = { + slug: TOKEN_ACTION_BUTTON_HIDDEN_TAG_SLUG, + name: 'Token action button hidden', + tagType: 'service', + ordinal: 0, + meta: null, +}; + +export function generateAddressMetadataInfo(addressHash: string, tag: AddressMetadataTagApi): AddressMetadataInfo { + return { + addresses: { + [ addressHash.toLowerCase() ]: { + tags: [ { ...tag, meta: JSON.stringify(tag.meta) } ], + reputation: null, + }, + }, + }; +} diff --git a/src/features/address-metadata/pages/tag-search/TagSearch.pw.tsx b/src/features/address-metadata/pages/tag-search/TagSearch.pw.tsx index 1092f54d3ba..6b174041271 100644 --- a/src/features/address-metadata/pages/tag-search/TagSearch.pw.tsx +++ b/src/features/address-metadata/pages/tag-search/TagSearch.pw.tsx @@ -46,7 +46,7 @@ const hooksConfig = { }, }; -test('base view +@mobile', async({ render, mockTextAd, mockApiResponse }) => { +test('base view', async({ render, mockTextAd, mockApiResponse }) => { await mockTextAd(); await mockApiResponse( 'core:addresses_metadata_search', diff --git a/src/features/address-metadata/pages/tag-search/TagSearch.tsx b/src/features/address-metadata/pages/tag-search/TagSearch.tsx index f91050431b8..7237909ea4f 100644 --- a/src/features/address-metadata/pages/tag-search/TagSearch.tsx +++ b/src/features/address-metadata/pages/tag-search/TagSearch.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, chakra, Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; +import { chakra, Flex } from '@chakra-ui/react'; import React from 'react'; import type { MetadataTag as TMetadataTag, MetadataTagType } from '../../components/tag/types'; @@ -13,14 +12,15 @@ import { TOP_ADDRESS } from 'src/slices/address/stubs/address'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import MetadataTag from '../../components/tag/MetadataTag'; -import TagSearchListItem from './TagSearchListItem'; import TagSearchTable from './TagSearchTable'; const TagSearch = () => { @@ -30,9 +30,9 @@ const TagSearch = () => { const tagType = getQueryParamString(router.query.tagType); const tagName = getQueryParamString(router.query.tagName); - const { isError, isPlaceholderData, data, pagination } = useQueryWithPages({ + const { isError, isInitialLoading, isTransitioning, data, pagination } = useApiPaginatedQuery({ resourceName: 'core:addresses_metadata_search', - filters: { + queryParams: { slug, tag_type: tagType, }, @@ -48,26 +48,13 @@ const TagSearch = () => { }); const content = data?.items ? ( - <> - <Box hideBelow="lg"> - <TagSearchTable - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - items={ data.items } - isLoading={ isPlaceholderData } - /> - </Box> - <Box hideFrom="lg"> - { data.items.map((item, index) => { - return ( - <TagSearchListItem - key={ item.hash + (isPlaceholderData ? index : '') } - item={ item } - isLoading={ isPlaceholderData } - /> - ); - }) } - </Box> - </> + <TableContainerScrollable> + <TagSearchTable + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + items={ data.items } + isLoading={ isInitialLoading } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -86,14 +73,14 @@ const TagSearch = () => { return ( <Flex alignItems="center" columnGap={ 2 } flexWrap="wrap" rowGap={ 1 }> - <Skeleton loading={ isPlaceholderData } display="inline-block"> + <Skeleton loading={ isInitialLoading } display="inline-block"> Found{ ' ' } <chakra.span fontWeight={ 700 }> { num }{ data?.next_page_params || pagination.page > 1 ? '+' : '' } </chakra.span>{ ' ' } matching result{ num > 1 ? 's' : '' } for </Skeleton> - <MetadataTag data={ tagData } isLoading={ isPlaceholderData } noLink/> + <MetadataTag data={ tagData } isLoading={ isInitialLoading } noLink/> </Flex> ); })(); @@ -108,6 +95,7 @@ const TagSearch = () => { itemsNum={ data?.items.length } emptyText={ text } actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/address-metadata/pages/tag-search/TagSearchListItem.tsx b/src/features/address-metadata/pages/tag-search/TagSearchListItem.tsx deleted file mode 100644 index 27b17c95b56..00000000000 --- a/src/features/address-metadata/pages/tag-search/TagSearchListItem.tsx +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { HStack } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import { currencyUnits } from 'src/slices/chain/units'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -type Props = { - item: schemas['TopAddress']; - isLoading?: boolean; -}; - -const TagSearchListItem = ({ - item, - isLoading, -}: Props) => { - - return ( - <ListItemMobile rowGap={ 3 }> - <AddressEntity - address={ item } - isLoading={ isLoading } - fontWeight={ 700 } - w="100%" - /> - <HStack gap={ 3 } maxW="100%" alignItems="flex-start"> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 } flexShrink={ 0 }>{ `Balance ${ currencyUnits.ether }` }</Skeleton> - <NativeCoinValue - amount={ item.coin_balance } - noSymbol - loading={ isLoading } - fontSize="sm" - color="text.secondary" - /> - </HStack> - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 }>Txn count</Skeleton> - <Skeleton loading={ isLoading } fontSize="sm" color="text.secondary"> - <span>{ Number(item.transactions_count).toLocaleString() }</span> - </Skeleton> - </HStack> - </ListItemMobile> - ); -}; - -export default React.memo(TagSearchListItem); diff --git a/src/features/address-metadata/pages/tag-search/TagSearchTable.tsx b/src/features/address-metadata/pages/tag-search/TagSearchTable.tsx index 34192791cb0..de1d5155e0b 100644 --- a/src/features/address-metadata/pages/tag-search/TagSearchTable.tsx +++ b/src/features/address-metadata/pages/tag-search/TagSearchTable.tsx @@ -6,6 +6,8 @@ import type { schemas } from '@blockscout/api-types'; import { currencyUnits } from 'src/slices/chain/units'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; + import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; import TagSearchTableItem from './TagSearchTableItem'; @@ -16,20 +18,24 @@ interface Props { isLoading?: boolean; } +const getBaseKey = (item: schemas['TopAddress']): string => item.hash; + const TagSearchTable = ({ items, top, isLoading }: Props) => { + const keys = useUniqueKeys(items, getBaseKey); + return ( - <TableRoot> + <TableRoot minW="500px"> <TableHeaderSticky top={ top }> <TableRow> - <TableColumnHeader width="70%">Address</TableColumnHeader> - <TableColumnHeader width="15%" isNumeric>{ `Balance ${ currencyUnits.ether }` }</TableColumnHeader> - <TableColumnHeader width="15%" isNumeric>Txn count</TableColumnHeader> + <TableColumnHeader width="60%">Address</TableColumnHeader> + <TableColumnHeader width="20%" isNumeric>{ `Balance ${ currencyUnits.ether }` }</TableColumnHeader> + <TableColumnHeader width="20%" isNumeric>Txn count</TableColumnHeader> </TableRow> </TableHeaderSticky> <TableBody> { items.map((item, index) => ( <TagSearchTableItem - key={ item.hash + (isLoading ? index : '') } + key={ keys[index] } item={ item } isLoading={ isLoading } /> diff --git a/src/features/address-metadata/pages/tag-search/__screenshots__/TagSearch.pw.tsx_default_base-view-1.png b/src/features/address-metadata/pages/tag-search/__screenshots__/TagSearch.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..aa4cd939824 Binary files /dev/null and b/src/features/address-metadata/pages/tag-search/__screenshots__/TagSearch.pw.tsx_default_base-view-1.png differ diff --git a/src/features/address-metadata/pages/tag-search/__screenshots__/TagSearch.pw.tsx_default_base-view-mobile-1.png b/src/features/address-metadata/pages/tag-search/__screenshots__/TagSearch.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index f07c8715c06..00000000000 Binary files a/src/features/address-metadata/pages/tag-search/__screenshots__/TagSearch.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/address-metadata/pages/tag-search/__screenshots__/TagSearch.pw.tsx_mobile_base-view-mobile-1.png b/src/features/address-metadata/pages/tag-search/__screenshots__/TagSearch.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index ea41795db38..00000000000 Binary files a/src/features/address-metadata/pages/tag-search/__screenshots__/TagSearch.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/address-metadata/pages/tag-submition/TagSubmitionForm.tsx b/src/features/address-metadata/pages/tag-submition/TagSubmitionForm.tsx index 874be8b175b..06300ee7b22 100644 --- a/src/features/address-metadata/pages/tag-submition/TagSubmitionForm.tsx +++ b/src/features/address-metadata/pages/tag-submition/TagSubmitionForm.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, Grid, GridItem } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { SubmitHandler } from 'react-hook-form'; import { useForm, FormProvider } from 'react-hook-form'; @@ -18,6 +17,7 @@ import useReCaptcha from 'src/services/re-captcha/useReCaptcha'; import getErrorObj from 'src/shared/errors/get-error-obj'; import getErrorObjPayload from 'src/shared/errors/get-error-obj-payload'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { useRouter } from 'src/shared/router/useRouter'; import { Button } from 'src/toolkit/chakra/button'; import { Heading } from 'src/toolkit/chakra/heading'; @@ -55,7 +55,7 @@ const TagSubmitionForm = ({ config, userInfo, onSubmitResult }: Props) => { router.query.companyName || router.query.companyWebsite ) { - router.replace({ pathname: '/public-tags/submit' }, undefined, { shallow: true }); + router.replace({ pathname: '/public-tags/submit' }, { shallow: true }); } }, [ router ]); diff --git a/src/features/address-metadata/pages/tag-submition/TagSubmitionResult.tsx b/src/features/address-metadata/pages/tag-submition/TagSubmitionResult.tsx index bf010aeaee2..6c17314efc4 100644 --- a/src/features/address-metadata/pages/tag-submition/TagSubmitionResult.tsx +++ b/src/features/address-metadata/pages/tag-submition/TagSubmitionResult.tsx @@ -2,11 +2,12 @@ import { Flex, Grid, GridItem } from '@chakra-ui/react'; import { pickBy } from 'es-toolkit'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { FormSubmitResult } from './types'; +import { route } from 'src/shared/router/routes'; + import { Alert } from 'src/toolkit/chakra/alert'; import { Button } from 'src/toolkit/chakra/button'; import { Heading } from 'src/toolkit/chakra/heading'; diff --git a/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionForm.pw.tsx_default_base-view-mobile-1.png b/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionForm.pw.tsx_default_base-view-mobile-1.png index bc57228dc34..41adcebacca 100644 Binary files a/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionForm.pw.tsx_default_base-view-mobile-1.png and b/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionForm.pw.tsx_default_base-view-mobile-1.png differ diff --git a/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionForm.pw.tsx_mobile_base-view-mobile-1.png b/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionForm.pw.tsx_mobile_base-view-mobile-1.png index 8c5a1a55c3c..bc62143a652 100644 Binary files a/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionForm.pw.tsx_mobile_base-view-mobile-1.png and b/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionForm.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionResult.pw.tsx_mobile_all-success-result-view-mobile-1.png b/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionResult.pw.tsx_mobile_all-success-result-view-mobile-1.png index 6b2c6e4e7d9..42257625790 100644 Binary files a/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionResult.pw.tsx_mobile_all-success-result-view-mobile-1.png and b/src/features/address-metadata/pages/tag-submition/__screenshots__/TagSubmitionResult.pw.tsx_mobile_all-success-result-view-mobile-1.png differ diff --git a/src/features/address-metadata/pages/tag-submition/result/TagSubmitionResultWithErrors.tsx b/src/features/address-metadata/pages/tag-submition/result/TagSubmitionResultWithErrors.tsx index fd36d7b3859..a923852f9d7 100644 --- a/src/features/address-metadata/pages/tag-submition/result/TagSubmitionResultWithErrors.tsx +++ b/src/features/address-metadata/pages/tag-submition/result/TagSubmitionResultWithErrors.tsx @@ -2,7 +2,6 @@ import { Box, Flex, Grid, GridItem } from '@chakra-ui/react'; import { pickBy } from 'es-toolkit'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { FormSubmitResultGrouped } from '../types'; @@ -10,6 +9,7 @@ import type { FormSubmitResultGrouped } from '../types'; import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; import { Button } from 'src/toolkit/chakra/button'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/features/address-metadata/pages/tag-submition/utils.ts b/src/features/address-metadata/pages/tag-submition/utils.ts index 846a454ac0e..e0d2e86f511 100644 --- a/src/features/address-metadata/pages/tag-submition/utils.ts +++ b/src/features/address-metadata/pages/tag-submition/utils.ts @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { pickBy, isEqual } from 'es-toolkit'; -import type { Route } from 'nextjs-routes'; import type { FormFieldTag, FormFields, FormSubmitResult, FormSubmitResultGrouped, FormSubmitResultItemGrouped, SubmitRequestBody } from './types'; import type { UserInfo } from 'src/features/account/types/api'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import type { Route } from 'src/shared/router/routes'; export function convertFormDataToRequestsBody(data: FormFields): Array<SubmitRequestBody> { const result: Array<SubmitRequestBody> = []; diff --git a/src/features/address-metadata/types/api.ts b/src/features/address-metadata/types/api.ts index 7c94d86db57..64059638545 100644 --- a/src/features/address-metadata/types/api.ts +++ b/src/features/address-metadata/types/api.ts @@ -9,7 +9,7 @@ export interface AddressMetadataInfo { }>; } -export type AddressMetadataTagType = 'name' | 'generic' | 'classifier' | 'information' | 'note' | 'protocol'; +export type AddressMetadataTagType = 'name' | 'generic' | 'classifier' | 'information' | 'note' | 'protocol' | 'service'; // Response model from Metadata microservice API export interface AddressMetadataTag { @@ -43,6 +43,7 @@ export interface AddressMetadataTagApi extends Omit<AddressMetadataTag, 'meta'> alertTextColor?: string; alertStatus?: string; cexDeposit?: string; + hidden?: string; } | null; } diff --git a/src/features/address-metadata/utils/build-app-action-url.spec.ts b/src/features/address-metadata/utils/build-app-action-url.spec.ts new file mode 100644 index 00000000000..6da859566a1 --- /dev/null +++ b/src/features/address-metadata/utils/build-app-action-url.spec.ts @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { buildAppActionUrl } from './build-app-action-url'; + +const ADDRESS = '0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9'; +const TX_HASH = '0xabc'; +const placeholders = { address: ADDRESS, chainId: '1', txHash: TX_HASH }; + +describe('buildAppActionUrl', () => { + it('substitutes every placeholder, lowercasing the address', () => { + const result = buildAppActionUrl('https://example.com/{chainId}/{address}?token={address}&tx={txHash}', placeholders, 'Token'); + expect(result).toBe( + `https://example.com/1/${ ADDRESS.toLowerCase() }?token=${ ADDRESS.toLowerCase() }&tx=${ TX_HASH }&utm_source=blockscout&utm_medium=token`, + ); + }); + + it('appends utm params, with the medium depending on the source', () => { + expect(buildAppActionUrl('https://example.com/swap', placeholders, 'NFT collection')) + .toBe('https://example.com/swap?utm_source=blockscout&utm_medium=token'); + expect(buildAppActionUrl('https://example.com/swap', placeholders, 'NFT item')) + .toBe('https://example.com/swap?utm_source=blockscout&utm_medium=token'); + expect(buildAppActionUrl('https://example.com/swap', placeholders, 'Txn')) + .toBe('https://example.com/swap?utm_source=blockscout&utm_medium=tx'); + }); + + it('replaces missing placeholder values with an empty string', () => { + const result = buildAppActionUrl( + 'https://example.com/?a={address}&c={chainId}&t={txHash}', + { address: undefined, chainId: undefined, txHash: undefined }, + 'Token', + ); + expect(result).toBe('https://example.com/?a=&c=&t=&utm_source=blockscout&utm_medium=token'); + }); + + it('returns undefined for a malformed template', () => { + expect(buildAppActionUrl('not a url', placeholders, 'Token')).toBeUndefined(); + }); +}); diff --git a/src/features/address-metadata/utils/build-app-action-url.ts b/src/features/address-metadata/utils/build-app-action-url.ts new file mode 100644 index 00000000000..3d137b3612e --- /dev/null +++ b/src/features/address-metadata/utils/build-app-action-url.ts @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +export type AppActionSource = 'Token' | 'NFT collection' | 'NFT item' | 'Txn'; + +interface Placeholders { + readonly address: string | undefined; + readonly chainId: string | undefined; + readonly txHash: string | undefined; +} + +const UTM_MEDIUM: Record<AppActionSource, string> = { + Token: 'token', + 'NFT collection': 'token', + 'NFT item': 'token', + Txn: 'tx', +}; + +export function buildAppActionUrl(template: string, placeholders: Placeholders, source: AppActionSource): string | undefined { + const substituted = template + .replaceAll('{address}', placeholders.address?.toLowerCase() ?? '') + .replaceAll('{chainId}', placeholders.chainId ?? '') + .replaceAll('{txHash}', placeholders.txHash ?? ''); + + try { + const url = new URL(substituted); + url.searchParams.set('utm_source', 'blockscout'); + url.searchParams.set('utm_medium', UTM_MEDIUM[source]); + return url.toString(); + } catch { + return undefined; + } +} diff --git a/src/features/address-metadata/utils/get-app-action-data.spec.ts b/src/features/address-metadata/utils/get-app-action-data.spec.ts new file mode 100644 index 00000000000..2f4de2ceab8 --- /dev/null +++ b/src/features/address-metadata/utils/get-app-action-data.spec.ts @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { hiddenProtocolTagWithMeta, nameTag, protocolTag, protocolTagWithMeta } from 'src/features/address-metadata/mocks/tags'; + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import { getAppActionData } from './get-app-action-data'; + +const appIdOnlyTag = { ...protocolTagWithMeta, meta: { ...protocolTagWithMeta.meta, appMarketplaceURL: undefined } }; +const styledProtocolTag = { ...protocolTag, meta: { textColor: '#FFFFFF' } }; + +describe('getAppActionData', () => { + it('takes the first protocol tag that carries an app action, skipping protocol tags without one', () => { + expect(getAppActionData([ nameTag, protocolTag, styledProtocolTag, hiddenProtocolTagWithMeta ])).toBe(hiddenProtocolTagWithMeta.meta); + }); + + it('ignores an app action on a non-protocol tag', () => { + expect(getAppActionData([ { ...hiddenProtocolTagWithMeta, tagType: 'generic' } ])).toBeNull(); + }); + + it('is null when no tag carries an app action', () => { + expect(getAppActionData([ nameTag, protocolTag, styledProtocolTag ])).toBeNull(); + expect(getAppActionData(undefined)).toBeNull(); + }); + + it('treats an app id as an app action only when the marketplace is enabled', async() => { + await withEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_ENABLED', 'true' ] ], async() => { + const { getAppActionData } = await import('./get-app-action-data'); + expect(getAppActionData([ appIdOnlyTag ])).toBe(appIdOnlyTag.meta); + }); + + await withEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_ENABLED', 'false' ] ], async() => { + const { getAppActionData } = await import('./get-app-action-data'); + expect(getAppActionData([ appIdOnlyTag ])).toBeNull(); + }); + }); +}); diff --git a/src/features/address-metadata/utils/get-app-action-data.ts b/src/features/address-metadata/utils/get-app-action-data.ts new file mode 100644 index 00000000000..d2a80a03f80 --- /dev/null +++ b/src/features/address-metadata/utils/get-app-action-data.ts @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { AddressMetadataTagFormatted } from 'src/features/address-metadata/types/client'; + +import config from 'src/config'; + +export type AppActionData = NonNullable<AddressMetadataTagFormatted['meta']>; + +export function getAppActionData(tags: Array<AddressMetadataTagFormatted> | undefined): AppActionData | null { + const tag = tags?.find(({ tagType, meta }) => + tagType === 'protocol' && (meta?.appMarketplaceURL || (config.features.marketplace.isEnabled && meta?.appID)), + ); + return tag?.meta ?? null; +} diff --git a/src/features/address-metadata/utils/get-visible-protocol-tags.spec.ts b/src/features/address-metadata/utils/get-visible-protocol-tags.spec.ts new file mode 100644 index 00000000000..cc64af755e9 --- /dev/null +++ b/src/features/address-metadata/utils/get-visible-protocol-tags.spec.ts @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { hiddenProtocolTagWithMeta, nameTag, protocolTag, protocolTagWithMeta } from 'src/features/address-metadata/mocks/tags'; + +import { describe, expect, it } from 'vitest'; + +import { getVisibleProtocolTags } from './get-visible-protocol-tags'; + +describe('getVisibleProtocolTags', () => { + it('keeps the protocol tags that are not hidden, in order', () => { + expect(getVisibleProtocolTags([ hiddenProtocolTagWithMeta, nameTag, protocolTagWithMeta, protocolTag ])) + .toEqual([ protocolTagWithMeta, protocolTag ]); + }); + + it('is empty when there is no visible protocol tag', () => { + expect(getVisibleProtocolTags([ hiddenProtocolTagWithMeta, nameTag ])).toEqual([]); + expect(getVisibleProtocolTags(undefined)).toEqual([]); + }); +}); diff --git a/src/features/address-metadata/utils/get-visible-protocol-tags.ts b/src/features/address-metadata/utils/get-visible-protocol-tags.ts new file mode 100644 index 00000000000..d9f677fef83 --- /dev/null +++ b/src/features/address-metadata/utils/get-visible-protocol-tags.ts @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { AddressMetadataTagType } from 'src/features/address-metadata/types/api'; + +import { isHiddenTag } from './is-hidden-tag'; + +interface ProtocolTagCandidate { + readonly tagType: AddressMetadataTagType; + readonly meta?: { readonly hidden?: unknown } | null; +} + +export function getVisibleProtocolTags<T extends ProtocolTagCandidate>(tags: ReadonlyArray<T> | undefined): Array<T> { + return tags?.filter((tag) => tag.tagType === 'protocol' && !isHiddenTag(tag)) ?? []; +} diff --git a/src/features/address-metadata/utils/is-hidden-tag.spec.ts b/src/features/address-metadata/utils/is-hidden-tag.spec.ts new file mode 100644 index 00000000000..dceba63693a --- /dev/null +++ b/src/features/address-metadata/utils/is-hidden-tag.spec.ts @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { isHiddenTag } from './is-hidden-tag'; + +describe('isHiddenTag', () => { + it('is true only for the exact string "true"', () => { + expect(isHiddenTag({ meta: { hidden: 'true' } })).toBe(true); + expect(isHiddenTag({ meta: { hidden: 'false' } })).toBe(false); + expect(isHiddenTag({ meta: { hidden: true } })).toBe(false); + expect(isHiddenTag({ meta: { hidden: 'TRUE' } })).toBe(false); + }); + + it('is false when meta is absent, null or lacks the field', () => { + expect(isHiddenTag({})).toBe(false); + expect(isHiddenTag({ meta: null })).toBe(false); + expect(isHiddenTag({ meta: {} })).toBe(false); + }); + + it('is true for every tag of the service type, whatever its meta', () => { + expect(isHiddenTag({ tagType: 'service' })).toBe(true); + expect(isHiddenTag({ tagType: 'service', meta: { hidden: 'false' } })).toBe(true); + expect(isHiddenTag({ tagType: 'protocol', meta: null })).toBe(false); + }); +}); diff --git a/src/features/address-metadata/utils/is-hidden-tag.ts b/src/features/address-metadata/utils/is-hidden-tag.ts new file mode 100644 index 00000000000..0ca224187db --- /dev/null +++ b/src/features/address-metadata/utils/is-hidden-tag.ts @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { MetadataTagType } from 'src/features/address-metadata/components/tag/types'; +import type { AddressMetadataTagType } from 'src/features/address-metadata/types/api'; + +export const SERVICE_TAG_TYPE = 'service' satisfies AddressMetadataTagType; + +interface TagWithMeta { + readonly tagType?: MetadataTagType; + readonly meta?: { readonly hidden?: unknown } | null; +} + +export function isHiddenTag(tag: TagWithMeta): boolean { + return tag.tagType === SERVICE_TAG_TYPE || tag.meta?.hidden === 'true'; +} diff --git a/src/features/address-metadata/utils/parse-meta-payload.spec.ts b/src/features/address-metadata/utils/parse-meta-payload.spec.ts new file mode 100644 index 00000000000..1364753535d --- /dev/null +++ b/src/features/address-metadata/utils/parse-meta-payload.spec.ts @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import parseMetaPayload from './parse-meta-payload'; + +describe('parseMetaPayload', () => { + it('keeps known string fields, including the hidden flag', () => { + const meta = JSON.stringify({ + appActionButtonText: 'Buy', + appMarketplaceURL: 'https://example.com/{address}', + bgColor: '#000', + hidden: 'true', + }); + + expect(parseMetaPayload(meta)).toEqual({ + appActionButtonText: 'Buy', + appMarketplaceURL: 'https://example.com/{address}', + bgColor: '#000', + hidden: 'true', + }); + }); + + it('drops unknown fields and known fields with non-string values', () => { + const meta = JSON.stringify({ tagUrl: 'https://example.com', hidden: true, projectName: 'Duck', verifiedDomains: [ 'a' ] }); + + expect(parseMetaPayload(meta)).toEqual({ tagUrl: 'https://example.com' }); + }); + + it('returns an empty object for an empty JSON object', () => { + expect(parseMetaPayload('{}')).toEqual({}); + }); + + it('returns null for null, invalid JSON, or a non-object payload', () => { + expect(parseMetaPayload(null)).toBeNull(); + expect(parseMetaPayload('not json')).toBeNull(); + expect(parseMetaPayload('"string"')).toBeNull(); + expect(parseMetaPayload('[]')).toBeNull(); + expect(parseMetaPayload('null')).toBeNull(); + }); +}); diff --git a/src/features/address-metadata/utils/parse-meta-payload.ts b/src/features/address-metadata/utils/parse-meta-payload.ts index b8a8d2fa551..6b5a4407213 100644 --- a/src/features/address-metadata/utils/parse-meta-payload.ts +++ b/src/features/address-metadata/utils/parse-meta-payload.ts @@ -36,6 +36,7 @@ export default function parseMetaPayload(meta: AddressMetadataTag['meta']): Addr 'alertTextColor', 'alertStatus', 'cexDeposit', + 'hidden', ]; for (const stringField of stringFields) { diff --git a/src/features/address-profile-api/hooks/useAddressProfileApiQuery.tsx b/src/features/address-profile-api/hooks/useAddressProfileApiQuery.ts similarity index 100% rename from src/features/address-profile-api/hooks/useAddressProfileApiQuery.tsx rename to src/features/address-profile-api/hooks/useAddressProfileApiQuery.ts diff --git a/src/features/ads/banner/components/AdbutlerBanner.spec.tsx b/src/features/ads/banner/components/AdbutlerBanner.spec.tsx new file mode 100644 index 00000000000..e21ec25ffe9 --- /dev/null +++ b/src/features/ads/banner/components/AdbutlerBanner.spec.tsx @@ -0,0 +1,75 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render } from 'vitest/lib'; +import withEnvs from 'vitest/utils/mockEnvs'; + +// jsdom under vitest executes inline scripts; the real AdButler loader and placement snippets are not under test here +vi.mock('next/script', () => ({ 'default': () => null })); + +const ADBUTLER_ENVS: Array<[string, string]> = [ + [ 'NEXT_PUBLIC_AD_BANNER_PROVIDER', 'adbutler' ], + [ 'NEXT_PUBLIC_AD_ADBUTLER_CONFIG_DESKTOP', '{"id":"123","width":"728","height":"90"}' ], + [ 'NEXT_PUBLIC_AD_ADBUTLER_CONFIG_MOBILE', '{"id":"456","width":"320","height":"100"}' ], +]; + +interface Placement { + handler: (opt: { place: number }) => void; + opt: { place: number }; +} + +function installAdButler() { + const register = vi.fn(); + window.AdButler = { ads: undefined as unknown as Array<unknown>, register }; + return { register, placements: () => window.AdButler.ads as Array<Placement> }; +} + +describe('AdbutlerBanner', () => { + afterEach(() => { + cleanup(); + window.AdButler = undefined as unknown as Window['AdButler']; + }); + + it('places one desktop ad per mount and registers it with the configured zone', async() => { + await withEnvs(ADBUTLER_ENVS, async() => { + const { register, placements } = installAdButler(); + const { 'default': AdbutlerBanner } = await import('./AdbutlerBanner'); + + const { rerender } = render(<AdbutlerBanner format="desktop"/>); + + expect(placements()).toHaveLength(1); + expect(document.getElementById('ad-banner')?.innerHTML).toBe('<div id="placement_123_0"></div>'); + + const [ { handler, opt } ] = placements(); + handler(opt); + expect(register).toHaveBeenCalledWith(182226, '123', [ '728', '90' ], 'placement_123_0', opt); + + rerender(<AdbutlerBanner format="desktop"/>); + expect(placements()).toHaveLength(1); + }); + }); + + it('places the mobile ad for the mobile format', async() => { + await withEnvs(ADBUTLER_ENVS, async() => { + const { placements } = installAdButler(); + const { 'default': AdbutlerBanner } = await import('./AdbutlerBanner'); + + render(<AdbutlerBanner format="mobile"/>); + + expect(placements()).toHaveLength(1); + expect(document.getElementById('ad-banner')?.innerHTML).toBe('<div id="placement_456_0"></div>'); + }); + }); + + it('renders nothing when the adbutler provider is not configured', async() => { + await withEnvs([ [ 'NEXT_PUBLIC_AD_BANNER_PROVIDER', 'slise' ] ], async() => { + const { 'default': AdbutlerBanner } = await import('./AdbutlerBanner'); + + render(<AdbutlerBanner/>); + + expect(document.getElementById('ad-banner')).toBeNull(); + }); + }); +}); diff --git a/src/features/ads/banner/components/AdbutlerBanner.tsx b/src/features/ads/banner/components/AdbutlerBanner.tsx index 09589de5616..d27290f367c 100644 --- a/src/features/ads/banner/components/AdbutlerBanner.tsx +++ b/src/features/ads/banner/components/AdbutlerBanner.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex, chakra } from '@chakra-ui/react'; -import { useRouter } from 'next/navigation'; import Script from 'next/script'; import React from 'react'; @@ -23,8 +22,6 @@ import { const feature = config.features.adsBanner; const AdbutlerBanner = ({ className, format = 'responsive' }: BannerProps) => { - const router = useRouter(); - const isMobileViewport = useIsMobile(); const isMobile = format === 'mobile' || (format === 'responsive' && isMobileViewport); @@ -58,7 +55,7 @@ const AdbutlerBanner = ({ className, format = 'responsive' }: BannerProps) => { ); }, opt: { place: plc++, keywords: abkw, domain: 'servedbyadbutler.com', click: 'CLICK_MACRO_PLACEHOLDER' } }); } - }, [ router, isMobile ]); + }, [ isMobile ]); if (!('adButler' in feature)) { return null; diff --git a/src/features/ads/banner/components/SpecifyBanner.spec.tsx b/src/features/ads/banner/components/SpecifyBanner.spec.tsx new file mode 100644 index 00000000000..3f630daff22 --- /dev/null +++ b/src/features/ads/banner/components/SpecifyBanner.spec.tsx @@ -0,0 +1,136 @@ +// @vitest-environment jsdom +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { SpecifyAd } from '@specify-sh/publisher-sdk'; +import React from 'react'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, render, screen } from 'vitest/lib'; +import flushPromises from 'vitest/utils/flushPromises'; + +import SpecifyBanner from './SpecifyBanner'; + +interface Deferred { + resolve: (ad: SpecifyAd | null) => void; +} + +const serves: Array<Deferred> = []; +const identityListeners: Array<() => void> = []; +const identified: Array<unknown> = []; + +vi.mock('@specify-sh/publisher-sdk', () => ({ + ImageFormat: { LONG_BANNER: 'LONG_BANNER', SHORT_BANNER: 'SHORT_BANNER' }, + 'default': class Specify { + setCookieConsent() {} + identify(address: unknown) { + identified.push(address); + } + onIdentityChange(listener: () => void) { + identityListeners.push(listener); + return () => {}; + } + serve() { + return new Promise<SpecifyAd | null>((resolve) => { + serves.push({ resolve }); + }); + } + }, +})); + +const AD: SpecifyAd = { + adId: 'ad-1', + campaignId: 'campaign-1', + communityLogo: '', + communityName: 'Community', + content: '', + ctaLabel: 'Open', + ctaUrl: 'https://example.com', + headline: 'Hello', + imageFormat: 'LONG_BANNER', + imageUrl: 'https://content.specify.sh/ad.png', +}; + +const resolveServe = async(index: number, ad: SpecifyAd | null) => { + await act(async() => { + serves[index].resolve(ad); + await flushPromises(); + }); +}; + +const fireIdentityChange = async() => { + await act(async() => { + identityListeners.forEach((listener) => listener()); + await flushPromises(); + }); +}; + +describe('SpecifyBanner', () => { + beforeEach(() => { + serves.length = 0; + identityListeners.length = 0; + identified.length = 0; + }); + + afterEach(cleanup); + + it('registers the connected wallet with Specify', async() => { + render(<SpecifyBanner address="0x1111111111111111111111111111111111111111" isLoading={ false } onEmpty={ vi.fn() } format="desktop"/>); + + await resolveServe(0, null); + + expect(identified).toEqual([ '0x1111111111111111111111111111111111111111' ]); + }); + + it('registers nothing without a wallet', async() => { + render(<SpecifyBanner address={ undefined } isLoading={ false } onEmpty={ vi.fn() } format="desktop"/>); + + await resolveServe(0, null); + + expect(identified).toEqual([]); + }); + + it('shows the served ad', async() => { + const onEmpty = vi.fn(); + render(<SpecifyBanner address={ undefined } isLoading={ false } onEmpty={ onEmpty } format="desktop"/>); + + await resolveServe(0, AD); + + expect(screen.getByAltText('Hello').getAttribute('src')).toBe(AD.imageUrl); + expect(onEmpty).not.toHaveBeenCalled(); + }); + + it('hands the slot over when the only request misses', async() => { + const onEmpty = vi.fn(); + render(<SpecifyBanner address={ undefined } isLoading={ false } onEmpty={ onEmpty } format="desktop"/>); + + await resolveServe(0, null); + + expect(onEmpty).toHaveBeenCalledTimes(1); + }); + + it('keeps the slot while an identity retry is still in flight after an anonymous miss', async() => { + const onEmpty = vi.fn(); + render(<SpecifyBanner address={ undefined } isLoading={ false } onEmpty={ onEmpty } format="desktop"/>); + + await fireIdentityChange(); + expect(serves).toHaveLength(2); + + await resolveServe(0, null); + expect(onEmpty).not.toHaveBeenCalled(); + + await resolveServe(1, AD); + expect(screen.getByAltText('Hello')).toBeDefined(); + expect(onEmpty).not.toHaveBeenCalled(); + }); + + it('does not replace a filled slot when the identity improves', async() => { + const onEmpty = vi.fn(); + render(<SpecifyBanner address={ undefined } isLoading={ false } onEmpty={ onEmpty } format="desktop"/>); + + await resolveServe(0, AD); + await fireIdentityChange(); + + expect(serves).toHaveLength(1); + expect(screen.getByAltText('Hello')).toBeDefined(); + }); +}); diff --git a/src/features/ads/banner/components/SpecifyBanner.tsx b/src/features/ads/banner/components/SpecifyBanner.tsx index 5cc09a00396..1b3d133542d 100644 --- a/src/features/ads/banner/components/SpecifyBanner.tsx +++ b/src/features/ads/banner/components/SpecifyBanner.tsx @@ -1,8 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, chakra } from '@chakra-ui/react'; -import type { SpecifyAd } from '@specify-sh/sdk'; -import Specify, { ImageFormat } from '@specify-sh/sdk'; +import type { SpecifyAd } from '@specify-sh/publisher-sdk'; +import { ImageFormat } from '@specify-sh/publisher-sdk'; import React from 'react'; import type { BannerProps } from '../types/client'; @@ -17,8 +17,7 @@ import { MOBILE_BANNER_WIDTH, MOBILE_BANNER_HEIGHT, } from '../utils/consts'; - -const PUBLISHER_KEY = 'spk_uq51124ciii28vt00f8za4m5hibpuh'; +import { getSpecifyClient } from '../utils/specify-client'; type Props = BannerProps & { address: `0x${ string }` | undefined; @@ -33,32 +32,57 @@ const SpecifyBanner = ({ className, format = 'responsive', address, onEmpty, isL const [ isFetching, setIsFetching ] = React.useState(true); React.useEffect(() => { - if (!isLoading) { - const specify = new Specify({ - publisherKey: PUBLISHER_KEY, - cacheMostRecentAddress: true, - }); - const fetchContent = async() => { - try { - const content = await specify.serve( - address ? [ address as `0x${ string }` ] : null, - { imageFormat: isMobile ? ImageFormat.SHORT_BANNER : ImageFormat.LONG_BANNER }, - ); - if (content?.imageUrl) { - setAd(content); - } else { - onEmpty(); - } - } catch (error) { + if (address) { + getSpecifyClient().identify(address); + } + }, [ address ]); + + React.useEffect(() => { + if (isLoading) { + return; + } + + let isStale = false; + let isFilled = false; + let inFlightCount = 0; + const specify = getSpecifyClient(); + + const serveAd = async() => { + inFlightCount++; + try { + const content = await specify.serve(null, { + imageFormat: isMobile ? ImageFormat.SHORT_BANNER : ImageFormat.LONG_BANNER, + }); + if (isStale) { + return; + } + if (!isFilled && content?.imageUrl) { + isFilled = true; + setAd(content); + setIsFetching(false); + } + } catch {} finally { + inFlightCount--; + if (!isStale && !isFilled && inFlightCount === 0) { onEmpty(); - } finally { setIsFetching(false); } - }; + } + }; - fetchContent(); - } - }, [ address, isMobile, onEmpty, isLoading ]); + const unsubscribe = specify.onIdentityChange(() => { + if (!isStale && !isFilled) { + serveAd(); + } + }); + + serveAd(); + + return () => { + isStale = true; + unsubscribe(); + }; + }, [ isMobile, onEmpty, isLoading ]); const handleClick = React.useCallback(() => { window.open(ad?.ctaUrl, '_blank', 'noopener,noreferrer'); @@ -80,7 +104,7 @@ const SpecifyBanner = ({ className, format = 'responsive', address, onEmpty, isL ); } - if (!ad) return null; + if (!ad?.imageUrl) return null; return ( <Image diff --git a/src/features/ads/banner/utils/specify-client.ts b/src/features/ads/banner/utils/specify-client.ts new file mode 100644 index 00000000000..c018b4ff08b --- /dev/null +++ b/src/features/ads/banner/utils/specify-client.ts @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import Specify from '@specify-sh/publisher-sdk'; + +import config from 'src/config'; + +const PUBLISHER_KEY = 'spk_uq51124ciii28vt00f8za4m5hibpuh'; + +let client: Specify | undefined; + +export function getSpecifyClient(): Specify { + if (!client) { + client = new Specify({ publisherKey: PUBLISHER_KEY }); + client.setCookieConsent(config.services.usercentrics?.consent.specify ?? true); + } + + return client; +} diff --git a/src/features/ads/common/hooks/useAdblockDetect.tsx b/src/features/ads/common/hooks/useAdblockDetect.ts similarity index 100% rename from src/features/ads/common/hooks/useAdblockDetect.tsx rename to src/features/ads/common/hooks/useAdblockDetect.ts diff --git a/src/features/advanced-filter/components/ColumnsButton.tsx b/src/features/advanced-filter/components/ColumnsButton.tsx deleted file mode 100644 index 478943b0407..00000000000 --- a/src/features/advanced-filter/components/ColumnsButton.tsx +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { chakra } from '@chakra-ui/react'; -import React from 'react'; - -import type { ColumnsIds } from '../types/client'; - -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import { Button } from 'src/toolkit/chakra/button'; -import { Checkbox, CheckboxGroup } from 'src/toolkit/chakra/checkbox'; -import { PopoverBody, PopoverContent, PopoverRoot, PopoverTrigger } from 'src/toolkit/chakra/popover'; - -import { TABLE_COLUMNS } from '../utils/consts'; - -interface Props { - columns: Record<ColumnsIds, boolean>; - onChange: (val: Record<ColumnsIds, boolean>) => void; -} - -const ColumnsButton = ({ columns, onChange }: Props) => { - const handleValueChange = React.useCallback((value: Array<string>) => { - const newCols = value.reduce((acc, key) => { - acc[key as ColumnsIds] = true; - return acc; - }, {} as Record<ColumnsIds, boolean>); - onChange(newCols); - }, [ onChange ]); - - return ( - <PopoverRoot> - <PopoverTrigger> - <Button - variant="dropdown" - size="sm" - px={{ base: 1, lg: 3 }} - > - <SpriteIcon name="columns" boxSize={ 5 } color="inherit"/> - <chakra.span hideBelow="lg">Columns</chakra.span> - </Button> - </PopoverTrigger> - <PopoverContent> - <PopoverBody px={ 4 } py={ 6 } display="flex" flexDir="column" rowGap={ 5 }> - <CheckboxGroup - defaultValue={ Object.keys(columns).filter((key) => columns[key as ColumnsIds]) } - onValueChange={ handleValueChange } - display="grid" - gridTemplateColumns="160px 160px" - gap={ 3 } - > - { TABLE_COLUMNS.map(col => ( - <Checkbox - key={ col.id } - value={ col.id } - size="md" - > - { col.id === 'or_and' ? 'And/Or' : col.name } - </Checkbox> - )) } - </CheckboxGroup> - </PopoverBody> - </PopoverContent> - </PopoverRoot> - ); -}; - -export default ColumnsButton; diff --git a/src/features/advanced-filter/components/FilterByColumn.pw.tsx b/src/features/advanced-filter/components/FilterByColumn.pw.tsx index b33356a2c99..cbb58c1edf3 100644 --- a/src/features/advanced-filter/components/FilterByColumn.pw.tsx +++ b/src/features/advanced-filter/components/FilterByColumn.pw.tsx @@ -3,6 +3,8 @@ import React from 'react'; import type { ColumnsIds } from '../types/client'; +import * as statsMock from 'src/slices/chain/stats/mocks'; + import { test, expect } from 'playwright/lib'; import FilterByColumn from './FilterByColumn'; @@ -42,8 +44,9 @@ for (const column of columns) { await mockApiResponse('core:tokens', { items: [], next_page_params: null, - }); + }, { queryParams: { limit: '7' } }); await mockApiResponse('core:advanced_filter_methods', [], { queryParams: { q: '' } }); + await mockApiResponse('core:stats', { ...statsMock.base, coin_image: null }); await render( <FilterByColumn filters={ filters } diff --git a/src/features/advanced-filter/components/FilterByColumn.tsx b/src/features/advanced-filter/components/FilterByColumn.tsx index ac927540d2d..afb8d67e607 100644 --- a/src/features/advanced-filter/components/FilterByColumn.tsx +++ b/src/features/advanced-filter/components/FilterByColumn.tsx @@ -6,7 +6,7 @@ import type { AdvancedFilterParams } from '../types/api'; import type { ColumnsIds } from '../types/client'; import type { schemas } from '@blockscout/api-types'; -import TableColumnFilterWrapper from 'src/shared/filters/TableColumnFilterWrapper'; +import ColumnFilter from 'src/shared/filters/ColumnFilter'; import { NATIVE_TOKEN } from '../utils/consts'; import type { AddressFilterMode } from './filters/AddressFilter'; @@ -34,52 +34,50 @@ const FilterByColumn = ({ column, filters, columnName, handleFilterChange, searc case 'type': { const value = filters.transaction_types; return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Type" isLoading={ isLoading } selected={ Boolean(value && value.length) } > <TypeFilter { ...commonProps } value={ value }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } case 'method': { const value = filters.methods?.map(m => ({ name: searchParams?.methods[m] || m, method_id: m })); return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Method" isLoading={ isLoading } selected={ Boolean(value && value.length) } - w="350px" > <MethodFilter { ...commonProps } value={ value }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } case 'age': { const value = { age: filters.age || '' as const, from: filters.age_from || '', to: filters.age_to || '' }; return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Age" isLoading={ isLoading } selected={ Boolean(value.from || value.to || value.age) } - w="382px" > <AgeFilter { ...commonProps } value={ value }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } case 'or_and': { return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="And/Or" isLoading={ isLoading } selected - w="106px" + contentProps={{ w: '106px' }} value={ filters.address_relation === 'and' ? 'AND' : 'OR' } > <AddressRelationFilter { ...commonProps } value={ filters.address_relation }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } case 'from': { @@ -88,14 +86,14 @@ const FilterByColumn = ({ column, filters, columnName, handleFilterChange, searc const value = (valueInclude || []).concat(valueExclude || []); return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Address from" isLoading={ isLoading } selected={ Boolean(value.length) } - w="480px" + contentProps={{ w: '480px' }} > <AddressFilter { ...commonProps } type="from" value={ value }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } @@ -105,27 +103,26 @@ const FilterByColumn = ({ column, filters, columnName, handleFilterChange, searc const value = (valueInclude || []).concat(valueExclude || []); return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Address to" isLoading={ isLoading } selected={ Boolean(value.length) } - w="480px" + contentProps={{ w: '480px' }} > <AddressFilter { ...commonProps } type="to" value={ value }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } case 'amount': { const value = { from: filters.amount_from, to: filters.amount_to }; return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Amount" isLoading={ isLoading } selected={ Boolean(value.from || value.to) } - w="382px" > <AmountFilter { ...commonProps } value={ value }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } case 'asset': { @@ -145,14 +142,13 @@ const FilterByColumn = ({ column, filters, columnName, handleFilterChange, searc value.unshift({ token: NATIVE_TOKEN, mode: 'exclude' }); } return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Asset" isLoading={ isLoading } selected={ Boolean(value.length) } - w="382px" > <AssetFilter { ...commonProps } value={ value }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } default: { diff --git a/src/features/advanced-filter/components/ItemByColumn.spec.tsx b/src/features/advanced-filter/components/ItemByColumn.spec.tsx new file mode 100644 index 00000000000..9d9030d3fce --- /dev/null +++ b/src/features/advanced-filter/components/ItemByColumn.spec.tsx @@ -0,0 +1,69 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import { tokenInfoERC20a } from 'src/slices/token/mocks/info'; + +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from 'vitest/lib'; + +import { baseResponse } from '../mocks'; +import ItemByColumn from './ItemByColumn'; + +const coinTransfer = baseResponse.items[0]; +const tokenTransfer = { ...coinTransfer, token: tokenInfoERC20a }; +const contractCreation = { ...coinTransfer, to: null, created_contract: coinTransfer.from }; +const tokenTransferTooltip = 'View all token transfers for this address and token'; + +const openAddressTooltip = async() => { + const getAddressLink = () => screen.getAllByRole('link').find(link => link.getAttribute('href')?.startsWith('/address/')) as HTMLElement; + const getTextElement = () => getAddressLink().querySelector('span') as HTMLElement; + const initialTextElement = getTextElement(); + + fireEvent.pointerEnter(initialTextElement, { pointerType: 'mouse' }); + // jsdom does not preserve :hover when the lazy tooltip remounts its trigger. + await waitFor(() => expect(initialTextElement.isConnected).toBe(false)); + fireEvent.pointerEnter(getTextElement(), { pointerType: 'mouse' }); +}; + +describe('address entity tooltips', () => { + afterEach(() => cleanup()); + + it('does not render the token-transfer tooltip for a coin transfer "from" column', async() => { + render(<ItemByColumn item={ coinTransfer } column="from"/>); + await openAddressTooltip(); + await screen.findByText(coinTransfer.from?.hash ?? ''); + + expect(screen.queryByText(tokenTransferTooltip)).toBeNull(); + }); + + it('renders the token-transfer tooltip for a token transfer "from" column', async() => { + render(<ItemByColumn item={ tokenTransfer } column="from"/>); + await openAddressTooltip(); + + expect(await screen.findByText(tokenTransferTooltip)).toBeDefined(); + }); + + it('does not render the token-transfer tooltip for a coin transfer "to" column', async() => { + render(<ItemByColumn item={ coinTransfer } column="to"/>); + await openAddressTooltip(); + await screen.findByText(coinTransfer.to?.hash ?? ''); + + expect(screen.queryByText(tokenTransferTooltip)).toBeNull(); + }); + + it('renders the token-transfer tooltip for a token transfer "to" column', async() => { + render(<ItemByColumn item={ tokenTransfer } column="to"/>); + await openAddressTooltip(); + + expect(await screen.findByText(tokenTransferTooltip)).toBeDefined(); + }); + + it('does not render the token-transfer tooltip when falling back to a created contract', async() => { + render(<ItemByColumn item={ contractCreation } column="to"/>); + await openAddressTooltip(); + await screen.findByText(coinTransfer.from?.hash ?? ''); + + expect(screen.queryByText(tokenTransferTooltip)).toBeNull(); + }); +}); diff --git a/src/features/advanced-filter/components/ItemByColumn.tsx b/src/features/advanced-filter/components/ItemByColumn.tsx index 2ea9a2d9283..f75f8196e33 100644 --- a/src/features/advanced-filter/components/ItemByColumn.tsx +++ b/src/features/advanced-filter/components/ItemByColumn.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import React from 'react'; import type { ColumnsIds } from '../types/client'; import type { schemas } from '@blockscout/api-types'; @@ -9,8 +8,11 @@ import type { ClusterChainConfig } from 'src/features/multichain/types/client'; import { isConfidentialTokenType } from 'src/slices/token/utils/token-types'; import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; +import AddressEntityWithTokenFilter from 'src/slices/address/components/entity/AddressEntityWithTokenFilter'; import AddressFromToIcon from 'src/slices/address/components/from-to/AddressFromToIcon'; +import { getTokenTransferUiMultiplier } from 'src/slices/token-transfer/utils/get-token-transfer-ui-multiplier'; import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; +import { formatUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; import TxEntity from 'src/slices/tx/components/entity/TxEntity'; import config from 'src/config'; @@ -31,6 +33,24 @@ type Props = { chainConfig?: ClusterChainConfig['app_config']; }; +type Address = NonNullable<Props['item']['from']>; + +const renderAddressEntity = (address: Address, item: Props['item'], isLoading?: boolean) => { + if (!item.token?.address_hash) { + return <AddressEntity address={ address } truncation="constant" isLoading={ isLoading }/>; + } + + return ( + <AddressEntityWithTokenFilter + address={ address } + truncation="constant" + isLoading={ isLoading } + tokenHash={ item.token.address_hash } + tokenSymbol={ item.token.symbol ?? undefined } + /> + ); +}; + const ItemByColumn = ({ item, column, isLoading, chainConfig }: Props) => { switch (column) { case 'tx_hash': @@ -49,7 +69,7 @@ const ItemByColumn = ({ item, column, isLoading, chainConfig }: Props) => { case 'from': return item.from ? ( <Flex w="100%"> - <AddressEntity address={ item.from } truncation="constant" isLoading={ isLoading }/> + { renderAddressEntity(item.from, item, isLoading) } </Flex> ) : null; case 'to': { @@ -59,7 +79,7 @@ const ItemByColumn = ({ item, column, isLoading, chainConfig }: Props) => { } return ( <Flex w="100%"> - <AddressEntity address={ address } truncation="constant" isLoading={ isLoading }/> + { renderAddressEntity(address, item, isLoading) } </Flex> ); } @@ -70,6 +90,10 @@ const ItemByColumn = ({ item, column, isLoading, chainConfig }: Props) => { type="unspecified" /> ); + case 'multiplier': { + const multiplier = getTokenTransferUiMultiplier(item, chainConfig); + return multiplier ? <Skeleton loading={ isLoading } color="text.secondary">{ formatUiMultiplier(multiplier) }</Skeleton> : null; + } case 'amount': { if (item.token?.type === 'ERC-721') { return <Skeleton loading={ isLoading }>1</Skeleton>; @@ -82,6 +106,7 @@ const ItemByColumn = ({ item, column, isLoading, chainConfig }: Props) => { <AssetValue amount={ item.total?.value } decimals={ item.total.decimals } + multiplier={ getTokenTransferUiMultiplier(item, chainConfig) } loading={ isLoading } /> ); diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_age-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_age-filter-dark-mode-1.png index 39645879cac..9afbde6ea1e 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_age-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_age-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_amount-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_amount-filter-dark-mode-1.png index d6e8566b7c8..30ae8fa78d7 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_amount-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_amount-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_asset-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_asset-filter-dark-mode-1.png index d671c57cc6d..a48dfa61242 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_asset-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_asset-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_from-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_from-filter-dark-mode-1.png index 2267c34def1..4fa0d1bbc43 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_from-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_from-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_method-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_method-filter-dark-mode-1.png index 9f7558cc10c..3a85d7e54cc 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_method-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_method-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_or-and-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_or-and-filter-dark-mode-1.png index 679cf76093b..0d62c9d8f1e 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_or-and-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_or-and-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_to-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_to-filter-dark-mode-1.png index 5b8aa426a78..99d9f9fbef4 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_to-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_to-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_type-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_type-filter-dark-mode-1.png index 0111957b14a..a454d3de45b 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_type-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_dark-color-mode_type-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_age-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_age-filter-dark-mode-1.png index f60ff432d1c..62bcc8529ca 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_age-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_age-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_amount-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_amount-filter-dark-mode-1.png index 7c5592a85f4..35aa168eef7 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_amount-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_amount-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_asset-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_asset-filter-dark-mode-1.png index 16a6b06d62c..0549788f679 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_asset-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_asset-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_from-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_from-filter-dark-mode-1.png index 22114ee4358..ec355202c4b 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_from-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_from-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_method-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_method-filter-dark-mode-1.png index 30fc3ce7267..1b2e1226afe 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_method-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_method-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_to-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_to-filter-dark-mode-1.png index fe1394300be..25bafd8cc44 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_to-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_to-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_type-filter-dark-mode-1.png b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_type-filter-dark-mode-1.png index 535a52bdb7e..ebbb059d7b9 100644 Binary files a/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_type-filter-dark-mode-1.png and b/src/features/advanced-filter/components/__screenshots__/FilterByColumn.pw.tsx_default_type-filter-dark-mode-1.png differ diff --git a/src/features/advanced-filter/components/filters/AddressFilter.tsx b/src/features/advanced-filter/components/filters/AddressFilter.tsx index 56e5c189bf9..1941127011a 100644 --- a/src/features/advanced-filter/components/filters/AddressFilter.tsx +++ b/src/features/advanced-filter/components/filters/AddressFilter.tsx @@ -7,7 +7,8 @@ import React from 'react'; import type { AdvancedFilterParams } from '../../types/api'; -import TableColumnFilter from 'src/shared/filters/TableColumnFilter'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; import { Field } from 'src/toolkit/chakra/field'; import { Input } from 'src/toolkit/chakra/input'; @@ -105,8 +106,9 @@ const AddressFilter = ({ type, value = [], handleFilterChange }: Props) => { const handleModeSelectChange = React.useCallback((index: number) => ({ value }: { value: Array<string> }) => { setCurrentValue(prev => { - prev[index] = { ...prev[index], mode: value[0] as AddressFilterMode }; - return [ ...prev ]; + const newVal = [ ...prev ]; + newVal[index] = { ...newVal[index], mode: value[0] as AddressFilterMode }; + return newVal; }); }, []); @@ -165,31 +167,33 @@ const AddressFilter = ({ type, value = [], handleFilterChange }: Props) => { const isTouched = !isEqual(currentValue.filter(i => i.address).map(addressFilterToKey).sort(), value.map(addressFilterToKey).sort()); return ( - <TableColumnFilter - title={ type === 'from' ? 'From address' : 'To address' } - isFilled={ Boolean(currentValue[0].address) } + <ColumnFilterContent isTouched={ isTouched && !hasErrors } onFilter={ onFilter } - onReset={ onReset } - hasReset > - <VStack gap={ 2 }> - { currentValue.map((item, index) => ( - <AddressFilterInput - key={ index } - address={ item.address } - mode={ item.mode } - isLast={ index === currentValue.length - 1 } - onModeChange={ handleModeSelectChange(index) } - onChange={ handleAddressChange(index) } - onBlur={ handleAddressBlur(index) } - onClear={ handleAddressClear(index) } - onAddFieldClick={ onAddFieldClick } - isInvalid={ Boolean(touched[index]) && Boolean(item.address) && !ADDRESS_REGEXP.test(item.address) } - /> - )) } - </VStack> - </TableColumnFilter> + <ColumnFilterContentSection + title={ type === 'from' ? 'From address' : 'To address' } + isFilled={ Boolean(currentValue[0].address) } + onReset={ onReset } + > + <VStack gap={ 2 }> + { currentValue.map((item, index) => ( + <AddressFilterInput + key={ index } + address={ item.address } + mode={ item.mode } + isLast={ index === currentValue.length - 1 } + onModeChange={ handleModeSelectChange(index) } + onChange={ handleAddressChange(index) } + onBlur={ handleAddressBlur(index) } + onClear={ handleAddressClear(index) } + onAddFieldClick={ onAddFieldClick } + isInvalid={ Boolean(touched[index]) && Boolean(item.address) && !ADDRESS_REGEXP.test(item.address) } + /> + )) } + </VStack> + </ColumnFilterContentSection> + </ColumnFilterContent> ); }; diff --git a/src/features/advanced-filter/components/filters/AmountFilter.tsx b/src/features/advanced-filter/components/filters/AmountFilter.tsx index d94362fa497..1c103bc691e 100644 --- a/src/features/advanced-filter/components/filters/AmountFilter.tsx +++ b/src/features/advanced-filter/components/filters/AmountFilter.tsx @@ -7,7 +7,8 @@ import React from 'react'; import type { AdvancedFilterParams } from '../../types/api'; -import TableColumnFilter from 'src/shared/filters/TableColumnFilter'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; import TagGroupSelect from 'src/shared/tags/select/TagGroupSelect'; import { Input } from 'src/toolkit/chakra/input'; @@ -77,29 +78,29 @@ const AmountFilter = ({ value = {}, handleFilterChange }: Props) => { }, [ handleFilterChange ]); return ( - <TableColumnFilter - title="Amount" - isFilled={ Boolean(currentValue.from || currentValue.to) } + <ColumnFilterContent isTouched={ !isEqual(currentValue, value) } onFilter={ onFilter } - onReset={ onReset } - hasReset > - <PopoverCloseTriggerWrapper> - <Flex gap={ 3 }> - <TagGroupSelect<string> - items={ PRESETS.map((preset) => ({ id: preset.value, title: preset.name })) } - onChange={ onPresetChange } - value={ (!currentValue.from || currentValue.from === '0') ? PRESETS.find(preset => preset.value === currentValue.to)?.value : undefined } - /> + <ColumnFilterContentSection title="Maximum amount" isFilled={ Boolean(currentValue.to) } onReset={ onReset }> + <PopoverCloseTriggerWrapper> + <Flex gap={ 3 }> + <TagGroupSelect<string> + items={ PRESETS.map((preset) => ({ id: preset.value, title: preset.name })) } + onChange={ onPresetChange } + value={ (!currentValue.from || currentValue.from === '0') ? PRESETS.find(preset => preset.value === currentValue.to)?.value : undefined } + /> + </Flex> + </PopoverCloseTriggerWrapper> + </ColumnFilterContentSection> + <ColumnFilterContentSection title="Amount range"> + <Flex alignItems="center"> + <Input value={ currentValue.from } onChange={ handleFromChange } placeholder="From" type="number" size="sm"/> + <Text mx={ 3 }>{ ndash }</Text> + <Input value={ currentValue.to } onChange={ handleToChange } placeholder="To" type="number" size="sm"/> </Flex> - </PopoverCloseTriggerWrapper> - <Flex mt={ 3 } alignItems="center"> - <Input value={ currentValue.from } onChange={ handleFromChange } placeholder="From" type="number" size="sm"/> - <Text mx={ 3 }>{ ndash }</Text> - <Input value={ currentValue.to } onChange={ handleToChange } placeholder="To" type="number" size="sm"/> - </Flex> - </TableColumnFilter> + </ColumnFilterContentSection> + </ColumnFilterContent> ); }; diff --git a/src/features/advanced-filter/components/filters/AssetFilter.tsx b/src/features/advanced-filter/components/filters/AssetFilter.tsx index 96d17f70dd5..0c1c59818ff 100644 --- a/src/features/advanced-filter/components/filters/AssetFilter.tsx +++ b/src/features/advanced-filter/components/filters/AssetFilter.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Flex, Text, Spinner, createListCollection } from '@chakra-ui/react'; +import { Flex, Text, Spinner, createListCollection, VStack } from '@chakra-ui/react'; import { isEqual } from 'es-toolkit'; import React from 'react'; @@ -12,7 +12,8 @@ import useApiQuery from 'src/api/hooks/useApiQuery'; import * as TokenEntity from 'src/slices/token/components/entity/TokenEntity'; import NativeTokenIcon from 'src/slices/token/components/icon/TokenIconNative'; -import TableColumnFilter from 'src/shared/filters/TableColumnFilter'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; import useDebounce from 'src/shared/hooks/useDebounce'; import { Checkbox, CheckboxGroup } from 'src/toolkit/chakra/checkbox'; @@ -94,41 +95,62 @@ const AssetFilter = ({ value = [], handleFilterChange }: Props) => { }, [ handleFilterChange, currentValue ]); return ( - <TableColumnFilter - title="Asset" - isFilled={ Boolean(currentValue.length) } + <ColumnFilterContent isTouched={ !isEqual(currentValue.map(i => JSON.stringify(i)).sort(), value.map(i => JSON.stringify(i)).sort()) } onFilter={ onFilter } - onReset={ onReset } - hasReset > - <FilterInput - size="sm" - onChange={ onSearchChange } - placeholder="Token name or symbol" - initialValue={ searchTerm } - /> - { !searchTerm && currentValue.map((item, index) => ( - <Flex key={ item.token.address_hash } alignItems="center"> - <Select - collection={ collection } - placeholder="Select mode" - defaultValue={ [ item.mode || 'include' ] } - onValueChange={ handleModeSelectChange(index) } - portalled={ false } - w="105px" - minW="105px" - mr={ 3 } - /> - <TokenEntity.default token={ item.token } noLink noCopy flexGrow={ 1 }/> - <ClearButton onClick={ handleRemove(index) }/> - </Flex> - )) } - { tokensQuery.isLoading && <Spinner display="block" mt={ 3 }/> } + <ColumnFilterContentSection title="Asset" isFilled={ Boolean(currentValue.length) } onReset={ onReset }> + <FilterInput + size="sm" + onChange={ onSearchChange } + placeholder="Token name or symbol" + initialValue={ searchTerm } + /> + { !searchTerm && currentValue.length > 0 && ( + <VStack gap={ 2 } alignItems="stretch"> + { currentValue.map((item, index) => ( + <Flex key={ item.token.address_hash } alignItems="center"> + <Select + collection={ collection } + placeholder="Select mode" + defaultValue={ [ item.mode || 'include' ] } + onValueChange={ handleModeSelectChange(index) } + portalled={ false } + w="105px" + minW="105px" + mr={ 3 } + /> + <TokenEntity.default token={ item.token } noLink noCopy flexGrow={ 1 }/> + <ClearButton onClick={ handleRemove(index) }/> + </Flex> + )) } + </VStack> + ) } + { tokensQuery.isLoading && <Spinner display="block"/> } + { searchTerm && tokensQuery.data && !tokensQuery.data?.items.length && <Text>No tokens found</Text> } + { searchTerm && tokensQuery.data && Boolean(tokensQuery.data?.items.length) && ( + <Flex display="flex" flexDir="column" rowGap={ 3 } maxH="250px" overflowY="scroll" ml="-4px"> + <CheckboxGroup value={ currentValue.map(i => i.token.address_hash) } orientation="vertical"> + { tokensQuery.data.items.map(token => ( + <Checkbox + key={ token.address_hash } + value={ token.address_hash } + id={ token.address_hash } + onChange={ onTokenClick(token) } + overflow="hidden" + w="100%" + pl={ 1 } + > + <TokenEntity.default token={ token } noLink noCopy/> + </Checkbox> + )) } + </CheckboxGroup> + </Flex> + ) } + </ColumnFilterContentSection> { tokensQuery.data && !searchTerm && ( - <> - <Text color="text.secondary" fontWeight="600" mt={ 3 }>Popular</Text> - <Flex rowGap={ 3 } flexWrap="wrap" gap={ 3 } mb={ 2 }> + <ColumnFilterContentSection title="Popular"> + <Flex flexWrap="wrap" gap={ 2 }> { [ NATIVE_TOKEN, ...tokensQuery.data.items ].map(token => ( <Tag key={ token.address_hash } @@ -143,29 +165,9 @@ const AssetFilter = ({ value = [], handleFilterChange }: Props) => { </Tag> )) } </Flex> - </> - ) } - { searchTerm && tokensQuery.data && !tokensQuery.data?.items.length && <Text>No tokens found</Text> } - { searchTerm && tokensQuery.data && Boolean(tokensQuery.data?.items.length) && ( - <Flex display="flex" flexDir="column" rowGap={ 3 } maxH="250px" overflowY="scroll" mt={ 3 } ml="-4px"> - <CheckboxGroup value={ currentValue.map(i => i.token.address_hash) } orientation="vertical"> - { tokensQuery.data.items.map(token => ( - <Checkbox - key={ token.address_hash } - value={ token.address_hash } - id={ token.address_hash } - onChange={ onTokenClick(token) } - overflow="hidden" - w="100%" - pl={ 1 } - > - <TokenEntity.default token={ token } noLink noCopy/> - </Checkbox> - )) } - </CheckboxGroup> - </Flex> + </ColumnFilterContentSection> ) } - </TableColumnFilter> + </ColumnFilterContent> ); }; diff --git a/src/features/advanced-filter/components/filters/BaseAgeFilter.tsx b/src/features/advanced-filter/components/filters/BaseAgeFilter.tsx index 4cd86d81ab8..1f7734d4b28 100644 --- a/src/features/advanced-filter/components/filters/BaseAgeFilter.tsx +++ b/src/features/advanced-filter/components/filters/BaseAgeFilter.tsx @@ -8,7 +8,8 @@ import React from 'react'; import { ADVANCED_FILTER_AGES, type AdvancedFilterAge } from '../../types/api'; import dayjs from 'src/shared/date-and-time/dayjs'; -import TableColumnFilter from 'src/shared/filters/TableColumnFilter'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; import TagGroupSelect from 'src/shared/tags/select/TagGroupSelect'; import { Input } from 'src/toolkit/chakra/input'; @@ -41,23 +42,13 @@ type Props<T> = { }; const DateInput = ({ value, onChange, placeholder, max }: { value: string; onChange: (value: string) => void; placeholder: string; max: string }) => { - const [ tempValue, setTempValue ] = React.useState(value || ''); - - // reset - React.useEffect(() => { - if (!value) { - setTempValue(''); - } - }, [ value ]); - const handleChange = React.useCallback((event: ChangeEvent<HTMLInputElement>) => { - setTempValue(event.target.value); onChange(event.target.value); }, [ onChange ]); return ( <Input - value={ tempValue } + value={ value } onChange={ handleChange } placeholder={ placeholder } type="date" @@ -159,39 +150,39 @@ function BaseAgeFilter<T>({ }, [ currentValue, value, dateConverter ]); return ( - <TableColumnFilter - title="Set last duration" - isFilled={ Boolean(currentValue.from || currentValue.to || currentValue.age) } + <ColumnFilterContent isTouched={ isTouched } onFilter={ onFilter } - onReset={ onReset } - hasReset > - <Flex gap={ 3 }> - <PopoverCloseTriggerWrapper> - <TagGroupSelect<AdvancedFilterAge> - items={ ADVANCED_FILTER_AGES.map(val => ({ id: val, title: val })) } - onChange={ onPresetChange } - value={ currentValue.age || undefined } + <ColumnFilterContentSection title="Set last duration" onReset={ onReset } isFilled={ Boolean(currentValue.from || currentValue.to || currentValue.age) }> + <Flex gap={ 3 }> + <PopoverCloseTriggerWrapper> + <TagGroupSelect<AdvancedFilterAge> + items={ ADVANCED_FILTER_AGES.map(val => ({ id: val, title: val })) } + onChange={ onPresetChange } + value={ currentValue.age || undefined } + /> + </PopoverCloseTriggerWrapper> + </Flex> + </ColumnFilterContentSection> + <ColumnFilterContentSection title="Date range"> + <Flex> + <DateInput + value={ currentValue.age ? '' : currentValue.from } + onChange={ handleFromChange } + placeholder="From" + max={ dayjs().format('YYYY-MM-DD') } + /> + <Text mx={ 3 }>{ ndash }</Text> + <DateInput + value={ currentValue.age ? '' : currentValue.to } + onChange={ handleToChange } + placeholder="To" + max={ dayjs().format('YYYY-MM-DD') } /> - </PopoverCloseTriggerWrapper> - </Flex> - <Flex mt={ 3 }> - <DateInput - value={ currentValue.age ? '' : currentValue.from } - onChange={ handleFromChange } - placeholder="From" - max={ dayjs().format('YYYY-MM-DD') } - /> - <Text mx={ 3 }>{ ndash }</Text> - <DateInput - value={ currentValue.age ? '' : currentValue.to } - onChange={ handleToChange } - placeholder="To" - max={ dayjs().format('YYYY-MM-DD') } - /> - </Flex> - </TableColumnFilter> + </Flex> + </ColumnFilterContentSection> + </ColumnFilterContent> ); } diff --git a/src/features/advanced-filter/components/filters/MethodFilter.tsx b/src/features/advanced-filter/components/filters/MethodFilter.tsx index cc89c16d209..eb2baf02a36 100644 --- a/src/features/advanced-filter/components/filters/MethodFilter.tsx +++ b/src/features/advanced-filter/components/filters/MethodFilter.tsx @@ -9,7 +9,8 @@ import type { schemas } from '@blockscout/api-types'; import useApiQuery from 'src/api/hooks/useApiQuery'; -import TableColumnFilter from 'src/shared/filters/TableColumnFilter'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; import useDebounce from 'src/shared/hooks/useDebounce'; import { Badge } from 'src/toolkit/chakra/badge'; @@ -73,50 +74,49 @@ const MethodFilter = ({ value = [], handleFilterChange }: Props) => { handleFilterChange(NAMES_PARAM, currentValue.map(item => item.name || '')); }, [ handleFilterChange, currentValue ]); + const methods = (searchTerm ? methodsQuery.data : methodsList) || []; + return ( - <TableColumnFilter - title="Method" - isFilled={ Boolean(currentValue.length) } + <ColumnFilterContent isTouched={ !isEqual(currentValue.map(i => JSON.stringify(i)).sort(), value.map(i => JSON.stringify(i)).sort()) } onFilter={ onFilter } - onReset={ onReset } - hasReset > - <FilterInput - size="sm" - onChange={ onSearchChange } - placeholder="Find by function name/ method ID" - mb={ 3 } - /> - { methodsQuery.isLoading && <Spinner/> } - { methodsQuery.isError && <span>Something went wrong. Please try again.</span> } - { Boolean(searchTerm) && methodsQuery.data?.length === 0 && <span>No results found.</span> } - { methodsQuery.data && ( - // added negative margin because of checkbox focus styles & overflow hidden - <Flex display="flex" flexDir="column" rowGap={ 3 } maxH="250px" overflowY="scroll"> - <CheckboxGroup - value={ currentValue.length ? currentValue.map(i => i.method_id) : [ ] } - orientation="vertical" - > - { (searchTerm ? methodsQuery.data : (methodsList || [])).map(method => ( - <Checkbox - key={ method.method_id } - value={ method.method_id } - data-id={ method.method_id } - onChange={ handleChange } - > - <Flex justifyContent="space-between" alignItems="center" id={ method.method_id }> - <chakra.span overflow="hidden" whiteSpace="nowrap" textOverflow="ellipsis">{ method.name || method.method_id }</chakra.span> - <Badge colorPalette="gray" truncated ml="auto"> - { method.method_id } - </Badge> - </Flex> - </Checkbox> - )) } - </CheckboxGroup> - </Flex> - ) } - </TableColumnFilter> + <ColumnFilterContentSection title="Method" onReset={ onReset } isFilled={ Boolean(currentValue.length) }> + <FilterInput + size="sm" + onChange={ onSearchChange } + placeholder="Find by function name/ method ID" + /> + { methodsQuery.isLoading && <Spinner/> } + { methodsQuery.isError && <span>Something went wrong. Please try again.</span> } + { Boolean(searchTerm) && methodsQuery.data?.length === 0 && <span>No results found.</span> } + { methods.length > 0 && ( + <Flex display="flex" flexDir="column" maxH="250px" overflowY="scroll"> + <CheckboxGroup + value={ currentValue.length ? currentValue.map(i => i.method_id) : [ ] } + orientation="vertical" + > + { methods.map(method => ( + <Checkbox + key={ method.method_id } + value={ method.method_id } + data-id={ method.method_id } + onChange={ handleChange } + labelProps={{ w: '100%', minW: '0' }} + > + <Flex justifyContent="space-between" alignItems="center" id={ method.method_id } w="100%"> + <chakra.span overflow="hidden" whiteSpace="nowrap" textOverflow="ellipsis">{ method.name || method.method_id }</chakra.span> + <Badge colorPalette="gray" truncated ml="auto"> + { method.method_id } + </Badge> + </Flex> + </Checkbox> + )) } + </CheckboxGroup> + </Flex> + ) } + </ColumnFilterContentSection> + </ColumnFilterContent> ); }; diff --git a/src/features/advanced-filter/components/filters/TypeFilter.tsx b/src/features/advanced-filter/components/filters/TypeFilter.tsx index a388d8908a4..b9c45a5a473 100644 --- a/src/features/advanced-filter/components/filters/TypeFilter.tsx +++ b/src/features/advanced-filter/components/filters/TypeFilter.tsx @@ -1,69 +1,53 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Flex } from '@chakra-ui/react'; -import { isEqual, without } from 'es-toolkit'; +import { isEqual } from 'es-toolkit'; import React from 'react'; import type { AdvancedFilterParams, AdvancedFilterType } from '../../types/api'; import { useMultichainContext } from 'src/features/multichain/context'; -import TableColumnFilter from 'src/shared/filters/TableColumnFilter'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; import { Checkbox, CheckboxGroup } from 'src/toolkit/chakra/checkbox'; import { getAdvancedFilterTypes } from '../../utils/lib'; -const RESET_VALUE = 'all'; - const FILTER_PARAM = 'transaction_types'; +const NO_TYPES: Array<AdvancedFilterType> = []; + type Props = { - value?: Array<AdvancedFilterType | typeof RESET_VALUE>; + value?: Array<AdvancedFilterType>; handleFilterChange: (filed: keyof AdvancedFilterParams, value: Array<AdvancedFilterType>) => void; }; -const TypeFilter = ({ value = [ RESET_VALUE ], handleFilterChange }: Props) => { - const [ currentValue, setCurrentValue ] = React.useState<Array<AdvancedFilterType | typeof RESET_VALUE>>([ ...value ]); +const TypeFilter = ({ value = NO_TYPES, handleFilterChange }: Props) => { + const [ currentValue, setCurrentValue ] = React.useState<Array<AdvancedFilterType>>([ ...value ]); const multichainContext = useMultichainContext(); const handleChange = React.useCallback((value: Array<string>) => { - setCurrentValue((prev) => { - if (value.length === 0) { - return [ RESET_VALUE ]; - } - - const diff = value.filter(item => !prev.includes(item)); - if (diff.includes(RESET_VALUE)) { - return [ RESET_VALUE ]; - } - - return without(value as Array<AdvancedFilterType>, RESET_VALUE); - }); + setCurrentValue(value as Array<AdvancedFilterType>); }, []); - const onReset = React.useCallback(() => setCurrentValue([ RESET_VALUE ]), []); + const onReset = React.useCallback(() => setCurrentValue([]), []); const onFilter = React.useCallback(() => { - const value: Array<AdvancedFilterType> = currentValue.filter(item => item !== RESET_VALUE) as Array<AdvancedFilterType>; - handleFilterChange(FILTER_PARAM, value); + handleFilterChange(FILTER_PARAM, currentValue); }, [ handleFilterChange, currentValue ]); const advancedFilterTypes = React.useMemo(() => { - return getAdvancedFilterTypes(multichainContext?.chain?.app_config, true); + return getAdvancedFilterTypes(multichainContext?.chain?.app_config); }, [ multichainContext?.chain?.app_config ]); return ( - <TableColumnFilter - title="Transaction type" - isFilled={ !(currentValue.length === 1 && currentValue[0] === RESET_VALUE) } - isTouched={ !isEqual(currentValue.sort(), value.sort()) } + <ColumnFilterContent + isTouched={ !isEqual(currentValue.slice().sort(), value.slice().sort()) } onFilter={ onFilter } - onReset={ onReset } - hasReset > - <Flex display="flex" flexDir="column" rowGap={ 3 }> + <ColumnFilterContentSection title="Transaction type" onReset={ onReset } isFilled={ currentValue.length > 0 }> <CheckboxGroup value={ currentValue } onValueChange={ handleChange } orientation="vertical"> { advancedFilterTypes.map(type => ( <Checkbox @@ -74,8 +58,8 @@ const TypeFilter = ({ value = [ RESET_VALUE ], handleFilterChange }: Props) => { </Checkbox> )) } </CheckboxGroup> - </Flex> - </TableColumnFilter> + </ColumnFilterContentSection> + </ColumnFilterContent> ); }; diff --git a/src/features/advanced-filter/mocks.ts b/src/features/advanced-filter/mocks.ts index 9ae558fa30d..b6d3922128e 100644 --- a/src/features/advanced-filter/mocks.ts +++ b/src/features/advanced-filter/mocks.ts @@ -1,6 +1,7 @@ import type { operations } from '@blockscout/api-types'; import * as addressParamMock from 'src/slices/address/mocks/address-param'; +import * as tokenInfoMock from 'src/slices/token/mocks/info'; export const baseResponse: operations['AdvancedFilterController.list']['json'] = { items: [ @@ -91,6 +92,35 @@ export const baseResponse: operations['AdvancedFilterController.list']['json'] = token_transfer_batch_index: null, token_transfer_index: null, }, + { + timestamp: '2024-12-06T12:38:59.000000Z', + total: { + decimals: '18', + value: '100000000000000000000', + ui_multiplier: '1690000000000000000', + }, + type: 'ERC-8056', + value: null, + hash: '0xd872e60be3db1ef32aabd863af2037330decb3dd73a3786df7a9540b38597fbd', + from: { + ...addressParamMock.withoutName, + hash: '0xA955675Dac496eB2c384D2d288e6C07fDb2234AF', + }, + token: tokenInfoMock.tokenInfoERC8056, + to: { + ...addressParamMock.withoutName, + hash: '0x242ba6d68FfEb4a098B591B32d370F973FF882B7', + }, + method: 'transfer', + fee: '63849188818350', + block_number: 0, + internal_transaction_index: null, + transaction_index: 0, + created_contract: null, + status: 'ok', + token_transfer_batch_index: null, + token_transfer_index: null, + }, ], next_page_params: { block_number: 5867485, diff --git a/src/features/advanced-filter/pages/index/AdvancedFilter.pw.tsx b/src/features/advanced-filter/pages/index/AdvancedFilter.pw.tsx index 426b42f0598..23cc6fe1266 100644 --- a/src/features/advanced-filter/pages/index/AdvancedFilter.pw.tsx +++ b/src/features/advanced-filter/pages/index/AdvancedFilter.pw.tsx @@ -1,15 +1,19 @@ -import React from 'react'; +import * as csvExportMock from 'src/features/csv-export/mocks'; -import { test, expect } from 'playwright/lib'; +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { expect, test } from 'playwright/lib'; import * as advancedFilterMock from '../../mocks'; import AdvancedFilter from './AdvancedFilter'; -test('base view +@dark-mode', async({ render, mockApiResponse, mockTextAd }) => { +test('base view +@dark-mode', async({ render, mockApiResponse, mockTextAd, mockEnvs }) => { + await mockEnvs(ENVS_MAP.additionalTokenTypes); await mockTextAd(); await mockApiResponse('core:advanced_filter', advancedFilterMock.baseResponse); await mockApiResponse('core:tokens', { items: [], next_page_params: null }, { queryParams: { limit: '7', q: '' } }); await mockApiResponse('core:advanced_filter_methods', [], { queryParams: { q: '' } }); + await mockApiResponse('core:config_csv_export', csvExportMock.config); const component = await render(<AdvancedFilter/>); diff --git a/src/features/advanced-filter/pages/index/AdvancedFilter.spec.tsx b/src/features/advanced-filter/pages/index/AdvancedFilter.spec.tsx new file mode 100644 index 00000000000..d44c298b763 --- /dev/null +++ b/src/features/advanced-filter/pages/index/AdvancedFilter.spec.tsx @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import React from 'react'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from 'vitest/lib'; +import { routerStandIn, RouterStandInProvider } from 'vitest/utils/routerStandIn'; + +import * as advancedFilterMock from '../../mocks'; +import AdvancedFilter from './AdvancedFilter'; + +const STORAGE_KEY = 'table_columns_advanced_filter'; + +beforeEach(() => { + fetchMock.resetMocks(); + fetchMock.mockResponse((request) => { + if (new URL(request.url).pathname === '/api/v2/advanced-filters') { + return { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(advancedFilterMock.baseResponse) }; + } + return { status: 404, body: '{}' }; + }); + routerStandIn.reset({ pathname: '/advanced-filter', query: {} }); +}); + +afterEach(() => { + cleanup(); + window.localStorage.clear(); +}); + +async function renderPage() { + render(<RouterStandInProvider><AdvancedFilter/></RouterStandInProvider>); + await waitFor(() => expect(document.querySelectorAll('tbody tr').length).toBeGreaterThan(0)); +} + +function getHeaderNames() { + return Array.from(document.querySelectorAll('thead th')).map((header) => header.textContent); +} + +describe('advanced filter page, column settings', () => { + it('renders the table with the stored columns', async() => { + window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ visibility: { method: false }, order: [ 'fee', 'tx_hash' ] })); + + await renderPage(); + + const headers = getHeaderNames(); + expect(headers.slice(0, 2)).toEqual([ 'Fee', 'Tx hash' ]); + expect(headers).not.toContain('Method'); + }); + + it('neither renders nor offers the multiplier column on a chain without the UI multiplier', async() => { + window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ visibility: { multiplier: true }, order: [ 'multiplier' ] })); + + await renderPage(); + + expect(getHeaderNames()).not.toContain('Multiplier'); + fireEvent.click(screen.getByRole('button', { name: 'Columns' })); + expect(await screen.findByRole('checkbox', { name: 'Fee' })).toBeTruthy(); + expect(screen.queryByRole('checkbox', { name: 'Multiplier' })).toBeNull(); + }); +}); diff --git a/src/features/advanced-filter/pages/index/AdvancedFilter.tsx b/src/features/advanced-filter/pages/index/AdvancedFilter.tsx index 1d94006e98f..4203e1320a4 100644 --- a/src/features/advanced-filter/pages/index/AdvancedFilter.tsx +++ b/src/features/advanced-filter/pages/index/AdvancedFilter.tsx @@ -1,19 +1,14 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { - Text, - Flex, - HStack, -} from '@chakra-ui/react'; import { omit } from 'es-toolkit'; -import { useRouter } from 'next/router'; import React from 'react'; import type { AdvancedFilterParams } from '../../types/api'; -import { ADVANCED_FILTER_AGES, ADVANCED_FILTER_ADDRESS_RELATION } from '../../types/api'; -import type { ColumnsIds } from '../../types/client'; +import { ADVANCED_FILTER_ADDRESS_RELATION, ADVANCED_FILTER_AGES } from '../../types/api'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; import useApiQuery from 'src/api/hooks/useApiQuery'; +import type { PaginationFilters } from 'src/api/resources'; import ActionBar from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; @@ -22,63 +17,73 @@ import CsvExport from 'src/features/csv-export/components/CsvExport'; import { useMultichainContext } from 'src/features/multichain/context'; import dayjs from 'src/shared/date-and-time/dayjs'; +import FilterTagsRow from 'src/shared/filters/FilterTagsRow'; +import ColumnsButton from 'src/shared/lists/columns/ColumnsButton'; +import type { TableColumnsAnalytics } from 'src/shared/lists/columns/usePersistedColumns'; +import { usePersistedColumns } from 'src/shared/lists/columns/usePersistedColumns'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { usePaginationParams } from 'src/shared/pagination/usePaginationParams'; import { generateListStub } from 'src/shared/pagination/utils'; import getFilterValueFromQuery from 'src/shared/router/get-filter-value-from-query'; import getFilterValuesFromQuery from 'src/shared/router/get-filter-values-from-query'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import getValuesArrayFromQuery from 'src/shared/router/get-values-array-from-query'; -import SpriteIcon from 'src/sprite/SpriteIcon'; -import { Link } from 'src/toolkit/chakra/link'; import { Tag } from 'src/toolkit/chakra/tag'; -import ColumnsButton from '../../components/ColumnsButton'; import { ADVANCED_FILTER_ITEM } from '../../stubs'; -import { TABLE_COLUMNS } from '../../utils/consts'; +import { getColumnStates, TABLE_COLUMNS } from '../../utils/consts'; import { getAdvancedFilterTypes, getDurationFromAge, getFilterTags } from '../../utils/lib'; import AdvancedFilterTable from './AdvancedFilterTable'; -const COLUMNS_CHECKED = {} as Record<ColumnsIds, boolean>; -TABLE_COLUMNS.forEach(c => COLUMNS_CHECKED[c.id] = true); +const SELECTOR_COLUMNS = TABLE_COLUMNS.map(c => c.id === 'or_and' ? { ...c, name: 'And/Or' } : c); +const COLUMNS_ANALYTICS: TableColumnsAnalytics = { Table: 'Advanced filter' }; + +const AGE_RANGE_FIELDS = [ 'age_from', 'age_to' ] as const; + +type UrlFilters = PaginationFilters<'core:advanced_filter'>; + +function getFiltersFromQuery(query: UrlFilters, chainConfig: ClusterChainConfig['app_config'] | undefined): AdvancedFilterParams { + const age = getFilterValueFromQuery(ADVANCED_FILTER_AGES, query.age); + const addressRelation = getFilterValueFromQuery(ADVANCED_FILTER_ADDRESS_RELATION, query.address_relation); + return { + transaction_types: getFilterValuesFromQuery(getAdvancedFilterTypes(chainConfig).map(t => t.id), query.transaction_types), + methods: getValuesArrayFromQuery(query.methods), + methods_names: getValuesArrayFromQuery(query.methods_names), + amount_from: getQueryParamString(query.amount_from), + amount_to: getQueryParamString(query.amount_to), + age, + age_to: age ? dayjs().toISOString() : getQueryParamString(query.age_to), + age_from: age ? dayjs((dayjs().valueOf() - getDurationFromAge(age))).toISOString() : getQueryParamString(query.age_from), + address_relation: addressRelation, + token_contract_address_hashes_to_exclude: getValuesArrayFromQuery(query.token_contract_address_hashes_to_exclude), + token_contract_symbols_to_exclude: getValuesArrayFromQuery(query.token_contract_symbols_to_exclude), + token_contract_address_hashes_to_include: getValuesArrayFromQuery(query.token_contract_address_hashes_to_include), + token_contract_symbols_to_include: getValuesArrayFromQuery(query.token_contract_symbols_to_include), + to_address_hashes_to_include: getValuesArrayFromQuery(query.to_address_hashes_to_include), + from_address_hashes_to_include: getValuesArrayFromQuery(query.from_address_hashes_to_include), + to_address_hashes_to_exclude: getValuesArrayFromQuery(query.to_address_hashes_to_exclude), + from_address_hashes_to_exclude: getValuesArrayFromQuery(query.from_address_hashes_to_exclude), + }; +} const AdvancedFilter = () => { - const router = useRouter(); const multichainContext = useMultichainContext(); + const chainConfig = multichainContext?.chain?.app_config; + + // Keyed by the filter values rather than the object: the URL object changes on every page change, and an age + // preset's computed range must stay the same across pages so cached pages are found again. + const urlFiltersKey = JSON.stringify(usePaginationParams('core:advanced_filter').filters); + const filters = React.useMemo( + () => getFiltersFromQuery(JSON.parse(urlFiltersKey) as UrlFilters, chainConfig), + [ urlFiltersKey, chainConfig ], + ); - const [ filters, setFilters ] = React.useState<AdvancedFilterParams>(() => { - const age = getFilterValueFromQuery(ADVANCED_FILTER_AGES, router.query.age); - const addressRelation = getFilterValueFromQuery(ADVANCED_FILTER_ADDRESS_RELATION, router.query.address_relation); - return { - transaction_types: getFilterValuesFromQuery( - getAdvancedFilterTypes(multichainContext?.chain?.app_config).map(t => t.id), - router.query.transaction_types, - ), - methods: getValuesArrayFromQuery(router.query.methods), - methods_names: getValuesArrayFromQuery(router.query.methods_names), - amount_from: getQueryParamString(router.query.amount_from), - amount_to: getQueryParamString(router.query.amount_to), - age, - age_to: age ? dayjs().toISOString() : getQueryParamString(router.query.age_to), - age_from: age ? dayjs((dayjs().valueOf() - getDurationFromAge(age))).toISOString() : getQueryParamString(router.query.age_from), - address_relation: addressRelation, - token_contract_address_hashes_to_exclude: getValuesArrayFromQuery(router.query.token_contract_address_hashes_to_exclude), - token_contract_symbols_to_exclude: getValuesArrayFromQuery(router.query.token_contract_symbols_to_exclude), - token_contract_address_hashes_to_include: getValuesArrayFromQuery(router.query.token_contract_address_hashes_to_include), - token_contract_symbols_to_include: getValuesArrayFromQuery(router.query.token_contract_symbols_to_include), - to_address_hashes_to_include: getValuesArrayFromQuery(router.query.to_address_hashes_to_include), - from_address_hashes_to_include: getValuesArrayFromQuery(router.query.from_address_hashes_to_include), - to_address_hashes_to_exclude: getValuesArrayFromQuery(router.query.to_address_hashes_to_exclude), - from_address_hashes_to_exclude: getValuesArrayFromQuery(router.query.from_address_hashes_to_exclude), - }; - }); - - const [ columns, setColumns ] = React.useState<Record<ColumnsIds, boolean>>(COLUMNS_CHECKED); - const { data, isError, isLoading, pagination, onFilterChange, isPlaceholderData, queryHash } = useQueryWithPages({ + const { data, isError, isLoading, pagination, onFilterChange, isInitialLoading, isTransitioning, queryHash } = useApiPaginatedQuery({ resourceName: 'core:advanced_filter', - filters, + queryParams: filters, options: { placeholderData: generateListStub<'core:advanced_filter'>( ADVANCED_FILTER_ITEM, @@ -104,17 +109,26 @@ const AdvancedFilter = () => { useApiQuery('core:tokens', { queryParams: { limit: '7', q: '' }, queryOptions: { refetchOnMount: false } }); useApiQuery('core:advanced_filter_methods', { queryParams: { q: '' }, queryOptions: { refetchOnMount: false } }); - const handleFilterChange = React.useCallback(<T extends keyof AdvancedFilterParams>(field: T, val: AdvancedFilterParams[T]) => { - setFilters(prevState => { - const newState = { ...prevState }; + const latestFilters = React.useRef(filters); + latestFilters.current = filters; + const pendingFilters = React.useRef<AdvancedFilterParams | null>(null); - newState[field] = val; - onFilterChange(newState.age ? omit(newState, [ 'age_from', 'age_to' ]) : newState); - return newState; - }); + // The filter components report one field per call and several per user action (an age preset sets its range + // and the preset, the asset filter sets addresses and symbols). The calls of one tick are collected and + // pushed to the URL together, so one action is one navigation and one request. + const handleFilterChange = React.useCallback(<T extends keyof AdvancedFilterParams>(field: T, val: AdvancedFilterParams[T]) => { + if (pendingFilters.current === null) { + pendingFilters.current = { ...latestFilters.current }; + queueMicrotask(() => { + const nextFilters = pendingFilters.current ?? {}; + pendingFilters.current = null; + onFilterChange(nextFilters.age ? omit(nextFilters, AGE_RANGE_FIELDS) : nextFilters); + }); + } + pendingFilters.current[field] = val; }, [ onFilterChange ]); - const onClearFilter = React.useCallback((key: keyof AdvancedFilterParams) => () => { + const handleClearFilter = React.useCallback((key: keyof AdvancedFilterParams) => { if (key === 'methods') { handleFilterChange('methods_names', undefined); } @@ -132,18 +146,27 @@ const AdvancedFilter = () => { }, [ handleFilterChange ]); const clearAllFilters = React.useCallback(() => { - setFilters({}); onFilterChange({}); }, [ onFilterChange ]); - const columnsToShow = TABLE_COLUMNS.filter(c => columns[c.id]); + const columnStates = React.useMemo(() => getColumnStates(chainConfig), [ chainConfig ]); + const { columns, selectableColumns, checkedColumns, isCustomized, onColumnsChange, onColumnsReorder, onColumnsReset } = usePersistedColumns({ + storageKey: 'table_columns_advanced_filter', + columns: SELECTOR_COLUMNS, + states: columnStates, + analytics: COLUMNS_ANALYTICS, + }); + const columnsToShow = React.useMemo( + // Stryker disable next-line ConditionalExpression: every id comes from TABLE_COLUMNS, so find always hits; the filter narrows away undefined + () => columns.map((id) => TABLE_COLUMNS.find((column) => column.id === id)).filter((column) => column !== undefined), + [ columns ], + ); + const filterTags = React.useMemo(() => getFilterTags(filters, chainConfig), [ filters, chainConfig ]); if (isLoading) { return null; } - const filterTags = getFilterTags(filters, multichainContext?.chain?.app_config); - const content = data?.items ? ( <AdvancedFilterTable items={ data.items } @@ -151,14 +174,21 @@ const AdvancedFilter = () => { filters={ filters } searchParams={ data.search_params } handleFilterChange={ handleFilterChange } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } resetKey={ queryHash } /> ) : null; const actionBar = ( <ActionBar mt={ -6 }> - <ColumnsButton columns={ columns } onChange={ setColumns }/> + <ColumnsButton + tableColumns={ selectableColumns } + columns={ checkedColumns } + onChange={ onColumnsChange } + onOrderChange={ onColumnsReorder } + selected={ isCustomized } + onReset={ onColumnsReset } + /> <CsvExport type="advanced_filters" resourceName="core:advanced_filter_csv" @@ -179,27 +209,17 @@ const AdvancedFilter = () => { title="Advanced filter" withTextAd /> - <Flex mb={ 4 } justifyContent="space-between" alignItems="start"> - <Text fontSize="lg" mr={ 3 } lineHeight="24px" w="100px">Filtered by:</Text> - { filterTags.length !== 0 && ( - <Link onClick={ clearAllFilters } display="flex" alignItems="center" justifyContent="end" gap={ 2 } fontSize="sm" w="150px"> - <SpriteIcon name="repeat" boxSize={ 5 }/> - Reset filters - </Link> - ) } - </Flex> - <HStack gap={ 2 } flexWrap="wrap" mb={ 6 }> - { multichainContext?.chain && ( + <FilterTagsRow + mb={ 6 } + tags={ filterTags } + onClear={ handleClearFilter } + onClearAll={ clearAllFilters } + leadingTags={ multichainContext?.chain && ( <Tag variant="filter" label="Chain"> { multichainContext.chain.app_config.chain.name } </Tag> ) } - { filterTags.map(t => ( - <Tag key={ t.name } variant="filter" onClose={ onClearFilter(t.key) } closable label={ t.name }> - { t.value } - </Tag> - )) } - { filterTags.length === 0 && ( + placeholderTags={ ( <> <Tag variant="filter" label="Type"> All @@ -209,7 +229,7 @@ const AdvancedFilter = () => { </Tag> </> ) } - </HStack> + /> <DataList isError={ isError } itemsNum={ data?.items.length } @@ -219,6 +239,7 @@ const AdvancedFilter = () => { emptyStateProps={{ term: 'transaction', }} + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/advanced-filter/pages/index/AdvancedFilterTable.tsx b/src/features/advanced-filter/pages/index/AdvancedFilterTable.tsx index 5f6407f456b..269156a82fb 100644 --- a/src/features/advanced-filter/pages/index/AdvancedFilterTable.tsx +++ b/src/features/advanced-filter/pages/index/AdvancedFilterTable.tsx @@ -4,7 +4,6 @@ import { Box, chakra, } from '@chakra-ui/react'; -import React from 'react'; import type { AdvancedFilterParams } from '../../types/api'; import type { TxTableColumn } from '../../types/client'; @@ -63,7 +62,7 @@ const AdvancedFilterTable = ({ whiteSpace="normal" > { Boolean(column.name) && ( - <chakra.span mr={ 2 } lineHeight="24px" verticalAlign="middle"> + <chakra.span mr={ column.noFilter ? 0 : 2 } lineHeight="24px" verticalAlign="middle"> { column.id === 'age' ? 'Timestamp' : column.name } </chakra.span> ) } diff --git a/src/features/advanced-filter/pages/index/__screenshots__/AdvancedFilter.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/features/advanced-filter/pages/index/__screenshots__/AdvancedFilter.pw.tsx_dark-color-mode_base-view-dark-mode-1.png index 485104e8593..2f7d758323a 100644 Binary files a/src/features/advanced-filter/pages/index/__screenshots__/AdvancedFilter.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and b/src/features/advanced-filter/pages/index/__screenshots__/AdvancedFilter.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/features/advanced-filter/pages/index/__screenshots__/AdvancedFilter.pw.tsx_default_base-view-dark-mode-1.png b/src/features/advanced-filter/pages/index/__screenshots__/AdvancedFilter.pw.tsx_default_base-view-dark-mode-1.png index b518ae9d6dc..158fb320c7c 100644 Binary files a/src/features/advanced-filter/pages/index/__screenshots__/AdvancedFilter.pw.tsx_default_base-view-dark-mode-1.png and b/src/features/advanced-filter/pages/index/__screenshots__/AdvancedFilter.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/features/advanced-filter/types/client.ts b/src/features/advanced-filter/types/client.ts index b1f6f3da488..76b05fd5295 100644 --- a/src/features/advanced-filter/types/client.ts +++ b/src/features/advanced-filter/types/client.ts @@ -1,10 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -export type ColumnsIds = 'tx_hash' | 'type' | 'method' | 'age' | 'from' | 'or_and' | 'to' | 'amount' | 'asset' | 'fee'; +export type ColumnsIds = 'tx_hash' | 'type' | 'method' | 'age' | 'from' | 'or_and' | 'to' | 'multiplier' | 'amount' | 'asset' | 'fee'; export type TxTableColumn = { id: ColumnsIds; name: string; width: string; isNumeric?: boolean; + noFilter?: boolean; }; diff --git a/src/features/advanced-filter/utils/consts.spec.ts b/src/features/advanced-filter/utils/consts.spec.ts new file mode 100644 index 00000000000..a96c67d623f --- /dev/null +++ b/src/features/advanced-filter/utils/consts.spec.ts @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +import { chainA } from 'src/features/multichain/mocks/chains'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const chainWithoutErc8056 = chainA.app_config as ClusterChainConfig['app_config']; + +const chainWithErc8056 = { + ...chainWithoutErc8056, + slices: { + ...chainWithoutErc8056.slices, + token: { + ...chainWithoutErc8056.slices.token, + additionalTypes: [ { id: 'ERC-8056', name: 'ERC-8056' } ], + }, + }, +} as ClusterChainConfig['app_config']; + +describe('getColumnStates', () => { + it('shows the multiplier column when the instance enables ERC-8056', async() => { + const state = await withEnvs(ENVS_MAP.additionalTokenTypes, async() => { + const { getColumnStates } = await import('./consts'); + return getColumnStates().multiplier; + }); + expect(state).toBe('on'); + }); + + it('places the multiplier column between to and amount', async() => { + const { TABLE_COLUMNS } = await import('./consts'); + const ids = TABLE_COLUMNS.map((column) => column.id); + expect(ids.slice(ids.indexOf('to'), ids.indexOf('amount') + 1)).toEqual([ 'to', 'multiplier', 'amount' ]); + }); + + it('shows every other column', async() => { + const { getColumnStates } = await import('./consts'); + expect(Object.entries(getColumnStates()).filter(([ , state ]) => state !== 'on').map(([ id ]) => id)).toEqual([ 'multiplier' ]); + }); + + it('hides the multiplier column when the instance does not enable ERC-8056', async() => { + const { getColumnStates } = await import('./consts'); + expect(getColumnStates().multiplier).toBe('unavailable'); + }); + + it('shows the multiplier column when the focused chain enables ERC-8056, regardless of the cluster config', async() => { + const { getColumnStates } = await import('./consts'); + expect(getColumnStates(chainWithErc8056).multiplier).toBe('on'); + }); + + it('hides the multiplier column when the focused chain does not enable ERC-8056, regardless of the cluster config', async() => { + const state = await withEnvs(ENVS_MAP.additionalTokenTypes, async() => { + const { getColumnStates } = await import('./consts'); + return getColumnStates(chainWithoutErc8056).multiplier; + }); + expect(state).toBe('unavailable'); + }); +}); diff --git a/src/features/advanced-filter/utils/consts.ts b/src/features/advanced-filter/utils/consts.ts index 79ca6d2a07f..076c4951077 100644 --- a/src/features/advanced-filter/utils/consts.ts +++ b/src/features/advanced-filter/utils/consts.ts @@ -1,9 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { AdvancedFilterParams } from '../types/api'; -import type { TxTableColumn } from '../types/client'; +import type { ColumnsIds, TxTableColumn } from '../types/client'; +import type { ColumnStates } from 'src/shared/lists/columns/types'; +import type { ChainConfig } from 'src/slices/token/types/client'; import { toTokenModel } from 'src/slices/token/utils/model'; +import { isTokenMultiplierEnabled } from 'src/slices/token/utils/ui-multiplier'; import config from 'src/config'; @@ -43,6 +46,13 @@ export const TABLE_COLUMNS: Array<TxTableColumn> = [ name: 'To', width: '160px', }, + { + id: 'multiplier', + name: 'Multiplier', + width: '90px', + isNumeric: true, + noFilter: true, + }, { id: 'amount', name: 'Amount', @@ -62,6 +72,22 @@ export const TABLE_COLUMNS: Array<TxTableColumn> = [ }, ] as const; +export function getColumnStates(chainConfig?: ChainConfig): ColumnStates<ColumnsIds> { + return { + tx_hash: 'on', + type: 'on', + method: 'on', + age: 'on', + from: 'on', + or_and: 'on', + to: 'on', + multiplier: isTokenMultiplierEnabled(chainConfig) ? 'on' : 'unavailable', + amount: 'on', + asset: 'on', + fee: 'on', + }; +} + export const NATIVE_TOKEN = toTokenModel({ name: config.chain.currency.name || '', icon_url: '', diff --git a/src/features/advanced-filter/utils/lib.spec.ts b/src/features/advanced-filter/utils/lib.spec.ts new file mode 100644 index 00000000000..6e5ff642b26 --- /dev/null +++ b/src/features/advanced-filter/utils/lib.spec.ts @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getFilterTags } from './lib'; + +const ADDRESS_FROM = '0x7aC52f69655b2045A0212300a1d26360c7aC0E4b'; +const ADDRESS_TO = '0x1234567890abcdef1234567890abcdef12345678'; +const TOKEN_ADDRESS = '0x514910771AF9Ca656af840dff83E8264EcF986CA'; + +describe('getFilterTags', () => { + it('returns no tags when no filter is set', () => { + expect(getFilterTags({})).toEqual([]); + }); + + it('middle-truncates address hashes and joins several with a comma', () => { + const tags = getFilterTags({ + from_address_hashes_to_include: [ ADDRESS_FROM, ADDRESS_TO ], + to_address_hashes_to_exclude: [ ADDRESS_TO ], + }); + + expect(tags).toEqual([ + { key: 'from_address_hashes_to_include', name: 'From', value: '0x7a...0E4b, 0x12...5678' }, + { key: 'to_address_hashes_to_exclude', name: 'To Exc', value: '0x12...5678' }, + ]); + }); + + it('shows token symbols instead of contract addresses when the symbols are known', () => { + const tags = getFilterTags({ + token_contract_address_hashes_to_include: [ TOKEN_ADDRESS, 'native' ], + token_contract_symbols_to_include: [ 'LINK', 'ETH' ], + }); + + expect(tags).toEqual([ + { key: 'token_contract_address_hashes_to_include', name: 'Asset', value: 'LINK, ETH' }, + ]); + }); + + it('falls back to the method id when its name is unknown', () => { + const tags = getFilterTags({ + methods: [ '0xa9059cbb', '0x095ea7b3' ], + methods_names: [ 'transfer', '' ], + }); + + expect(tags).toEqual([ + { key: 'methods', name: 'Methods', value: 'transfer, 0x095ea7b3' }, + ]); + }); + + it('maps transaction type ids to their display names', () => { + const tags = getFilterTags({ transaction_types: [ 'coin_transfer', 'contract_creation' ] }); + + expect(tags).toEqual([ + { key: 'transaction_types', name: 'Type', value: 'Coin Transfer, Contract Creation' }, + ]); + }); + + it('hides the date range when a preset age is set', () => { + const tags = getFilterTags({ age: '7d', age_from: '2024-01-01', age_to: '2024-01-07' }); + + expect(tags).toEqual([ + { key: 'age', name: 'Age', value: '7d' }, + ]); + }); + + it('formats the date range as dates when no preset age is set', () => { + const tags = getFilterTags({ age_from: '2024-01-01T10:00:00Z', age_to: '2024-01-07T10:00:00Z' }); + + expect(tags).toEqual([ + { key: 'age_from', name: 'Date from', value: '2024-01-01' }, + { key: 'age_to', name: 'Date to', value: '2024-01-07' }, + ]); + }); + + it('never shows the address relation as a tag', () => { + expect(getFilterTags({ address_relation: 'and' })).toEqual([]); + }); +}); diff --git a/src/features/advanced-filter/utils/lib.ts b/src/features/advanced-filter/utils/lib.ts index a4f13e075fa..8547156237d 100644 --- a/src/features/advanced-filter/utils/lib.ts +++ b/src/features/advanced-filter/utils/lib.ts @@ -9,15 +9,12 @@ import { getTokenTypes } from 'src/slices/token/utils/token-types'; import dayjs from 'src/shared/date-and-time/dayjs'; import { HOUR, DAY, MONTH } from 'src/toolkit/utils/consts'; +import { shortenString } from 'src/toolkit/utils/texts'; import { FILTER_PARAM_NAMES } from './consts'; -export const getAdvancedFilterTypes = (chainConfig?: Array<ClusterChainConfig['app_config']> | ClusterChainConfig['app_config'], withAll = false) => { +export const getAdvancedFilterTypes = (chainConfig?: Array<ClusterChainConfig['app_config']> | ClusterChainConfig['app_config']) => { return [ - ...(withAll ? [ { - id: 'all', - name: 'All', - } ] : []), { id: 'coin_transfer', name: 'Coin Transfer', @@ -61,7 +58,7 @@ function getFilterValueWithNames(values?: Array<string>, names?: Array<string>) } else if (Array.isArray(names) && Array.isArray(values)) { return names.map((n, i) => n ? n : values[i]).join(', '); } else { - return names; + return names.join(', '); } } @@ -107,6 +104,13 @@ export function getFilterTags(filters: AdvancedFilterParams, chainConfig?: Clust valueStr = dayjs(filtersToShow.age_to).format('YYYY-MM-DD'); break; } + case 'from_address_hashes_to_include': + case 'from_address_hashes_to_exclude': + case 'to_address_hashes_to_include': + case 'to_address_hashes_to_exclude': { + valueStr = castArray(value).map((hash) => shortenString(hash)).join(', '); + break; + } default: { valueStr = castArray(value).join(', '); } diff --git a/src/features/alternative-explorers/components/AlternativeExplorers.pw.tsx b/src/features/alternative-explorers/components/AlternativeExplorers.pw.tsx index b7b6fd9ca9f..59b4aee1807 100644 --- a/src/features/alternative-explorers/components/AlternativeExplorers.pw.tsx +++ b/src/features/alternative-explorers/components/AlternativeExplorers.pw.tsx @@ -6,6 +6,6 @@ import AlternativeExplorers from './AlternativeExplorers'; test('base view', async({ render, page }) => { const component = await render(<AlternativeExplorers type="tx" pathParam="0x123"/>); - await component.getByLabel('Verify with other explorers').click(); + await component.getByLabel('Verify with other sources').click(); await expect(page).toHaveScreenshot({ clip: { x: 0, y: 0, width: 300, height: 150 } }); }); diff --git a/src/features/alternative-explorers/components/AlternativeExplorers.tsx b/src/features/alternative-explorers/components/AlternativeExplorers.tsx index f9d6eae3c65..fa29f4772a9 100644 --- a/src/features/alternative-explorers/components/AlternativeExplorers.tsx +++ b/src/features/alternative-explorers/components/AlternativeExplorers.tsx @@ -6,6 +6,7 @@ import React from 'react'; import type { AlternativeExplorer as TAlternativeExplorer } from '../types/client'; import config from 'src/config'; +import { getFeaturePayload } from 'src/config/utils/features'; import VerifyWith from 'src/shared/links/VerifyWith'; import SpriteIcon from 'src/sprite/SpriteIcon'; @@ -21,7 +22,7 @@ interface Props { const AlternativeExplorers = ({ className, type, pathParam }: Props) => { const explorersLinks = React.useMemo(() => { - return config.features.alternativeExplorers.items + return (getFeaturePayload(config.features.alternativeExplorers)?.items ?? []) .filter((explorer) => typeof explorer.paths[type] === 'string') .map((explorer) => { const path = explorer.paths[type] || ''; @@ -54,7 +55,7 @@ const AlternativeExplorers = ({ className, type, pathParam }: Props) => { <VerifyWith className={ className } links={ explorersLinks } - label="Verify with other explorers" + label="Verify with other sources" longText={ `${ explorersLinks.length } Explorer${ explorersLinks.length > 1 ? 's' : '' }` } shortText={ explorersLinks.length.toString() } /> diff --git a/src/features/alternative-explorers/components/__screenshots__/AlternativeExplorers.pw.tsx_default_base-view-1.png b/src/features/alternative-explorers/components/__screenshots__/AlternativeExplorers.pw.tsx_default_base-view-1.png index 50ca94e3dbf..60a60a7686b 100644 Binary files a/src/features/alternative-explorers/components/__screenshots__/AlternativeExplorers.pw.tsx_default_base-view-1.png and b/src/features/alternative-explorers/components/__screenshots__/AlternativeExplorers.pw.tsx_default_base-view-1.png differ diff --git a/src/features/alternative-explorers/config.ts b/src/features/alternative-explorers/config.ts index 5104f72c876..0a16c6e12ac 100644 --- a/src/features/alternative-explorers/config.ts +++ b/src/features/alternative-explorers/config.ts @@ -3,9 +3,25 @@ import type { AlternativeExplorer } from './types/client'; import { getEnvValue, parseEnvJson } from 'src/config/utils/envs'; +import type { Feature } from 'src/config/utils/features'; -export const config = Object.freeze({ - items: parseEnvJson<Array<AlternativeExplorer>>(getEnvValue('NEXT_PUBLIC_NETWORK_EXPLORERS')) || [], -}); +const title = 'Alternative explorers'; + +const config: Feature<{ items: Array<AlternativeExplorer> }> = (() => { + const items = parseEnvJson<Array<AlternativeExplorer>>(getEnvValue('NEXT_PUBLIC_NETWORK_EXPLORERS')); + + if (items && items.length > 0) { + return Object.freeze({ + title, + isEnabled: true, + items, + }); + } + + return Object.freeze({ + title, + isEnabled: false, + }); +})(); export default config; diff --git a/src/features/alternative-explorers/utils/explorers.ts b/src/features/alternative-explorers/utils/explorers.ts index 984aa0cd020..4bef92c4324 100644 --- a/src/features/alternative-explorers/utils/explorers.ts +++ b/src/features/alternative-explorers/utils/explorers.ts @@ -5,11 +5,12 @@ import { mapValues } from 'es-toolkit'; import type { AlternativeExplorer } from '../types/client'; import config from 'src/config'; +import { getFeaturePayload } from 'src/config/utils/features'; import { stripTrailingSlash, addLeadingSlash } from 'src/toolkit/utils/url'; const chainExplorers: Array<AlternativeExplorer> = (() => { - return config.features.alternativeExplorers.items.map((explorer) => ({ + return (getFeaturePayload(config.features.alternativeExplorers)?.items ?? []).map((explorer) => ({ ...explorer, baseUrl: stripTrailingSlash(explorer.baseUrl), paths: mapValues(explorer.paths, (value) => value ? stripTrailingSlash(addLeadingSlash(value)) : value), diff --git a/src/features/api-docs/config.ts b/src/features/api-docs/config.ts index 1bcefa1ead1..f42337325fc 100644 --- a/src/features/api-docs/config.ts +++ b/src/features/api-docs/config.ts @@ -8,7 +8,7 @@ import chain from 'src/slices/chain/config'; import { getEnvValue, parseEnvJson } from 'src/config/utils/envs'; import type { Feature } from 'src/config/utils/features'; -// Chains served by the Pro API send users straight to the developer portal, +// Chains served by the Blockscout API send users straight to the developer portal, // so the in-app documentation is skipped unless an operator asks for it explicitly. const DEV_PORTAL_URL = 'https://dev.blockscout.com/?utm_source=blockscout&utm_medium=navigation'; diff --git a/src/features/api-docs/pages/index/ApiDocs.tsx b/src/features/api-docs/pages/index/ApiDocs.tsx index 3f0576e6021..8079e3d1fb1 100644 --- a/src/features/api-docs/pages/index/ApiDocs.tsx +++ b/src/features/api-docs/pages/index/ApiDocs.tsx @@ -18,15 +18,18 @@ import RestApi from './RestApi'; import RpcApi from './RpcApi'; const feature = getFeaturePayload(config.features.apiDocs); +const multichainFeature = config.features.multichain; const ApiDocs = () => { const tabs: Array<TabItemRegular> = [ { id: 'rest_api', title: 'REST API', component: <RestApi/> }, - { id: 'eth_rpc_api', title: 'ETH RPC API', component: <EthRpcApi/> }, - { id: 'rpc_api', title: 'RPC API endpoints', component: <RpcApi/> }, - { id: 'graphql_api', title: 'GraphQL API', component: <GraphQL/> }, - ].filter(({ id }) => feature?.mode === 'internal' && feature.tabs.includes(id)); + !multichainFeature.isEnabled && { id: 'eth_rpc_api', title: 'ETH RPC API', component: <EthRpcApi/> }, + !multichainFeature.isEnabled && { id: 'rpc_api', title: 'RPC API endpoints', component: <RpcApi/> }, + !multichainFeature.isEnabled && { id: 'graphql_api', title: 'GraphQL API', component: <GraphQL/> }, + ] + .filter(Boolean) + .filter(({ id }) => feature?.mode === 'internal' && feature.tabs.includes(id)); return ( <> diff --git a/src/features/api-docs/utils/rest-api.spec.ts b/src/features/api-docs/utils/rest-api.spec.ts index 856d77c09ea..a750fbbe6c4 100644 --- a/src/features/api-docs/utils/rest-api.spec.ts +++ b/src/features/api-docs/utils/rest-api.spec.ts @@ -1,4 +1,4 @@ -import type { ApiPropsFull } from 'src/api/config'; +import type { ApiPropsFull } from 'src/api/types'; import { describe, test, expect } from 'vitest'; diff --git a/src/features/api-docs/utils/rest-api.ts b/src/features/api-docs/utils/rest-api.ts index eab34883e37..4afae3d9d81 100644 --- a/src/features/api-docs/utils/rest-api.ts +++ b/src/features/api-docs/utils/rest-api.ts @@ -1,8 +1,7 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { SwaggerRequest } from '../types/client'; - -import type { ApiPropsBase, ApiPropsFull } from 'src/api/config'; +import type { ApiPropsBase, ApiPropsFull } from 'src/api/types'; import config from 'src/config'; @@ -119,4 +118,12 @@ export const REST_API_SECTIONS = [ requestInterceptor: microserviceRequestInterceptorFactory(config.apis.interchainIndexer), }, }, + config.apis.multichainStats && { + id: 'multichain-stats-api', + title: 'Multichain stats API', + swagger: { + url: getMicroserviceSwaggerUrl(config.apis.multichainStats), + requestInterceptor: microserviceRequestInterceptorFactory(config.apis.multichainStats), + }, + }, ].filter(Boolean); diff --git a/src/features/bridged-tokens/hooks/useBridgedTokensQuery.ts b/src/features/bridged-tokens/hooks/useBridgedTokensQuery.ts index eb855016557..eb548fb9057 100644 --- a/src/features/bridged-tokens/hooks/useBridgedTokensQuery.ts +++ b/src/features/bridged-tokens/hooks/useBridgedTokensQuery.ts @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TokensSortingValue, TokensSortingField, TokensSorting } from 'src/slices/token/types/api'; @@ -10,8 +9,8 @@ import { SORT_OPTIONS } from 'src/slices/token/utils/list-utils'; import { getBridgedChainsFilterValue } from 'src/features/bridged-tokens/utils/bridged-chains-filter'; -import useDebounce from 'src/shared/hooks/useDebounce'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; @@ -24,19 +23,8 @@ interface Props { } export default function useBridgedTokensQuery({ enabled }: Props) { - const router = useRouter(); - - const q = getQueryParamString(router.query.q); - - const [ searchTerm, setSearchTerm ] = React.useState<string>(q ?? ''); - const [ bridgeChains, setBridgeChains ] = React.useState<Array<string> | undefined>(getBridgedChainsFilterValue(router.query.chain_ids)); - const [ sort, setSort ] = React.useState<TokensSortingValue>(getSortValueFromQuery<TokensSortingValue>(router.query, SORT_OPTIONS) ?? 'default'); - - const debouncedSearchTerm = useDebounce(searchTerm, 300); - const query = useQueryWithPages({ + const query = useApiPaginatedQuery({ resourceName: 'core:tokens_bridged', - filters: { q: debouncedSearchTerm, chain_ids: bridgeChains }, - sorting: getSortParamsFromValue<TokensSortingValue, TokensSortingField, TokensSorting['order']>(sort), options: { enabled, placeholderData: generateListStub<'core:tokens_bridged'>( @@ -47,21 +35,22 @@ export default function useBridgedTokensQuery({ enabled }: Props) { }, }); - const onSearchTermChange = React.useCallback((value: string) => { - query.onFilterChange({ q: value, chain_ids: bridgeChains }); - setSearchTerm(value); - }, [ bridgeChains, query ]); + const searchTerm = getQueryParamString(query.filters.q); + const chainIdsParam = query.filters.chain_ids; + const bridgeChains = React.useMemo(() => getBridgedChainsFilterValue(chainIdsParam), [ chainIdsParam ]); + const sort = getSortValueFromQuery<TokensSortingValue>({ ...query.sorting }, SORT_OPTIONS) ?? 'default'; + + const { onFilterChange, onSortingChange } = query; + + const onSearchTermChange = useDebouncedFilterChange((value) => onFilterChange({ q: value, chain_ids: bridgeChains })); const onBridgeChainsChange = React.useCallback((value: Array<string>) => { - query.onFilterChange({ q: debouncedSearchTerm, chain_ids: value }); - setBridgeChains(value); - }, [ debouncedSearchTerm, query ]); + onFilterChange({ q: searchTerm, chain_ids: value }); + }, [ searchTerm, onFilterChange ]); const onSortChange: OnValueChangeHandler = React.useCallback(({ value }) => { - const sortValue = value[0] as TokensSortingValue; - setSort(sortValue); - query.onSortingChange(getSortParamsFromValue(sortValue)); - }, [ query ]); + onSortingChange(getSortParamsFromValue<TokensSortingValue, TokensSortingField, TokensSorting['order']>(value[0] as TokensSortingValue)); + }, [ onSortingChange ]); return React.useMemo(() => ({ query, diff --git a/src/features/bubblemaps/components/BubblemapsMap.tsx b/src/features/bubblemaps/components/BubblemapsMap.tsx new file mode 100644 index 00000000000..2a8488e88af --- /dev/null +++ b/src/features/bubblemaps/components/BubblemapsMap.tsx @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Box, Center, chakra } from '@chakra-ui/react'; +import React from 'react'; + +import config from 'src/config'; + +import { ContentLoader } from 'src/toolkit/components/loaders/ContentLoader'; + +const feature = config.features.bubblemaps; + +// fixed on every viewport, per https://docs.bubblemaps.io/iframe/quickstart (600px minimum) +const MAP_HEIGHT = '700px'; + +interface Props { + hash: string; + isLoading: boolean; +} + +const BubblemapsMap = ({ hash, isLoading }: Props) => { + const [ isFrameLoading, setIsFrameLoading ] = React.useState(true); + + const handleIframeLoad = React.useCallback(() => { + setIsFrameLoading(false); + }, []); + + if (!feature.isEnabled) { + return null; + } + + const url = new URL('https://iframe.bubblemaps.io/map'); + url.searchParams.set('address', hash); + url.searchParams.set('chain', feature.chainSlug); + url.searchParams.set('partnerId', feature.partnerId); + + return ( + <Box + h={ MAP_HEIGHT } + w="100%" + borderWidth="1px" + borderColor="border.divider" + borderRadius="base" + overflow="hidden" + > + { (isLoading || isFrameLoading) && ( + <Center h="100%"> + <ContentLoader/> + </Center> + ) } + { !isLoading && ( + <chakra.iframe + src={ url.toString() } + title="Bubblemaps" + allow="clipboard-write" + w="100%" + h="100%" + border="none" + display={ isFrameLoading ? 'none' : 'block' } + onLoad={ handleIframeLoad } + /> + ) } + </Box> + ); +}; + +export default React.memo(BubblemapsMap); diff --git a/src/features/bubblemaps/config.spec.ts b/src/features/bubblemaps/config.spec.ts new file mode 100644 index 00000000000..9b0ff519d90 --- /dev/null +++ b/src/features/bubblemaps/config.spec.ts @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import type bubblemapsConfig from './config'; + +async function loadConfig(envs: Array<[ string, string ]>): Promise<typeof bubblemapsConfig> { + return withEnvs(envs, async() => { + // `src/config` has to be imported first: reaching it through `./config` instead enters the + // graph mid-cycle, and `src/shell/metadata/config` then reads `app.baseUrl` off an + // uninitialised module + await import('src/config'); + return (await import('./config')).default; + }); +} + +describe('bubblemaps feature config', () => { + it('is enabled with both the chain slug and the partner id', async() => { + expect(await loadConfig(ENVS_MAP.bubblemaps)).toMatchObject({ + isEnabled: true, + chainSlug: 'eth', + partnerId: 'demo', + }); + }); + + it('is disabled without the chain slug', async() => { + expect((await loadConfig([ [ 'NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID', 'demo' ] ])).isEnabled).toBe(false); + }); + + it('is disabled without the partner id', async() => { + expect((await loadConfig([ [ 'NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG', 'eth' ] ])).isEnabled).toBe(false); + }); +}); diff --git a/src/features/bubblemaps/config.ts b/src/features/bubblemaps/config.ts new file mode 100644 index 00000000000..b3b2fa16892 --- /dev/null +++ b/src/features/bubblemaps/config.ts @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import app from 'src/config/app'; +import { getEnvValue } from 'src/config/utils/envs'; +import type { Feature } from 'src/config/utils/features'; + +const title = 'Bubblemaps'; + +const chainSlug = getEnvValue('NEXT_PUBLIC_BUBBLEMAPS_CHAIN_SLUG'); +const partnerId = getEnvValue('NEXT_PUBLIC_BUBBLEMAPS_PARTNER_ID'); + +const config: Feature<{ chainSlug: string; partnerId: string }> = (() => { + if (!app.isPrivateMode && chainSlug && partnerId) { + return Object.freeze({ + title, + isEnabled: true, + chainSlug, + partnerId, + }); + } + + return Object.freeze({ + title, + isEnabled: false, + }); +})(); + +export default config; diff --git a/src/features/chain-stats/components/ChartWidgetContainer.tsx b/src/features/chain-stats/components/ChartWidgetContainer.tsx index b71b0444771..bc385b578fb 100644 --- a/src/features/chain-stats/components/ChartWidgetContainer.tsx +++ b/src/features/chain-stats/components/ChartWidgetContainer.tsx @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route, type Route } from 'nextjs-routes'; import React from 'react'; import type { StatsIntervalIds } from '../types/client'; +import { route, type Route } from 'src/shared/router/routes'; import { useChartsConfig } from 'src/shared/stats/line-chart-config'; import { ChartResolution } from 'src/toolkit/components/charts'; diff --git a/src/features/chain-stats/hooks/useChainStats.ts b/src/features/chain-stats/hooks/useChainStats.ts new file mode 100644 index 00000000000..99118987c57 --- /dev/null +++ b/src/features/chain-stats/hooks/useChainStats.ts @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { uniqBy } from 'es-toolkit'; +import React from 'react'; + +import type { ChainStatsChart, ChainStatsPayload, ChainStatsSection, StatsIntervalIds } from '../types/client'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +import useApiQuery from 'src/api/hooks/useApiQuery'; + +import { CROSS_CHAIN_TXS_SECTIONS } from 'src/features/cross-chain-txs/utils/chain-stats'; + +import config from 'src/config'; +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; + +import { CHAIN_STATS_CHARTS } from '../stubs/charts'; + +function isSectionMatches(section: ChainStatsSection, currentSection: string): boolean { + return currentSection === 'all' || section.id === currentSection; +} + +function isChartNameMatches(q: string, chart: ChainStatsChart) { + return chart.title.toLowerCase().includes(q.toLowerCase()); +} + +interface Props { + chain?: ClusterChainConfig; +} + +export default function useChainStats({ chain }: Props = {}) { + const router = useRouter(); + + const [ sectionId, setSectionId ] = React.useState('all'); + const [ filterQuery, setFilterQuery ] = React.useState(''); + const [ initialFilterQuery, setInitialFilterQuery ] = React.useState(''); + const [ interval, setInterval ] = React.useState<StatsIntervalIds>('oneMonth'); + + const { data, isPlaceholderData, isError } = useApiQuery<'stats:lines', unknown, ChainStatsPayload>('stats:lines', { + queryOptions: { + placeholderData: CHAIN_STATS_CHARTS, + select: (data) => { + const crossChainTxsFeature = (chain?.app_config || config).features.crossChainTxs; + if (!crossChainTxsFeature.isEnabled) { + return data; + } + + const sections: Array<ChainStatsSection> = data.sections.slice(); + + for (const extraSection of CROSS_CHAIN_TXS_SECTIONS) { + const existingSection = sections.find((section) => section.id === extraSection.id); + if (existingSection) { + existingSection.charts = uniqBy([ + ...existingSection.charts, + ...extraSection.charts, + ], (chart) => chart.id); + } else { + sections.push(extraSection); + } + } + + return { + sections, + }; + }, + }, + chain, + }); + + React.useEffect(() => { + if (!isPlaceholderData && !isError) { + const chartId = getQueryParamString(router.query.chartId); + const chartName = data?.sections.map((section) => section.charts.find((chart) => chart.id === chartId)).filter(Boolean)[0]?.title; + if (chartName) { + setInitialFilterQuery(chartName); + setFilterQuery(chartName); + router.replace({ pathname: '/stats' }, { scroll: false }); + } + } + // run only when data is loaded + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ isPlaceholderData ]); + + const displayedSections = React.useMemo(() => { + return data?.sections + ?.map((section) => { + const charts = section.charts.filter((chart) => isSectionMatches(section, sectionId) && isChartNameMatches(filterQuery, chart)); + + return { + ...section, + charts, + }; + }).filter((section) => section.charts.length > 0); + }, [ sectionId, data?.sections, filterQuery ]); + + return React.useMemo(() => ({ + sections: data?.sections, + displayedSections, + sectionId, + + isLoading: isPlaceholderData, + isError, + + initialFilterQuery, + filterQuery, + + interval, + + onFilterChange: setFilterQuery, + onSectionChange: setSectionId, + onIntervalChange: setInterval, + }), [ data?.sections, displayedSections, sectionId, isPlaceholderData, isError, initialFilterQuery, filterQuery, interval ]); +} diff --git a/src/features/chain-stats/hooks/useChainStats.tsx b/src/features/chain-stats/hooks/useChainStats.tsx deleted file mode 100644 index 9c8d4e730bb..00000000000 --- a/src/features/chain-stats/hooks/useChainStats.tsx +++ /dev/null @@ -1,113 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { uniqBy } from 'es-toolkit'; -import { useRouter } from 'next/router'; -import React from 'react'; - -import type { ChainStatsChart, ChainStatsPayload, ChainStatsSection, StatsIntervalIds } from '../types/client'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; - -import useApiQuery from 'src/api/hooks/useApiQuery'; - -import { CROSS_CHAIN_TXS_SECTIONS } from 'src/features/cross-chain-txs/utils/chain-stats'; - -import config from 'src/config'; -import getQueryParamString from 'src/shared/router/get-query-param-string'; - -import { CHAIN_STATS_CHARTS } from '../stubs/charts'; - -function isSectionMatches(section: ChainStatsSection, currentSection: string): boolean { - return currentSection === 'all' || section.id === currentSection; -} - -function isChartNameMatches(q: string, chart: ChainStatsChart) { - return chart.title.toLowerCase().includes(q.toLowerCase()); -} - -interface Props { - chain?: ClusterChainConfig; -} - -export default function useChainStats({ chain }: Props = {}) { - const router = useRouter(); - - const [ sectionId, setSectionId ] = React.useState('all'); - const [ filterQuery, setFilterQuery ] = React.useState(''); - const [ initialFilterQuery, setInitialFilterQuery ] = React.useState(''); - const [ interval, setInterval ] = React.useState<StatsIntervalIds>('oneMonth'); - - const { data, isPlaceholderData, isError } = useApiQuery<'stats:lines', unknown, ChainStatsPayload>('stats:lines', { - queryOptions: { - placeholderData: CHAIN_STATS_CHARTS, - select: (data) => { - const crossChainTxsFeature = (chain?.app_config || config).features.crossChainTxs; - if (!crossChainTxsFeature.isEnabled) { - return data; - } - - const sections: Array<ChainStatsSection> = data.sections.slice(); - - for (const extraSection of CROSS_CHAIN_TXS_SECTIONS) { - const existingSection = sections.find((section) => section.id === extraSection.id); - if (existingSection) { - existingSection.charts = uniqBy([ - ...existingSection.charts, - ...extraSection.charts, - ], (chart) => chart.id); - } else { - sections.push(extraSection); - } - } - - return { - sections, - }; - }, - }, - chain, - }); - - React.useEffect(() => { - if (!isPlaceholderData && !isError) { - const chartId = getQueryParamString(router.query.chartId); - const chartName = data?.sections.map((section) => section.charts.find((chart) => chart.id === chartId)).filter(Boolean)[0]?.title; - if (chartName) { - setInitialFilterQuery(chartName); - setFilterQuery(chartName); - router.replace({ pathname: '/stats' }, undefined, { scroll: false }); - } - } - // run only when data is loaded - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ isPlaceholderData ]); - - const displayedSections = React.useMemo(() => { - return data?.sections - ?.map((section) => { - const charts = section.charts.filter((chart) => isSectionMatches(section, sectionId) && isChartNameMatches(filterQuery, chart)); - - return { - ...section, - charts, - }; - }).filter((section) => section.charts.length > 0); - }, [ sectionId, data?.sections, filterQuery ]); - - return React.useMemo(() => ({ - sections: data?.sections, - displayedSections, - sectionId, - - isLoading: isPlaceholderData, - isError, - - initialFilterQuery, - filterQuery, - - interval, - - onFilterChange: setFilterQuery, - onSectionChange: setSectionId, - onIntervalChange: setInterval, - }), [ data?.sections, displayedSections, sectionId, isPlaceholderData, isError, initialFilterQuery, filterQuery, interval ]); -} diff --git a/src/features/chain-stats/hooks/useChartQuery.tsx b/src/features/chain-stats/hooks/useChartQuery.ts similarity index 100% rename from src/features/chain-stats/hooks/useChartQuery.tsx rename to src/features/chain-stats/hooks/useChartQuery.ts diff --git a/src/features/chain-stats/mocks/transactions.ts b/src/features/chain-stats/mocks/transactions.ts new file mode 100644 index 00000000000..77008a7b79c --- /dev/null +++ b/src/features/chain-stats/mocks/transactions.ts @@ -0,0 +1,39 @@ +import type * as stats from '@blockscout/stats-types'; + +export const base: stats.TransactionsPageStats = { + pending_transactions_30m: { + id: 'pendingTxns30m', + value: '1245', + title: 'Pending transactions', + description: 'Transactions in the queue over the last 30 minutes', + units: '', + }, + transactions_24h: { + id: 'newTxns24h', + value: '1197340', + title: 'Transactions', + description: 'Transactions over the last 24 hours', + units: '', + }, + operational_transactions_24h: { + id: 'opTxns24h', + value: '1100000', + title: 'Operational transactions', + description: 'Operational transactions over the last 24 hours', + units: '', + }, + transactions_fee_24h: { + id: 'txnsFee24h', + value: '6734.1', + title: 'Transactions fees', + description: 'Fees paid over the last 24 hours', + units: 'ETH', + }, + average_transactions_fee_24h: { + id: 'averageTxnFee24h', + value: '0.0056', + title: 'Avg. transaction fee', + description: 'Average fee paid over the last 24 hours', + units: 'ETH', + }, +}; diff --git a/src/features/chain-stats/pages/details/ChainStatsDetails.tsx b/src/features/chain-stats/pages/details/ChainStatsDetails.tsx index b1182a2f896..e2ce7d917df 100644 --- a/src/features/chain-stats/pages/details/ChainStatsDetails.tsx +++ b/src/features/chain-stats/pages/details/ChainStatsDetails.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { StatsIntervalIds } from '../../types/client'; @@ -23,6 +22,7 @@ import { ALL_OPTION, isAllOption } from 'src/shared/external-chains/ChainSelect' import useIsInitialLoading from 'src/shared/hooks/useIsInitialLoading'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { useQueryParams } from 'src/shared/router/useQueryParams'; +import { useRouter } from 'src/shared/router/useRouter'; import type { OnValueChangeHandler } from 'src/toolkit/chakra/select'; diff --git a/src/features/chain-stats/pages/details/ChainStatsDetailsLineChart.tsx b/src/features/chain-stats/pages/details/ChainStatsDetailsLineChart.tsx index 7edc2eee82d..57f15f778e6 100644 --- a/src/features/chain-stats/pages/details/ChainStatsDetailsLineChart.tsx +++ b/src/features/chain-stats/pages/details/ChainStatsDetailsLineChart.tsx @@ -12,7 +12,7 @@ import ChainSelect from 'src/features/multichain/components/ChainSelect'; import { useMultichainContext } from 'src/features/multichain/context'; import useRoutedChainSelect from 'src/features/multichain/hooks/useRoutedChainSelect'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { useChartsConfig } from 'src/shared/stats/line-chart-config'; import type { OnValueChangeHandler, SelectOption } from 'src/toolkit/chakra/select'; @@ -66,7 +66,7 @@ const ChainStatsDetailsLineChart = ({ }, [ onZoomReset, onResolutionChange ]); const handleShare = React.useCallback(async() => { - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { Type: 'Share chart', Info: id }); + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Share chart', Info: id }); }, [ id ]); const resolutionCollection = React.useMemo(() => { diff --git a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png index 161d3a61d41..2e39ee44efa 100644 Binary files a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png and b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_dark-color-mode_cross-chain-txs-paths-view-dark-mode-mobile-1.png b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_dark-color-mode_cross-chain-txs-paths-view-dark-mode-mobile-1.png index f6dc06e02d3..464d7fbdc03 100644 Binary files a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_dark-color-mode_cross-chain-txs-paths-view-dark-mode-mobile-1.png and b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_dark-color-mode_cross-chain-txs-paths-view-dark-mode-mobile-1.png differ diff --git a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_default_base-view-dark-mode-mobile-1.png b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_default_base-view-dark-mode-mobile-1.png index 1b6d0bd3748..c3558f54596 100644 Binary files a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_default_base-view-dark-mode-mobile-1.png and b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_default_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_default_cross-chain-txs-paths-view-dark-mode-mobile-1.png b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_default_cross-chain-txs-paths-view-dark-mode-mobile-1.png index 676e4ab2f78..b007e63a8b5 100644 Binary files a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_default_cross-chain-txs-paths-view-dark-mode-mobile-1.png and b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_default_cross-chain-txs-paths-view-dark-mode-mobile-1.png differ diff --git a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_mobile_base-view-dark-mode-mobile-1.png b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_mobile_base-view-dark-mode-mobile-1.png index 124976e0ee4..1f62f952bb1 100644 Binary files a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_mobile_base-view-dark-mode-mobile-1.png and b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_mobile_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_mobile_cross-chain-txs-paths-view-dark-mode-mobile-1.png b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_mobile_cross-chain-txs-paths-view-dark-mode-mobile-1.png index d35f44f7673..18167f7f375 100644 Binary files a/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_mobile_cross-chain-txs-paths-view-dark-mode-mobile-1.png and b/src/features/chain-stats/pages/details/__screenshots__/ChainStatsDetails.pw.tsx_mobile_cross-chain-txs-paths-view-dark-mode-mobile-1.png differ diff --git a/src/features/chain-stats/pages/index/ChainStatsCounters.tsx b/src/features/chain-stats/pages/index/ChainStatsCounters.tsx index 8f747f2078b..b9970f99af2 100644 --- a/src/features/chain-stats/pages/index/ChainStatsCounters.tsx +++ b/src/features/chain-stats/pages/index/ChainStatsCounters.tsx @@ -1,16 +1,20 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Grid } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; import config from 'src/config'; import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; import { CHAIN_STATS_COUNTER } from '../../stubs/counters'; +const COLUMNS_NUM = { + desktop: 4, + mobile: 2, +}; const UNITS_WITHOUT_SPACE = [ 's' ]; const ChainStatsCounters = () => { @@ -32,10 +36,7 @@ const ChainStatsCounters = () => { } return ( - <Grid - gridTemplateColumns={{ base: 'repeat(2, calc((100% - 4px) / 2))', lg: 'repeat(4, calc((100% - 3 * 8px) / 4))' }} - gridGap={{ base: 1, lg: 2 }} - > + <StatsContainer columnsNum={ COLUMNS_NUM }> { data?.counters?.map(({ id, title, value, units, description }, index) => { @@ -61,7 +62,7 @@ const ChainStatsCounters = () => { ); }) } - </Grid> + </StatsContainer> ); }; diff --git a/src/features/chain-stats/utils/chart.ts b/src/features/chain-stats/utils/chart.ts index 30e2e361a03..6893e052e5e 100644 --- a/src/features/chain-stats/utils/chart.ts +++ b/src/features/chain-stats/utils/chart.ts @@ -1,9 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { Route } from 'nextjs-routes'; -import { route } from 'nextjs-routes'; - import config from 'src/config'; +import type { Route } from 'src/shared/router/routes'; +import { route } from 'src/shared/router/routes'; export function getChartUrl(href?: Route) { return href ? `${ config.app.baseUrl }${ route(href) }` : undefined; diff --git a/src/features/chain-stats/utils/interval.ts b/src/features/chain-stats/utils/interval.ts index 7772ed64dec..d6378539e79 100644 --- a/src/features/chain-stats/utils/interval.ts +++ b/src/features/chain-stats/utils/interval.ts @@ -1,11 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { NextRouter } from 'next/router'; - import { StatsIntervalId, type StatsIntervalIds } from '../types/client'; import { ChartResolution } from 'src/toolkit/components/charts/types'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import type { Router } from 'src/shared/router/useRouter'; import { formatDate } from 'src/shared/stats/line-chart-utils'; export const STATS_INTERVALS: { [key in StatsIntervalIds]: { title: string; shortTitle: string; start?: Date } } = { @@ -57,7 +56,7 @@ export function getDatesFromInterval(interval: StatsIntervalIds): { start?: stri }; } -export function getIntervalFromQuery(router: NextRouter): StatsIntervalIds | undefined { +export function getIntervalFromQuery(router: Router): StatsIntervalIds | undefined { const intervalFromQuery = getQueryParamString(router.query.interval); if (!intervalFromQuery || !Object.values(StatsIntervalId).includes(intervalFromQuery as StatsIntervalIds)) { diff --git a/src/features/chain-stats/utils/resolution.ts b/src/features/chain-stats/utils/resolution.ts index dca5b68c433..b5713d46908 100644 --- a/src/features/chain-stats/utils/resolution.ts +++ b/src/features/chain-stats/utils/resolution.ts @@ -1,14 +1,13 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { NextRouter } from 'next/router'; - import { ChartResolution } from 'src/toolkit/components/charts/types'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import type { Router } from 'src/shared/router/useRouter'; export const DEFAULT_RESOLUTION = ChartResolution.DAY; -export function getResolutionFromQuery(router: NextRouter): ChartResolution { +export function getResolutionFromQuery(router: Router): ChartResolution { const resolutionFromQuery = getQueryParamString(router.query.resolution) as (keyof typeof ChartResolution | undefined); if (!resolutionFromQuery || !ChartResolution[resolutionFromQuery]) { diff --git a/src/features/chain-variants/beacon-chain/components/BeaconChainDepositSignature.tsx b/src/features/chain-variants/beacon-chain/components/BeaconChainDepositSignature.tsx index e076780ed1a..9c55b98395b 100644 --- a/src/features/chain-variants/beacon-chain/components/BeaconChainDepositSignature.tsx +++ b/src/features/chain-variants/beacon-chain/components/BeaconChainDepositSignature.tsx @@ -1,19 +1,17 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { chakra, Text } from '@chakra-ui/react'; +import { chakra } from '@chakra-ui/react'; import React from 'react'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedTextTooltip } from 'src/toolkit/components/truncation/TruncatedTextTooltip'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const BeaconChainDepositSignature = ({ signature, isLoading }: { signature: string; isLoading: boolean }) => { return ( <Skeleton loading={ isLoading } display="grid" gridTemplateColumns="1fr 24px" overflow="hidden"> - <TruncatedTextTooltip label={ signature }> - <Text overflow="hidden" textOverflow="ellipsis" whiteSpace="nowrap">{ signature }</Text> - </TruncatedTextTooltip> + <Truncate value={ signature } type="end" w="100%"/> <CopyToClipboard text={ signature }/> </Skeleton> ); diff --git a/src/features/chain-variants/beacon-chain/components/BeaconChainValidatorLink.tsx b/src/features/chain-variants/beacon-chain/components/BeaconChainValidatorLink.tsx index bb74f9bf23e..d6f7c7a3afc 100644 --- a/src/features/chain-variants/beacon-chain/components/BeaconChainValidatorLink.tsx +++ b/src/features/chain-variants/beacon-chain/components/BeaconChainValidatorLink.tsx @@ -8,7 +8,7 @@ import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedTextTooltip } from 'src/toolkit/components/truncation/TruncatedTextTooltip'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const feature = config.features.beaconChain; @@ -41,9 +41,7 @@ const BeaconChainValidatorLink = ({ pubkey, isLoading }: { pubkey: string; isLoa display="grid" gridTemplateColumns="auto 20px" > - <TruncatedTextTooltip label={ pubkey }> - <Text overflow="hidden" textOverflow="ellipsis" whiteSpace="nowrap">{ pubkey }</Text> - </TruncatedTextTooltip> + <Truncate value={ pubkey } type="end" w="100%"/> </Link> ); } diff --git a/src/features/chain-variants/beacon-chain/pages/address/AddressDeposits.tsx b/src/features/chain-variants/beacon-chain/pages/address/AddressDeposits.tsx index 1ff395c2202..04c2f49c23e 100644 --- a/src/features/chain-variants/beacon-chain/pages/address/AddressDeposits.tsx +++ b/src/features/chain-variants/beacon-chain/pages/address/AddressDeposits.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; @@ -8,9 +7,10 @@ import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ import useIsMounted from 'src/shared/hooks/useIsMounted'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { TableContainerScrollable } from 'src/toolkit/chakra/table'; @@ -27,7 +27,7 @@ const AddressDeposits = ({ shouldRender = true, isQueryEnabled = true }: Props) const hash = getQueryParamString(router.query.hash); - const { data, isPlaceholderData, isError, pagination, queryHash } = useQueryWithPages({ + const { data, isInitialLoading, isTransitioning, isError, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:address_deposits', pathParams: { hash }, options: { @@ -49,7 +49,7 @@ const AddressDeposits = ({ shouldRender = true, isQueryEnabled = true }: Props) items={ data.items } view="address" top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } resetKey={ queryHash } /> </TableContainerScrollable> @@ -67,6 +67,7 @@ const AddressDeposits = ({ shouldRender = true, isQueryEnabled = true }: Props) itemsNum={ data?.items?.length } emptyText="There are no deposits for this address." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/beacon-chain/pages/address/AddressWithdrawals.tsx b/src/features/chain-variants/beacon-chain/pages/address/AddressWithdrawals.tsx index 5248c87457c..66401a7aa40 100644 --- a/src/features/chain-variants/beacon-chain/pages/address/AddressWithdrawals.tsx +++ b/src/features/chain-variants/beacon-chain/pages/address/AddressWithdrawals.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; @@ -11,9 +10,10 @@ import { WITHDRAWAL } from 'src/features/chain-variants/beacon-chain/stubs/withd import useIsMounted from 'src/shared/hooks/useIsMounted'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { TableContainerScrollable } from 'src/toolkit/chakra/table'; @@ -27,7 +27,7 @@ const AddressWithdrawals = ({ shouldRender = true, isQueryEnabled = true }: Prop const hash = getQueryParamString(router.query.hash); - const { data, isPlaceholderData, isError, pagination, queryHash } = useQueryWithPages({ + const { data, isInitialLoading, isTransitioning, isError, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:address_withdrawals', pathParams: { hash }, options: { @@ -49,7 +49,7 @@ const AddressWithdrawals = ({ shouldRender = true, isQueryEnabled = true }: Prop items={ data.items } view="address" top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } resetKey={ queryHash } /> </TableContainerScrollable> @@ -67,6 +67,7 @@ const AddressWithdrawals = ({ shouldRender = true, isQueryEnabled = true }: Prop itemsNum={ data?.items?.length } emptyText="There are no withdrawals for this address." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/beacon-chain/pages/block/BlockDeposits.tsx b/src/features/chain-variants/beacon-chain/pages/block/BlockDeposits.tsx index 415c677b213..4c5626fbfa9 100644 --- a/src/features/chain-variants/beacon-chain/pages/block/BlockDeposits.tsx +++ b/src/features/chain-variants/beacon-chain/pages/block/BlockDeposits.tsx @@ -1,40 +1,30 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import DataList from 'src/shared/lists/DataList'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; + +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import BeaconChainDepositsList from '../deposits/BeaconChainDepositsList'; import BeaconChainDepositsTable from '../deposits/BeaconChainDepositsTable'; type Props = { - blockDepositsQuery: QueryWithPagesResult<'core:block_deposits'>; + blockDepositsQuery: ApiPaginatedQueryResult<'core:block_deposits'>; }; const TABS_HEIGHT = 88; const BlockDeposits = ({ blockDepositsQuery }: Props) => { const content = blockDepositsQuery.data?.items ? ( - <> - <Box hideFrom="lg"> - <BeaconChainDepositsList - items={ blockDepositsQuery.data.items } - isLoading={ blockDepositsQuery.isPlaceholderData } - view="block" - resetKey={ blockDepositsQuery.queryHash } - /> - </Box> - <Box hideBelow="lg"> - <BeaconChainDepositsTable - items={ blockDepositsQuery.data.items } - isLoading={ blockDepositsQuery.isPlaceholderData } - top={ blockDepositsQuery.pagination.isVisible ? TABS_HEIGHT : 0 } - view="block" - resetKey={ blockDepositsQuery.queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <BeaconChainDepositsTable + items={ blockDepositsQuery.data.items } + isLoading={ blockDepositsQuery.isInitialLoading } + top={ blockDepositsQuery.pagination.isVisible ? TABS_HEIGHT : 0 } + view="block" + resetKey={ blockDepositsQuery.queryHash } + /> + </TableContainerScrollable> ) : null ; return ( @@ -42,6 +32,7 @@ const BlockDeposits = ({ blockDepositsQuery }: Props) => { isError={ blockDepositsQuery.isError } itemsNum={ blockDepositsQuery.data?.items?.length } emptyText="There are no deposits for this block." + isTransitioning={ blockDepositsQuery.isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/beacon-chain/pages/block/BlockWithdrawals.tsx b/src/features/chain-variants/beacon-chain/pages/block/BlockWithdrawals.tsx index a5713794a36..111e2e4f200 100644 --- a/src/features/chain-variants/beacon-chain/pages/block/BlockWithdrawals.tsx +++ b/src/features/chain-variants/beacon-chain/pages/block/BlockWithdrawals.tsx @@ -1,40 +1,30 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import DataList from 'src/shared/lists/DataList'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; + +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import BeaconChainWithdrawalsList from '../withdrawals/BeaconChainWithdrawalsList'; import BeaconChainWithdrawalsTable from '../withdrawals/BeaconChainWithdrawalsTable'; type Props = { - blockWithdrawalsQuery: QueryWithPagesResult<'core:block_withdrawals'>; + blockWithdrawalsQuery: ApiPaginatedQueryResult<'core:block_withdrawals'>; }; const TABS_HEIGHT = 88; const BlockWithdrawals = ({ blockWithdrawalsQuery }: Props) => { const content = blockWithdrawalsQuery.data?.items ? ( - <> - <Box hideFrom="lg"> - <BeaconChainWithdrawalsList - items={ blockWithdrawalsQuery.data.items } - isLoading={ blockWithdrawalsQuery.isPlaceholderData } - view="block" - resetKey={ blockWithdrawalsQuery.queryHash } - /> - </Box> - <Box hideBelow="lg"> - <BeaconChainWithdrawalsTable - items={ blockWithdrawalsQuery.data.items } - isLoading={ blockWithdrawalsQuery.isPlaceholderData } - top={ blockWithdrawalsQuery.pagination.isVisible ? TABS_HEIGHT : 0 } - view="block" - resetKey={ blockWithdrawalsQuery.queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <BeaconChainWithdrawalsTable + items={ blockWithdrawalsQuery.data.items } + isLoading={ blockWithdrawalsQuery.isInitialLoading } + top={ blockWithdrawalsQuery.pagination.isVisible ? TABS_HEIGHT : 0 } + view="block" + resetKey={ blockWithdrawalsQuery.queryHash } + /> + </TableContainerScrollable> ) : null ; return ( @@ -42,6 +32,7 @@ const BlockWithdrawals = ({ blockWithdrawalsQuery }: Props) => { isError={ blockWithdrawalsQuery.isError } itemsNum={ blockWithdrawalsQuery.data?.items?.length } emptyText="There are no withdrawals for this block." + isTransitioning={ blockWithdrawalsQuery.isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/beacon-chain/pages/block/useBlockDepositsQuery.ts b/src/features/chain-variants/beacon-chain/pages/block/useBlockDepositsQuery.ts index fa0631bdfec..ee69042d58c 100644 --- a/src/features/chain-variants/beacon-chain/pages/block/useBlockDepositsQuery.ts +++ b/src/features/chain-variants/beacon-chain/pages/block/useBlockDepositsQuery.ts @@ -3,13 +3,13 @@ import type { BlockQuery } from 'src/slices/block/hooks/useBlockQuery'; import config from 'src/config'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { DEPOSIT } from '../../stubs/deposits'; -export type BlockDepositsQuery = QueryWithPagesResult<'core:block_deposits'> & { +export type BlockDepositsQuery = ApiPaginatedQueryResult<'core:block_deposits'> & { isDegradedData: boolean; }; @@ -23,7 +23,7 @@ const beaconChainFeature = config.features.beaconChain; // No deposits data in RPC, so we use API only export default function useBlockDepositsQuery({ heightOrHash, blockQuery, tab }: Params): BlockDepositsQuery { - const apiQuery = useQueryWithPages({ + const apiQuery = useApiPaginatedQuery({ resourceName: 'core:block_deposits', pathParams: { height_or_hash: heightOrHash }, options: { diff --git a/src/features/chain-variants/beacon-chain/pages/block/useBlockWithdrawalsQuery.spec.ts b/src/features/chain-variants/beacon-chain/pages/block/useBlockWithdrawalsQuery.spec.ts new file mode 100644 index 00000000000..c0b185b1995 --- /dev/null +++ b/src/features/chain-variants/beacon-chain/pages/block/useBlockWithdrawalsQuery.spec.ts @@ -0,0 +1,37 @@ +// @vitest-environment jsdom + +import type { BlockQuery } from 'src/slices/block/hooks/useBlockQuery'; + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { renderHook, act, cleanup } from 'vitest/lib'; +import flushPromises from 'vitest/utils/flushPromises'; +import { routerStandIn } from 'vitest/utils/routerStandIn'; + +import useBlockWithdrawalsQuery from './useBlockWithdrawalsQuery'; + +const BLOCK_HEIGHT = '9004925'; + +const loadedBlockQuery = { isPlaceholderData: false, isDegradedData: false } as BlockQuery; + +beforeEach(() => { + fetchMock.resetMocks(); + routerStandIn.reset({ pathname: '/block/[height_or_hash]', query: { height_or_hash: BLOCK_HEIGHT, tab: 'withdrawals' } }); +}); + +afterEach(cleanup); + +describe('useBlockWithdrawalsQuery', () => { + it('stays on the placeholder without requests when the beacon chain feature is off', async() => { + const { result } = renderHook( + () => useBlockWithdrawalsQuery({ heightOrHash: BLOCK_HEIGHT, blockQuery: loadedBlockQuery, tab: 'withdrawals' }), + { wrapper: routerStandIn.appWrapper }, + ); + await act(flushPromises); + + expect(fetchMock.mock.calls).toHaveLength(0); + expect(result.current.isPlaceholderData).toBe(true); + expect(result.current.isDegradedData).toBe(false); + expect(result.current.isTransitioning).toBe(false); + expect(result.current.pagination).toMatchObject({ page: 1, isLoading: true }); + }); +}); diff --git a/src/features/chain-variants/beacon-chain/pages/block/useBlockWithdrawalsQuery.ts b/src/features/chain-variants/beacon-chain/pages/block/useBlockWithdrawalsQuery.ts index caaddf3be61..858b28c390c 100644 --- a/src/features/chain-variants/beacon-chain/pages/block/useBlockWithdrawalsQuery.ts +++ b/src/features/chain-variants/beacon-chain/pages/block/useBlockWithdrawalsQuery.ts @@ -18,8 +18,8 @@ import { getPublicClient, isPublicClientAvailable } from 'src/features/connect-w import config from 'src/config'; import hexToDecimal from 'src/shared/data/transformers/hex-to-decimal'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub, emptyPagination } from 'src/shared/pagination/utils'; import { SECOND } from 'src/toolkit/utils/consts'; @@ -28,7 +28,7 @@ import { WITHDRAWAL } from '../../stubs/withdrawals'; type RpcResponseType = GetBlockReturnType<Chain, false, 'latest'> | null; -export type BlockWithdrawalsQuery = QueryWithPagesResult<'core:block_withdrawals'> & { +export type BlockWithdrawalsQuery = ApiPaginatedQueryResult<'core:block_withdrawals'> & { isDegradedData: boolean; }; @@ -41,7 +41,7 @@ interface Params { export default function useBlockWithdrawalsQuery({ heightOrHash, blockQuery, tab }: Params): BlockWithdrawalsQuery { const [ isRefetchEnabled, setRefetchEnabled ] = React.useState(false); - const apiQuery = useQueryWithPages({ + const apiQuery = useApiPaginatedQuery({ resourceName: 'core:block_withdrawals', pathParams: { height_or_hash: heightOrHash }, options: { @@ -131,17 +131,19 @@ export default function useBlockWithdrawalsQuery({ heightOrHash, blockQuery, tab ((apiQuery.isError || apiQuery.isPlaceholderData) && apiQuery.errorUpdateCount > 0) ) && rpcQuery.data && isPublicClientAvailable); - const rpcQueryWithPages: QueryWithPagesResult<'core:block_withdrawals'> = { + const rpcPaginatedQuery: ApiPaginatedQueryResult<'core:block_withdrawals'> = { ...rpcQuery as UseQueryResult<operations['BlockController.withdrawals']['json'], ResourceError>, pagination: emptyPagination, onFilterChange: () => {}, onSortingChange: () => {}, - chainValue: undefined, - onChainValueChange: () => {}, + filters: apiQuery.filters, + sorting: apiQuery.sorting, queryHash: hashKey(rpcQueryKey), + isInitialLoading: rpcQuery.isPlaceholderData, + isTransitioning: false, }; - const query = isRpcQuery ? rpcQueryWithPages : apiQuery; + const query = isRpcQuery ? rpcPaginatedQuery : apiQuery; return { ...query, diff --git a/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDeposits.pw.tsx b/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDeposits.pw.tsx index e757f5d9890..29764dd7144 100644 --- a/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDeposits.pw.tsx +++ b/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDeposits.pw.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; -import { test, expect, devices } from 'playwright/lib'; +import { test, expect } from 'playwright/lib'; import { data as depositsData } from '../../mocks/deposits'; import BeaconChainDeposits from './BeaconChainDeposits'; @@ -14,15 +14,3 @@ test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { const component = await render(<BeaconChainDeposits/>); await expect(component).toHaveScreenshot(); }); - -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { - await mockEnvs(ENVS_MAP.beaconChain); - await mockTextAd(); - await mockApiResponse('core:deposits', depositsData); - await mockApiResponse('core:deposits_counters', { deposits_count: 111111 }); - const component = await render(<BeaconChainDeposits/>); - await expect(component).toHaveScreenshot(); - }); -}); diff --git a/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDeposits.tsx b/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDeposits.tsx index 6d338bd1862..f6bfa178746 100644 --- a/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDeposits.tsx +++ b/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDeposits.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Text } from '@chakra-ui/react'; import BigNumber from 'bignumber.js'; import React from 'react'; @@ -12,19 +12,19 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import config from 'src/config'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { DEPOSIT } from '../../stubs/deposits'; -import BeaconChainDepositsList from './BeaconChainDepositsList'; import BeaconChainDepositsTable from './BeaconChainDepositsTable'; const feature = config.features.beaconChain; const BeaconChainDeposits = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:deposits', options: { placeholderData: generateListStub<'core:deposits'>(DEPOSIT, 50, { next_page_params: { @@ -43,25 +43,15 @@ const BeaconChainDeposits = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <BeaconChainDepositsList - items={ data.items } - view="list" - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - <Box hideBelow="lg"> - <BeaconChainDepositsTable - items={ data.items } - view="list" - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <BeaconChainDepositsTable + items={ data.items } + view="list" + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -70,7 +60,7 @@ const BeaconChainDeposits = () => { } return ( - <Skeleton loading={ countersQuery.isPlaceholderData || isPlaceholderData } display="flex" flexWrap="wrap"> + <Skeleton loading={ countersQuery.isPlaceholderData || isInitialLoading } display="flex" flexWrap="wrap"> { countersQuery.data && ( <Text lineHeight={{ base: '24px', lg: '32px' }}> { BigNumber(countersQuery.data.deposits_count).toFormat() } deposits processed @@ -90,6 +80,7 @@ const BeaconChainDeposits = () => { itemsNum={ data?.items.length } emptyText="There are no deposits." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDepositsList.tsx b/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDepositsList.tsx deleted file mode 100644 index 32487378815..00000000000 --- a/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDepositsList.tsx +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import BeaconChainDepositsListItem from './BeaconChainDepositsListItem'; - -interface Props { - isLoading?: boolean; - items: Array<schemas['BeaconDeposit']>; - view: 'list' | 'block' | 'address'; - resetKey?: string; -} - -const DepositsList = ({ items, view, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => { - - const key = item.index + (isLoading ? String(index) : ''); - return ( - <BeaconChainDepositsListItem - key={ key } - item={ item } - view={ view } - isLoading={ isLoading } - /> - ); - }) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(DepositsList); diff --git a/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDepositsListItem.tsx b/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDepositsListItem.tsx deleted file mode 100644 index 050e5f58342..00000000000 --- a/src/features/chain-variants/beacon-chain/pages/deposits/BeaconChainDepositsListItem.tsx +++ /dev/null @@ -1,123 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import BeaconChainDepositSignature from '../../components/BeaconChainDepositSignature'; -import BeaconChainDepositStatusTag from '../../components/BeaconChainDepositStatusTag'; -import BeaconChainValidatorLink from '../../components/BeaconChainValidatorLink'; - -const feature = config.features.beaconChain; - -interface Props { - item: schemas['BeaconDeposit']; - view: 'list' | 'address' | 'block'; - isLoading?: boolean; -}; - -const BeaconChainDepositsListItem = ({ item, isLoading, view }: Props) => { - if (!feature.isEnabled || feature.withdrawalsOnly) { - return null; - } - - return ( - <ListItemMobileGrid.Container gridTemplateColumns="120px auto"> - - { item.transaction_hash && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Transaction hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntity hash={ item.transaction_hash } isLoading={ isLoading } truncation="constant_long"/> - </ListItemMobileGrid.Value> - </> - ) } - - { view !== 'block' && ( - <> - { item.block_number && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Block</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntity - number={ item.block_number } - hash={ item.block_hash } - isLoading={ isLoading } - /> - </ListItemMobileGrid.Value> - </> - ) } - - { item.block_timestamp && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.block_timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - </> - ) } - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Value</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <NativeCoinValue - amount={ item.amount } - loading={ isLoading } - /> - </ListItemMobileGrid.Value> - - { view !== 'address' && item.from_address && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>From</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity - address={ item.from_address } - isLoading={ isLoading } - truncation="constant" - /> - </ListItemMobileGrid.Value> - </> - ) } - - { item.pubkey && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>PubKey</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BeaconChainValidatorLink pubkey={ item.pubkey } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - </> - ) } - - { item.signature && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Signature</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BeaconChainDepositSignature signature={ item.signature } isLoading={ Boolean(isLoading) }/> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BeaconChainDepositStatusTag status={ item.status } isLoading={ Boolean(isLoading) }/> - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default BeaconChainDepositsListItem; diff --git a/src/features/chain-variants/beacon-chain/pages/deposits/__screenshots__/BeaconChainDeposits.pw.tsx_default_base-view-1.png b/src/features/chain-variants/beacon-chain/pages/deposits/__screenshots__/BeaconChainDeposits.pw.tsx_default_base-view-1.png index 96b8076de9d..2e7defabc2e 100644 Binary files a/src/features/chain-variants/beacon-chain/pages/deposits/__screenshots__/BeaconChainDeposits.pw.tsx_default_base-view-1.png and b/src/features/chain-variants/beacon-chain/pages/deposits/__screenshots__/BeaconChainDeposits.pw.tsx_default_base-view-1.png differ diff --git a/src/features/chain-variants/beacon-chain/pages/deposits/__screenshots__/BeaconChainDeposits.pw.tsx_default_mobile-base-view-1.png b/src/features/chain-variants/beacon-chain/pages/deposits/__screenshots__/BeaconChainDeposits.pw.tsx_default_mobile-base-view-1.png deleted file mode 100644 index 46b019241d1..00000000000 Binary files a/src/features/chain-variants/beacon-chain/pages/deposits/__screenshots__/BeaconChainDeposits.pw.tsx_default_mobile-base-view-1.png and /dev/null differ diff --git a/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawals.pw.tsx b/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawals.pw.tsx index a76ff98be59..6c4ac4fac8f 100644 --- a/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawals.pw.tsx +++ b/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawals.pw.tsx @@ -6,7 +6,7 @@ import { test, expect } from 'playwright/lib'; import { data as withdrawalsData } from '../../mocks/withdrawals'; import BeaconChainWithdrawals from './BeaconChainWithdrawals'; -test('base view +@mobile', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { +test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { await mockEnvs(ENVS_MAP.beaconChain); await mockTextAd(); await mockApiResponse('core:withdrawals', withdrawalsData); diff --git a/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawals.tsx b/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawals.tsx index f7e53489bda..e490912c9a9 100644 --- a/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawals.tsx +++ b/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawals.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Text } from '@chakra-ui/react'; import BigNumber from 'bignumber.js'; import React from 'react'; @@ -14,20 +14,20 @@ import { currencyUnits } from 'src/slices/chain/units'; import config from 'src/config'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import calculateUsdValue from 'src/shared/values/entity/calculateUsdValue'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { WITHDRAWAL } from '../../stubs/withdrawals'; -import BeaconChainWithdrawalsList from './BeaconChainWithdrawalsList'; import BeaconChainWithdrawalsTable from './BeaconChainWithdrawalsTable'; const feature = config.features.beaconChain; const BeaconChainWithdrawals = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:withdrawals', options: { placeholderData: generateListStub<'core:withdrawals'>(WITHDRAWAL, 50, { next_page_params: { @@ -47,25 +47,15 @@ const BeaconChainWithdrawals = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <BeaconChainWithdrawalsList - items={ data.items } - view="list" - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - <Box hideBelow="lg"> - <BeaconChainWithdrawalsTable - items={ data.items } - view="list" - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <BeaconChainWithdrawalsTable + items={ data.items } + view="list" + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -74,11 +64,14 @@ const BeaconChainWithdrawals = () => { } return ( - <Skeleton loading={ countersQuery.isPlaceholderData || isPlaceholderData } display="flex" flexWrap="wrap"> + <Skeleton loading={ countersQuery.isPlaceholderData || isInitialLoading } display="flex" flexWrap="wrap"> { countersQuery.data && ( <Text lineHeight={{ base: '24px', lg: '32px' }}> { BigNumber(countersQuery.data.withdrawals_count).toFormat() } withdrawals processed - and { calculateUsdValue({ amount: countersQuery.data.withdrawals_sum }).valueStr } { currencyUnits.ether } withdrawn + and { calculateUsdValue({ + amount: countersQuery.data.withdrawals_sum, + decimals: String(config.chain.currency.decimals), + }).valueStr } { currencyUnits.ether } withdrawn </Text> ) } </Skeleton> @@ -95,6 +88,7 @@ const BeaconChainWithdrawals = () => { itemsNum={ data?.items.length } emptyText="There are no withdrawals." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawalsList.tsx b/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawalsList.tsx deleted file mode 100644 index 85d17a86e9e..00000000000 --- a/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawalsList.tsx +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import BeaconChainWithdrawalsListItem from './BeaconChainWithdrawalsListItem'; - -interface Props { - isLoading?: boolean; - items: Array<schemas['BeaconWithdrawal']>; - view: 'address' | 'block' | 'list'; - resetKey?: string; -}; - -const WithdrawalsList = ({ items, view, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => { - - const key = item.index + (isLoading ? String(index) : ''); - - return ( - <BeaconChainWithdrawalsListItem - key={ key } - item={ item } - view={ view } - isLoading={ isLoading } - /> - ); - }) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(WithdrawalsList); diff --git a/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawalsListItem.tsx b/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawalsListItem.tsx deleted file mode 100644 index 1d14675ce59..00000000000 --- a/src/features/chain-variants/beacon-chain/pages/withdrawals/BeaconChainWithdrawalsListItem.tsx +++ /dev/null @@ -1,90 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -const feature = config.features.beaconChain; - -interface Props { - item: schemas['BeaconWithdrawal']; - view: 'address' | 'block' | 'list'; - isLoading?: boolean; -} - -const BeaconChainWithdrawalsListItem = ({ item, isLoading, view }: Props) => { - if (!feature.isEnabled) { - return null; - } - - return ( - <ListItemMobileGrid.Container gridTemplateColumns="100px auto"> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Index</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block">{ item.index }</Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Validator index</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block">{ item.validator_index }</Skeleton> - </ListItemMobileGrid.Value> - - { view !== 'block' && item.block_number && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Block</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntity - number={ item.block_number } - isLoading={ isLoading } - textStyle="sm" - /> - </ListItemMobileGrid.Value> - </> - ) } - - { view !== 'address' && item.receiver && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>To</ListItemMobileGrid.Label><ListItemMobileGrid.Value> - <AddressEntity - address={ item.receiver } - isLoading={ isLoading } - truncation="constant" - /> - </ListItemMobileGrid.Value> - </> - ) } - - { view !== 'block' && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Value</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <NativeCoinValue amount={ item.amount } loading={ isLoading }/> - </ListItemMobileGrid.Value> - </> - ) } - - </ListItemMobileGrid.Container> - ); -}; - -export default BeaconChainWithdrawalsListItem; diff --git a/src/features/chain-variants/beacon-chain/pages/withdrawals/__screenshots__/BeaconChainWithdrawals.pw.tsx_default_base-view-1.png b/src/features/chain-variants/beacon-chain/pages/withdrawals/__screenshots__/BeaconChainWithdrawals.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..710e12ddf7f Binary files /dev/null and b/src/features/chain-variants/beacon-chain/pages/withdrawals/__screenshots__/BeaconChainWithdrawals.pw.tsx_default_base-view-1.png differ diff --git a/src/features/chain-variants/beacon-chain/pages/withdrawals/__screenshots__/BeaconChainWithdrawals.pw.tsx_default_base-view-mobile-1.png b/src/features/chain-variants/beacon-chain/pages/withdrawals/__screenshots__/BeaconChainWithdrawals.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index ad6defc4c9a..00000000000 Binary files a/src/features/chain-variants/beacon-chain/pages/withdrawals/__screenshots__/BeaconChainWithdrawals.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/beacon-chain/pages/withdrawals/__screenshots__/BeaconChainWithdrawals.pw.tsx_mobile_base-view-mobile-1.png b/src/features/chain-variants/beacon-chain/pages/withdrawals/__screenshots__/BeaconChainWithdrawals.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 0146cbd07f6..00000000000 Binary files a/src/features/chain-variants/beacon-chain/pages/withdrawals/__screenshots__/BeaconChainWithdrawals.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsBlackfort.pw.tsx b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsBlackfort.pw.tsx index 67ff9da0c1b..5846864cd2e 100644 --- a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsBlackfort.pw.tsx +++ b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsBlackfort.pw.tsx @@ -8,7 +8,7 @@ import Validators from './ValidatorsBlackfort'; const chainType = 'blackfort'; -test('base view +@mobile', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { +test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { await mockEnvs([ [ 'NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE', chainType ], ]); diff --git a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsBlackfort.tsx b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsBlackfort.tsx index fc593cef6eb..6927c1b5516 100644 --- a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsBlackfort.tsx +++ b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsBlackfort.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, createListCollection, HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { @@ -18,15 +17,16 @@ import { VALIDATOR_BLACKFORT } from 'src/features/chain-variants/blackfort/stubs import config from 'src/config'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; import getSortValueFromQuery from 'src/shared/sort/get-sort-value-from-query'; import Sort from 'src/shared/sort/Sort'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import { VALIDATORS_BLACKFORT_SORT_OPTIONS } from './utils'; import ValidatorsCounters from './ValidatorsCounters'; -import ValidatorsList from './ValidatorsList'; import ValidatorsTable from './ValidatorsTable'; const sortCollection = createListCollection({ @@ -34,15 +34,8 @@ const sortCollection = createListCollection({ }); const ValidatorsBlackfort = () => { - const router = useRouter(); - const [ sort, setSort ] = - React.useState<ValidatorsBlackfortSortingValue>( - getSortValueFromQuery<ValidatorsBlackfortSortingValue>(router.query, VALIDATORS_BLACKFORT_SORT_OPTIONS) ?? 'default', - ); - - const { isError, isPlaceholderData, data, pagination, onSortingChange, queryHash } = useQueryWithPages({ + const { isError, isInitialLoading, isTransitioning, data, pagination, sorting, onSortingChange, queryHash } = useApiPaginatedQuery({ resourceName: 'core:validators_blackfort', - sorting: getSortParamsFromValue<ValidatorsBlackfortSortingValue, ValidatorsBlackfortSortingField, ValidatorsBlackfortSorting['order']>(sort), options: { enabled: config.features.validators.isEnabled, placeholderData: generateListStub<'core:validators_blackfort'>( @@ -53,10 +46,14 @@ const ValidatorsBlackfort = () => { }, }); + const sort = getSortValueFromQuery<ValidatorsBlackfortSortingValue>({ ...sorting }, VALIDATORS_BLACKFORT_SORT_OPTIONS) ?? 'default'; + const handleSortChange = React.useCallback(({ value }: { value: Array<string> }) => { - const sortValue = value[0] as ValidatorsBlackfortSortingValue; - setSort(sortValue); - onSortingChange(sortValue === 'default' ? undefined : getSortParamsFromValue(sortValue)); + onSortingChange( + getSortParamsFromValue<ValidatorsBlackfortSortingValue, ValidatorsBlackfortSortingField, ValidatorsBlackfortSorting['order']>( + value[0] as ValidatorsBlackfortSortingValue, + ), + ); }, [ onSortingChange ]); const sortButton = ( @@ -82,21 +79,16 @@ const ValidatorsBlackfort = () => { ); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <ValidatorsList data={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <ValidatorsTable - data={ data.items } - sort={ sort } - setSorting={ handleSortChange } - isLoading={ isPlaceholderData } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <ValidatorsTable + data={ data.items } + sort={ sort } + setSorting={ handleSortChange } + isLoading={ isInitialLoading } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; return ( @@ -108,6 +100,7 @@ const ValidatorsBlackfort = () => { itemsNum={ data?.items.length } emptyText="There are no validators." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsCounters.tsx b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsCounters.tsx index 203767af365..239d45cfa2c 100644 --- a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsCounters.tsx +++ b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsCounters.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -8,6 +7,7 @@ import useApiQuery from 'src/api/hooks/useApiQuery'; import { VALIDATORS_BLACKFORT_COUNTERS } from 'src/features/chain-variants/blackfort/stubs/validators'; import config from 'src/config'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; const ValidatorsCounters = () => { @@ -23,14 +23,14 @@ const ValidatorsCounters = () => { } return ( - <Box columnGap={ 3 } rowGap={ 3 } mb={ 6 } display="grid" gridTemplateColumns={{ base: '1fr', lg: 'repeat(2, 1fr)' }}> + <StatsContainer mb={ 6 }> <StatsWidget label="Total validators" value={ Number(countersQuery.data.validators_count).toLocaleString() } diff={ Number(countersQuery.data.new_validators_count_24h).toLocaleString() } isLoading={ countersQuery.isPlaceholderData } /> - </Box> + </StatsContainer> ); }; diff --git a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsList.tsx b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsList.tsx deleted file mode 100644 index 16aad4dfcd7..00000000000 --- a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { ValidatorBlackfort } from 'src/features/chain-variants/blackfort/types/api'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ValidatorsListItem from './ValidatorsListItem'; - -interface Props { - data: Array<ValidatorBlackfort>; - isLoading: boolean; - resetKey?: string; -} - -const ValidatorsList = ({ data, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <ValidatorsListItem - key={ item.address.hash + (isLoading ? index : '') } - data={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(ValidatorsList); diff --git a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsListItem.tsx b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsListItem.tsx deleted file mode 100644 index b4e87b3a2a0..00000000000 --- a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsListItem.tsx +++ /dev/null @@ -1,71 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex } from '@chakra-ui/react'; -import React from 'react'; - -import type { ValidatorBlackfort } from 'src/features/chain-variants/blackfort/types/api'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; - -interface Props { - data: ValidatorBlackfort; - isLoading?: boolean; -} - -const ValidatorsListItem = ({ data, isLoading }: Props) => { - - return ( - <ListItemMobileGrid.Container gridTemplateColumns="130px auto"> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Address</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity - isLoading={ isLoading } - address={ data.address } - truncation="constant" - /> - </ListItemMobileGrid.Value> - - { data.name && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Name</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Flex><TruncatedText text={ data.name } loading={ isLoading }/></Flex> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Commission</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - { `${ data.commission / 100 }%` } - </Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Self bonded</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <NativeCoinValue - amount={ data.self_bonded_amount } - loading={ isLoading } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Delegated amount</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <NativeCoinValue - amount={ data.delegated_amount } - loading={ isLoading } - /> - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default React.memo(ValidatorsListItem); diff --git a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsTable.tsx b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsTable.tsx index be4ce1a22c2..66255166948 100644 --- a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsTable.tsx +++ b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsTable.tsx @@ -10,6 +10,7 @@ import type { import { currencyUnits } from 'src/slices/chain/units'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import getNextSortValue from 'src/shared/sort/get-next-sort-value'; @@ -27,8 +28,11 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: ValidatorBlackfort): string => item.address.hash; + const ValidatorsTable = ({ data, sort, setSorting, isLoading, top, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); const onSortToggle = React.useCallback((field: ValidatorsBlackfortSortingField) => { const value = getNextSortValue<ValidatorsBlackfortSortingField, ValidatorsBlackfortSortingValue>(VALIDATORS_BLACKFORT_SORT_SEQUENCE, field)(sort); @@ -36,7 +40,7 @@ const ValidatorsTable = ({ data, sort, setSorting, isLoading, top, resetKey }: P }, [ sort, setSorting ]); return ( - <TableRoot> + <TableRoot minW="1000px"> <TableHeaderSticky top={ top }> <TableRow> <TableColumnHeaderSortable @@ -56,7 +60,7 @@ const ValidatorsTable = ({ data, sort, setSorting, isLoading, top, resetKey }: P <TableBody> { data.slice(0, renderedItemsNum).map((item, index) => ( <ValidatorsTableItem - key={ item.address.hash + (isLoading ? index : '') } + key={ keys[index] } data={ item } isLoading={ isLoading }/> )) } diff --git a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsTableItem.tsx b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsTableItem.tsx index f5c06cea979..11a68180508 100644 --- a/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsTableItem.tsx +++ b/src/features/chain-variants/blackfort/pages/validator-index/ValidatorsTableItem.tsx @@ -11,7 +11,7 @@ import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props { data: ValidatorBlackfort; @@ -30,7 +30,7 @@ const ValidatorsTableItem = ({ data, isLoading }: Props) => { </TableCell> <TableCell verticalAlign="middle"> <Flex> - <TruncatedText text={ data.name } loading={ isLoading }/> + <Truncate value={ data.name } type="end" loading={ isLoading }/> </Flex> </TableCell> <TableCell verticalAlign="middle" isNumeric> diff --git a/src/features/chain-variants/blackfort/pages/validator-index/__screenshots__/ValidatorsBlackfort.pw.tsx_default_base-view-1.png b/src/features/chain-variants/blackfort/pages/validator-index/__screenshots__/ValidatorsBlackfort.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..fe4367c701e Binary files /dev/null and b/src/features/chain-variants/blackfort/pages/validator-index/__screenshots__/ValidatorsBlackfort.pw.tsx_default_base-view-1.png differ diff --git a/src/features/chain-variants/blackfort/pages/validator-index/__screenshots__/ValidatorsBlackfort.pw.tsx_default_base-view-mobile-1.png b/src/features/chain-variants/blackfort/pages/validator-index/__screenshots__/ValidatorsBlackfort.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index a66f390e070..00000000000 Binary files a/src/features/chain-variants/blackfort/pages/validator-index/__screenshots__/ValidatorsBlackfort.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/blackfort/pages/validator-index/__screenshots__/ValidatorsBlackfort.pw.tsx_mobile_base-view-mobile-1.png b/src/features/chain-variants/blackfort/pages/validator-index/__screenshots__/ValidatorsBlackfort.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 7c5de02a80c..00000000000 Binary files a/src/features/chain-variants/blackfort/pages/validator-index/__screenshots__/ValidatorsBlackfort.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/celo/components/entity/EpochEntity.tsx b/src/features/chain-variants/celo/components/entity/EpochEntity.tsx index dddd246d363..2ce7c582fa5 100644 --- a/src/features/chain-variants/celo/components/entity/EpochEntity.tsx +++ b/src/features/chain-variants/celo/components/entity/EpochEntity.tsx @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as EntityBase from 'src/shared/entities/components'; import { distributeEntityProps } from 'src/shared/entities/utils'; +import { route } from 'src/shared/router/routes'; type LinkProps = EntityBase.LinkBaseProps & Pick<EntityProps, 'number'>; diff --git a/src/features/chain-variants/celo/pages/address/AddressCeloAccount.tsx b/src/features/chain-variants/celo/pages/address/AddressCeloAccount.tsx index 2dde9072651..40f1fe65bc1 100644 --- a/src/features/chain-variants/celo/pages/address/AddressCeloAccount.tsx +++ b/src/features/chain-variants/celo/pages/address/AddressCeloAccount.tsx @@ -13,7 +13,7 @@ import * as DetailedInfoItemBreakdown from 'src/shared/detailed-info/DetailedInf import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; import { Link } from 'src/toolkit/chakra/link'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props { isLoading?: boolean; @@ -30,7 +30,7 @@ const AddressCeloAccount = ({ isLoading, data }: Props) => { Celo account </DetailedInfo.ItemLabel> <DetailedInfo.ItemValue multiRow> - { data.name && <TruncatedText text={ data.name } mr={ 3 }/> } + { data.name && <Truncate value={ data.name } type="end" mr={ 3 }/> } <DetailedInfoItemBreakdown.Container loading={ isLoading }> <DetailedInfoItemBreakdown.Row label="Type" @@ -45,7 +45,7 @@ const AddressCeloAccount = ({ isLoading, data }: Props) => { hint="Link to additional information published by the account owner" > <Link href={ data.metadata_url } external> - <TruncatedText text={ data.metadata_url }/> + <Truncate value={ data.metadata_url } type="end"/> </Link> </DetailedInfoItemBreakdown.Row> ) } diff --git a/src/features/chain-variants/celo/pages/address/AddressEpochRewards.pw.tsx b/src/features/chain-variants/celo/pages/address/AddressEpochRewards.pw.tsx index 70daefc3737..607cfb2ce0d 100644 --- a/src/features/chain-variants/celo/pages/address/AddressEpochRewards.pw.tsx +++ b/src/features/chain-variants/celo/pages/address/AddressEpochRewards.pw.tsx @@ -14,7 +14,7 @@ const hooksConfig = { }, }; -test('base view +@mobile', async({ render, mockApiResponse }) => { +test('base view', async({ render, mockApiResponse }) => { await mockApiResponse('core:address_epoch_rewards', epochRewards, { pathParams: { hash: ADDRESS_HASH } }); const component = await render( <Box pt={{ base: '134px', lg: 6 }}> diff --git a/src/features/chain-variants/celo/pages/address/AddressEpochRewards.tsx b/src/features/chain-variants/celo/pages/address/AddressEpochRewards.tsx index 8896b640671..ce3058f80e7 100644 --- a/src/features/chain-variants/celo/pages/address/AddressEpochRewards.tsx +++ b/src/features/chain-variants/celo/pages/address/AddressEpochRewards.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; @@ -11,9 +10,10 @@ import CsvExport from 'src/features/csv-export/components/CsvExport'; import useIsMounted from 'src/shared/hooks/useIsMounted'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { TableContainerScrollable } from 'src/toolkit/chakra/table'; @@ -30,7 +30,7 @@ const AddressEpochRewards = ({ shouldRender = true, isQueryEnabled = true }: Pro const hash = getQueryParamString(router.query.hash); - const rewardsQuery = useQueryWithPages({ + const rewardsQuery = useApiPaginatedQuery({ resourceName: 'core:address_epoch_rewards', pathParams: { hash, @@ -56,7 +56,7 @@ const AddressEpochRewards = ({ shouldRender = true, isQueryEnabled = true }: Pro <AddressEpochRewardsTable items={ rewardsQuery.data.items } top={ rewardsQuery.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ rewardsQuery.isPlaceholderData } + isLoading={ rewardsQuery.isInitialLoading } resetKey={ rewardsQuery.queryHash } /> </TableContainerScrollable> @@ -85,6 +85,7 @@ const AddressEpochRewards = ({ shouldRender = true, isQueryEnabled = true }: Pro itemsNum={ rewardsQuery.data?.items?.length } emptyText="There are no epoch rewards for this address." actionBar={ actionBar } + isTransitioning={ rewardsQuery.isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/celo/pages/address/AddressEpochRewardsListItem.tsx b/src/features/chain-variants/celo/pages/address/AddressEpochRewardsListItem.tsx deleted file mode 100644 index 0d672c26f00..00000000000 --- a/src/features/chain-variants/celo/pages/address/AddressEpochRewardsListItem.tsx +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import EpochEntity from 'src/features/chain-variants/celo/components/entity/EpochEntity'; -import EpochRewardTypeTag from 'src/features/chain-variants/celo/components/EpochRewardTypeTag'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import TokenValue from 'src/shared/values/entity/TokenValue'; - -type Props = { - item: schemas['ElectionReward']; - isLoading?: boolean; -}; - -const AddressEpochRewardsListItem = ({ item, isLoading }: Props) => { - return ( - <ListItemMobileGrid.Container gridTemplateColumns="100px auto"> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Epoch #</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <EpochEntity number={ String(item.epoch_number) } noIcon isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.block_timestamp } - isLoading={ isLoading } - color="text.secondary" - display="inline-block" - /> - </ListItemMobileGrid.Value> - - { item.type && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Reward type</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <EpochRewardTypeTag type={ item.type } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Associated address</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity - address={ item.associated_account } - isLoading={ isLoading } - /> - </ListItemMobileGrid.Value> - - { item.token && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Value</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TokenValue - amount={ item.amount } - token={ item.token } - loading={ isLoading } - /> - </ListItemMobileGrid.Value> - </> - ) } - - </ListItemMobileGrid.Container> - ); -}; - -export default AddressEpochRewardsListItem; diff --git a/src/features/chain-variants/celo/pages/address/AddressEpochRewardsTableItem.tsx b/src/features/chain-variants/celo/pages/address/AddressEpochRewardsTableItem.tsx index c75f3980c30..cc7f557092a 100644 --- a/src/features/chain-variants/celo/pages/address/AddressEpochRewardsTableItem.tsx +++ b/src/features/chain-variants/celo/pages/address/AddressEpochRewardsTableItem.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -11,6 +10,7 @@ import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import EpochRewardTypeTag from 'src/features/chain-variants/celo/components/EpochRewardTypeTag'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import { route } from 'src/shared/router/routes'; import TokenValue from 'src/shared/values/entity/TokenValue'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/features/chain-variants/celo/pages/address/__screenshots__/AddressCeloAccount.pw.tsx_mobile_default-view-mobile-1.png b/src/features/chain-variants/celo/pages/address/__screenshots__/AddressCeloAccount.pw.tsx_mobile_default-view-mobile-1.png index ce6a9a3b12f..8784491fbdf 100644 Binary files a/src/features/chain-variants/celo/pages/address/__screenshots__/AddressCeloAccount.pw.tsx_mobile_default-view-mobile-1.png and b/src/features/chain-variants/celo/pages/address/__screenshots__/AddressCeloAccount.pw.tsx_mobile_default-view-mobile-1.png differ diff --git a/src/features/chain-variants/celo/pages/address/__screenshots__/AddressEpochRewards.pw.tsx_default_base-view-1.png b/src/features/chain-variants/celo/pages/address/__screenshots__/AddressEpochRewards.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..11c6fe53a50 Binary files /dev/null and b/src/features/chain-variants/celo/pages/address/__screenshots__/AddressEpochRewards.pw.tsx_default_base-view-1.png differ diff --git a/src/features/chain-variants/celo/pages/address/__screenshots__/AddressEpochRewards.pw.tsx_default_base-view-mobile-1.png b/src/features/chain-variants/celo/pages/address/__screenshots__/AddressEpochRewards.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 962ec432eac..00000000000 Binary files a/src/features/chain-variants/celo/pages/address/__screenshots__/AddressEpochRewards.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/celo/pages/address/__screenshots__/AddressEpochRewards.pw.tsx_mobile_base-view-mobile-1.png b/src/features/chain-variants/celo/pages/address/__screenshots__/AddressEpochRewards.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index ec5789991d9..00000000000 Binary files a/src/features/chain-variants/celo/pages/address/__screenshots__/AddressEpochRewards.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/celo/pages/block/BlockCeloEpochTag.tsx b/src/features/chain-variants/celo/pages/block/BlockCeloEpochTag.tsx index bcfa83a69b7..9ef969bd59e 100644 --- a/src/features/chain-variants/celo/pages/block/BlockCeloEpochTag.tsx +++ b/src/features/chain-variants/celo/pages/block/BlockCeloEpochTag.tsx @@ -1,11 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { HStack } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { BlockQuery } from 'src/slices/block/hooks/useBlockQuery'; +import { route } from 'src/shared/router/routes'; + import { Link } from 'src/toolkit/chakra/link'; import { Tag } from 'src/toolkit/chakra/tag'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; diff --git a/src/features/chain-variants/celo/pages/block/BlockDetailsBaseFeeCelo.pw.tsx b/src/features/chain-variants/celo/pages/block/BlockDetailsBaseFeeCelo.pw.tsx index 5c480528d29..15e94f78120 100644 --- a/src/features/chain-variants/celo/pages/block/BlockDetailsBaseFeeCelo.pw.tsx +++ b/src/features/chain-variants/celo/pages/block/BlockDetailsBaseFeeCelo.pw.tsx @@ -4,12 +4,14 @@ import React from 'react'; import type { BlockBaseFeeCelo } from 'src/features/chain-variants/celo/types/api'; import * as blockMock from 'src/slices/block/mocks/details'; +import * as tokenMock from 'src/slices/token/mocks/info'; import { test, expect } from 'playwright/lib'; import BlockDetailsBaseFeeCelo from './BlockDetailsBaseFeeCelo'; -test('base view +@mobile', async({ render }) => { +test('base view +@mobile', async({ render, mockAssetResponse }) => { + await mockAssetResponse(tokenMock.tokenInfoERC20a.icon_url as string, './playwright/mocks/image_s.jpg'); const component = await render( <Grid columnGap={ 8 } diff --git a/src/features/chain-variants/celo/pages/block/__screenshots__/BlockDetailsBaseFeeCelo.pw.tsx_default_base-view-mobile-1.png b/src/features/chain-variants/celo/pages/block/__screenshots__/BlockDetailsBaseFeeCelo.pw.tsx_default_base-view-mobile-1.png index 212012bc1fd..0e416842662 100644 Binary files a/src/features/chain-variants/celo/pages/block/__screenshots__/BlockDetailsBaseFeeCelo.pw.tsx_default_base-view-mobile-1.png and b/src/features/chain-variants/celo/pages/block/__screenshots__/BlockDetailsBaseFeeCelo.pw.tsx_default_base-view-mobile-1.png differ diff --git a/src/features/chain-variants/celo/pages/block/__screenshots__/BlockDetailsBaseFeeCelo.pw.tsx_mobile_base-view-mobile-1.png b/src/features/chain-variants/celo/pages/block/__screenshots__/BlockDetailsBaseFeeCelo.pw.tsx_mobile_base-view-mobile-1.png index 9c144c630ec..ee2d9a402a5 100644 Binary files a/src/features/chain-variants/celo/pages/block/__screenshots__/BlockDetailsBaseFeeCelo.pw.tsx_mobile_base-view-mobile-1.png and b/src/features/chain-variants/celo/pages/block/__screenshots__/BlockDetailsBaseFeeCelo.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/features/chain-variants/celo/pages/epoch-details/Epoch.pw.tsx b/src/features/chain-variants/celo/pages/epoch-details/Epoch.pw.tsx index ef979fa81e6..25f0b1acfe4 100644 --- a/src/features/chain-variants/celo/pages/epoch-details/Epoch.pw.tsx +++ b/src/features/chain-variants/celo/pages/epoch-details/Epoch.pw.tsx @@ -1,5 +1,7 @@ import React from 'react'; +import * as tokenMock from 'src/slices/token/mocks/info'; + import * as epochMock from 'src/features/chain-variants/celo/mocks/epoch'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; @@ -7,6 +9,10 @@ import { test, expect } from 'playwright/lib'; import Epoch from './Epoch'; +test.beforeEach(async({ mockAssetResponse }) => { + await mockAssetResponse(tokenMock.tokenInfoERC20a.icon_url as string, './playwright/mocks/image_s.jpg'); +}); + test('base view +@mobile', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { const hooksConfig = { router: { diff --git a/src/features/chain-variants/celo/pages/epoch-details/Epoch.tsx b/src/features/chain-variants/celo/pages/epoch-details/Epoch.tsx index 1aa3b69d1f3..5917a22c210 100644 --- a/src/features/chain-variants/celo/pages/epoch-details/Epoch.tsx +++ b/src/features/chain-variants/celo/pages/epoch-details/Epoch.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -16,6 +15,7 @@ import { CELO_EPOCH } from 'src/features/chain-variants/celo/stubs/epoch'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { Tag } from 'src/toolkit/chakra/tag'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; @@ -75,7 +75,7 @@ const EpochPageContent = () => { variant="subheading" { ...truncationProps } /> - { epochQuery.data.end_block_number && ( + { epochQuery.data.end_block_number !== null && ( <> <Box color="text.secondary">to</Box> <BlockEntity number={ epochQuery.data.end_block_number } variant="subheading" { ...truncationProps }/> diff --git a/src/features/chain-variants/celo/pages/epoch-details/__screenshots__/Epoch.pw.tsx_default_base-view-mobile-1.png b/src/features/chain-variants/celo/pages/epoch-details/__screenshots__/Epoch.pw.tsx_default_base-view-mobile-1.png index a7f580e01cd..95994736076 100644 Binary files a/src/features/chain-variants/celo/pages/epoch-details/__screenshots__/Epoch.pw.tsx_default_base-view-mobile-1.png and b/src/features/chain-variants/celo/pages/epoch-details/__screenshots__/Epoch.pw.tsx_default_base-view-mobile-1.png differ diff --git a/src/features/chain-variants/celo/pages/epoch-details/__screenshots__/Epoch.pw.tsx_mobile_base-view-mobile-1.png b/src/features/chain-variants/celo/pages/epoch-details/__screenshots__/Epoch.pw.tsx_mobile_base-view-mobile-1.png index 8c4dcccfe2c..b01184f5ade 100644 Binary files a/src/features/chain-variants/celo/pages/epoch-details/__screenshots__/Epoch.pw.tsx_mobile_base-view-mobile-1.png and b/src/features/chain-variants/celo/pages/epoch-details/__screenshots__/Epoch.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewardDetailsDesktop.tsx b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewardDetailsDesktop.tsx index bda2ff63eca..967e881ca31 100644 --- a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewardDetailsDesktop.tsx +++ b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewardDetailsDesktop.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Grid, GridItem, Text } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -10,6 +9,7 @@ import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import useLazyLoadedList from 'src/shared/pagination/useLazyLoadedList'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import AssetValue from 'src/shared/values/entity/AssetValue'; import { ContentLoader } from 'src/toolkit/components/loaders/ContentLoader'; diff --git a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewardDetailsMobile.tsx b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewardDetailsMobile.tsx deleted file mode 100644 index a1a632c762e..00000000000 --- a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewardDetailsMobile.tsx +++ /dev/null @@ -1,80 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box, Flex, Text } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import useLazyLoadedList from 'src/shared/pagination/useLazyLoadedList'; -import getQueryParamString from 'src/shared/router/get-query-param-string'; -import TokenValue from 'src/shared/values/entity/TokenValue'; - -import { ContentLoader } from 'src/toolkit/components/loaders/ContentLoader'; - -import { formatRewardType } from './utils'; - -interface Props { - type: keyof schemas['CeloEpochAggregatedElectionRewards']; - token: schemas['Token']; -} - -const CeloEpochElectionRewardDetailsMobile = ({ type, token }: Props) => { - const rootRef = React.useRef<HTMLDivElement>(null); - - const router = useRouter(); - const number = getQueryParamString(router.query.number); - - const { cutRef, query } = useLazyLoadedList({ - rootRef, - resourceName: 'core:epoch_celo_election_rewards', - pathParams: { number: number, reward_type: formatRewardType(type) }, - queryOptions: { - refetchOnMount: false, - }, - }); - - return ( - <Flex - flexDir="column" - rowGap={ 3 } - p={ 4 } - bgColor={{ _light: 'blackAlpha.50', _dark: 'whiteAlpha.50' }} - borderRadius="base" - maxH="360px" - overflowY="scroll" - > - - { query.data?.pages - .map((page) => page.items) - .flat() - .map((item, index) => { - return ( - <Flex key={ index } flexDir="column" alignItems="flex-start" rowGap={ 1 } fontWeight={ 400 }> - <AddressEntity address={ item.account } noIcon w="100%"/> - <TokenValue - amount={ item.amount } - token={ token } - tokenEntityProps={{ noIcon: true, ml: 1 }} - startElement={ <Box flexShrink={ 0 } color="text.secondary">got </Box> } - /> - <Flex columnGap={ 1 } alignItems="center" w="100%"> - <Box flexShrink={ 0 } color="text.secondary">on behalf of</Box> - <AddressEntity address={ item.associated_account } noIcon/> - </Flex> - </Flex> - ); - }) } - - { query.isFetching && <ContentLoader maxW="200px" mt={ 3 }/> } - - { query.isError && <Text color="text.error" mt={ 3 }>Something went wrong. Unable to load next page.</Text> } - - <Box h="0" w="100px" mt="-12px" ref={ cutRef }/> - </Flex> - ); -}; - -export default React.memo(CeloEpochElectionRewardDetailsMobile); diff --git a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewards.pw.tsx b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewards.pw.tsx index 3c06ad04a39..a9baf0e7146 100644 --- a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewards.pw.tsx +++ b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewards.pw.tsx @@ -1,5 +1,7 @@ import React from 'react'; +import * as tokenMock from 'src/slices/token/mocks/info'; + import * as celoEpochMock from 'src/features/chain-variants/celo/mocks/epoch'; import { test, expect } from 'playwright/lib'; @@ -13,7 +15,8 @@ const hooksConfig = { }, }; -test('base view', async({ render, mockApiResponse }) => { +test('base view', async({ render, mockApiResponse, mockAssetResponse }) => { + await mockAssetResponse(tokenMock.tokenInfoERC20a.icon_url as string, './playwright/mocks/image_s.jpg'); await mockApiResponse( 'core:epoch_celo_election_rewards', celoEpochMock.electionRewardDetails1, @@ -23,14 +26,3 @@ test('base view', async({ render, mockApiResponse }) => { await component.getByRole('cell', { name: 'Voting rewards' }).click(); await expect(component).toHaveScreenshot(); }); - -test('base view +@mobile -@default', async({ render, mockApiResponse }) => { - await mockApiResponse( - 'core:epoch_celo_election_rewards', - celoEpochMock.electionRewardDetails1, - { pathParams: { number, reward_type: 'voter' } }, - ); - const component = await render(<EpochElectionRewards data={ celoEpochMock.epoch1 }/>, { hooksConfig }); - await component.locator('div').filter({ hasText: 'Voting rewards' }).nth(3).click(); - await expect(component).toHaveScreenshot(); -}); diff --git a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewards.tsx b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewards.tsx index 6b1ca1bb6d4..64c4c2405cd 100644 --- a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewards.tsx +++ b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewards.tsx @@ -6,9 +6,8 @@ import React from 'react'; import type { schemas } from '@blockscout/api-types'; import { Heading } from 'src/toolkit/chakra/heading'; -import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; +import { TableBody, TableColumnHeader, TableContainerScrollable, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; -import EpochElectionRewardsListItem from './EpochElectionRewardsListItem'; import EpochElectionRewardsTableItem from './EpochElectionRewardsTableItem'; interface Props { @@ -24,8 +23,8 @@ const EpochElectionRewards = ({ data, isLoading }: Props) => { return ( <Box mt={ 6 }> <Heading level="3" mb={ 3 }>Election rewards</Heading> - <Box hideBelow="lg"> - <TableRoot style={{ tableLayout: 'auto' }}> + <TableContainerScrollable> + <TableRoot style={{ tableLayout: 'auto' }} minW="700px"> <TableHeaderSticky> <TableRow> <TableColumnHeader width="24px"/> @@ -54,26 +53,7 @@ const EpochElectionRewards = ({ data, isLoading }: Props) => { }) } </TableBody> </TableRoot> - </Box> - <Box hideFrom="lg"> - { Object.entries(data.aggregated_election_rewards).map((entry) => { - const key = entry[0] as keyof schemas['CeloEpochDetailed']['aggregated_election_rewards']; - const value = entry[1]; - - if (!value) { - return null; - } - - return ( - <EpochElectionRewardsListItem - key={ key } - type={ key } - isLoading={ isLoading } - data={ value } - /> - ); - }) } - </Box> + </TableContainerScrollable> </Box> ); }; diff --git a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewardsListItem.tsx b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewardsListItem.tsx deleted file mode 100644 index 51a7b442ac1..00000000000 --- a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/EpochElectionRewardsListItem.tsx +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box, Flex } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import EpochRewardTypeTag from 'src/features/chain-variants/celo/components/EpochRewardTypeTag'; - -import TokenValue from 'src/shared/values/entity/TokenValue'; -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import { IconButton } from 'src/toolkit/chakra/icon-button'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; - -import EpochElectionRewardDetailsMobile from './EpochElectionRewardDetailsMobile'; -import { getRewardNumText } from './utils'; - -interface Props { - data: schemas['CeloEpochAggregatedElectionReward']; - type: keyof schemas['CeloEpochAggregatedElectionRewards']; - isLoading?: boolean; -} - -const EpochElectionRewardsListItem = ({ data, isLoading, type }: Props) => { - const section = useDisclosure(); - - return ( - <Box - py={ 3 } - borderBottomWidth="1px" - borderColor="border.divider" - fontSize="sm" - onClick={ isLoading || !data.count ? undefined : section.onToggle } - cursor={ isLoading || !data.count ? undefined : 'pointer' } - > - <Flex my="3px" columnGap={ 3 } alignItems="center" flexWrap="wrap" rowGap={ 2 }> - { data.count ? ( - <Skeleton loading={ isLoading } display="flex" borderRadius="sm"> - <IconButton - aria-label={ section.open ? 'Collapse section' : 'Expand section' } - variant="link" - boxSize={ 6 } - > - <SpriteIcon - name="arrows/east-mini" - boxSize={ 6 } - transform={ section.open ? 'rotate(270deg)' : 'rotate(180deg)' } - transitionDuration="faster" - /> - </IconButton> - </Skeleton> - ) : <Box boxSize={ 6 }/> } - <EpochRewardTypeTag type={ type } isLoading={ isLoading }/> - <Skeleton loading={ isLoading } ml="auto">{ getRewardNumText(type, data.count) }</Skeleton> - <TokenValue - amount={ data.total } - token={ data.token } - accuracy={ 0 } - loading={ isLoading } - fontWeight={ 500 } - /> - </Flex> - { section.open && ( - <Box mt={ 2 }> - <EpochElectionRewardDetailsMobile type={ type } token={ data.token }/> - </Box> - ) } - </Box> - ); -}; - -export default React.memo(EpochElectionRewardsListItem); diff --git a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/__screenshots__/EpochElectionRewards.pw.tsx_default_base-view-1.png b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/__screenshots__/EpochElectionRewards.pw.tsx_default_base-view-1.png index 3ac096c7287..5fcca9e5aef 100644 Binary files a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/__screenshots__/EpochElectionRewards.pw.tsx_default_base-view-1.png and b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/__screenshots__/EpochElectionRewards.pw.tsx_default_base-view-1.png differ diff --git a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/__screenshots__/EpochElectionRewards.pw.tsx_mobile_base-view-mobile---default-1.png b/src/features/chain-variants/celo/pages/epoch-details/election-rewards/__screenshots__/EpochElectionRewards.pw.tsx_mobile_base-view-mobile---default-1.png deleted file mode 100644 index 2beb243f90d..00000000000 Binary files a/src/features/chain-variants/celo/pages/epoch-details/election-rewards/__screenshots__/EpochElectionRewards.pw.tsx_mobile_base-view-mobile---default-1.png and /dev/null differ diff --git a/src/features/chain-variants/celo/pages/epoch-index/Epochs.pw.tsx b/src/features/chain-variants/celo/pages/epoch-index/Epochs.pw.tsx index cf6e9d70abd..688a2a51f7c 100644 --- a/src/features/chain-variants/celo/pages/epoch-index/Epochs.pw.tsx +++ b/src/features/chain-variants/celo/pages/epoch-index/Epochs.pw.tsx @@ -7,7 +7,7 @@ import { test, expect } from 'playwright/lib'; import Epochs from './Epochs'; -test('base view +@mobile', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { +test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { await mockEnvs(ENVS_MAP.celo); await mockTextAd(); await mockApiResponse('core:epochs_celo', epochsList); diff --git a/src/features/chain-variants/celo/pages/epoch-index/Epochs.tsx b/src/features/chain-variants/celo/pages/epoch-index/Epochs.tsx index 89fdb65e806..1c378c63ba4 100644 --- a/src/features/chain-variants/celo/pages/epoch-index/Epochs.tsx +++ b/src/features/chain-variants/celo/pages/epoch-index/Epochs.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; @@ -11,14 +10,15 @@ import { CELO_EPOCH_ITEM } from 'src/features/chain-variants/celo/stubs/epoch'; import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; -import EpochsList from './EpochsList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import EpochsTable from './EpochsTable'; const EpochsPageContent = () => { - const epochsQuery = useQueryWithPages({ + const epochsQuery = useApiPaginatedQuery({ resourceName: 'core:epochs_celo', options: { placeholderData: generateListStub<'core:epochs_celo'>(CELO_EPOCH_ITEM, 50, { next_page_params: { @@ -34,7 +34,7 @@ const EpochsPageContent = () => { </ActionBar> ) : null; - const isLoading = epochsQuery.isPlaceholderData; + const isLoading = epochsQuery.isInitialLoading; const content = (() => { if (epochsQuery.isError) { @@ -42,23 +42,14 @@ const EpochsPageContent = () => { } return epochsQuery.data?.items ? ( - <> - <Box hideBelow="lg"> - <EpochsTable - items={ epochsQuery.data.items } - top={ epochsQuery.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isLoading } - resetKey={ epochsQuery.queryHash } - /> - </Box> - <Box hideFrom="lg"> - <EpochsList - items={ epochsQuery.data.items } - isLoading={ isLoading } - resetKey={ epochsQuery.queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <EpochsTable + items={ epochsQuery.data.items } + top={ epochsQuery.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isLoading } + resetKey={ epochsQuery.queryHash } + /> + </TableContainerScrollable> ) : null; })(); @@ -70,6 +61,7 @@ const EpochsPageContent = () => { itemsNum={ epochsQuery.data?.items?.length } emptyText="There are no epochs." actionBar={ actionBar } + isTransitioning={ epochsQuery.isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/celo/pages/epoch-index/EpochsList.tsx b/src/features/chain-variants/celo/pages/epoch-index/EpochsList.tsx deleted file mode 100644 index e4dfa17808e..00000000000 --- a/src/features/chain-variants/celo/pages/epoch-index/EpochsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import EpochsListItem from './EpochsListItem'; - -type Props = { - items: Array<schemas['CeloEpoch']>; - isLoading?: boolean; - resetKey?: string; -}; - -const EpochsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <EpochsListItem - key={ item.number + (isLoading ? String(index) : '') } - item={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default EpochsList; diff --git a/src/features/chain-variants/celo/pages/epoch-index/EpochsListItem.tsx b/src/features/chain-variants/celo/pages/epoch-index/EpochsListItem.tsx deleted file mode 100644 index 7f1cae11cee..00000000000 --- a/src/features/chain-variants/celo/pages/epoch-index/EpochsListItem.tsx +++ /dev/null @@ -1,80 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { HStack } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import CeloEpochStatus from 'src/features/chain-variants/celo/components/CeloEpochStatus'; -import EpochEntity from 'src/features/chain-variants/celo/components/entity/EpochEntity'; - -import dayjs from 'src/shared/date-and-time/dayjs'; -import Time from 'src/shared/date-and-time/Time'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import TextSeparator from 'src/shared/texts/TextSeparator'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - item: schemas['CeloEpoch']; - isLoading?: boolean; -} - -const EpochsListItem = ({ item, isLoading }: Props) => { - return ( - <ListItemMobile rowGap={ 1 } py={ 3 } w="full" textStyle="sm" fontWeight={ 500 } alignItems="stretch"> - <HStack minH="30px" gap={ 3 }> - <EpochEntity number={ String(item.number) } isLoading={ isLoading }/> - <Skeleton loading={ isLoading } color="text.secondary" fontWeight={ 400 } ml="auto"><span>{ item.type }</span></Skeleton> - <CeloEpochStatus isFinalized={ item.is_finalized } loading={ isLoading }/> - </HStack> - { item.timestamp && ( - <Skeleton loading={ isLoading } display="flex" alignItems="center" minH="30px" color="text.secondary"> - <div>{ dayjs(item.timestamp).fromNow() }</div> - <TextSeparator/> - <Time timestamp={ item.timestamp } format="lll_s"/> - </Skeleton> - ) } - <HStack minH="30px"> - <Skeleton loading={ isLoading }>Block range</Skeleton> - <Skeleton loading={ isLoading } color="text.secondary"> - <span>{ item.start_block_number } - { item.end_block_number || '' }</span> - </Skeleton> - </HStack> - { item.distribution?.community_transfer && 'value' in item.distribution.community_transfer ? ( - <HStack minH="30px"> - <Skeleton loading={ isLoading }>Community</Skeleton> - <NativeCoinValue - amount={ item.distribution.community_transfer.value } - loading={ isLoading } - color="text.secondary" - /> - </HStack> - ) : null } - { item.distribution?.carbon_offsetting_transfer && 'value' in item.distribution.carbon_offsetting_transfer ? ( - <HStack minH="30px"> - <Skeleton loading={ isLoading }>Carbon offset</Skeleton> - <NativeCoinValue - amount={ item.distribution.carbon_offsetting_transfer.value } - loading={ isLoading } - color="text.secondary" - /> - </HStack> - ) : null } - { item.distribution?.transfers_total ? ( - <HStack minH="30px"> - <Skeleton loading={ isLoading }>Total</Skeleton> - <NativeCoinValue - amount={ item.distribution?.transfers_total.value } - noSymbol - loading={ isLoading } - color="text.secondary" - /> - </HStack> - ) : null } - </ListItemMobile> - ); -}; - -export default EpochsListItem; diff --git a/src/features/chain-variants/celo/pages/epoch-index/__screenshots__/Epochs.pw.tsx_default_base-view-1.png b/src/features/chain-variants/celo/pages/epoch-index/__screenshots__/Epochs.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..e70de02296e Binary files /dev/null and b/src/features/chain-variants/celo/pages/epoch-index/__screenshots__/Epochs.pw.tsx_default_base-view-1.png differ diff --git a/src/features/chain-variants/celo/pages/epoch-index/__screenshots__/Epochs.pw.tsx_default_base-view-mobile-1.png b/src/features/chain-variants/celo/pages/epoch-index/__screenshots__/Epochs.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 7ae9d493031..00000000000 Binary files a/src/features/chain-variants/celo/pages/epoch-index/__screenshots__/Epochs.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/celo/pages/epoch-index/__screenshots__/Epochs.pw.tsx_mobile_base-view-mobile-1.png b/src/features/chain-variants/celo/pages/epoch-index/__screenshots__/Epochs.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 5fefcc7761b..00000000000 Binary files a/src/features/chain-variants/celo/pages/epoch-index/__screenshots__/Epochs.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/eden/pages/tx/TxDetailsEden.tsx b/src/features/chain-variants/eden/pages/tx/TxDetailsEden.tsx index 0a78dbb6892..c0a6bca1501 100644 --- a/src/features/chain-variants/eden/pages/tx/TxDetailsEden.tsx +++ b/src/features/chain-variants/eden/pages/tx/TxDetailsEden.tsx @@ -12,7 +12,7 @@ import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; /** One call of a sponsored batch transaction. `to` is `null` for a contract-creation call. */ type TransactionEdenCall = NonNullable<schemas['TransactionResponse']['calls']>[number]; @@ -47,7 +47,7 @@ const CallRow = ({ to, value, input, isLoading }: TransactionEdenCall & { isLoad <NativeCoinValue amount={ value } loading={ isLoading }/> </div> <Flex alignItems="flex-start" whiteSpace="normal" wordBreak="break-all"> - <TruncatedText text={ input } loading={ isLoading }/> + <Truncate value={ input } type="end" loading={ isLoading }/> <CopyToClipboard text={ input } isLoading={ isLoading }/> </Flex> </> diff --git a/src/features/chain-variants/mega-eth/pages/uptime/UptimeStats.tsx b/src/features/chain-variants/mega-eth/pages/uptime/UptimeStats.tsx index 016b61145ee..2cc8f03a340 100644 --- a/src/features/chain-variants/mega-eth/pages/uptime/UptimeStats.tsx +++ b/src/features/chain-variants/mega-eth/pages/uptime/UptimeStats.tsx @@ -1,10 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { UptimeRealTimeData } from 'src/features/chain-variants/mega-eth/types/api'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; interface Props { @@ -14,13 +14,7 @@ interface Props { const UptimeStats = ({ realtimeData }: Props) => { return ( - <Box - columnGap={ 2 } - rowGap={ 2 } - mb={ 8 } - display="grid" - gridTemplateColumns={{ base: '1fr', lg: 'repeat(4, 1fr)' }} - > + <StatsContainer mb={ 8 }> <StatsWidget label="Current TPS" hint="Number of transactions processed per second on the network" @@ -42,7 +36,7 @@ const UptimeStats = ({ realtimeData }: Props) => { valuePostfix=" ms" value={ realtimeData ? Number(realtimeData.instant_mini_block_interval).toLocaleString(undefined, { maximumFractionDigits: 2 }) : '-' } /> - </Box> + </StatsContainer> ); }; diff --git a/src/features/chain-variants/mega-eth/pages/uptime/__screenshots__/Uptime.pw.tsx_default_default-view-1.png b/src/features/chain-variants/mega-eth/pages/uptime/__screenshots__/Uptime.pw.tsx_default_default-view-1.png index b4d45c5df54..43bf8d897e5 100644 Binary files a/src/features/chain-variants/mega-eth/pages/uptime/__screenshots__/Uptime.pw.tsx_default_default-view-1.png and b/src/features/chain-variants/mega-eth/pages/uptime/__screenshots__/Uptime.pw.tsx_default_default-view-1.png differ diff --git a/src/features/chain-variants/mega-eth/pages/uptime/__screenshots__/Uptime.pw.tsx_default_default-view-2.png b/src/features/chain-variants/mega-eth/pages/uptime/__screenshots__/Uptime.pw.tsx_default_default-view-2.png index 3ef90aaae7a..c6b15519954 100644 Binary files a/src/features/chain-variants/mega-eth/pages/uptime/__screenshots__/Uptime.pw.tsx_default_default-view-2.png and b/src/features/chain-variants/mega-eth/pages/uptime/__screenshots__/Uptime.pw.tsx_default_default-view-2.png differ diff --git a/src/features/chain-variants/stability/pages/validator-index/ValidatorsCounters.tsx b/src/features/chain-variants/stability/pages/validator-index/ValidatorsCounters.tsx index cef6ba51b1e..494e8bb5537 100644 --- a/src/features/chain-variants/stability/pages/validator-index/ValidatorsCounters.tsx +++ b/src/features/chain-variants/stability/pages/validator-index/ValidatorsCounters.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -8,6 +7,7 @@ import useApiQuery from 'src/api/hooks/useApiQuery'; import { VALIDATORS_STABILITY_COUNTERS } from 'src/features/chain-variants/stability/stubs/validators'; import config from 'src/config'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; const ValidatorsCounters = () => { @@ -23,7 +23,7 @@ const ValidatorsCounters = () => { } return ( - <Box columnGap={ 3 } rowGap={ 3 } mb={ 6 } display="grid" gridTemplateColumns={{ base: '1fr', lg: 'repeat(2, 1fr)' }}> + <StatsContainer mb={ 6 }> <StatsWidget label="Total validators" value={ Number(countersQuery.data.validators_count).toLocaleString() } @@ -35,7 +35,7 @@ const ValidatorsCounters = () => { value={ `${ Number(countersQuery.data.active_validators_percentage).toLocaleString() }%` } isLoading={ countersQuery.isPlaceholderData } /> - </Box> + </StatsContainer> ); }; diff --git a/src/features/chain-variants/stability/pages/validator-index/ValidatorsList.tsx b/src/features/chain-variants/stability/pages/validator-index/ValidatorsList.tsx deleted file mode 100644 index eb85fd854b1..00000000000 --- a/src/features/chain-variants/stability/pages/validator-index/ValidatorsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { ValidatorStability } from 'src/features/chain-variants/stability/types/api'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ValidatorsListItem from './ValidatorsListItem'; - -interface Props { - data: Array<ValidatorStability>; - isLoading: boolean; - resetKey?: string; -} - -const ValidatorsList = ({ data, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <ValidatorsListItem - key={ item.address.hash + (isLoading ? index : '') } - data={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(ValidatorsList); diff --git a/src/features/chain-variants/stability/pages/validator-index/ValidatorsListItem.tsx b/src/features/chain-variants/stability/pages/validator-index/ValidatorsListItem.tsx deleted file mode 100644 index af9c4ffb65d..00000000000 --- a/src/features/chain-variants/stability/pages/validator-index/ValidatorsListItem.tsx +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { ValidatorStability } from 'src/features/chain-variants/stability/types/api'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import ValidatorStatus from 'src/features/chain-variants/stability/components/ValidatorStabilityStatus'; - -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - data: ValidatorStability; - isLoading?: boolean; -} - -const ValidatorsListItem = ({ data, isLoading }: Props) => { - - return ( - <ListItemMobileGrid.Container> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Address</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity - isLoading={ isLoading } - address={ data.address } - truncation="constant" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <ValidatorStatus state={ data.state } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Blocks</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - { data.blocks_validated_count.toLocaleString() } - </Skeleton> - </ListItemMobileGrid.Value> - </ListItemMobileGrid.Container> - ); -}; - -export default React.memo(ValidatorsListItem); diff --git a/src/features/chain-variants/stability/pages/validator-index/ValidatorsStability.pw.tsx b/src/features/chain-variants/stability/pages/validator-index/ValidatorsStability.pw.tsx index 9a730fd41aa..3db1023ce25 100644 --- a/src/features/chain-variants/stability/pages/validator-index/ValidatorsStability.pw.tsx +++ b/src/features/chain-variants/stability/pages/validator-index/ValidatorsStability.pw.tsx @@ -8,7 +8,7 @@ import Validators from './ValidatorsStability'; const chainType = 'stability'; -test('base view +@mobile', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { +test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { await mockEnvs([ [ 'NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE', chainType ], ]); diff --git a/src/features/chain-variants/stability/pages/validator-index/ValidatorsStability.tsx b/src/features/chain-variants/stability/pages/validator-index/ValidatorsStability.tsx index baee009a2b2..4feebf63889 100644 --- a/src/features/chain-variants/stability/pages/validator-index/ValidatorsStability.tsx +++ b/src/features/chain-variants/stability/pages/validator-index/ValidatorsStability.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, createListCollection, HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { @@ -11,7 +10,6 @@ import type { ValidatorsStabilitySortingValue, } from 'src/features/chain-variants/stability/types/api'; -// import useDebounce from 'src/shared/hooks/useDebounce'; import ActionBar from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; @@ -21,17 +19,18 @@ import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; import getSortValueFromQuery from 'src/shared/sort/get-sort-value-from-query'; import Sort from 'src/shared/sort/Sort'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import { VALIDATORS_STABILITY_SORT_OPTIONS } from './utils'; import ValidatorsCounters from './ValidatorsCounters'; import ValidatorsFilter from './ValidatorsFilter'; -import ValidatorsList from './ValidatorsList'; import ValidatorsTable from './ValidatorsTable'; const sortCollection = createListCollection({ @@ -39,25 +38,10 @@ const sortCollection = createListCollection({ }); const ValidatorsStability = () => { - const router = useRouter(); - // const [ searchTerm, setSearchTerm ] = React.useState(getQueryParamString(router.query.address_hash) || undefined); - const [ statusFilter, setStatusFilter ] = - React.useState(getQueryParamString(router.query.state_filter) as ValidatorsStabilityFilters['state_filter'] || undefined); - const [ sort, setSort ] = React.useState<ValidatorsStabilitySortingValue>( - getSortValueFromQuery<ValidatorsStabilitySortingValue>(router.query, VALIDATORS_STABILITY_SORT_OPTIONS) ?? 'default', - ); - - // const debouncedSearchTerm = useDebounce(searchTerm || '', 300); - const isMobile = useIsMobile(); - const { isError, isPlaceholderData, data, pagination, onFilterChange, onSortingChange, queryHash } = useQueryWithPages({ + const { isError, isInitialLoading, isTransitioning, data, pagination, filters, sorting, onFilterChange, onSortingChange, queryHash } = useApiPaginatedQuery({ resourceName: 'core:validators_stability', - filters: { - // address_hash: debouncedSearchTerm, - state_filter: statusFilter, - }, - sorting: getSortParamsFromValue<ValidatorsStabilitySortingValue, ValidatorsStabilitySortingField, ValidatorsStabilitySorting['order']>(sort), options: { enabled: config.features.validators.isEnabled, placeholderData: generateListStub<'core:validators_stability'>( @@ -68,13 +52,8 @@ const ValidatorsStability = () => { }, }); - // const handleSearchTermChange = React.useCallback((value: string) => { - // onFilterChange({ - // address_hash: value, - // state_filter: statusFilter - // }); - // setSearchTerm(value); - // }, [ statusFilter, onFilterChange ]); + const statusFilter = getQueryParamString(filters.state_filter) as ValidatorsStabilityFilters['state_filter'] || undefined; + const sort = getSortValueFromQuery<ValidatorsStabilitySortingValue>({ ...sorting }, VALIDATORS_STABILITY_SORT_OPTIONS) ?? 'default'; const handleStateFilterChange = React.useCallback((value: string | Array<string>) => { if (Array.isArray(value)) { @@ -83,32 +62,20 @@ const ValidatorsStability = () => { const state = value === 'all' ? undefined : value as ValidatorsStabilityFilters['state_filter']; - onFilterChange({ - // address_hash: debouncedSearchTerm, - state_filter: state, - }); - setStatusFilter(state); + onFilterChange({ state_filter: state }); }, [ onFilterChange ]); const handleSortChange = React.useCallback(({ value }: { value: Array<string> }) => { - const sortValue = value[0] as ValidatorsStabilitySortingValue; - setSort(sortValue); - onSortingChange(sortValue === 'default' ? undefined : getSortParamsFromValue(sortValue)); + onSortingChange( + getSortParamsFromValue<ValidatorsStabilitySortingValue, ValidatorsStabilitySortingField, ValidatorsStabilitySorting['order']>( + value[0] as ValidatorsStabilitySortingValue, + ), + ); }, [ onSortingChange ]); const filterMenu = <ValidatorsFilter onChange={ handleStateFilterChange } defaultValue={ statusFilter } hasActiveFilter={ Boolean(statusFilter) }/>; - // const filterInput = ( - // <FilterInput - // w={{ base: '100%', lg: '350px' }} - // size="xs" - // onChange={ handleSearchTermChange } - // placeholder="Search by validator's address hash" - // initialValue={ searchTerm } - // /> - // ); - const sortButton = ( <Sort name="validators_sorting" @@ -123,13 +90,11 @@ const ValidatorsStability = () => { <HStack gap={ 3 } mb={ 6 } display={{ base: 'flex', lg: 'none' }}> { filterMenu } { sortButton } - { /* { filterInput } */ } </HStack> { (!isMobile || pagination.isVisible) && ( <ActionBar mt={ -6 }> <HStack gap={ 3 } display={{ base: 'none', lg: 'flex' }}> { filterMenu } - { /* { filterInput } */ } </HStack> <Pagination ml="auto" { ...pagination }/> </ActionBar> @@ -138,20 +103,15 @@ const ValidatorsStability = () => { ); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <ValidatorsList data={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <ValidatorsTable - data={ data.items } - sort={ sort } - setSorting={ handleSortChange } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <ValidatorsTable + data={ data.items } + sort={ sort } + setSorting={ handleSortChange } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; return ( @@ -162,14 +122,12 @@ const ValidatorsStability = () => { isError={ isError } itemsNum={ data?.items.length } emptyText="There are no validators." - hasActiveFilters={ Boolean( - // searchTerm || - statusFilter, - ) } + hasActiveFilters={ Boolean(statusFilter) } emptyStateProps={{ term: 'validator', }} actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/stability/pages/validator-index/ValidatorsTable.tsx b/src/features/chain-variants/stability/pages/validator-index/ValidatorsTable.tsx index 635994be068..02ed7f80c1d 100644 --- a/src/features/chain-variants/stability/pages/validator-index/ValidatorsTable.tsx +++ b/src/features/chain-variants/stability/pages/validator-index/ValidatorsTable.tsx @@ -10,6 +10,7 @@ import type { import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import getNextSortValue from 'src/shared/sort/get-next-sort-value'; @@ -26,8 +27,11 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: ValidatorStability): string => item.address.hash; + const ValidatorsTable = ({ data, sort, setSorting, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); const onSortToggle = React.useCallback((field: ValidatorsStabilitySortingField) => { const value = getNextSortValue<ValidatorsStabilitySortingField, ValidatorsStabilitySortingValue>(VALIDATORS_STABILITY_SORT_SEQUENCE, field)(sort); @@ -35,7 +39,7 @@ const ValidatorsTable = ({ data, sort, setSorting, isLoading, resetKey }: Props) }, [ sort, setSorting ]); return ( - <TableRoot> + <TableRoot minW="500px"> <TableHeaderSticky top={ ACTION_BAR_HEIGHT_DESKTOP }> <TableRow> <TableColumnHeader width="50%">Validator's address</TableColumnHeader> @@ -61,7 +65,7 @@ const ValidatorsTable = ({ data, sort, setSorting, isLoading, resetKey }: Props) <TableBody> { data.slice(0, renderedItemsNum).map((item, index) => ( <ValidatorsTableItem - key={ item.address.hash + (isLoading ? index : '') } + key={ keys[index] } data={ item } isLoading={ isLoading }/> )) } diff --git a/src/features/chain-variants/stability/pages/validator-index/__screenshots__/ValidatorsStability.pw.tsx_default_base-view-1.png b/src/features/chain-variants/stability/pages/validator-index/__screenshots__/ValidatorsStability.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..7004dec6014 Binary files /dev/null and b/src/features/chain-variants/stability/pages/validator-index/__screenshots__/ValidatorsStability.pw.tsx_default_base-view-1.png differ diff --git a/src/features/chain-variants/stability/pages/validator-index/__screenshots__/ValidatorsStability.pw.tsx_default_base-view-mobile-1.png b/src/features/chain-variants/stability/pages/validator-index/__screenshots__/ValidatorsStability.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 897f2baf38b..00000000000 Binary files a/src/features/chain-variants/stability/pages/validator-index/__screenshots__/ValidatorsStability.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/stability/pages/validator-index/__screenshots__/ValidatorsStability.pw.tsx_mobile_base-view-mobile-1.png b/src/features/chain-variants/stability/pages/validator-index/__screenshots__/ValidatorsStability.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 1b42ef0354a..00000000000 Binary files a/src/features/chain-variants/stability/pages/validator-index/__screenshots__/ValidatorsStability.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/suave/pages/kettle/KettleTxs.tsx b/src/features/chain-variants/suave/pages/kettle/KettleTxs.tsx index f31c358b2ef..971079147a5 100644 --- a/src/features/chain-variants/suave/pages/kettle/KettleTxs.tsx +++ b/src/features/chain-variants/suave/pages/kettle/KettleTxs.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import PageTitle from 'src/shell/page/title/PageTitle'; @@ -9,16 +8,17 @@ import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import TxsWithFrontendSorting from 'src/slices/tx/pages/index/list/TxsWithFrontendSorting'; import { TX_ITEM } from 'src/slices/tx/stubs/tx'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; const KettleTxs = () => { const router = useRouter(); const hash = getQueryParamString(router.query.hash); - const query = useQueryWithPages({ + const query = useApiPaginatedQuery({ resourceName: 'core:txs_execution_node', pathParams: { hash }, options: { diff --git a/src/features/chain-variants/tac/components/AddressEntityTacTon.tsx b/src/features/chain-variants/tac/components/AddressEntityTacTon.tsx index 2e4be5620f5..f5380a7c6d9 100644 --- a/src/features/chain-variants/tac/components/AddressEntityTacTon.tsx +++ b/src/features/chain-variants/tac/components/AddressEntityTacTon.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as tac from '@blockscout/tac-operation-lifecycle-types'; @@ -9,6 +8,7 @@ import * as tac from '@blockscout/tac-operation-lifecycle-types'; import * as AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; const tacFeature = config.features.tac; diff --git a/src/features/chain-variants/tac/components/SearchBarSuggestTacOperation.tsx b/src/features/chain-variants/tac/components/SearchBarSuggestTacOperation.tsx index a36c58bb634..27883850d5f 100644 --- a/src/features/chain-variants/tac/components/SearchBarSuggestTacOperation.tsx +++ b/src/features/chain-variants/tac/components/SearchBarSuggestTacOperation.tsx @@ -7,9 +7,9 @@ import type { SearchResultTacOperation } from 'src/features/chain-variants/tac/t import type { ItemsProps } from 'src/slices/search/components/search-bar/SearchBarSuggest/types'; import Time from 'src/shared/date-and-time/Time'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import { Badge } from 'src/toolkit/chakra/badge'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import * as TacOperationEntity from './TacOperationEntity'; import TacOperationStatus from './TacOperationStatus'; @@ -18,7 +18,7 @@ const SearchBarSuggestTacOperation = ({ data, isMobile }: ItemsProps<SearchResul const icon = <TacOperationEntity.Icon status={ data.tac_operation.status }/>; const hash = ( <chakra.mark overflow="hidden" whiteSpace="nowrap" fontWeight={ 700 } mr={ 2 }> - <HashStringShortenDynamic hash={ data.tac_operation.operation_id } noTooltip/> + <Truncate value={ data.tac_operation.operation_id } tooltip={ false }/> </chakra.mark> ); const status = ( diff --git a/src/features/chain-variants/tac/components/TacOperationEntity.tsx b/src/features/chain-variants/tac/components/TacOperationEntity.tsx index ef7509f868a..819b649d339 100644 --- a/src/features/chain-variants/tac/components/TacOperationEntity.tsx +++ b/src/features/chain-variants/tac/components/TacOperationEntity.tsx @@ -1,13 +1,13 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Spinner, chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as tac from '@blockscout/tac-operation-lifecycle-types'; import * as EntityBase from 'src/shared/entities/components'; import { distributeEntityProps } from 'src/shared/entities/utils'; +import { route } from 'src/shared/router/routes'; type LinkProps = EntityBase.LinkBaseProps & Pick<EntityProps, 'id'>; diff --git a/src/features/chain-variants/tac/pages/operation-details/TacOperation.pw.tsx b/src/features/chain-variants/tac/pages/operation-details/TacOperation.pw.tsx index 70f113d0978..71d44042ff9 100644 --- a/src/features/chain-variants/tac/pages/operation-details/TacOperation.pw.tsx +++ b/src/features/chain-variants/tac/pages/operation-details/TacOperation.pw.tsx @@ -20,7 +20,6 @@ test('base view +@dark-mode +@mobile', async({ render, mockTextAd, mockApiRespon { hooksConfig: { router: { query: { id: tacOperationMock.tacOperation.operation_id }, - isReady: true, }, } }, ); @@ -46,7 +45,6 @@ test('pending operation', async({ render, mockTextAd, mockApiResponse, mockEnvs { hooksConfig: { router: { query: { id: tacOperationMock.tacOperation.operation_id }, - isReady: true, }, } }, ); diff --git a/src/features/chain-variants/tac/pages/operation-details/TacOperation.tsx b/src/features/chain-variants/tac/pages/operation-details/TacOperation.tsx index 9cacaee5088..c0ec4dc98d3 100644 --- a/src/features/chain-variants/tac/pages/operation-details/TacOperation.tsx +++ b/src/features/chain-variants/tac/pages/operation-details/TacOperation.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -11,6 +10,7 @@ import TextAd from 'src/features/ads/text/components/TextAd'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import TacOperationEntity from '../../components/TacOperationEntity'; import TacOperationTag from '../../components/TacOperationTag'; diff --git a/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png b/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png index 1abaea3c32e..d35affbe59e 100644 Binary files a/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png and b/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_default_base-view-dark-mode-mobile-1.png b/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_default_base-view-dark-mode-mobile-1.png index 4bfd88e4dc1..78049423ae2 100644 Binary files a/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_default_base-view-dark-mode-mobile-1.png and b/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_default_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_default_pending-operation-1.png b/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_default_pending-operation-1.png index b61832a8bb0..c8eb21e5aac 100644 Binary files a/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_default_pending-operation-1.png and b/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_default_pending-operation-1.png differ diff --git a/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_mobile_base-view-dark-mode-mobile-1.png b/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_mobile_base-view-dark-mode-mobile-1.png index 084b9d01732..1b46ef8c024 100644 Binary files a/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_mobile_base-view-dark-mode-mobile-1.png and b/src/features/chain-variants/tac/pages/operation-details/__screenshots__/TacOperation.pw.tsx_mobile_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/chain-variants/tac/pages/operations/TacOperations.tsx b/src/features/chain-variants/tac/pages/operations/TacOperations.tsx index 6063b2d21f6..85b497cbf1e 100644 --- a/src/features/chain-variants/tac/pages/operations/TacOperations.tsx +++ b/src/features/chain-variants/tac/pages/operations/TacOperations.tsx @@ -1,37 +1,30 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import ActionBar from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; -import useDebounce from 'src/shared/hooks/useDebounce'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { FilterInput } from 'src/toolkit/components/filters/FilterInput'; import { TAC_OPERATION } from '../../stubs'; -import TacOperationsList from './TacOperationsList'; import TacOperationsTable from './TacOperationsTable'; const TacOperations = () => { - const router = useRouter(); - const [ searchTerm, setSearchTerm ] = React.useState(getQueryParamString(router.query.q) || undefined); - - const debouncedSearchTerm = useDebounce(searchTerm || '', 300); - const isMobile = useIsMobile(); - const { isError, isPlaceholderData, data, pagination, onFilterChange, queryHash } = useQueryWithPages({ + const { isError, isInitialLoading, isTransitioning, data, pagination, filters, onFilterChange, queryHash } = useApiPaginatedQuery({ resourceName: 'tac:operations', - filters: { q: debouncedSearchTerm }, options: { placeholderData: generateListStub<'tac:operations'>( TAC_OPERATION, @@ -41,10 +34,9 @@ const TacOperations = () => { }, }); - const handleSearchTermChange = React.useCallback((value: string) => { - onFilterChange({ q: value }); - setSearchTerm(value); - }, [ onFilterChange ]); + const searchTerm = getQueryParamString(filters.q) || undefined; + + const handleSearchTermChange = useDebouncedFilterChange((value) => onFilterChange({ q: value })); const filterInput = ( <FilterInput @@ -73,14 +65,9 @@ const TacOperations = () => { ); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <TacOperationsList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <TacOperationsTable items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - </> + <TableContainerScrollable> + <TacOperationsTable items={ data.items } isLoading={ isInitialLoading } resetKey={ queryHash }/> + </TableContainerScrollable> ) : null; return ( @@ -90,11 +77,12 @@ const TacOperations = () => { isError={ isError } itemsNum={ data?.items?.length } emptyText="There are no operations." - hasActiveFilters={ Boolean(debouncedSearchTerm) } + hasActiveFilters={ Boolean(searchTerm) } emptyStateProps={{ term: 'operation', }} actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/tac/pages/operations/TacOperationsList.tsx b/src/features/chain-variants/tac/pages/operations/TacOperationsList.tsx deleted file mode 100644 index ced22f6a897..00000000000 --- a/src/features/chain-variants/tac/pages/operations/TacOperationsList.tsx +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type * as tac from '@blockscout/tac-operation-lifecycle-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import TacOperationsListItem from './TacOperationsListItem'; - -type Props = { - items: Array<tac.V2OperationBriefDetails>; - isLoading?: boolean; - resetKey?: string; -}; - -const TacOperationsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <TacOperationsListItem - key={ String(item.operation_id) + (isLoading ? index : '') } - isLoading={ isLoading } - item={ item } - /> - )) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - ); -}; - -export default TacOperationsList; diff --git a/src/features/chain-variants/tac/pages/operations/TacOperationsListItem.tsx b/src/features/chain-variants/tac/pages/operations/TacOperationsListItem.tsx deleted file mode 100644 index de82ccfd0f5..00000000000 --- a/src/features/chain-variants/tac/pages/operations/TacOperationsListItem.tsx +++ /dev/null @@ -1,71 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { HStack } from '@chakra-ui/react'; -import React from 'react'; - -import type * as tac from '@blockscout/tac-operation-lifecycle-types'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Badge } from 'src/toolkit/chakra/badge'; - -import AddressEntityTacTon from '../../components/AddressEntityTacTon'; -import TacOperationEntity from '../../components/TacOperationEntity'; -import TacOperationStatus from '../../components/TacOperationStatus'; - -type Props = { item: tac.V2OperationBriefDetails; isLoading?: boolean }; - -const TacOperationsListItem = ({ item, isLoading }: Props) => { - return ( - <ListItemMobileGrid.Container> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Operation</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TacOperationEntity - id={ item.operation_id } - status={ item.status } - isLoading={ isLoading } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.timestamp } - isLoading={ isLoading } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <HStack gap={ 1 } flexWrap="wrap"> - <TacOperationStatus - status={ item.status } - type={ item.type } - errorReason={ item.error_reason } - isLoading={ isLoading } - isRollback={ item.rollback } - /> - { item.rollback && <Badge loading={ isLoading }>Rollback</Badge> } - </HStack> - </ListItemMobileGrid.Value> - - { item.sender && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Sender</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntityTacTon - address={{ hash: item.sender.address }} - chainType={ item.sender.blockchain } - isLoading={ isLoading } - /> - </ListItemMobileGrid.Value> - </> - ) } - - </ListItemMobileGrid.Container> - ); -}; - -export default TacOperationsListItem; diff --git a/src/features/chain-variants/tac/pages/operations/TacOperationsTable.tsx b/src/features/chain-variants/tac/pages/operations/TacOperationsTable.tsx index 74419bd3fe5..687a05a6a89 100644 --- a/src/features/chain-variants/tac/pages/operations/TacOperationsTable.tsx +++ b/src/features/chain-variants/tac/pages/operations/TacOperationsTable.tsx @@ -7,6 +7,7 @@ import type * as tac from '@blockscout/tac-operation-lifecycle-types'; import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -19,8 +20,11 @@ type Props = { resetKey?: string; }; +const getBaseKey = (item: tac.V2OperationBriefDetails): string => String(item.operation_id); + const TacOperationsTable = ({ items, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( <AddressHighlightProvider> @@ -38,7 +42,7 @@ const TacOperationsTable = ({ items, isLoading, resetKey }: Props) => { </TableHeaderSticky> <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( - <TacOperationsTableItem key={ String(item.operation_id) + (isLoading ? index : '') } item={ item } isLoading={ isLoading }/> + <TacOperationsTableItem key={ keys[index] } item={ item } isLoading={ isLoading }/> )) } <TableRow ref={ cutRef }/> </TableBody> diff --git a/src/features/chain-variants/zeta-chain/components/AddressEntityZetaChain.pw.tsx b/src/features/chain-variants/zeta-chain/components/AddressEntityZetaChain.pw.tsx index e2f9b24b005..3c2b840bcf7 100644 --- a/src/features/chain-variants/zeta-chain/components/AddressEntityZetaChain.pw.tsx +++ b/src/features/chain-variants/zeta-chain/components/AddressEntityZetaChain.pw.tsx @@ -12,6 +12,7 @@ import AddressEntityZetaChain from './AddressEntityZetaChain'; test.use({ viewport: { width: 180, height: 140 } }); const CCTX_CONFIG_URL = 'http://localhost:3000/zeta-config.json'; +const SEPOLIA_LOGO_URL = 'https://example.com/sepolia-logo.svg'; test.beforeEach(async({ mockEnvs, mockConfigResponse }) => { await mockEnvs([ @@ -24,7 +25,7 @@ test.beforeEach(async({ mockEnvs, mockConfigResponse }) => { }); test('with chain icon', async({ render, mockAssetResponse }) => { - await mockAssetResponse('https://example.com/sepolia-logo.svg', './playwright/mocks/image_svg.svg'); + await mockAssetResponse(SEPOLIA_LOGO_URL, './playwright/mocks/image_svg.svg'); const component = await render( <AddressEntityZetaChain address={ addressParamMock.withoutName } @@ -35,13 +36,17 @@ test('with chain icon', async({ render, mockAssetResponse }) => { await expect(component).toHaveScreenshot(); }); -test('with chain icon stub +@dark-mode', async({ render }) => { +test('with chain icon stub +@dark-mode', async({ render, page }) => { + // the stub replaces the loading skeleton only after the global interceptor aborts the logo request + const chainLogoRequestFailed = page.waitForEvent('requestfailed', (request) => request.url() === SEPOLIA_LOGO_URL); + const component = await render( <AddressEntityZetaChain address={ addressParamMock.withoutName } chainId="11155111" />, ); + await chainLogoRequestFailed; await expect(component).toHaveScreenshot(); }); diff --git a/src/features/chain-variants/zeta-chain/components/SearchBarSuggestZetaChainCCTX.tsx b/src/features/chain-variants/zeta-chain/components/SearchBarSuggestZetaChainCCTX.tsx index b6927a07a40..40093f604cb 100644 --- a/src/features/chain-variants/zeta-chain/components/SearchBarSuggestZetaChainCCTX.tsx +++ b/src/features/chain-variants/zeta-chain/components/SearchBarSuggestZetaChainCCTX.tsx @@ -9,9 +9,9 @@ import SearchBarSuggestItemLink from 'src/slices/search/components/search-bar/Se import Time from 'src/shared/date-and-time/Time'; import { route } from 'src/shared/router/routes'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import SpriteIcon from 'src/sprite/SpriteIcon'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import { SECOND } from 'src/toolkit/utils/consts'; interface Props { @@ -27,7 +27,7 @@ const SearchBarSuggestZetaChainCCTX = ({ data, isMobile, searchTerm, onClick }: // search term can be either cctx hash or observed hash (hash from another chain) const hash = ( <chakra.span as={ searchTerm === data.index ? 'mark' : 'span' } overflow="hidden" whiteSpace="nowrap" fontWeight={ 700 }> - <HashStringShortenDynamic hash={ data.index } noTooltip/> + <Truncate value={ data.index } tooltip={ false }/> </chakra.span> ); diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-details/ZetaChainCCTX.pw.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-details/ZetaChainCCTX.pw.tsx index cc218c92eec..670f4f06da0 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-details/ZetaChainCCTX.pw.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-details/ZetaChainCCTX.pw.tsx @@ -1,5 +1,7 @@ import React from 'react'; +import * as statsMock from 'src/slices/chain/stats/mocks'; + import { zetaChainCCTX, zetaChainCCTXFailed } from 'src/features/chain-variants/zeta-chain/mocks/cctx'; import { zetaChainCCTXConfig } from 'src/features/chain-variants/zeta-chain/mocks/cctx-config'; @@ -17,10 +19,11 @@ const hooksConfig = { }, }; -test.beforeEach(async({ mockEnvs, mockTextAd, mockConfigResponse, mockAssetResponse }) => { +test.beforeEach(async({ mockEnvs, mockTextAd, mockConfigResponse, mockAssetResponse, mockApiResponse }) => { await mockEnvs(ENVS_MAP.zetaChain); await mockTextAd(); await mockConfigResponse('NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', CCTX_CONFIG_URL, zetaChainCCTXConfig); + await mockApiResponse('core:stats', statsMock.base); await mockAssetResponse(zetaChainCCTXConfig[1].chain_logo, './playwright/mocks/image_s.jpg'); await mockAssetResponse(zetaChainCCTXConfig[2].chain_logo, './playwright/mocks/image_svg.svg'); }); diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-details/ZetaChainCCTX.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-details/ZetaChainCCTX.tsx index c733c3becd0..c6235b58ad6 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-details/ZetaChainCCTX.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-details/ZetaChainCCTX.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -13,6 +12,7 @@ import { ZETA_CHAIN_CCTX } from 'src/features/chain-variants/zeta-chain/stubs'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import ZetaChainCCTXDetails from './ZetaChainCCTXDetails'; diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_dark-color-mode_failed-transaction-dark-mode-mobile-1.png b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_dark-color-mode_failed-transaction-dark-mode-mobile-1.png index ea61a7a9b7a..c8276b1891d 100644 Binary files a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_dark-color-mode_failed-transaction-dark-mode-mobile-1.png and b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_dark-color-mode_failed-transaction-dark-mode-mobile-1.png differ diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_dark-color-mode_successful-transaction-dark-mode-mobile-1.png b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_dark-color-mode_successful-transaction-dark-mode-mobile-1.png index f08a0b6be84..214af65b3a0 100644 Binary files a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_dark-color-mode_successful-transaction-dark-mode-mobile-1.png and b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_dark-color-mode_successful-transaction-dark-mode-mobile-1.png differ diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_default_failed-transaction-dark-mode-mobile-1.png b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_default_failed-transaction-dark-mode-mobile-1.png index ab5a5cc1876..cbd51aa2cd6 100644 Binary files a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_default_failed-transaction-dark-mode-mobile-1.png and b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_default_failed-transaction-dark-mode-mobile-1.png differ diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_default_successful-transaction-dark-mode-mobile-1.png b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_default_successful-transaction-dark-mode-mobile-1.png index f12c14743a2..5eec6bfc44a 100644 Binary files a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_default_successful-transaction-dark-mode-mobile-1.png and b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_default_successful-transaction-dark-mode-mobile-1.png differ diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_mobile_failed-transaction-dark-mode-mobile-1.png b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_mobile_failed-transaction-dark-mode-mobile-1.png index 27ad2f67bb0..f52858b8b07 100644 Binary files a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_mobile_failed-transaction-dark-mode-mobile-1.png and b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_mobile_failed-transaction-dark-mode-mobile-1.png differ diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_mobile_successful-transaction-dark-mode-mobile-1.png b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_mobile_successful-transaction-dark-mode-mobile-1.png index 211e74a48b2..a13590cd6da 100644 Binary files a/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_mobile_successful-transaction-dark-mode-mobile-1.png and b/src/features/chain-variants/zeta-chain/pages/cctx-details/__screenshots__/ZetaChainCCTX.pw.tsx_mobile_successful-transaction-dark-mode-mobile-1.png differ diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/TransactionsZetaChain.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/TransactionsZetaChain.tsx index 20adf7577f9..f033263b469 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/TransactionsZetaChain.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/TransactionsZetaChain.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -21,9 +20,10 @@ import AdvancedFilterLink from 'src/features/advanced-filter/components/Advanced import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -38,9 +38,9 @@ const TransactionsZetaChain = () => { const isMobile = useIsMobile(); const tab = getQueryParamString(router.query.tab); - const txsWithBlobsQuery = useQueryWithPages({ + const txsWithBlobsQuery = useApiPaginatedQuery({ resourceName: 'core:txs', - filters: { type: 'blob_transaction' }, + queryParams: { type: 'blob_transaction' }, options: { enabled: config.features.dataAvailability.isEnabled && tab === 'blob_txs', placeholderData: generateListStub<'core:txs'>(TX_ITEM, 50, { next_page_params: { @@ -51,7 +51,7 @@ const TransactionsZetaChain = () => { }, }); - const txsWatchlistQuery = useQueryWithPages({ + const txsWatchlistQuery = useApiPaginatedQuery({ resourceName: 'core:txs_watchlist', options: { enabled: tab === 'watchlist', diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainAddressFilter.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainAddressFilter.tsx index b2b32cc6bec..40a682e6f97 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainAddressFilter.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainAddressFilter.tsx @@ -11,7 +11,8 @@ import useZetaChainConfig from 'src/features/chain-variants/zeta-chain/hooks/use import type { Props as ChainSelectBaseProps } from 'src/shared/external-chains/ChainSelect'; import ChainSelectBase from 'src/shared/external-chains/ChainSelect'; -import TableColumnFilter from 'src/shared/filters/TableColumnFilter'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; import { Input } from 'src/toolkit/chakra/input'; import { InputGroup } from 'src/toolkit/chakra/input-group'; @@ -91,6 +92,7 @@ const ChainSelect = ({ chainsConfig, value, onValueChange, ...props }: ChainSele }} contentProps={{ zIndex: 'modal2', + pt: 0, }} /> ); @@ -161,19 +163,15 @@ const ZetaChainAddressFilter = ({ const isTouched = !isEqual( currentValue.map(item => item.address.trim()).filter(Boolean).sort(), - value.sort(), - ) || !isEqual(currentChainValue.sort(), chainValue.sort()); + value.slice().sort(), + ) || !isEqual(currentChainValue.slice().sort(), chainValue.slice().sort()); return ( - <TableColumnFilter - title={ title } - isFilled={ isFilled } + <ColumnFilterContent isTouched={ isTouched } onFilter={ onFilter } - onReset={ onReset } - hasReset > - <VStack gap={ 3 } align="stretch"> + <ColumnFilterContentSection title={ title } isFilled={ isFilled } onReset={ onReset }> <ChainSelect value={ currentChainValue } onValueChange={ handleChainChange } @@ -193,8 +191,8 @@ const ZetaChainAddressFilter = ({ /> )) } </VStack> - </VStack> - </TableColumnFilter> + </ColumnFilterContentSection> + </ColumnFilterContent> ); }; diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainAssetFilter.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainAssetFilter.tsx index 5cf18a78d36..a56f11ec8a4 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainAssetFilter.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainAssetFilter.tsx @@ -15,7 +15,8 @@ import NativeTokenIcon from 'src/slices/token/components/icon/TokenIconNative'; import { toTokenModel } from 'src/slices/token/utils/model'; import config from 'src/config'; -import TableColumnFilter from 'src/shared/filters/TableColumnFilter'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; import useDebounce from 'src/shared/hooks/useDebounce'; import { PopoverCloseTriggerWrapper } from 'src/toolkit/chakra/popover'; @@ -127,38 +128,67 @@ const ZetaChainAssetFilter = ({ value = null, handleFilterChange }: Props) => { }, [ handleFilterChange ]); return ( - <TableColumnFilter - title="Asset" - isFilled={ Boolean(currentValue) } + <ColumnFilterContent isTouched={ !isEqual(currentValue, value) } onFilter={ onFilter } - onReset={ onReset } - hasReset > - <FilterInput - placeholder="Search by token name or symbol" - initialValue={ searchTerm } - onChange={ onSearchChange } - loading={ tokensQuery.isLoading } - /> - { !searchTerm && currentValue && ( - <Flex key={ currentValue.address_hash } alignItems="center"> - <Flex alignItems="center" gap={ 2 } flexGrow={ 1 }> - { currentValue.symbol === 'ZETA' ? ( - <NativeTokenIcon boxSize={ 5 } mr={ 2 }/> - ) : ( - <TokenEntity.Icon token={ currentValue }/> - ) } - <TokenEntity.Content token={ currentValue } onlySymbol/> + <ColumnFilterContentSection title="Asset" isFilled={ Boolean(currentValue) } onReset={ onReset }> + <FilterInput + placeholder="Search by token name or symbol" + initialValue={ searchTerm } + onChange={ onSearchChange } + loading={ tokensQuery.isLoading } + /> + { !searchTerm && currentValue && ( + <Flex key={ currentValue.address_hash } alignItems="center"> + <Flex alignItems="center" gap={ 2 } flexGrow={ 1 }> + { currentValue.symbol === 'ZETA' ? ( + <NativeTokenIcon boxSize={ 5 } mr={ 2 }/> + ) : ( + <TokenEntity.Icon token={ currentValue }/> + ) } + <TokenEntity.Content token={ currentValue } onlySymbol/> + </Flex> + <ClearButton onClick={ handleRemove }/> </Flex> - <ClearButton onClick={ handleRemove }/> - </Flex> - ) } - { tokensQuery.isLoading && <Spinner display="block" mt={ 3 }/> } + ) } + { tokensQuery.isLoading && <Spinner display="block"/> } + { searchTerm && tokensQuery.data && !filteredTokens.length && <Text>No tokens found</Text> } + { searchTerm && tokensQuery.data && Boolean(filteredTokens.length) && ( + <Flex display="flex" flexDir="column" rowGap={ 2 } maxH="250px" overflowY="scroll" ml="-4px"> + { filteredTokens.map(token => ( + <PopoverCloseTriggerWrapper key={ token.zrc20_contract_address }> + <Flex + alignItems="center" + p={ 2 } + borderRadius="md" + cursor="pointer" + _hover={{ bg: 'selected.control.bg' }} + onClick={ onTokenClick(token) } + > + { /* FIXME: I'd use TokenEntity here, but it prevents onTokenClick callback from being called */ } + <TokenEntity.Icon token={ toTokenModel({ + address_hash: token.zrc20_contract_address, + symbol: token.symbol, + name: token.name, + decimals: token.decimals.toString(), + total_supply: null, + icon_url: token.icon_url, + type: 'ERC-20', + holders_count: null, + exchange_rate: null, + circulating_market_cap: null, + }) }/> + { token.symbol || token.name || token.zrc20_contract_address } + </Flex> + </PopoverCloseTriggerWrapper> + )) } + </Flex> + ) } + </ColumnFilterContentSection> { tokensQuery.data && !searchTerm && ( - <> - <Text color="text.secondary" fontWeight="600" mt={ 3 }>Popular</Text> - <Flex rowGap={ 3 } flexWrap="wrap" gap={ 3 } mb={ 2 }> + <ColumnFilterContentSection title="Popular"> + <Flex flexWrap="wrap" gap={ 2 }> { [ ZETA_NATIVE_TOKEN, ...filteredTokens.map(token => toTokenModel({ address_hash: token.zrc20_contract_address, symbol: token.symbol, @@ -185,41 +215,9 @@ const ZetaChainAssetFilter = ({ value = null, handleFilterChange }: Props) => { </PopoverCloseTriggerWrapper> )) } </Flex> - </> - ) } - { searchTerm && tokensQuery.data && !filteredTokens.length && <Text>No tokens found</Text> } - { searchTerm && tokensQuery.data && Boolean(filteredTokens.length) && ( - <Flex display="flex" flexDir="column" rowGap={ 3 } maxH="250px" overflowY="scroll" mt={ 3 } ml="-4px"> - { filteredTokens.map(token => ( - <PopoverCloseTriggerWrapper key={ token.zrc20_contract_address }> - <Flex - alignItems="center" - p={ 2 } - borderRadius="md" - cursor="pointer" - _hover={{ bg: 'gray.50' }} - onClick={ onTokenClick(token) } - > - { /* FIXME: I'd use TokenEntity here, but it prevents onTokenClick callback from being called */ } - <TokenEntity.Icon token={ toTokenModel({ - address_hash: token.zrc20_contract_address, - symbol: token.symbol, - name: token.name, - decimals: token.decimals.toString(), - total_supply: null, - icon_url: token.icon_url, - type: 'ERC-20', - holders_count: null, - exchange_rate: null, - circulating_market_cap: null, - }) }/> - { token.symbol || token.name || token.zrc20_contract_address } - </Flex> - </PopoverCloseTriggerWrapper> - )) } - </Flex> + </ColumnFilterContentSection> ) } - </TableColumnFilter> + </ColumnFilterContent> ); }; diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXListItem.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXListItem.tsx deleted file mode 100644 index 5e03951b8b0..00000000000 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXListItem.tsx +++ /dev/null @@ -1,73 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Grid, VStack, Text } from '@chakra-ui/react'; -import React from 'react'; - -import type { CctxListItem } from '@blockscout/zetachain-cctx-types'; - -import AddressEntityZetaChain from 'src/features/chain-variants/zeta-chain/components/AddressEntityZetaChain'; -import TxEntityZetaChainCC from 'src/features/chain-variants/zeta-chain/components/TxEntityZetaChainCC'; -import ZetaChainCCTXReducedStatus from 'src/features/chain-variants/zeta-chain/components/ZetaChainCCTXReducedStatus'; -import ZetaChainCCTXValue from 'src/features/chain-variants/zeta-chain/components/ZetaChainCCTXValue'; - -import dayjs from 'src/shared/date-and-time/dayjs'; -import Time from 'src/shared/date-and-time/Time'; -import TextSeparator from 'src/shared/texts/TextSeparator'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { SECOND } from 'src/toolkit/utils/consts'; - -type Props = { - tx: CctxListItem; - isLoading?: boolean; - animation?: string; -}; - -const LatestZetaChainCCTXItem = ({ tx, isLoading, animation }: Props) => { - return ( - <VStack - width="100%" - borderBottom="1px solid" - borderColor="border.divider" - py={ 3 } - fontSize="sm" - alignItems="start" - gap={ 2 } - animation={ animation } - > - <ZetaChainCCTXReducedStatus status={ tx.status_reduced } isLoading={ isLoading } type="full"/> - <TxEntityZetaChainCC hash={ tx.index } isLoading={ isLoading } truncation="constant_long" fontWeight={ 600 }/> - <Skeleton loading={ isLoading } display="flex" color="text.secondary" gap={ 2 } justifyContent="start"> - { dayjs(Number(tx.last_update_timestamp) * SECOND).fromNow() } - <TextSeparator mx={ 0 }/> - <Time timestamp={ Number(tx.last_update_timestamp) * SECOND } format="lll_s"/> - </Skeleton> - <Grid gridTemplateColumns="100px 1fr" gap={ 2 }> - <Text>Sender</Text> - <AddressEntityZetaChain - address={{ hash: tx.sender_address }} - chainId={ tx.source_chain_id.toString() } - isLoading={ isLoading } - truncation="constant" - /> - <Text>Receiver</Text> - <AddressEntityZetaChain - address={{ hash: tx.receiver_address }} - chainId={ tx.target_chain_id.toString() } - isLoading={ isLoading } - truncation="constant" - /> - <Text>Asset</Text> - <ZetaChainCCTXValue - coinType={ tx.coin_type } - tokenSymbol={ tx.token_symbol } - amount={ tx.amount } - decimals={ tx.decimals } - isLoading={ isLoading } - /> - </Grid> - </VStack> - ); -}; - -export default React.memo(LatestZetaChainCCTXItem); diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsStats.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsStats.tsx index 0934556b255..d16fcec91d6 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsStats.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsStats.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { BoxProps } from '@chakra-ui/react'; -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -10,6 +9,7 @@ import { TXS_STATS_MICROSERVICE } from 'src/slices/tx/stubs/tx'; import config from 'src/config'; import getStatsLabelFromTitle from 'src/shared/stats/get-stats-label-from-title'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; interface Props extends BoxProps {} @@ -34,18 +34,8 @@ const ZetaChainCCTXsStats = (props: Props) => { const cctxPendingCountTotal = txsStatsQuery.data?.pending_zetachain_cross_chain_txns; const cctxCount24h = txsStatsQuery.data?.new_zetachain_cross_chain_txns_24h; - const itemsCount = [ - cctxCountTotal, - cctxPendingCountTotal, - cctxCount24h, - ].filter(item => item !== null && item !== undefined).length; - return ( - <Box - display="grid" - gridTemplateColumns={{ base: '1fr', lg: `repeat(${ itemsCount }, calc(${ 100 / itemsCount }% - 9px))` }} - rowGap={ 3 } - columnGap={ 3 } + <StatsContainer mb={ 6 } { ...props } > @@ -71,7 +61,7 @@ const ZetaChainCCTXsStats = (props: Props) => { isLoading={ isLoading } /> ) } - </Box> + </StatsContainer> ); }; diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsTab.pw.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsTab.pw.tsx index 8053b86d7ec..de8c405bed3 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsTab.pw.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsTab.pw.tsx @@ -1,19 +1,21 @@ import { Box } from '@chakra-ui/react'; import React from 'react'; +import * as txsStatsMock from 'src/features/chain-stats/mocks/transactions'; import { zetaChainCCTXList } from 'src/features/chain-variants/zeta-chain/mocks/cctx'; import { zetaChainCCTXConfig } from 'src/features/chain-variants/zeta-chain/mocks/cctx-config'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; -import { test, expect, devices } from 'playwright/lib'; +import { test, expect } from 'playwright/lib'; import ZetaChainCCTXsTab from './ZetaChainCCTXsTab'; const CCTX_CONFIG_URL = 'http://localhost:3000/zeta-config.json'; -test.beforeEach(async({ mockEnvs, mockConfigResponse, mockAssetResponse }) => { +test.beforeEach(async({ mockEnvs, mockConfigResponse, mockAssetResponse, mockApiResponse }) => { await mockEnvs(ENVS_MAP.zetaChain); await mockConfigResponse('NEXT_PUBLIC_ZETACHAIN_SERVICE_CHAINS_CONFIG_URL', CCTX_CONFIG_URL, zetaChainCCTXConfig); + await mockApiResponse('stats:pages_transactions', txsStatsMock.base); await mockAssetResponse(zetaChainCCTXConfig[1].chain_logo, './playwright/mocks/image_s.jpg'); await mockAssetResponse(zetaChainCCTXConfig[2].chain_logo, './playwright/mocks/image_svg.svg'); }); @@ -41,31 +43,3 @@ test('base view +@dark-mode', async({ render, mockApiResponse }) => { await expect(component).toHaveScreenshot(); }); - -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - - test('base view +@dark-mode', async({ render, mockApiResponse }) => { - await mockApiResponse('zetachain:transactions', zetaChainCCTXList, { - queryParams: { - status_reduced: [ 'Success', 'Failed' ], - limit: 50, - offset: 0, - direction: 'DESC', - }, - }); - - const component = await render( - <Box pt="134px"> - <ZetaChainCCTXsTab/> - </Box>, { - hooksConfig: { - router: { - query: { tab: 'cctx' }, - }, - }, - }); - - await expect(component).toHaveScreenshot(); - }); -}); diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsTab.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsTab.tsx index 577ecf85029..8e9724ea416 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsTab.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXsTab.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { capitalize, omit } from 'es-toolkit/compat'; -import { useRouter } from 'next/router'; import React from 'react'; import { Direction } from '@blockscout/zetachain-cctx-types'; @@ -18,10 +17,12 @@ import { ZETA_CHAIN_CCTX_LIST_ITEM } from 'src/features/chain-variants/zeta-chai import dayjs from 'src/shared/date-and-time/dayjs'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { usePaginationParams } from 'src/shared/pagination/usePaginationParams'; import getFilterValueFromQuery from 'src/shared/router/get-filter-value-from-query'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import getValuesArrayFromQuery from 'src/shared/router/get-values-array-from-query'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -37,35 +38,40 @@ const TAB_LIST_PROPS = { }; const TABS_HEIGHT = 64; +const RESOURCE_NAME = 'zetachain:transactions'; + const hasNextPageFn = (nextPageParams: Record<string, unknown>) => { return nextPageParams.limit !== '0'; }; +// The URL carries an age preset without its range; the range is recomputed from "now" whenever the filters change. +function getFiltersFromQuery(query: ZetaChainCCTXFilterParams): ZetaChainCCTXFilterParams { + const age = getFilterValueFromQuery<AdvancedFilterAge>(ADVANCED_FILTER_AGES, query.age); + + return { + end_timestamp: age ? dayjs().unix().toString() : getQueryParamString(query.end_timestamp) || undefined, + start_timestamp: age ? dayjs(dayjs().valueOf() - getDurationFromAge(age)).unix().toString() : getQueryParamString(query.start_timestamp) || undefined, + age, + status_reduced: getFilterValueFromQuery<StatusReducedFilters>(ZETA_CHAIN_CCTX_STATUS_REDUCED_FILTERS, query.status_reduced), + sender_address: getValuesArrayFromQuery(query.sender_address), + receiver_address: getValuesArrayFromQuery(query.receiver_address), + source_chain_id: getValuesArrayFromQuery(query.source_chain_id), + target_chain_id: getValuesArrayFromQuery(query.target_chain_id), + token_symbol: getValuesArrayFromQuery(query.token_symbol), + coin_type: getFilterValueFromQuery<CoinTypeFilter>([ ZETA_CHAIN_CCTX_COIN_TYPE_FILTER ], query.coin_type), + }; +} + const ZetaChainCCTXsTab = () => { const router = useRouter(); const tab = getQueryParamString(router.query.tab); const isMobile = useIsMobile(); - const [ filters, setFilters ] = React.useState<ZetaChainCCTXFilterParams>(() => { - const age = getFilterValueFromQuery<AdvancedFilterAge>(ADVANCED_FILTER_AGES, router.query.age); - const startTimestampFromQuery = getQueryParamString(router.query.start_timestamp) ? getQueryParamString(router.query.start_timestamp) : undefined; - const endTimestampFromQuery = getQueryParamString(router.query.end_timestamp) ? getQueryParamString(router.query.end_timestamp) : undefined; - return { - end_timestamp: age ? dayjs().unix().toString() : endTimestampFromQuery, - start_timestamp: age ? dayjs((dayjs().valueOf() - getDurationFromAge(age))).unix().toString() : startTimestampFromQuery, - age, - status_reduced: getFilterValueFromQuery<StatusReducedFilters>(ZETA_CHAIN_CCTX_STATUS_REDUCED_FILTERS, router.query.status_reduced), - sender_address: getValuesArrayFromQuery(router.query.sender_address), - receiver_address: getValuesArrayFromQuery(router.query.receiver_address), - source_chain_id: getValuesArrayFromQuery(router.query.source_chain_id), - target_chain_id: getValuesArrayFromQuery(router.query.target_chain_id), - token_symbol: getValuesArrayFromQuery(router.query.token_symbol), - coin_type: getFilterValueFromQuery<CoinTypeFilter>([ ZETA_CHAIN_CCTX_COIN_TYPE_FILTER ], router.query.coin_type), - }; - }); + const { filters: filtersFromUrl } = usePaginationParams(RESOURCE_NAME); + const filters = React.useMemo(() => getFiltersFromQuery(filtersFromUrl), [ filtersFromUrl ]); - const cctxsValidatedQuery = useQueryWithPages({ - resourceName: 'zetachain:transactions', + const cctxsValidatedQuery = useApiPaginatedQuery({ + resourceName: RESOURCE_NAME, queryParams: { ...filters, limit: 50, @@ -80,8 +86,8 @@ const ZetaChainCCTXsTab = () => { hasNextPageFn, }); - const cctxsPendingQuery = useQueryWithPages({ - resourceName: 'zetachain:transactions', + const cctxsPendingQuery = useApiPaginatedQuery({ + resourceName: RESOURCE_NAME, queryParams: { ...filters, limit: 50, @@ -97,16 +103,26 @@ const ZetaChainCCTXsTab = () => { }); const query = tab === 'cctx_mined' ? cctxsValidatedQuery : cctxsPendingQuery; + const { onFilterChange } = query; - const handleFilterChange = React.useCallback(<T extends keyof ZetaChainCCTXFilterParams>(field: T, val: ZetaChainCCTXFilterParams[T]) => { - setFilters(prevState => { - const newState = { ...prevState }; - newState[field] = val; - query.onFilterChange(newState.age ? omit(newState, [ 'start_timestamp', 'end_timestamp' ]) : newState); + const latestFilters = React.useRef(filters); + latestFilters.current = filters; + const pendingFilters = React.useRef<ZetaChainCCTXFilterParams | null>(null); - return newState; - }); - }, [ query ]); + // The column filters report one field per call and several per user action (an age preset sets its range + // and the preset, the asset filter sets the coin type and the symbol). The calls of one tick are collected + // and pushed to the URL together, so one action is one navigation and one request. + const handleFilterChange = React.useCallback(<T extends keyof ZetaChainCCTXFilterParams>(field: T, val: ZetaChainCCTXFilterParams[T]) => { + if (pendingFilters.current === null) { + pendingFilters.current = { ...latestFilters.current }; + queueMicrotask(() => { + const nextFilters = pendingFilters.current ?? {}; + pendingFilters.current = null; + onFilterChange(nextFilters.age ? omit(nextFilters, [ 'start_timestamp', 'end_timestamp' ]) : nextFilters); + }); + } + pendingFilters.current[field] = val; + }, [ onFilterChange ]); const onClearFilter = React.useCallback((key: keyof ZetaChainCCTXFilterParams) => () => { if (key === 'age') { @@ -122,9 +138,8 @@ const ZetaChainCCTXsTab = () => { ); const clearAllFilters = React.useCallback(() => { - setFilters({}); - query.onFilterChange({}); - }, [ query ]); + onFilterChange({}); + }, [ onFilterChange ]); const verifiedTitle = capitalize(getChainValidationActionText()); @@ -136,7 +151,8 @@ const ZetaChainCCTXsTab = () => { <ZetaChainCCTxs pagination={ cctxsValidatedQuery.pagination } items={ cctxsValidatedQuery.data?.items } - isPlaceholderData={ cctxsValidatedQuery.isPlaceholderData } + isInitialLoading={ cctxsValidatedQuery.isInitialLoading } + isTransitioning={ cctxsValidatedQuery.isTransitioning } isError={ cctxsValidatedQuery.isError } top={ cctxsValidatedQuery.pagination.isVisible ? TABS_HEIGHT : 0 } filters={ filters } @@ -152,7 +168,8 @@ const ZetaChainCCTXsTab = () => { <ZetaChainCCTxs pagination={ cctxsPendingQuery.pagination } items={ cctxsPendingQuery.data?.items } - isPlaceholderData={ cctxsPendingQuery.isPlaceholderData } + isInitialLoading={ cctxsPendingQuery.isInitialLoading } + isTransitioning={ cctxsPendingQuery.isTransitioning } isError={ cctxsPendingQuery.isError } top={ cctxsPendingQuery.pagination.isVisible ? TABS_HEIGHT : 0 } filters={ filters } diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxs.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxs.tsx index 7bc44659371..a2c6245dc5b 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxs.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxs.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import { useQueryClient } from '@tanstack/react-query'; import React from 'react'; @@ -10,7 +9,6 @@ import type { ZetaChainCCTXFilterParams } from 'src/features/chain-variants/zeta import type { PaginationParams } from 'src/shared/pagination/types'; import { getResourceKey } from 'src/api/hooks/useApiQuery'; -import * as SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; import useSocketChannel from 'src/api/socket/useSocketChannel'; import useSocketMessage from 'src/api/socket/useSocketMessage'; @@ -20,7 +18,8 @@ import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import ZetaChainCCTxsList from './ZetaChainCCTxsList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import ZetaChainCCTxsTable from './ZetaChainCCTxsTable'; const OVERLOAD_COUNT = 75; @@ -29,7 +28,8 @@ type Props = { pagination: PaginationParams; top?: number; items?: Array<CctxListItem>; - isPlaceholderData: boolean; + isInitialLoading: boolean; + isTransitioning: boolean; isError: boolean; filters?: ZetaChainCCTXFilterParams; onFilterChange: <T extends keyof ZetaChainCCTXFilterParams>(field: T, val: ZetaChainCCTXFilterParams[T]) => void; @@ -42,7 +42,8 @@ const ZetaChainCCTxs = ({ pagination, top, items, - isPlaceholderData, + isInitialLoading, + isTransitioning, isError, filters = {}, onFilterChange, @@ -135,38 +136,20 @@ const ZetaChainCCTxs = ({ }); const content = ( - <> - <Box hideFrom="lg"> - { pagination.page === 1 && !hasFilters && ( - <SocketNewItemsNotice.Mobile - showErrorAlert={ showSocketErrorAlert } - type="cross_chain_transaction" - isLoading={ isPlaceholderData } - num={ showOverloadNotice ? 1 : 0 } - /> - ) } - <ZetaChainCCTxsList - txs={ items ?? [] } - isLoading={ isPlaceholderData } - resetKey={ resetKey } - /> - </Box> - <Box hideBelow="lg"> - <ZetaChainCCTxsTable - txs={ items ?? [] } - top={ top || 0 } - isLoading={ isPlaceholderData } - filters={ filters } - onFilterChange={ onFilterChange } - isPlaceholderData={ isPlaceholderData } - showStatusFilter={ showStatusFilter } - showSocketInfo={ pagination.page === 1 && !hasFilters } - showSocketErrorAlert={ showSocketErrorAlert } - socketInfoNum={ showOverloadNotice ? 1 : 0 } - resetKey={ resetKey } - /> - </Box> - </> + <TableContainerScrollable> + <ZetaChainCCTxsTable + txs={ items ?? [] } + top={ top || 0 } + isLoading={ isInitialLoading } + filters={ filters } + onFilterChange={ onFilterChange } + showStatusFilter={ showStatusFilter } + showSocketInfo={ pagination.page === 1 && !hasFilters } + showSocketErrorAlert={ showSocketErrorAlert } + socketInfoNum={ showOverloadNotice ? 1 : 0 } + resetKey={ resetKey } + /> + </TableContainerScrollable> ); const actionBar = (isMobile && pagination.isVisible) ? ( @@ -185,6 +168,7 @@ const ZetaChainCCTxs = ({ term: 'cross chain transaction', }} actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxsList.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxsList.tsx deleted file mode 100644 index 109648c8015..00000000000 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxsList.tsx +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { CctxListItem } from '@blockscout/zetachain-cctx-types'; - -import useInitialList from 'src/shared/lists/useInitialList'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ZetaChainCCTxsListItem from './ZetaChainCCTXListItem'; - -type Props = { - txs: Array<CctxListItem>; - isLoading?: boolean; - resetKey?: string; -}; - -const ZetaChainCCTxsList = ({ txs, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: txs, isEnabled: !isLoading, resetKey }); - const initialList = useInitialList({ - data: txs, - idFn: (item) => item.index, - enabled: !isLoading, - }); - - return ( - <Box> - { txs.slice(0, renderedItemsNum).map((item, index) => ( - <ZetaChainCCTxsListItem - key={ item.index + (isLoading ? index : '') } - tx={ item } - isLoading={ isLoading } - animation={ initialList.getAnimationProp(item) } - /> - )) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - ); -}; - -export default React.memo(ZetaChainCCTxsList); diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxsTable.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxsTable.tsx index 952aa638fe0..a8ab3ff4d48 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxsTable.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTxsTable.tsx @@ -11,6 +11,7 @@ import * as SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useInitialList from 'src/shared/lists/useInitialList'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; @@ -26,7 +27,6 @@ type Props = { isLoading?: boolean; filters?: ZetaChainCCTXFilterParams; onFilterChange: <T extends keyof ZetaChainCCTXFilterParams>(field: T, val: ZetaChainCCTXFilterParams[T]) => void; - isPlaceholderData?: boolean; showStatusFilter?: boolean; showSocketInfo?: boolean; showSocketErrorAlert?: boolean; @@ -34,6 +34,8 @@ type Props = { resetKey?: string; }; +const getBaseKey = (item: CctxListItem): string => item.index; + const ZetaChainCCTxsTable = ({ txs, top, @@ -41,7 +43,6 @@ const ZetaChainCCTxsTable = ({ isLoading, filters = {}, onFilterChange, - isPlaceholderData, showStatusFilter = true, showSocketInfo = false, showSocketErrorAlert = false, @@ -54,6 +55,7 @@ const ZetaChainCCTxsTable = ({ idFn: (item) => item.index, enabled: !isLoading, }); + const keys = useUniqueKeys(txs, getBaseKey); return ( <AddressHighlightProvider> @@ -70,7 +72,7 @@ const ZetaChainCCTxsTable = ({ columnName="Age" filters={ filters } handleFilterChange={ onFilterChange } - isLoading={ isPlaceholderData } + isLoading={ isLoading } /> <TimeFormatToggle ml={ 0 }/> </Flex> @@ -85,7 +87,7 @@ const ZetaChainCCTxsTable = ({ columnName="Status" filters={ filters } handleFilterChange={ onFilterChange } - isLoading={ isPlaceholderData } + isLoading={ isLoading } /> ) } </TableColumnHeader> @@ -98,7 +100,7 @@ const ZetaChainCCTxsTable = ({ columnName="Sender" filters={ filters } handleFilterChange={ onFilterChange } - isLoading={ isPlaceholderData } + isLoading={ isLoading } /> </TableColumnHeader> <TableColumnHeader width="165px"> @@ -110,7 +112,7 @@ const ZetaChainCCTxsTable = ({ columnName="Receiver" filters={ filters } handleFilterChange={ onFilterChange } - isLoading={ isPlaceholderData } + isLoading={ isLoading } /> </TableColumnHeader> <TableColumnHeader width="100%" isNumeric> @@ -122,7 +124,7 @@ const ZetaChainCCTxsTable = ({ columnName="Asset" filters={ filters } handleFilterChange={ onFilterChange } - isLoading={ isPlaceholderData } + isLoading={ isLoading } /> </TableColumnHeader> </TableRow> @@ -138,7 +140,7 @@ const ZetaChainCCTxsTable = ({ ) } { txs.slice(0, renderedItemsNum).map((item, index) => ( <ZetaChainCCTxsTableItem - key={ item.index + (isLoading ? index : '') } + key={ keys[index] } tx={ item } enableTimeIncrement={ enableTimeIncrement } isLoading={ isLoading } diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainEvmTransactions.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainEvmTransactions.tsx index 8621dbfd49f..fe8228d5ddb 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainEvmTransactions.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainEvmTransactions.tsx @@ -2,7 +2,6 @@ import { Flex } from '@chakra-ui/react'; import { capitalize } from 'es-toolkit/compat'; -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -17,9 +16,10 @@ import AdvancedFilterLink from 'src/features/advanced-filter/components/Advanced import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -36,9 +36,9 @@ const ZetaChainEvmTransactions = () => { const tab = getQueryParamString(router.query.tab); const isMobile = useIsMobile(); - const txsValidatedQuery = useQueryWithPages({ + const txsValidatedQuery = useApiPaginatedQuery({ resourceName: 'core:txs', - filters: { filter: 'validated' }, + queryParams: { filter: 'validated' }, options: { enabled: !tab || tab === 'zetachain' || tab === 'zetachain_validated', placeholderData: generateListStub<'core:txs'>(TX_ITEM, 50, { next_page_params: { @@ -50,9 +50,9 @@ const ZetaChainEvmTransactions = () => { }, }); - const txsPendingQuery = useQueryWithPages({ + const txsPendingQuery = useApiPaginatedQuery({ resourceName: 'core:txs', - filters: { filter: 'pending' }, + queryParams: { filter: 'pending' }, options: { enabled: tab === 'zetachain_pending', placeholderData: generateListStub<'core:txs'>(TX_ITEM, 50, { next_page_params: { diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainFilterByColumn.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainFilterByColumn.tsx index fbe76093684..e3ede2b5025 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainFilterByColumn.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainFilterByColumn.tsx @@ -9,7 +9,7 @@ import { ZETA_CHAIN_CCTX_COIN_TYPE_FILTER, type ZetaChainCCTXFilterParams } from import { toTokenModel } from 'src/slices/token/utils/model'; -import TableColumnFilterWrapper from 'src/shared/filters/TableColumnFilterWrapper'; +import ColumnFilter from 'src/shared/filters/ColumnFilter'; import ZetaChainAgeFilter from './ZetaChainAgeFilter'; import ZetaChainAssetFilter, { ZETA_NATIVE_TOKEN } from './ZetaChainAssetFilter'; @@ -27,6 +27,28 @@ type Props = { isLoading?: boolean; }; +function getAssetFilterValue(filters: ZetaChainCCTXFilterParams): schemas['Token'] | null { + if (filters.token_symbol?.[0]) { + return toTokenModel({ + address_hash: '', + symbol: filters.token_symbol[0], + name: filters.token_symbol[0], + decimals: '18', + total_supply: '0', + icon_url: null, + type: 'ERC-20', + holders_count: null, + exchange_rate: null, + circulating_market_cap: null, + reputation: null, + }); + } + if (filters.coin_type && castArray(filters.coin_type).includes(ZETA_CHAIN_CCTX_COIN_TYPE_FILTER)) { + return ZETA_NATIVE_TOKEN; + } + return null; +} + const ZetaChainFilterByColumn = ({ column, filters, columnName, handleFilterChange, isLoading }: Props) => { const commonProps = { columnName, handleFilterChange, isLoading }; @@ -34,87 +56,68 @@ const ZetaChainFilterByColumn = ({ column, filters, columnName, handleFilterChan case 'age': { const value = { age: (filters.age || '') as AdvancedFilterAge | '', from: filters.start_timestamp || '', to: filters.end_timestamp || '' }; return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Age" isLoading={ isLoading } selected={ Boolean(value.age || value.from || value.to) } - w="382px" + contentProps={{ w: '382px' }} > <ZetaChainAgeFilter { ...commonProps } value={ value }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } case 'status': { const value = filters.status_reduced ? castArray(filters.status_reduced) : []; return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Status" isLoading={ isLoading } selected={ Boolean(value && value.length) } - w="200px" + contentProps={{ w: '200px' }} > <ZetaChainStatusFilter { ...commonProps } value={ value }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } case 'sender': { const value = filters.sender_address ? castArray(filters.sender_address) : []; const chainValue = filters.source_chain_id ? castArray(filters.source_chain_id) : []; return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Sender" isLoading={ isLoading } selected={ Boolean(value && value.length) || Boolean(chainValue && chainValue.length) } - w="480px" + contentProps={{ w: '480px' }} > <ZetaChainSenderFilter { ...commonProps } value={ value } chainValue={ chainValue }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } case 'receiver': { const value = filters.receiver_address ? castArray(filters.receiver_address) : []; const chainValue = filters.target_chain_id ? castArray(filters.target_chain_id) : []; return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Receiver" isLoading={ isLoading } selected={ Boolean(value && value.length) || Boolean(chainValue && chainValue.length) } - w="480px" + contentProps={{ w: '480px' }} > <ZetaChainReceiverFilter { ...commonProps } value={ value } chainValue={ chainValue }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } case 'asset': { - let value: schemas['Token'] | null = null; - if (filters.coin_type && castArray(filters.coin_type).includes(ZETA_CHAIN_CCTX_COIN_TYPE_FILTER)) { - value = ZETA_NATIVE_TOKEN; - } - if (filters.token_symbol?.[0]) { - value = toTokenModel({ - address_hash: '', - symbol: filters.token_symbol[0], - name: filters.token_symbol[0], - decimals: '18', - total_supply: '0', - icon_url: null, - type: 'ERC-20', - holders_count: null, - exchange_rate: null, - circulating_market_cap: null, - reputation: null, - }); - } - + const value = getAssetFilterValue(filters); return ( - <TableColumnFilterWrapper + <ColumnFilter columnName="Asset" isLoading={ isLoading } selected={ Boolean(value) } - w="350px" + contentProps={{ w: '350px' }} > <ZetaChainAssetFilter { ...commonProps } value={ value }/> - </TableColumnFilterWrapper> + </ColumnFilter> ); } default: diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainFilterTags.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainFilterTags.tsx index d67a8678efd..62e3e245b18 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainFilterTags.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainFilterTags.tsx @@ -10,12 +10,12 @@ import useZetaChainConfig from 'src/features/chain-variants/zeta-chain/hooks/use import config from 'src/config'; import dayjs from 'src/shared/date-and-time/dayjs'; -import shortenString from 'src/shared/texts/shorten-string'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Link } from 'src/toolkit/chakra/link'; import { Tag } from 'src/toolkit/chakra/tag'; import { SECOND } from 'src/toolkit/utils/consts'; +import { shortenString } from 'src/toolkit/utils/texts'; type Props = { filters: ZetaChainCCTXFilterParams; diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainStatusFilter.tsx b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainStatusFilter.tsx index 16da6ffba4b..12c6ac7c4b5 100644 --- a/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainStatusFilter.tsx +++ b/src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainStatusFilter.tsx @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Flex } from '@chakra-ui/react'; import React from 'react'; import type { ZetaChainCCTXFilterParams, StatusReducedFilters } from 'src/features/chain-variants/zeta-chain/types/client'; -import TableColumnFilter from 'src/shared/filters/TableColumnFilter'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; import { Radio, RadioGroup } from 'src/toolkit/chakra/radio'; @@ -70,15 +70,11 @@ const ZetaChainStatusFilter = ({ value = [], handleFilterChange, onClose }: Prop }, [ handleStatusChange ]); return ( - <TableColumnFilter - title="Status" - isFilled={ currentValue !== 'all' } + <ColumnFilterContent isTouched={ isTouched } onFilter={ onFilter } - onReset={ onReset } - hasReset > - <Flex direction="column" gap={ 2 }> + <ColumnFilterContentSection title="Status" isFilled={ currentValue !== 'all' } onReset={ onReset }> <RadioGroup value={ currentValue } onValueChange={ handleRadioChange }> { STATUS_OPTIONS.map(option => ( <Radio key={ option.value } value={ option.value }> @@ -86,8 +82,8 @@ const ZetaChainStatusFilter = ({ value = [], handleFilterChange, onClose }: Prop </Radio> )) } </RadioGroup> - </Flex> - </TableColumnFilter> + </ColumnFilterContentSection> + </ColumnFilterContent> ); }; diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_dark-color-mode_base-view-dark-mode-1.png index 22be9bd365f..9414605b381 100644 Binary files a/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and b/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_dark-color-mode_mobile-base-view-dark-mode-1.png b/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_dark-color-mode_mobile-base-view-dark-mode-1.png deleted file mode 100644 index 0d418b879e0..00000000000 Binary files a/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_dark-color-mode_mobile-base-view-dark-mode-1.png and /dev/null differ diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_default_base-view-dark-mode-1.png b/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_default_base-view-dark-mode-1.png index 7ae65803d79..fba2dd489a1 100644 Binary files a/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_default_base-view-dark-mode-1.png and b/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_default_mobile-base-view-dark-mode-1.png b/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_default_mobile-base-view-dark-mode-1.png deleted file mode 100644 index 52f846ff5b0..00000000000 Binary files a/src/features/chain-variants/zeta-chain/pages/cctx-index/__screenshots__/ZetaChainCCTXsTab.pw.tsx_default_mobile-base-view-dark-mode-1.png and /dev/null differ diff --git a/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXItem.tsx b/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXItem.tsx index 30fe1f9d07c..faa3d9b39aa 100644 --- a/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXItem.tsx +++ b/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXItem.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Grid } from '@chakra-ui/react'; import React from 'react'; import type { CctxListItem } from '@blockscout/zetachain-cctx-types'; @@ -13,8 +12,11 @@ import ZetaChainCCTXValue from 'src/features/chain-variants/zeta-chain/component import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import { TableCell, TableRow } from 'src/toolkit/chakra/table'; import { SECOND } from 'src/toolkit/utils/consts'; +export const LATEST_ZETA_CHAIN_CCTXS_TABLE_MIN_WIDTH = '800px'; + type Props = { tx: CctxListItem; isLoading?: boolean; @@ -23,35 +25,38 @@ type Props = { const LatestZetaChainCCTXItem = ({ tx, isLoading, animation }: Props) => { return ( - <Grid - gridTemplateColumns="18px 120px 80px 350px auto" - gridGap={ 3 } - width="100%" - minW="740px" - borderBottom="1px solid" - borderColor="border.divider" - alignItems="center" - p={ 4 } - fontSize="sm" - animation={ animation } - - > - <ZetaChainCCTXReducedStatus status={ tx.status_reduced } isLoading={ isLoading }/> - <TxEntityZetaChainCC truncation="constant" hash={ tx.index } isLoading={ isLoading } fontWeight={ 600 }/> - <TimeWithTooltip color="text.secondary" timestamp={ Number(tx.last_update_timestamp) * SECOND } isLoading={ isLoading } timeFormat="relative"/> - <AddressFromTo - from={{ hash: tx.sender_address, chainId: tx.source_chain_id.toString(), chainType: 'zeta' }} - to={{ hash: tx.receiver_address, chainId: tx.target_chain_id.toString(), chainType: 'zeta' }} - isLoading={ isLoading } - /> - <ZetaChainCCTXValue - coinType={ tx.coin_type } - tokenSymbol={ tx.token_symbol } - amount={ tx.amount } - decimals={ tx.decimals } - isLoading={ isLoading } - /> - </Grid> + <TableRow animation={ animation }> + <TableCell w="36px"> + <ZetaChainCCTXReducedStatus status={ tx.status_reduced } isLoading={ isLoading }/> + </TableCell> + <TableCell w="160px"> + <TxEntityZetaChainCC truncation="constant" hash={ tx.index } isLoading={ isLoading } fontWeight={ 600 }/> + </TableCell> + <TableCell w="92px"> + <TimeWithTooltip + color="text.secondary" + timestamp={ Number(tx.last_update_timestamp) * SECOND } + isLoading={ isLoading } + timeFormat="relative" + /> + </TableCell> + <TableCell w="362px"> + <AddressFromTo + from={{ hash: tx.sender_address, chainId: tx.source_chain_id.toString(), chainType: 'zeta' }} + to={{ hash: tx.receiver_address, chainId: tx.target_chain_id.toString(), chainType: 'zeta' }} + isLoading={ isLoading } + /> + </TableCell> + <TableCell> + <ZetaChainCCTXValue + coinType={ tx.coin_type } + tokenSymbol={ tx.token_symbol } + amount={ tx.amount } + decimals={ tx.decimals } + isLoading={ isLoading } + /> + </TableCell> + </TableRow> ); }; diff --git a/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXs.pw.tsx b/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXs.pw.tsx index 004eedb9e5c..83f4b74811a 100644 --- a/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXs.pw.tsx +++ b/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXs.pw.tsx @@ -6,7 +6,7 @@ import { zetaChainCCTXList } from 'src/features/chain-variants/zeta-chain/mocks/ import { zetaChainCCTXConfig } from 'src/features/chain-variants/zeta-chain/mocks/cctx-config'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; -import { test, expect, devices } from 'playwright/lib'; +import { test, expect } from 'playwright/lib'; import LatestZetaChainCCTXs from './LatestZetaChainCCTXs'; @@ -34,20 +34,3 @@ test('base view +@dark-mode', async({ render, mockApiResponse }) => { await expect(component).toHaveScreenshot(); }); - -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - test('base view', async({ render, mockApiResponse }) => { - await mockApiResponse('zetachain:transactions', zetaChainCCTXList, { - queryParams: { - limit: 3, - offset: 0, - direction: zetaChainCCTXType.Direction.DESC, - }, - }); - - const component = await render(<LatestZetaChainCCTXs/>); - - await expect(component).toHaveScreenshot(); - }); -}); diff --git a/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXs.tsx b/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXs.tsx index fb75130f6cc..c1bff91e80f 100644 --- a/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXs.tsx +++ b/src/features/chain-variants/zeta-chain/pages/home/LatestZetaChainCCTXs.tsx @@ -2,7 +2,6 @@ import { Box, Flex, Text } from '@chakra-ui/react'; import { useQueryClient } from '@tanstack/react-query'; -import { route } from 'nextjs-routes'; import React from 'react'; import { Direction } from '@blockscout/zetachain-cctx-types'; @@ -17,20 +16,19 @@ import useSocketMessage from 'src/api/socket/useSocketMessage'; import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; import LatestTxsFallback from 'src/slices/home/pages/index/txs/LatestTxsFallback'; -import ZetaChainCCTXListItem from 'src/features/chain-variants/zeta-chain/pages/cctx-index/ZetaChainCCTXListItem'; import { ZETA_CHAIN_CCTX_LIST_ITEM } from 'src/features/chain-variants/zeta-chain/stubs'; -import useIsMobile from 'src/shared/hooks/useIsMobile'; import useInitialList from 'src/shared/lists/useInitialList'; import { generateListStub } from 'src/shared/pagination/utils'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; +import { TableBody, TableContainerScrollable, TableRoot } from 'src/toolkit/chakra/table'; -import LatestZetaChainCCTXItem from './LatestZetaChainCCTXItem'; +import LatestZetaChainCCTXItem, { LATEST_ZETA_CHAIN_CCTXS_TABLE_MIN_WIDTH } from './LatestZetaChainCCTXItem'; const LatestZetaChainCCTXs = () => { - const isMobile = useIsMobile(); - const txsCount = isMobile ? 3 : 8; + const txsCount = 8; const { data, isPlaceholderData, isError } = useApiQuery('zetachain:transactions', { queryOptions: { placeholderData: generateListStub<'zetachain:transactions'>( @@ -123,32 +121,29 @@ const LatestZetaChainCCTXs = () => { const cctxsUrl = route({ pathname: '/txs', query: { tab: 'cctx' } }); return ( <> - <SocketNewItemsNotice - type="cross_chain_transaction" - isLoading={ isPlaceholderData } - showErrorAlert={ showSocketErrorAlert } - borderBottomRadius={ 0 } - /> - <Box mb={ 3 } display={{ base: 'block', lg: 'none' }}> - { data.items.slice(0, txsCount).map(((tx, index) => ( - <ZetaChainCCTXListItem - key={ tx.index + (isPlaceholderData ? index : '') } - tx={ tx } - isLoading={ isPlaceholderData } - animation={ initialList.getAnimationProp(tx) } - /> - ))) } - </Box> <AddressHighlightProvider> - <Box mb={ 3 } display={{ base: 'none', lg: 'block' }}> - { data.items.slice(0, txsCount).map(((tx, index) => ( - <LatestZetaChainCCTXItem - key={ tx.index + (isPlaceholderData ? index : '') } - tx={ tx } + <Box mb={ 3 } textStyle="sm"> + <TableContainerScrollable> + <SocketNewItemsNotice + type="cross_chain_transaction" isLoading={ isPlaceholderData } - animation={ initialList.getAnimationProp(tx) } + showErrorAlert={ showSocketErrorAlert } + borderBottomRadius={ 0 } + minW={ LATEST_ZETA_CHAIN_CCTXS_TABLE_MIN_WIDTH } /> - ))) } + <TableRoot minW={ LATEST_ZETA_CHAIN_CCTXS_TABLE_MIN_WIDTH }> + <TableBody> + { data.items.slice(0, txsCount).map(((tx, index) => ( + <LatestZetaChainCCTXItem + key={ tx.index + (isPlaceholderData ? index : '') } + tx={ tx } + isLoading={ isPlaceholderData } + animation={ initialList.getAnimationProp(tx) } + /> + ))) } + </TableBody> + </TableRoot> + </TableContainerScrollable> </Box> </AddressHighlightProvider> <Flex justifyContent="center"> diff --git a/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_dark-color-mode_base-view-dark-mode-1.png index 2e550c5efc1..33909c4b61b 100644 Binary files a/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and b/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_default_base-view-dark-mode-1.png b/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_default_base-view-dark-mode-1.png index 8743edd16af..d660eb8053f 100644 Binary files a/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_default_base-view-dark-mode-1.png and b/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_default_mobile-base-view-1.png b/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_default_mobile-base-view-1.png deleted file mode 100644 index 33efd706318..00000000000 Binary files a/src/features/chain-variants/zeta-chain/pages/home/__screenshots__/LatestZetaChainCCTXs.pw.tsx_default_mobile-base-view-1.png and /dev/null differ diff --git a/src/features/chain-variants/zilliqa/components/ValidatorEntity.tsx b/src/features/chain-variants/zilliqa/components/ValidatorEntity.tsx index 1396ef99d9a..93682e8f919 100644 --- a/src/features/chain-variants/zilliqa/components/ValidatorEntity.tsx +++ b/src/features/chain-variants/zilliqa/components/ValidatorEntity.tsx @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as EntityBase from 'src/shared/entities/components'; import { distributeEntityProps } from 'src/shared/entities/utils'; +import { route } from 'src/shared/router/routes'; type LinkProps = EntityBase.LinkBaseProps & Pick<EntityProps, 'id'>; diff --git a/src/features/chain-variants/zilliqa/pages/block/__screenshots__/BlockDetailsZilliqaQuorumCertificate.pw.tsx_mobile_aggregated-quorum-certificate-mobile-1.png b/src/features/chain-variants/zilliqa/pages/block/__screenshots__/BlockDetailsZilliqaQuorumCertificate.pw.tsx_mobile_aggregated-quorum-certificate-mobile-1.png index d54c6e81f12..70225423a57 100644 Binary files a/src/features/chain-variants/zilliqa/pages/block/__screenshots__/BlockDetailsZilliqaQuorumCertificate.pw.tsx_mobile_aggregated-quorum-certificate-mobile-1.png and b/src/features/chain-variants/zilliqa/pages/block/__screenshots__/BlockDetailsZilliqaQuorumCertificate.pw.tsx_mobile_aggregated-quorum-certificate-mobile-1.png differ diff --git a/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorDetails.pw.tsx b/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorDetails.pw.tsx index 4c0f8c00b48..65daa9c6831 100644 --- a/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorDetails.pw.tsx +++ b/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorDetails.pw.tsx @@ -1,5 +1,7 @@ import React from 'react'; +import * as statsMock from 'src/slices/chain/stats/mocks'; + import * as validatorsMock from 'src/features/chain-variants/zilliqa/mocks/validators'; import { test, expect } from 'playwright/lib'; @@ -7,7 +9,8 @@ import * as pwConfig from 'playwright/utils/config'; import ValidatorDetails from './ValidatorDetails'; -test('base view +@mobile', async({ render, page }) => { +test('base view +@mobile', async({ render, page, mockApiResponse }) => { + await mockApiResponse('core:stats', statsMock.base); const component = await render(<ValidatorDetails data={ validatorsMock.validatorDetails } isLoading={ false }/>); await expect(component).toHaveScreenshot({ diff --git a/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorDetails.tsx b/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorDetails.tsx index c29b58b45e8..608ef76cf45 100644 --- a/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorDetails.tsx +++ b/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorDetails.tsx @@ -12,10 +12,10 @@ import NativeTokenIcon from 'src/slices/token/components/icon/TokenIconNative'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import DetailedInfoSponsoredItem from 'src/shared/detailed-info/DetailedInfoSponsoredItem'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props { data: schemas['ZilliqaStakerDetailed']; @@ -62,7 +62,7 @@ const ValidatorDetails = ({ data, isLoading }: Props) => { <DetailedInfo.ItemValue> <Flex alignItems="center" w="100%" minWidth={ 0 }> <Skeleton loading={ isLoading } maxW="calc(100% - 28px)" overflow="hidden"> - <HashStringShortenDynamic hash={ data.peer_id }/> + <Truncate value={ data.peer_id }/> </Skeleton> <CopyToClipboard text={ data.peer_id } isLoading={ isLoading }/> </Flex> diff --git a/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorZilliqa.tsx b/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorZilliqa.tsx index 54a1ac0079a..2ee2c1dd482 100644 --- a/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorZilliqa.tsx +++ b/src/features/chain-variants/zilliqa/pages/validator-details/ValidatorZilliqa.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -14,6 +13,7 @@ import { VALIDATOR_ZILLIQA } from 'src/features/chain-variants/zilliqa/stubs/val import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import ValidatorDetails from './ValidatorDetails'; diff --git a/src/features/chain-variants/zilliqa/pages/validator-details/__screenshots__/ValidatorDetails.pw.tsx_mobile_base-view-mobile-1.png b/src/features/chain-variants/zilliqa/pages/validator-details/__screenshots__/ValidatorDetails.pw.tsx_mobile_base-view-mobile-1.png index 3b26fe1d8b9..2bece1f5e69 100644 Binary files a/src/features/chain-variants/zilliqa/pages/validator-details/__screenshots__/ValidatorDetails.pw.tsx_mobile_base-view-mobile-1.png and b/src/features/chain-variants/zilliqa/pages/validator-details/__screenshots__/ValidatorDetails.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsList.tsx b/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsList.tsx deleted file mode 100644 index 9dcddedd68a..00000000000 --- a/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ValidatorsListItem from './ValidatorsListItem'; - -interface Props { - data: Array<schemas['ZilliqaStaker']>; - isLoading: boolean; - resetKey?: string; -} - -const ValidatorsList = ({ data, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <ValidatorsListItem - key={ item.bls_public_key + (isLoading ? index : '') } - data={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(ValidatorsList); diff --git a/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsListItem.tsx b/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsListItem.tsx deleted file mode 100644 index fab222bdf68..00000000000 --- a/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsListItem.tsx +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import ValidatorEntity from 'src/features/chain-variants/zilliqa/components/ValidatorEntity'; - -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - data: schemas['ZilliqaStaker']; - isLoading?: boolean; -} - -const ValidatorsListItem = ({ data, isLoading }: Props) => { - - return ( - <ListItemMobileGrid.Container> - - <ListItemMobileGrid.Label isLoading={ isLoading }>BLS public key</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <ValidatorEntity - isLoading={ isLoading } - id={ data.bls_public_key } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Index</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block"> - { data.index } - </Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Balance</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <NativeCoinValue - amount={ data.balance } - loading={ isLoading } - /> - </ListItemMobileGrid.Value> - </ListItemMobileGrid.Container> - ); -}; - -export default React.memo(ValidatorsListItem); diff --git a/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsTable.tsx b/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsTable.tsx index 841e50673dd..8ae4bbd0e43 100644 --- a/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsTable.tsx +++ b/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsTable.tsx @@ -5,6 +5,7 @@ import React from 'react'; import type { schemas } from '@blockscout/api-types'; import config from 'src/config'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -18,11 +19,14 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: schemas['ZilliqaStaker']): string => item.bls_public_key; + const ValidatorsTable = ({ data, isLoading, top, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); return ( - <TableRoot> + <TableRoot minW="900px"> <TableHeaderSticky top={ top }> <TableRow> <TableColumnHeader width="50%">BLS public key</TableColumnHeader> @@ -35,7 +39,7 @@ const ValidatorsTable = ({ data, isLoading, top, resetKey }: Props) => { <TableBody> { data.slice(0, renderedItemsNum).map((item, index) => ( <ValidatorsTableItem - key={ item.bls_public_key + (isLoading ? index : '') } + key={ keys[index] } data={ item } isLoading={ isLoading }/> )) } diff --git a/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsZilliqa.pw.tsx b/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsZilliqa.pw.tsx index 5a07f3630bc..6546365edd7 100644 --- a/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsZilliqa.pw.tsx +++ b/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsZilliqa.pw.tsx @@ -8,7 +8,7 @@ import Validators from './ValidatorsZilliqa'; const chainType = 'zilliqa'; -test('base view +@mobile', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { +test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { await mockEnvs([ [ 'NEXT_PUBLIC_VALIDATORS_CHAIN_TYPE', chainType ], ]); diff --git a/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsZilliqa.tsx b/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsZilliqa.tsx index 64af52bd734..33ee2550687 100644 --- a/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsZilliqa.tsx +++ b/src/features/chain-variants/zilliqa/pages/validator-index/ValidatorsZilliqa.tsx @@ -11,14 +11,15 @@ import { VALIDATORS_ZILLIQA_ITEM } from 'src/features/chain-variants/zilliqa/stu import config from 'src/config'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; -import ValidatorsList from './ValidatorsList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import ValidatorsTable from './ValidatorsTable'; const ValidatorsZilliqa = () => { - const { isError, isPlaceholderData, data, pagination, queryHash } = useQueryWithPages({ + const { isError, isInitialLoading, isTransitioning, data, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:validators_zilliqa', options: { enabled: config.features.validators.isEnabled, @@ -37,19 +38,14 @@ const ValidatorsZilliqa = () => { ) : null; const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <ValidatorsList data={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <ValidatorsTable - data={ data.items } - isLoading={ isPlaceholderData } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <ValidatorsTable + data={ data.items } + isLoading={ isInitialLoading } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; return ( @@ -60,6 +56,7 @@ const ValidatorsZilliqa = () => { itemsNum={ data?.items.length } emptyText="There are no validators." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/chain-variants/zilliqa/pages/validator-index/__screenshots__/ValidatorsZilliqa.pw.tsx_default_base-view-1.png b/src/features/chain-variants/zilliqa/pages/validator-index/__screenshots__/ValidatorsZilliqa.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..ca3e16c8588 Binary files /dev/null and b/src/features/chain-variants/zilliqa/pages/validator-index/__screenshots__/ValidatorsZilliqa.pw.tsx_default_base-view-1.png differ diff --git a/src/features/chain-variants/zilliqa/pages/validator-index/__screenshots__/ValidatorsZilliqa.pw.tsx_default_base-view-mobile-1.png b/src/features/chain-variants/zilliqa/pages/validator-index/__screenshots__/ValidatorsZilliqa.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index ec208457141..00000000000 Binary files a/src/features/chain-variants/zilliqa/pages/validator-index/__screenshots__/ValidatorsZilliqa.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/chain-variants/zilliqa/pages/validator-index/__screenshots__/ValidatorsZilliqa.pw.tsx_mobile_base-view-mobile-1.png b/src/features/chain-variants/zilliqa/pages/validator-index/__screenshots__/ValidatorsZilliqa.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 45a23451546..00000000000 Binary files a/src/features/chain-variants/zilliqa/pages/validator-index/__screenshots__/ValidatorsZilliqa.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/connect-wallet/CONTEXT.md b/src/features/connect-wallet/CONTEXT.md index e4c374e90cc..df1864b742b 100644 --- a/src/features/connect-wallet/CONTEXT.md +++ b/src/features/connect-wallet/CONTEXT.md @@ -55,6 +55,12 @@ disabled *fallback*. detect it and turn transparent (render children directly) — without that they would wait forever for a readiness signal only the deferred path emits. Moving dynamic mode onto the deferred model is a known follow-up. + Its hooks reach the synchronous `useWallet` / `useAccount` hubs through + `utils/dynamic-hooks.ts`, registered by `DynamicProvider`. Keep them off a + static import (the reown bundle grows) and off any post-paint suspend: a + suspend into a root boundary after first paint stops every mounted zag + presence machine, and a tab switched in that window keeps the old panel + visible (#3788). Before changing anything in the dynamic-mode graph, verify it in a production build (`pnpm prod:preset <alias>`) against an instance whose `NEXT_PUBLIC_ACCOUNT_AUTH_PROVIDER=dynamic`, not just in dev — reshaping it once diff --git a/src/features/connect-wallet/components/AccountPublisher.tsx b/src/features/connect-wallet/components/AccountPublisher.ts similarity index 100% rename from src/features/connect-wallet/components/AccountPublisher.tsx rename to src/features/connect-wallet/components/AccountPublisher.ts diff --git a/src/features/connect-wallet/components/DynamicProvider.tsx b/src/features/connect-wallet/components/DynamicProvider.tsx index 69e5cee32fb..b8384958675 100644 --- a/src/features/connect-wallet/components/DynamicProvider.tsx +++ b/src/features/connect-wallet/components/DynamicProvider.tsx @@ -16,11 +16,14 @@ import { getResourceKey } from 'src/api/hooks/useApiQuery'; import useGetCsrfToken from 'src/features/account/hooks/useGetCsrfToken'; import useLogout from 'src/features/account/hooks/useLogout'; +import useAccountDynamic from 'src/features/connect-wallet/hooks/account/useAccountDynamic'; +import useWalletDynamic from 'src/features/connect-wallet/hooks/wallet/useWalletDynamic'; import { chains } from 'src/features/connect-wallet/utils/chains'; +import { registerDynamicHooks } from 'src/features/connect-wallet/utils/dynamic-hooks'; import wagmiConfig from 'src/features/connect-wallet/utils/wagmi-config'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import getErrorMessage from 'src/shared/errors/get-error-message'; import { toaster } from 'src/toolkit/chakra/toaster'; @@ -28,6 +31,8 @@ import { castToString } from 'src/toolkit/utils/guards'; const feature = config.features.connectWallet; +registerDynamicHooks({ useWallet: useWalletDynamic, useAccount: useAccountDynamic }); + const walletConnectors = [ EthereumWalletConnectors, ZeroDevSmartWalletConnectors, @@ -75,7 +80,7 @@ const DynamicProvider = ({ children }: Props) => { } queryClient.setQueryData(getResourceKey('core:user_info'), () => response); csrfQuery.refetch(); - mixpanel.logEvent(mixpanel.EventTypes.LOGIN, { + analytics.logEvent(analytics.EventTypes.LOGIN, { Action: 'Success', Source: 'Dynamic', }); diff --git a/src/features/connect-wallet/hooks/account/useAccountDynamicLazy.ts b/src/features/connect-wallet/hooks/account/useAccountDynamicLazy.ts deleted file mode 100644 index f1768f38b25..00000000000 --- a/src/features/connect-wallet/hooks/account/useAccountDynamicLazy.ts +++ /dev/null @@ -1,15 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; -import type { UseAccountReturnType } from 'wagmi'; - -// Light wrapper that keeps the heavy @dynamic-labs stack out of the reown/fallback critical bundle: the -// (untouched) dynamic account hook is loaded via a dynamic import — its own async chunk — and `use()` -// suspends until it resolves. See useWalletDynamicLazy for the gating rationale. -let hookPromise: Promise<() => UseAccountReturnType> | undefined; - -export default function useAccountDynamicLazy(): UseAccountReturnType { - hookPromise = hookPromise ?? import('./useAccountDynamic').then((module) => module.default); - const useAccountDynamic = React.use(hookPromise); - return useAccountDynamic(); -} diff --git a/src/features/connect-wallet/hooks/account/useAccountReown.spec.tsx b/src/features/connect-wallet/hooks/account/useAccountReown.spec.ts similarity index 100% rename from src/features/connect-wallet/hooks/account/useAccountReown.spec.tsx rename to src/features/connect-wallet/hooks/account/useAccountReown.spec.ts diff --git a/src/features/connect-wallet/hooks/useAccount.ts b/src/features/connect-wallet/hooks/useAccount.ts index ffcfe491196..27320dbd63c 100644 --- a/src/features/connect-wallet/hooks/useAccount.ts +++ b/src/features/connect-wallet/hooks/useAccount.ts @@ -3,7 +3,7 @@ import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; -import useAccountDynamicLazy from './account/useAccountDynamicLazy'; +import { useAccountDynamicRegistered } from '../utils/dynamic-hooks'; import useAccountFallback from './account/useAccountFallback'; import useAccountReown from './account/useAccountReown'; @@ -11,10 +11,10 @@ const payload = getFeaturePayload(config.features.connectWallet); // Synchronous hub (no top-level await): reown is a light Bridge-backed hook wired // directly, so the header's module graph no longer awaits the wallet/appkit chunks. The heavy dynamic -// stack stays lazy behind `useAccountDynamicLazy` so it never enters the reown/fallback bundle. +// stack is registered by `DynamicProvider` (see utils/dynamic-hooks) so it never enters the reown/fallback bundle. // eslint-disable-next-line no-nested-ternary const useAccount = payload?.connectorType === 'dynamic' ? - useAccountDynamicLazy : + useAccountDynamicRegistered : payload?.connectorType === 'reown' ? useAccountReown : useAccountFallback; diff --git a/src/features/connect-wallet/hooks/useWallet.ts b/src/features/connect-wallet/hooks/useWallet.ts index 02fa1285c4b..159fdbb9041 100644 --- a/src/features/connect-wallet/hooks/useWallet.ts +++ b/src/features/connect-wallet/hooks/useWallet.ts @@ -3,7 +3,7 @@ import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; -import useWalletDynamicLazy from './wallet/useWalletDynamicLazy'; +import { useWalletDynamicRegistered } from '../utils/dynamic-hooks'; import useWalletFallback from './wallet/useWalletFallback'; import useWalletReown from './wallet/useWalletReown'; @@ -11,11 +11,11 @@ const payload = getFeaturePayload(config.features.connectWallet); // Synchronous hub (no top-level await): reown is a light Bridge/Runtime-backed hook wired // directly, so the header's module graph no longer awaits the wallet/appkit chunks. The heavy dynamic -// stack stays lazy behind `useWalletDynamicLazy` so it never enters the reown/fallback bundle. +// stack is registered by `DynamicProvider` (see utils/dynamic-hooks) so it never enters the reown/fallback bundle. // (`useWalletReown`'s default already self-selects reown-vs-fallback, matching the reown branch.) // eslint-disable-next-line no-nested-ternary const useWallet = payload?.connectorType === 'dynamic' ? - useWalletDynamicLazy : + useWalletDynamicRegistered : payload?.connectorType === 'reown' ? useWalletReown : useWalletFallback; diff --git a/src/features/connect-wallet/hooks/wallet/types.ts b/src/features/connect-wallet/hooks/wallet/types.ts index 1713084d178..70a40ed573e 100644 --- a/src/features/connect-wallet/hooks/wallet/types.ts +++ b/src/features/connect-wallet/hooks/wallet/types.ts @@ -1,9 +1,9 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type * as mixpanel from 'src/services/mixpanel'; +import type * as analytics from 'src/shared/analytics'; export interface Params { - source: mixpanel.EventPayload<mixpanel.EventTypes.WALLET_CONNECT>['Source']; + source: analytics.EventPayload<analytics.EventTypes.WALLET_CONNECT>['Source']; onConnect?: () => void; } diff --git a/src/features/connect-wallet/hooks/wallet/useWalletDynamic.ts b/src/features/connect-wallet/hooks/wallet/useWalletDynamic.ts index 32419c2b8b1..a59dd4a7efa 100644 --- a/src/features/connect-wallet/hooks/wallet/useWalletDynamic.ts +++ b/src/features/connect-wallet/hooks/wallet/useWalletDynamic.ts @@ -6,7 +6,7 @@ import { useAccountEffect } from 'wagmi'; import type { Params, Result } from './types'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import useAccountDynamic from '../account/useAccountDynamic'; @@ -19,20 +19,20 @@ export default function useWalletDynamic({ source, onConnect }: Params): Result const openModal = React.useCallback(async() => { setShowDynamicUserProfile(true); - mixpanel.logEvent(mixpanel.EventTypes.ACCOUNT_ACCESS, { Action: 'Dropdown open' }); + analytics.logEvent(analytics.EventTypes.ACCOUNT_ACCESS, { Action: 'Dropdown open' }); }, [ setShowDynamicUserProfile ]); useDynamicEvents('authFlowOpen', async() => { if (!isConnectionStarted.current) { - mixpanel.logEvent(mixpanel.EventTypes.WALLET_CONNECT, { Source: source, Status: 'Started' }); + analytics.logEvent(analytics.EventTypes.WALLET_CONNECT, { Source: source, Status: 'Started' }); isConnectionStarted.current = true; } }); const handleAccountConnected = React.useCallback(({ isReconnected }: { isReconnected: boolean }) => { if (!isReconnected && isConnectionStarted.current) { - mixpanel.logEvent(mixpanel.EventTypes.WALLET_CONNECT, { Source: source, Status: 'Connected' }); - mixpanel.userProfile.setOnce({ + analytics.logEvent(analytics.EventTypes.WALLET_CONNECT, { Source: source, Status: 'Connected' }); + analytics.userProfile.setOnce({ 'With Connected Wallet': true, }); onConnect?.(); @@ -55,6 +55,7 @@ export default function useWalletDynamic({ source, onConnect }: Params): Result useAccountEffect({ onConnect: handleAccountConnected }); React.useEffect(() => { + // react-doctor-disable-next-line react-doctor/no-initialize-state -- hydration guard: SSR must never report a connected wallet setIsClientLoaded(true); }, []); diff --git a/src/features/connect-wallet/hooks/wallet/useWalletDynamicLazy.ts b/src/features/connect-wallet/hooks/wallet/useWalletDynamicLazy.ts deleted file mode 100644 index e83b809fa26..00000000000 --- a/src/features/connect-wallet/hooks/wallet/useWalletDynamicLazy.ts +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { Params, Result } from './types'; - -// The @dynamic-labs stack is heavy and only needed in `dynamic` connector mode. This light wrapper keeps -// it out of the reown/fallback critical bundle: the (untouched) dynamic wallet hook is pulled in via a -// dynamic import — its own async chunk — and `use()` suspends until it resolves. In dynamic mode the whole -// app already renders behind Web3Provider's `next/dynamic(ssr: false)` gate, so this suspends into that -// same window rather than adding a new visible loading state. -let hookPromise: Promise<(params: Params) => Result> | undefined; - -export default function useWalletDynamicLazy(params: Params): Result { - hookPromise = hookPromise ?? import('./useWalletDynamic').then((module) => module.default); - const useWalletDynamic = React.use(hookPromise); - return useWalletDynamic(params); -} diff --git a/src/features/connect-wallet/hooks/wallet/useWalletReown.spec.ts b/src/features/connect-wallet/hooks/wallet/useWalletReown.spec.ts new file mode 100644 index 00000000000..d533a990b63 --- /dev/null +++ b/src/features/connect-wallet/hooks/wallet/useWalletReown.spec.ts @@ -0,0 +1,166 @@ +// @vitest-environment jsdom + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, renderHook } from 'vitest/lib'; + +import type { ConnectionHandlers } from '../../utils/bridge'; +import { useWalletReown } from './useWalletReown'; + +const bridgeState = vi.hoisted(() => ({ + account: { address: undefined as string | undefined, status: 'disconnected' as string }, + connectionHandlers: undefined as ConnectionHandlers | undefined, +})); + +const runtimeMock = vi.hoisted(() => ({ + isReady: true, + openModal: vi.fn(() => Promise.resolve()), + disconnect: vi.fn(() => Promise.resolve()), + subscribeModalState: vi.fn(() => () => {}), +})); + +const analyticsMock = vi.hoisted(() => ({ + logEvent: vi.fn(), + userProfile: { setOnce: vi.fn() }, + EventTypes: { WALLET_CONNECT: 'WALLET_CONNECT' }, +})); + +vi.mock('../../utils/bridge', () => ({ + useWeb3Account: () => bridgeState.account, + subscribeConnection: (handlers: ConnectionHandlers) => { + bridgeState.connectionHandlers = handlers; + return () => { + bridgeState.connectionHandlers = undefined; + }; + }, +})); + +vi.mock('../../utils/runtime', () => ({ + ensureLoaded: () => Promise.resolve(runtimeMock), +})); + +vi.mock('src/shared/analytics', () => analyticsMock); + +describe('useWalletReown', () => { + beforeEach(() => { + vi.clearAllMocks(); + runtimeMock.isReady = true; + bridgeState.account = { address: undefined, status: 'disconnected' }; + bridgeState.connectionHandlers = undefined; + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe('connect', () => { + it('loads the runtime, opens the modal, and logs WALLET_CONNECT Started', async() => { + const { result } = renderHook(() => useWalletReown({ source: 'Header' })); + await act(async() => { + await result.current.connect(); + }); + + expect(runtimeMock.openModal).toHaveBeenCalledTimes(1); + expect(analyticsMock.logEvent).toHaveBeenCalledWith('WALLET_CONNECT', { Source: 'Header', Status: 'Started' }); + }); + + it('logs WALLET_CONNECT Connected + profile flag on a fresh connection after connect()', async() => { + const onConnect = vi.fn(); + const { result } = renderHook(() => useWalletReown({ source: 'Header', onConnect })); + await act(async() => { + await result.current.connect(); + }); + analyticsMock.logEvent.mockClear(); + + act(() => { + bridgeState.connectionHandlers?.onConnect?.({ address: '0x1', isReconnected: false }); + }); + + expect(analyticsMock.logEvent).toHaveBeenCalledWith('WALLET_CONNECT', { Source: 'Header', Status: 'Connected' }); + expect(analyticsMock.userProfile.setOnce).toHaveBeenCalledWith({ 'With Connected Wallet': true }); + expect(onConnect).toHaveBeenCalledTimes(1); + }); + + it('does not log Started, nor arm the user-initiated flag, when the runtime failed to load', async() => { + runtimeMock.isReady = false; + const onConnect = vi.fn(); + const { result } = renderHook(() => useWalletReown({ source: 'Header', onConnect })); + await act(async() => { + await result.current.connect(); + }); + + // the disabled runtime's openModal is a no-op, so nothing was started + expect(analyticsMock.logEvent).not.toHaveBeenCalled(); + + // and a later bridge connect must not be attributed to this click + act(() => { + bridgeState.connectionHandlers?.onConnect?.({ address: '0x1', isReconnected: false }); + }); + expect(analyticsMock.logEvent).not.toHaveBeenCalled(); + expect(onConnect).not.toHaveBeenCalled(); + }); + + it('does not log Connected for an auto-reconnect', async() => { + const { result } = renderHook(() => useWalletReown({ source: 'Header' })); + await act(async() => { + await result.current.connect(); + }); + analyticsMock.logEvent.mockClear(); + + act(() => { + bridgeState.connectionHandlers?.onConnect?.({ address: '0x1', isReconnected: true }); + }); + + expect(analyticsMock.logEvent).not.toHaveBeenCalled(); + }); + + it('does not log Connected when the connection was not user-initiated (openModal, not connect)', async() => { + const { result } = renderHook(() => useWalletReown({ source: 'Header' })); + await act(async() => { + await result.current.openModal(); + }); + + expect(analyticsMock.logEvent).not.toHaveBeenCalled(); + + act(() => { + bridgeState.connectionHandlers?.onConnect?.({ address: '0x1', isReconnected: false }); + }); + expect(analyticsMock.logEvent).not.toHaveBeenCalled(); + }); + }); + + describe('disconnect', () => { + it('calls the runtime disconnect action', async() => { + const { result } = renderHook(() => useWalletReown({ source: 'Header' })); + await act(async() => { + await result.current.disconnect(); + }); + expect(runtimeMock.disconnect).toHaveBeenCalledTimes(1); + }); + }); + + describe('account state mapping', () => { + it('is connected with the address when the bridge reports connected', () => { + bridgeState.account = { address: '0x1', status: 'connected' }; + const { result } = renderHook(() => useWalletReown({ source: 'Header' })); + expect(result.current.isConnected).toBe(true); + expect(result.current.isReconnecting).toBe(false); + expect(result.current.address).toBe('0x1'); + }); + + it('shows the persisted address in reconnecting style (no Connect flash)', () => { + bridgeState.account = { address: '0x1', status: 'reconnecting' }; + const { result } = renderHook(() => useWalletReown({ source: 'Header' })); + expect(result.current.isConnected).toBe(true); + expect(result.current.isReconnecting).toBe(true); + expect(result.current.address).toBe('0x1'); + }); + + it('is disconnected when the bridge reports disconnected', () => { + bridgeState.account = { address: undefined, status: 'disconnected' }; + const { result } = renderHook(() => useWalletReown({ source: 'Header' })); + expect(result.current.isConnected).toBe(false); + expect(result.current.isReconnecting).toBe(false); + expect(result.current.address).toBeUndefined(); + }); + }); +}); diff --git a/src/features/connect-wallet/hooks/wallet/useWalletReown.spec.tsx b/src/features/connect-wallet/hooks/wallet/useWalletReown.spec.tsx deleted file mode 100644 index fa1bfc95405..00000000000 --- a/src/features/connect-wallet/hooks/wallet/useWalletReown.spec.tsx +++ /dev/null @@ -1,166 +0,0 @@ -// @vitest-environment jsdom - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, renderHook } from 'vitest/lib'; - -import type { ConnectionHandlers } from '../../utils/bridge'; -import { useWalletReown } from './useWalletReown'; - -const bridgeState = vi.hoisted(() => ({ - account: { address: undefined as string | undefined, status: 'disconnected' as string }, - connectionHandlers: undefined as ConnectionHandlers | undefined, -})); - -const runtimeMock = vi.hoisted(() => ({ - isReady: true, - openModal: vi.fn(() => Promise.resolve()), - disconnect: vi.fn(() => Promise.resolve()), - subscribeModalState: vi.fn(() => () => {}), -})); - -const mixpanelMock = vi.hoisted(() => ({ - logEvent: vi.fn(), - userProfile: { setOnce: vi.fn() }, - EventTypes: { WALLET_CONNECT: 'WALLET_CONNECT' }, -})); - -vi.mock('../../utils/bridge', () => ({ - useWeb3Account: () => bridgeState.account, - subscribeConnection: (handlers: ConnectionHandlers) => { - bridgeState.connectionHandlers = handlers; - return () => { - bridgeState.connectionHandlers = undefined; - }; - }, -})); - -vi.mock('../../utils/runtime', () => ({ - ensureLoaded: () => Promise.resolve(runtimeMock), -})); - -vi.mock('src/services/mixpanel', () => mixpanelMock); - -describe('useWalletReown', () => { - beforeEach(() => { - vi.clearAllMocks(); - runtimeMock.isReady = true; - bridgeState.account = { address: undefined, status: 'disconnected' }; - bridgeState.connectionHandlers = undefined; - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - describe('connect', () => { - it('loads the runtime, opens the modal, and logs WALLET_CONNECT Started', async() => { - const { result } = renderHook(() => useWalletReown({ source: 'Header' })); - await act(async() => { - await result.current.connect(); - }); - - expect(runtimeMock.openModal).toHaveBeenCalledTimes(1); - expect(mixpanelMock.logEvent).toHaveBeenCalledWith('WALLET_CONNECT', { Source: 'Header', Status: 'Started' }); - }); - - it('logs WALLET_CONNECT Connected + profile flag on a fresh connection after connect()', async() => { - const onConnect = vi.fn(); - const { result } = renderHook(() => useWalletReown({ source: 'Header', onConnect })); - await act(async() => { - await result.current.connect(); - }); - mixpanelMock.logEvent.mockClear(); - - act(() => { - bridgeState.connectionHandlers?.onConnect?.({ address: '0x1', isReconnected: false }); - }); - - expect(mixpanelMock.logEvent).toHaveBeenCalledWith('WALLET_CONNECT', { Source: 'Header', Status: 'Connected' }); - expect(mixpanelMock.userProfile.setOnce).toHaveBeenCalledWith({ 'With Connected Wallet': true }); - expect(onConnect).toHaveBeenCalledTimes(1); - }); - - it('does not log Started, nor arm the user-initiated flag, when the runtime failed to load', async() => { - runtimeMock.isReady = false; - const onConnect = vi.fn(); - const { result } = renderHook(() => useWalletReown({ source: 'Header', onConnect })); - await act(async() => { - await result.current.connect(); - }); - - // the disabled runtime's openModal is a no-op, so nothing was started - expect(mixpanelMock.logEvent).not.toHaveBeenCalled(); - - // and a later bridge connect must not be attributed to this click - act(() => { - bridgeState.connectionHandlers?.onConnect?.({ address: '0x1', isReconnected: false }); - }); - expect(mixpanelMock.logEvent).not.toHaveBeenCalled(); - expect(onConnect).not.toHaveBeenCalled(); - }); - - it('does not log Connected for an auto-reconnect', async() => { - const { result } = renderHook(() => useWalletReown({ source: 'Header' })); - await act(async() => { - await result.current.connect(); - }); - mixpanelMock.logEvent.mockClear(); - - act(() => { - bridgeState.connectionHandlers?.onConnect?.({ address: '0x1', isReconnected: true }); - }); - - expect(mixpanelMock.logEvent).not.toHaveBeenCalled(); - }); - - it('does not log Connected when the connection was not user-initiated (openModal, not connect)', async() => { - const { result } = renderHook(() => useWalletReown({ source: 'Header' })); - await act(async() => { - await result.current.openModal(); - }); - - expect(mixpanelMock.logEvent).not.toHaveBeenCalled(); - - act(() => { - bridgeState.connectionHandlers?.onConnect?.({ address: '0x1', isReconnected: false }); - }); - expect(mixpanelMock.logEvent).not.toHaveBeenCalled(); - }); - }); - - describe('disconnect', () => { - it('calls the runtime disconnect action', async() => { - const { result } = renderHook(() => useWalletReown({ source: 'Header' })); - await act(async() => { - await result.current.disconnect(); - }); - expect(runtimeMock.disconnect).toHaveBeenCalledTimes(1); - }); - }); - - describe('account state mapping', () => { - it('is connected with the address when the bridge reports connected', () => { - bridgeState.account = { address: '0x1', status: 'connected' }; - const { result } = renderHook(() => useWalletReown({ source: 'Header' })); - expect(result.current.isConnected).toBe(true); - expect(result.current.isReconnecting).toBe(false); - expect(result.current.address).toBe('0x1'); - }); - - it('shows the persisted address in reconnecting style (no Connect flash)', () => { - bridgeState.account = { address: '0x1', status: 'reconnecting' }; - const { result } = renderHook(() => useWalletReown({ source: 'Header' })); - expect(result.current.isConnected).toBe(true); - expect(result.current.isReconnecting).toBe(true); - expect(result.current.address).toBe('0x1'); - }); - - it('is disconnected when the bridge reports disconnected', () => { - bridgeState.account = { address: undefined, status: 'disconnected' }; - const { result } = renderHook(() => useWalletReown({ source: 'Header' })); - expect(result.current.isConnected).toBe(false); - expect(result.current.isReconnecting).toBe(false); - expect(result.current.address).toBeUndefined(); - }); - }); -}); diff --git a/src/features/connect-wallet/hooks/wallet/useWalletReown.ts b/src/features/connect-wallet/hooks/wallet/useWalletReown.ts index 8ca5ada2286..f2520571922 100644 --- a/src/features/connect-wallet/hooks/wallet/useWalletReown.ts +++ b/src/features/connect-wallet/hooks/wallet/useWalletReown.ts @@ -6,7 +6,7 @@ import type { Params, Result } from './types'; import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { useWeb3Account, subscribeConnection } from '../../utils/bridge'; import { ensureLoaded } from '../../utils/runtime'; @@ -30,8 +30,8 @@ export function useWalletReown({ source, onConnect }: Params): Result { return subscribeConnection({ onConnect: ({ isReconnected }) => { if (!isReconnected && isConnectionStarted.current) { - mixpanel.logEvent(mixpanel.EventTypes.WALLET_CONNECT, { Source: source, Status: 'Connected' }); - mixpanel.userProfile.setOnce({ 'With Connected Wallet': true }); + analytics.logEvent(analytics.EventTypes.WALLET_CONNECT, { Source: source, Status: 'Connected' }); + analytics.userProfile.setOnce({ 'With Connected Wallet': true }); onConnectRef.current?.(); } isConnectionStarted.current = false; @@ -71,7 +71,7 @@ export function useWalletReown({ source, onConnect }: Params): Result { // the disabled runtime whose `openModal` is a no-op — there is nothing for the user to complete, and no // later bridge connect to attribute to this click. if (runtime.isReady) { - mixpanel.logEvent(mixpanel.EventTypes.WALLET_CONNECT, { Source: source, Status: 'Started' }); + analytics.logEvent(analytics.EventTypes.WALLET_CONNECT, { Source: source, Status: 'Started' }); isConnectionStarted.current = true; } }, [ source, loadAndOpenModal ]); diff --git a/src/features/connect-wallet/utils/dynamic-hooks.spec.ts b/src/features/connect-wallet/utils/dynamic-hooks.spec.ts new file mode 100644 index 00000000000..76febe506ed --- /dev/null +++ b/src/features/connect-wallet/utils/dynamic-hooks.spec.ts @@ -0,0 +1,33 @@ +// @vitest-environment jsdom + +import { describe, expect, test } from 'vitest'; +import { renderHook } from 'vitest/lib'; + +import { registerDynamicHooks, useAccountDynamicRegistered, useWalletDynamicRegistered } from './dynamic-hooks'; + +describe('dynamic hooks registry', () => { + test('throws a pointer to the provider while nothing is registered', () => { + expect(() => renderHook(() => useAccountDynamicRegistered())).toThrow('<DynamicProvider>'); + }); + + test('delegates to the registered hooks synchronously', () => { + registerDynamicHooks({ + useWallet: ({ source }) => ({ + connect: () => {}, + disconnect: () => {}, + isOpen: false, + isConnected: true, + isReconnecting: false, + address: `0x${ source }`, + openModal: async() => {}, + }), + useAccount: () => ({ address: '0xabc', isConnected: true } as never), + }); + + const wallet = renderHook(() => useWalletDynamicRegistered({ source: 'Header' })); + const account = renderHook(() => useAccountDynamicRegistered()); + + expect(wallet.result.current.address).toBe('0xHeader'); + expect(account.result.current.address).toBe('0xabc'); + }); +}); diff --git a/src/features/connect-wallet/utils/dynamic-hooks.ts b/src/features/connect-wallet/utils/dynamic-hooks.ts new file mode 100644 index 00000000000..55257c8b2f2 --- /dev/null +++ b/src/features/connect-wallet/utils/dynamic-hooks.ts @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { UseAccountReturnType } from 'wagmi'; + +import type { Params, Result } from '../hooks/wallet/types'; + +interface DynamicHooks { + readonly useWallet: (params: Params) => Result; + readonly useAccount: () => UseAccountReturnType; +} + +// The @dynamic-labs hooks must not be imported statically from the synchronous `useWallet` / `useAccount` +// hubs, or they would enter the reown/fallback bundle. `DynamicProvider` — itself an async chunk that +// wraps the whole app in dynamic mode — registers them at module scope instead, so by the time any child +// renders they resolve synchronously and nothing suspends after first paint. +let hooks: DynamicHooks | undefined; + +export function registerDynamicHooks(value: DynamicHooks): void { + hooks = value; +} + +function getDynamicHooks(): DynamicHooks { + if (!hooks) { + throw new Error('Dynamic wallet hooks are not registered: render inside <DynamicProvider>'); + } + return hooks; +} + +export function useWalletDynamicRegistered(params: Params): Result { + return getDynamicHooks().useWallet(params); +} + +export function useAccountDynamicRegistered(): UseAccountReturnType { + return getDynamicHooks().useAccount(); +} diff --git a/src/features/connect-wallet/utils/public-client.spec.ts b/src/features/connect-wallet/utils/public-client.spec.ts index fac07c06b00..98cbd6faf68 100644 --- a/src/features/connect-wallet/utils/public-client.spec.ts +++ b/src/features/connect-wallet/utils/public-client.spec.ts @@ -1,7 +1,19 @@ +// @vitest-environment jsdom + +import * as cookies from 'src/shared/storage/cookies'; + import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; const PUBLIC_CLIENT = { __brand: 'public-client' }; const HTTP_TRANSPORT = { __brand: 'http-transport' }; +const CONFIGURED_RPC_URL = 'https://localhost:1111'; +const CUSTOM_RPC_URL = 'https://rpc.custom.example'; +const CURRENT_CHAIN = { id: 1 }; +const NO_RPC_URL_ENVS: Array<[ string, string ]> = [ [ 'NEXT_PUBLIC_NETWORK_RPC_URL', '' ] ]; + +// jsdom serves the test page over http, where a `secure` cookie is silently dropped +const COOKIE_ATTRIBUTES = { secure: false }; const viemMock = vi.hoisted(() => ({ createPublicClient: vi.fn(), @@ -9,7 +21,7 @@ const viemMock = vi.hoisted(() => ({ })); const chainsMock = vi.hoisted(() => ({ - currentChain: undefined as { rpcUrls: { 'default': { http: Array<string> } } } | undefined, + currentChain: undefined as { id: number } | undefined, })); vi.mock('viem', () => viemMock); @@ -26,6 +38,11 @@ async function importModule() { return import('./public-client'); } +function setCustomRpcCookies(url: string, inUse: string) { + cookies.set(cookies.NAMES.CUSTOM_RPC_URL, url, COOKIE_ATTRIBUTES); + cookies.set(cookies.NAMES.CUSTOM_RPC_IN_USE, inUse, COOKIE_ATTRIBUTES); +} + describe('public-client', () => { beforeEach(() => { vi.resetModules(); @@ -37,25 +54,28 @@ describe('public-client', () => { afterEach(() => { vi.restoreAllMocks(); + cookies.remove(cookies.NAMES.CUSTOM_RPC_URL); + cookies.remove(cookies.NAMES.CUSTOM_RPC_IN_USE); }); describe('isPublicClientAvailable', () => { - it('is true when the current chain has a non-empty RPC URL', async() => { - chainsMock.currentChain = { rpcUrls: { 'default': { http: [ 'https://rpc.example' ] } } }; + it('is true when the current chain has a configured RPC URL', async() => { + chainsMock.currentChain = CURRENT_CHAIN; const { isPublicClientAvailable } = await importModule(); expect(isPublicClientAvailable).toBe(true); }); - it('is true when at least one RPC URL is non-empty (mirrors the filter(Boolean) guard)', async() => { - chainsMock.currentChain = { rpcUrls: { 'default': { http: [ '', 'https://rpc.example' ] } } }; - const { isPublicClientAvailable } = await importModule(); - expect(isPublicClientAvailable).toBe(true); + it('is false when the current chain is defined but has no RPC URL', async() => { + chainsMock.currentChain = CURRENT_CHAIN; + const isPublicClientAvailable = await withEnvs(NO_RPC_URL_ENVS, async() => (await importModule()).isPublicClientAvailable); + expect(isPublicClientAvailable).toBe(false); }); - it('is false when the current chain is defined but has no non-empty RPC URL', async() => { - chainsMock.currentChain = { rpcUrls: { 'default': { http: [ '' ] } } }; - const { isPublicClientAvailable } = await importModule(); - expect(isPublicClientAvailable).toBe(false); + it('is true when a custom RPC URL is in use even without a configured one', async() => { + chainsMock.currentChain = CURRENT_CHAIN; + setCustomRpcCookies(CUSTOM_RPC_URL, 'true'); + const isPublicClientAvailable = await withEnvs(NO_RPC_URL_ENVS, async() => (await importModule()).isPublicClientAvailable); + expect(isPublicClientAvailable).toBe(true); }); it('is true when there is no current chain (matches the old module-scope truthiness)', async() => { @@ -66,8 +86,8 @@ describe('public-client', () => { }); describe('getPublicClient', () => { - it('builds the client lazily with the same options the module scope used', async() => { - chainsMock.currentChain = { rpcUrls: { 'default': { http: [ 'https://rpc.example' ] } } }; + it('builds the client lazily over the configured RPC URL', async() => { + chainsMock.currentChain = CURRENT_CHAIN; const { getPublicClient } = await importModule(); expect(viemMock.createPublicClient).not.toHaveBeenCalled(); @@ -75,6 +95,7 @@ describe('public-client', () => { const client = await getPublicClient(); expect(client).toBe(PUBLIC_CLIENT); + expect(viemMock.http).toHaveBeenCalledWith(CONFIGURED_RPC_URL); expect(viemMock.createPublicClient).toHaveBeenCalledWith({ chain: chainsMock.currentChain, transport: HTTP_TRANSPORT, @@ -82,8 +103,28 @@ describe('public-client', () => { }); }); + it('builds the client over the custom RPC URL while it is in use', async() => { + chainsMock.currentChain = CURRENT_CHAIN; + setCustomRpcCookies(CUSTOM_RPC_URL, 'true'); + const { getPublicClient } = await importModule(); + + await getPublicClient(); + + expect(viemMock.http).toHaveBeenCalledWith(CUSTOM_RPC_URL); + }); + + it('builds the client over the configured RPC URL while the custom one is stored but not in use', async() => { + chainsMock.currentChain = CURRENT_CHAIN; + setCustomRpcCookies(CUSTOM_RPC_URL, 'false'); + const { getPublicClient } = await importModule(); + + await getPublicClient(); + + expect(viemMock.http).toHaveBeenCalledWith(CONFIGURED_RPC_URL); + }); + it('imports viem and builds the client only once across calls (memoized single-flight)', async() => { - chainsMock.currentChain = { rpcUrls: { 'default': { http: [ 'https://rpc.example' ] } } }; + chainsMock.currentChain = CURRENT_CHAIN; const { getPublicClient } = await importModule(); const [ a, b ] = await Promise.all([ getPublicClient(), getPublicClient() ]); @@ -96,15 +137,15 @@ describe('public-client', () => { }); it('resolves to undefined without importing viem when no client is available', async() => { - chainsMock.currentChain = { rpcUrls: { 'default': { http: [ '' ] } } }; - const { getPublicClient } = await importModule(); + chainsMock.currentChain = CURRENT_CHAIN; + const client = await withEnvs(NO_RPC_URL_ENVS, async() => (await importModule()).getPublicClient()); - await expect(getPublicClient()).resolves.toBeUndefined(); + expect(client).toBeUndefined(); expect(viemMock.createPublicClient).not.toHaveBeenCalled(); }); it('degrades to undefined when client construction throws', async() => { - chainsMock.currentChain = { rpcUrls: { 'default': { http: [ 'https://rpc.example' ] } } }; + chainsMock.currentChain = CURRENT_CHAIN; viemMock.createPublicClient.mockImplementation(() => { throw new Error('boom'); }); diff --git a/src/features/connect-wallet/utils/public-client.ts b/src/features/connect-wallet/utils/public-client.ts index 55a5d06f628..ebf9d8700ce 100644 --- a/src/features/connect-wallet/utils/public-client.ts +++ b/src/features/connect-wallet/utils/public-client.ts @@ -3,11 +3,13 @@ import type { PublicClient } from 'viem'; import { currentChain } from './chains'; +import { getRpcUrls } from './rpc-urls'; + +const rpcUrl: string | undefined = getRpcUrls().filter(Boolean)[0]; // Whether an RPC public client can be built for the current chain. Computed without importing // viem, so consumers can gate `enabled`/render synchronously while the client itself loads lazily. -export const isPublicClientAvailable = - !currentChain || currentChain.rpcUrls.default.http.filter(Boolean).length > 0; +export const isPublicClientAvailable = !currentChain || Boolean(rpcUrl); let publicClientPromise: Promise<PublicClient | undefined> | undefined; @@ -24,7 +26,7 @@ export function getPublicClient(): Promise<PublicClient | undefined> { const { createPublicClient, http } = await import('viem'); return createPublicClient({ chain: currentChain, - transport: http(), + transport: http(rpcUrl), batch: { multicall: true, }, diff --git a/src/features/connect-wallet/utils/rpc-urls.spec.ts b/src/features/connect-wallet/utils/rpc-urls.spec.ts new file mode 100644 index 00000000000..869150f8e1a --- /dev/null +++ b/src/features/connect-wallet/utils/rpc-urls.spec.ts @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import * as cookies from 'src/shared/storage/cookies'; + +import { afterEach, describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import { getCustomRpcUrl, getRpcUrls, resolveCustomRpcUrl } from './rpc-urls'; + +const CONFIGURED_RPC_URL = 'https://localhost:1111'; +const CORE_API_ETH_RPC_URL = 'https://localhost:3003/api/eth-rpc'; +const CUSTOM_RPC_URL = 'https://rpc.custom.example'; + +// jsdom serves the test page over http, where a `secure` cookie is silently dropped +const COOKIE_ATTRIBUTES = { secure: false }; + +function setCookie(name: cookies.NAMES, value: string | undefined) { + value === undefined ? cookies.remove(name) : cookies.set(name, value, COOKIE_ATTRIBUTES); +} + +function setCustomRpcCookies(url?: string, inUse?: string) { + setCookie(cookies.NAMES.CUSTOM_RPC_URL, url); + setCookie(cookies.NAMES.CUSTOM_RPC_IN_USE, inUse); +} + +afterEach(() => { + setCustomRpcCookies(); +}); + +describe('resolveCustomRpcUrl', () => { + it('returns the URL when it is https and the flag is on', () => { + expect(resolveCustomRpcUrl(CUSTOM_RPC_URL, 'true')).toBe(CUSTOM_RPC_URL); + }); + + it('ignores the URL when the flag is off or missing', () => { + expect(resolveCustomRpcUrl(CUSTOM_RPC_URL, 'false')).toBeUndefined(); + expect(resolveCustomRpcUrl(CUSTOM_RPC_URL, undefined)).toBeUndefined(); + }); + + it('ignores a non-https URL', () => { + expect(resolveCustomRpcUrl('http://rpc.custom.example', 'true')).toBeUndefined(); + expect(resolveCustomRpcUrl('javascript:alert(1)', 'true')).toBeUndefined(); + }); + + it('ignores a value that is not a URL', () => { + expect(resolveCustomRpcUrl('not a url', 'true')).toBeUndefined(); + expect(resolveCustomRpcUrl('', 'true')).toBeUndefined(); + expect(resolveCustomRpcUrl(undefined, 'true')).toBeUndefined(); + }); +}); + +describe('getCustomRpcUrl', () => { + it('reads the URL from the cookies when it is in use', () => { + setCustomRpcCookies(CUSTOM_RPC_URL, 'true'); + expect(getCustomRpcUrl()).toBe(CUSTOM_RPC_URL); + }); + + it('is undefined when the cookies are not set', () => { + expect(getCustomRpcUrl()).toBeUndefined(); + }); + + it('is undefined when the URL is stored but not in use', () => { + setCustomRpcCookies(CUSTOM_RPC_URL, 'false'); + expect(getCustomRpcUrl()).toBeUndefined(); + }); +}); + +describe('getRpcUrls', () => { + it('returns only the custom URL while it is in use', () => { + setCustomRpcCookies(CUSTOM_RPC_URL, 'true'); + expect(getRpcUrls({ withCoreApiFallback: true })).toEqual([ CUSTOM_RPC_URL ]); + }); + + it('returns the configured URLs when no custom URL is set', () => { + expect(getRpcUrls()).toEqual([ CONFIGURED_RPC_URL ]); + }); + + it('returns the configured URLs when the custom URL is invalid', () => { + setCustomRpcCookies('http://rpc.custom.example', 'true'); + expect(getRpcUrls()).toEqual([ CONFIGURED_RPC_URL ]); + }); + + it('returns the configured URLs when the custom URL is stored but not in use', () => { + setCustomRpcCookies(CUSTOM_RPC_URL, undefined); + expect(getRpcUrls()).toEqual([ CONFIGURED_RPC_URL ]); + }); + + it('appends the core API eth-rpc fallback to the configured URLs when asked', () => { + expect(getRpcUrls({ withCoreApiFallback: true })).toEqual([ CONFIGURED_RPC_URL, CORE_API_ETH_RPC_URL ]); + }); + + it('keeps the core API base path in the fallback URL', async() => { + const urls = await withEnvs([ [ 'NEXT_PUBLIC_API_BASE_PATH', '/poa/core' ] ], async() => { + const { getRpcUrls } = await import('./rpc-urls'); + return getRpcUrls({ withCoreApiFallback: true }); + }); + + expect(urls).toEqual([ CONFIGURED_RPC_URL, 'https://localhost:3003/poa/core/api/eth-rpc' ]); + }); +}); diff --git a/src/features/connect-wallet/utils/rpc-urls.ts b/src/features/connect-wallet/utils/rpc-urls.ts new file mode 100644 index 00000000000..3233aaeee3e --- /dev/null +++ b/src/features/connect-wallet/utils/rpc-urls.ts @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import config from 'src/config'; +import * as cookies from 'src/shared/storage/cookies'; + +export const CUSTOM_RPC_IN_USE_VALUE = 'true'; + +export function resolveCustomRpcUrl(url: string | undefined, inUseFlag: string | undefined): string | undefined { + if (inUseFlag !== CUSTOM_RPC_IN_USE_VALUE || !url) { + return; + } + + try { + return new URL(url).protocol === 'https:' ? url : undefined; + } catch { + return; + } +} + +export function getCustomRpcUrl(): string | undefined { + return resolveCustomRpcUrl(cookies.get(cookies.NAMES.CUSTOM_RPC_URL), cookies.get(cookies.NAMES.CUSTOM_RPC_IN_USE)); +} + +interface Options { + withCoreApiFallback?: boolean; +} + +export function getRpcUrls({ withCoreApiFallback }: Options = {}): Array<string> { + const customUrl = getCustomRpcUrl(); + + if (customUrl) { + return [ customUrl ]; + } + + const coreApi = config.apis.core; + const coreApiFallback = withCoreApiFallback && coreApi ? `${ coreApi.endpoint }${ coreApi.basePath ?? '' }/api/eth-rpc` : undefined; + + return [ ...config.chain.rpcUrls, coreApiFallback ].filter(Boolean); +} diff --git a/src/features/connect-wallet/utils/wagmi-config.ts b/src/features/connect-wallet/utils/wagmi-config.ts index ff46fe0f37b..919d71d84bd 100644 --- a/src/features/connect-wallet/utils/wagmi-config.ts +++ b/src/features/connect-wallet/utils/wagmi-config.ts @@ -5,9 +5,11 @@ import type { AppKitNetwork } from '@reown/appkit/networks'; import type { Chain, Transport } from 'viem'; import { fallback, http } from 'viem'; import { createConfig } from 'wagmi'; +import { coinbaseWallet } from 'wagmi/connectors'; import { chains, parentChain } from 'src/features/connect-wallet/utils/chains'; import { installEip6963AnnounceGuard } from 'src/features/connect-wallet/utils/install-eip6963-announce-guard'; +import { getRpcUrls } from 'src/features/connect-wallet/utils/rpc-urls'; import essentialDappsChainsConfig from 'src/features/marketplace/chains-config/essential-dapps'; import multichainConfig from 'src/features/multichain/chains-config'; @@ -15,19 +17,26 @@ import appConfig from 'src/config'; const feature = appConfig.features.connectWallet; +const buildTransport = (urls: Array<string>): Transport => fallback( + urls.filter(Boolean).map((url) => http(url, { batch: { wait: 100, batchSize: 5 } })), +); + +const getOwnChainTransport = (readOnly: boolean): Record<string, Transport> => { + if (!appConfig.chain.id) { + return {}; + } + + return { [appConfig.chain.id]: buildTransport(getRpcUrls({ withCoreApiFallback: readOnly })) }; +}; + const getChainTransportFromConfig = (config: Partial<typeof appConfig> | undefined, readOnly?: boolean): Record<string, Transport> => { if (!config?.chain?.id) { return {}; } - return { - [config.chain.id]: fallback( - config.chain.rpcUrls - .concat(readOnly && config.apis?.core ? `${ config.apis.core.endpoint }${ config.apis.core.basePath ?? '' }/api/eth-rpc` : '') - .filter(Boolean) - .map((url) => http(url, { batch: { wait: 100, batchSize: 5 } })), - ), - }; + const coreApiFallback = readOnly && config.apis?.core ? `${ config.apis.core.endpoint }${ config.apis.core.basePath ?? '' }/api/eth-rpc` : ''; + + return { [config.chain.id]: buildTransport([ ...config.chain.rpcUrls, coreApiFallback ]) }; }; const reduceExternalChainsToTransportConfig = (readOnly: boolean): Record<string, Transport> => { @@ -59,9 +68,9 @@ const wagmi = (() => { const wagmiConfig = createConfig({ chains: chains as [Chain, ...Array<Chain>], transports: { - ...getChainTransportFromConfig(appConfig, true), ...(parentChain ? { [parentChain.id]: http(parentChain.rpcUrls.default.http[0]) } : {}), ...reduceExternalChainsToTransportConfig(true), + ...getOwnChainTransport(true), }, // ssr:false — the config is only ever created client-side (lazily, off the critical path), so wagmi's // <Hydrate> restores persisted state and reconnects synchronously; no manual hydration is needed. @@ -77,11 +86,14 @@ const wagmi = (() => { networks: chains as Array<AppKitNetwork>, multiInjectedProviderDiscovery: true, transports: { - ...getChainTransportFromConfig(appConfig, false), ...(parentChain ? { [parentChain.id]: http() } : {}), ...reduceExternalChainsToTransportConfig(false), + ...getOwnChainTransport(false), }, projectId: feature.reown.projectId, + // the adapter adds its own Coinbase connector unless one exists; ours turns off the SDK telemetry, + // which is injected as an inline script and gets blocked by the CSP + connectors: [ coinbaseWallet({ preference: { options: 'all', telemetry: false } }) ], // ssr:false — see the note on the fallback config above; the adapter's config is client-only + lazy. ssr: false, batch: { multicall: { wait: 100, batchSize: 1024 } }, diff --git a/src/features/cross-chain-txs/components/ChainStatsDetailsCrossChainTxs.tsx b/src/features/cross-chain-txs/components/ChainStatsDetailsCrossChainTxs.tsx index 6c45429b443..5a5dfacb7ac 100644 --- a/src/features/cross-chain-txs/components/ChainStatsDetailsCrossChainTxs.tsx +++ b/src/features/cross-chain-txs/components/ChainStatsDetailsCrossChainTxs.tsx @@ -15,7 +15,7 @@ import ChainSelectMultichain from 'src/features/multichain/components/ChainSelec import type useRoutedChainSelect from 'src/features/multichain/hooks/useRoutedChainSelect'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import ChainSelect, { isAllOption } from 'src/shared/external-chains/ChainSelect'; import type { OnValueChangeHandler } from 'src/toolkit/chakra/select'; @@ -55,7 +55,7 @@ const ChainStatsDetailsCrossChainTxs = ({ const chainsQuery = useApiQuery('interchainIndexer:chains'); const handleShare = React.useCallback(async() => { - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { Type: 'Share chart', Info: chart.id }); + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Share chart', Info: chart.id }); }, [ chart.id ]); const counterPartyChainsConfig = React.useMemo(() => { diff --git a/src/features/cross-chain-txs/components/ChartWidgetContainerCrossChain.tsx b/src/features/cross-chain-txs/components/ChartWidgetContainerCrossChain.tsx index 11f97dd73f6..711be735405 100644 --- a/src/features/cross-chain-txs/components/ChartWidgetContainerCrossChain.tsx +++ b/src/features/cross-chain-txs/components/ChartWidgetContainerCrossChain.tsx @@ -1,13 +1,14 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { Props as ChartWidgetContainerProps } from 'src/features/chain-stats/components/ChartWidgetContainer'; import { getChartUrl } from 'src/features/chain-stats/utils/chart'; import { useMultichainContext } from 'src/features/multichain/context'; +import { route } from 'src/shared/router/routes'; + import { SankeyChartWidget } from 'src/toolkit/components/charts/sankey/SankeyChartWidget'; import useCrossChainChartQuery from '../hooks/useCrossChainChartQuery'; diff --git a/src/features/cross-chain-txs/components/CrossChainBridgeLink.tsx b/src/features/cross-chain-txs/components/CrossChainBridgeLink.tsx index 550cef57714..e1030534379 100644 --- a/src/features/cross-chain-txs/components/CrossChainBridgeLink.tsx +++ b/src/features/cross-chain-txs/components/CrossChainBridgeLink.tsx @@ -7,6 +7,7 @@ import type { BridgeInfo } from '@blockscout/interchain-indexer-types'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props extends JsxStyleProps { data: BridgeInfo | undefined; @@ -25,14 +26,16 @@ const CrossChainBridgeLink = ({ data, isLoading, messageId, ...rest }: Props) => const uiUrl = messageId && data.ui_url ? data.ui_url.replace('{{message_id}}', messageId) : data.ui_url; return ( - <Link href={ uiUrl || data.docs_url } external loading={ isLoading } { ...rest }> - { data.name } + <Link href={ uiUrl || data.docs_url } external loading={ isLoading } maxW="100%" { ...rest } > + <Truncate value={ data.name } type="end"/> </Link> ); } return ( - <Skeleton loading={ isLoading } { ...rest }>{ data.name }</Skeleton> + <Skeleton loading={ isLoading } maxW="100%" display="inline-flex" { ...rest }> + <Truncate value={ data.name } type="end"/> + </Skeleton> ); }; diff --git a/src/features/cross-chain-txs/components/CrossChainFromToTag.tsx b/src/features/cross-chain-txs/components/CrossChainFromToTag.tsx index 2e6b41bb8c5..beb3a6cef53 100644 --- a/src/features/cross-chain-txs/components/CrossChainFromToTag.tsx +++ b/src/features/cross-chain-txs/components/CrossChainFromToTag.tsx @@ -2,11 +2,10 @@ import React from 'react'; -import { Badge, type BadgeProps } from 'src/toolkit/chakra/badge'; +import AddressFromToTag from 'src/slices/address/components/from-to/AddressFromToTag'; +import type { TxCourseType } from 'src/slices/address/utils/tx'; -const SELF_TAG = { text: 'Self', colorPalette: 'gray' as const }; -const OUT_TAG = { text: 'Out', colorPalette: 'orange' as const }; -const IN_TAG = { text: 'In', colorPalette: 'purple' as const }; +import type { BadgeProps } from 'src/toolkit/chakra/badge'; interface Props extends BadgeProps { currentAddress: string; @@ -17,33 +16,23 @@ interface Props extends BadgeProps { const CrossChainFromToTag = ({ currentAddress, sender, recipient, isLoading, ...rest }: Props) => { - const { text, colorPalette } = (() => { + const type: Exclude<TxCourseType, 'unspecified'> = (() => { if (sender?.toLowerCase() === currentAddress.toLowerCase() && recipient?.toLowerCase() === currentAddress.toLowerCase()) { - return SELF_TAG; + return 'self'; } if (sender?.toLowerCase() === currentAddress.toLowerCase()) { - return OUT_TAG; + return 'out'; } if (recipient?.toLowerCase() === currentAddress.toLowerCase()) { - return IN_TAG; + return 'in'; } - return SELF_TAG; + return 'self'; })(); - return ( - <Badge - loading={ isLoading } - colorPalette={ colorPalette } - minW={ 10 } - justifyContent="center" - { ...rest } - > - { text } - </Badge> - ); + return <AddressFromToTag type={ type } isLoading={ isLoading } { ...rest }/>; }; export default React.memo(CrossChainFromToTag); diff --git a/src/features/cross-chain-txs/components/CrossChainMessageEntity.spec.tsx b/src/features/cross-chain-txs/components/CrossChainMessageEntity.spec.tsx new file mode 100644 index 00000000000..16506ce81f7 --- /dev/null +++ b/src/features/cross-chain-txs/components/CrossChainMessageEntity.spec.tsx @@ -0,0 +1,31 @@ +// @vitest-environment jsdom +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, render } from 'vitest/lib'; + +import CrossChainMessageEntity from './CrossChainMessageEntity'; + +const MESSAGE_ID = '0x057b42bbbfbb4900e155a554ae67632cb21e6f5a64d815fcad7f33abe552c059'; +const BRIDGE_ID = 2; +// the entity truncates the id in the middle, so only its ends survive in the rendered text +const MESSAGE_ID_TAIL = MESSAGE_ID.slice(-4); + +describe('CrossChainMessageEntity', () => { + afterEach(cleanup); + + it('links to the message within its bridge', () => { + const { container } = render(<CrossChainMessageEntity id={ MESSAGE_ID } bridgeId={ BRIDGE_ID }/>); + + expect(container.querySelector('a')?.getAttribute('href')).toBe(`/bridge/${ BRIDGE_ID }/cross-chain-tx/${ MESSAGE_ID }`); + }); + + it('renders unlinked when the bridge is unknown', () => { + const { container } = render(<CrossChainMessageEntity id={ MESSAGE_ID } bridgeId={ undefined }/>); + + expect(container.querySelector('a')).toBeNull(); + expect(container.textContent).toContain(MESSAGE_ID_TAIL); + }); +}); diff --git a/src/features/cross-chain-txs/components/CrossChainMessageEntity.tsx b/src/features/cross-chain-txs/components/CrossChainMessageEntity.tsx index 1225e7d135c..89cfc3c46f5 100644 --- a/src/features/cross-chain-txs/components/CrossChainMessageEntity.tsx +++ b/src/features/cross-chain-txs/components/CrossChainMessageEntity.tsx @@ -8,11 +8,11 @@ import { distributeEntityProps } from 'src/shared/entities/utils'; import getChainTooltipText from 'src/shared/external-chains/get-chain-tooltip-text'; import { route } from 'src/shared/router/routes'; -type LinkProps = EntityBase.LinkBaseProps & Pick<EntityProps, 'id'>; +type LinkProps = EntityBase.LinkBaseProps & Pick<EntityProps, 'id' | 'bridgeId'>; const Link = chakra((props: LinkProps) => { - const defaultHref = route( - { pathname: '/cross-chain-tx/[id]', query: { id: props.id } }, + const defaultHref = props.bridgeId === undefined ? undefined : route( + { pathname: '/bridge/[bridgeId]/cross-chain-tx/[id]', query: { bridgeId: String(props.bridgeId), id: props.id } }, { chain: props.chain, external: props.external }, ); @@ -82,17 +82,20 @@ const Container = EntityBase.Container; export interface EntityProps extends EntityBase.EntityBaseProps { id: string; + bridgeId: number | undefined; } const CrossChainMessageEntity = (props: EntityProps) => { const partsProps = distributeEntityProps(props); const content = <Content { ...partsProps.content }/>; + // a message is only addressable within its bridge, so without one there is no route to link to + const noLink = props.noLink || props.bridgeId === undefined; return ( <Container { ...partsProps.container }> <Icon { ...partsProps.icon }/> - { props.noLink ? content : <Link { ...partsProps.link }>{ content }</Link> } + { noLink ? content : <Link { ...partsProps.link }>{ content }</Link> } <Copy { ...partsProps.copy }/> </Container> ); diff --git a/src/features/cross-chain-txs/components/filters/ChainFilter.tsx b/src/features/cross-chain-txs/components/filters/ChainFilter.tsx new file mode 100644 index 00000000000..7768f263968 --- /dev/null +++ b/src/features/cross-chain-txs/components/filters/ChainFilter.tsx @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Flex, Spinner, chakra } from '@chakra-ui/react'; +import { isEqual } from 'es-toolkit'; +import React from 'react'; + +import useApiQuery from 'src/api/hooks/useApiQuery'; + +import ChainIcon from 'src/shared/external-chains/ChainIcon'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; + +import { Checkbox, CheckboxGroup } from 'src/toolkit/chakra/checkbox'; +import { FilterInput } from 'src/toolkit/components/filters/FilterInput'; + +import type { CrossChainColumnFilterField } from './utils'; +import { filterChainOptions, joinFilterValue, splitFilterValue } from './utils'; + +export const SEARCH_THRESHOLD = 10; + +const DIRECTIONS = { + source: { field: 'src_chain_ids', title: 'Source tx chains' }, + destination: { field: 'dst_chain_ids', title: 'Destination tx chains' }, +} as const satisfies Record<string, { field: CrossChainColumnFilterField; title: string }>; + +export type ChainFilterDirection = keyof typeof DIRECTIONS; + +interface Props { + direction: ChainFilterDirection; + value: string | undefined; + handleFilterChange: (field: CrossChainColumnFilterField, value: string | undefined) => void; +} + +const ChainFilter = ({ direction, value, handleFilterChange }: Props) => { + const { field, title } = DIRECTIONS[direction]; + const [ currentValue, setCurrentValue ] = React.useState<Array<string>>(() => splitFilterValue(value)); + const [ searchTerm, setSearchTerm ] = React.useState(''); + + const chainsQuery = useApiQuery('interchainIndexer:chains', { queryOptions: { refetchOnMount: false } }); + + const chains = chainsQuery.data?.items; + const hasSearch = (chains?.length ?? 0) >= SEARCH_THRESHOLD; + const visibleChains = React.useMemo(() => filterChainOptions(chains, searchTerm), [ chains, searchTerm ]); + + const handleReset = React.useCallback(() => setCurrentValue([]), []); + + const handleFilter = React.useCallback(() => { + handleFilterChange(field, joinFilterValue(currentValue)); + }, [ handleFilterChange, field, currentValue ]); + + return ( + <ColumnFilterContent + isTouched={ !isEqual(currentValue.slice().sort(), splitFilterValue(value).sort()) } + onFilter={ handleFilter } + > + <ColumnFilterContentSection title={ title } onReset={ handleReset } isFilled={ currentValue.length > 0 }> + { hasSearch && ( + <FilterInput + size="sm" + onChange={ setSearchTerm } + placeholder="Find by chain name or chain ID" + /> + ) } + { chainsQuery.isPending && <Spinner size="md"/> } + { chainsQuery.isError && <span>Something went wrong. Please try again.</span> } + { chains && visibleChains.length === 0 && <span>No results found.</span> } + { visibleChains.length > 0 && ( + <Flex flexDir="column" maxH="250px" overflowY="auto"> + <CheckboxGroup value={ currentValue } onValueChange={ setCurrentValue } orientation="vertical"> + { visibleChains.map((chain) => ( + <Checkbox key={ chain.id } value={ chain.id } labelProps={{ minW: 0 }}> + <Flex alignItems="center" columnGap={ 2 } minW={ 0 }> + <ChainIcon data={ chain } alt={ `${ chain.name } logo` } noTooltip flexShrink={ 0 }/> + <chakra.span overflow="hidden" whiteSpace="nowrap" textOverflow="ellipsis"> + { chain.name || `Chain ${ chain.id }` } + </chakra.span> + </Flex> + </Checkbox> + )) } + </CheckboxGroup> + </Flex> + ) } + </ColumnFilterContentSection> + </ColumnFilterContent> + ); +}; + +export default React.memo(ChainFilter); diff --git a/src/features/cross-chain-txs/components/filters/CrossChainFilterByColumn.tsx b/src/features/cross-chain-txs/components/filters/CrossChainFilterByColumn.tsx new file mode 100644 index 00000000000..b90ec3a9b05 --- /dev/null +++ b/src/features/cross-chain-txs/components/filters/CrossChainFilterByColumn.tsx @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { CrossChainFilters } from 'src/features/cross-chain-txs/types/api'; + +import ColumnFilter from 'src/shared/filters/ColumnFilter'; + +import ChainFilter from './ChainFilter'; +import ProtocolFilter from './ProtocolFilter'; +import type { CrossChainColumnFilterField, CrossChainFilterChangeHandler } from './utils'; + +export type CrossChainFilterColumn = 'source' | 'destination' | 'protocol'; + +const KEEP_DRAFT_ON_CLOSE = { unmountOnExit: false } as const; + +interface Props { + column: CrossChainFilterColumn; + filters: CrossChainFilters; + onFilterChange: CrossChainFilterChangeHandler; + isLoading?: boolean; +} + +const CrossChainFilterByColumn = ({ column, filters, onFilterChange, isLoading }: Props) => { + const handleFilterChange = React.useCallback((field: CrossChainColumnFilterField, value: string | undefined) => { + onFilterChange({ ...filters, [field]: value }); + }, [ filters, onFilterChange ]); + + switch (column) { + case 'source': { + return ( + <ColumnFilter + columnName="Source tx" + isLoading={ isLoading } + selected={ Boolean(filters.src_chain_ids) } + rootProps={ KEEP_DRAFT_ON_CLOSE } + > + <ChainFilter key={ filters.src_chain_ids } direction="source" value={ filters.src_chain_ids } handleFilterChange={ handleFilterChange }/> + </ColumnFilter> + ); + } + case 'destination': { + return ( + <ColumnFilter + columnName="Destination tx" + isLoading={ isLoading } + selected={ Boolean(filters.dst_chain_ids) } + rootProps={ KEEP_DRAFT_ON_CLOSE } + > + <ChainFilter key={ filters.dst_chain_ids } direction="destination" value={ filters.dst_chain_ids } handleFilterChange={ handleFilterChange }/> + </ColumnFilter> + ); + } + case 'protocol': { + return ( + <ColumnFilter + columnName="Protocol" + isLoading={ isLoading } + selected={ Boolean(filters.bridge_ids) } + rootProps={ KEEP_DRAFT_ON_CLOSE } + > + <ProtocolFilter key={ filters.bridge_ids } value={ filters.bridge_ids } handleFilterChange={ handleFilterChange }/> + </ColumnFilter> + ); + } + } +}; + +export default React.memo(CrossChainFilterByColumn); diff --git a/src/features/cross-chain-txs/components/filters/CrossChainFilterTags.tsx b/src/features/cross-chain-txs/components/filters/CrossChainFilterTags.tsx new file mode 100644 index 00000000000..6108a4b50f3 --- /dev/null +++ b/src/features/cross-chain-txs/components/filters/CrossChainFilterTags.tsx @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { FlexProps } from '@chakra-ui/react'; +import React from 'react'; + +import type { CrossChainFilters } from 'src/features/cross-chain-txs/types/api'; + +import useApiQuery from 'src/api/hooks/useApiQuery'; + +import FilterTagsRow from 'src/shared/filters/FilterTagsRow'; + +import type { CrossChainColumnFilterField, CrossChainFilterChangeHandler } from './utils'; +import { getCrossChainFilterTags, hasActiveColumnFilters } from './utils'; + +interface Props extends FlexProps { + filters: CrossChainFilters; + onFilterChange: CrossChainFilterChangeHandler; +} + +const CrossChainFilterTags = ({ filters, onFilterChange, ...rest }: Props) => { + const isActive = hasActiveColumnFilters(filters); + + const chainsQuery = useApiQuery('interchainIndexer:chains', { queryOptions: { enabled: isActive, refetchOnMount: false } }); + const bridgesQuery = useApiQuery('interchainIndexer:bridges', { queryOptions: { enabled: isActive, refetchOnMount: false } }); + + const tags = React.useMemo( + () => getCrossChainFilterTags( + filters, + chainsQuery.data?.items, + bridgesQuery.data?.items, + { chains: chainsQuery.isPending, bridges: bridgesQuery.isPending }, + ), + [ filters, chainsQuery.data?.items, bridgesQuery.data?.items, chainsQuery.isPending, bridgesQuery.isPending ], + ); + + const handleClear = React.useCallback((field: CrossChainColumnFilterField) => { + onFilterChange({ ...filters, [field]: undefined }); + }, [ filters, onFilterChange ]); + + const handleClearAll = React.useCallback(() => { + onFilterChange({ q: filters.q }); + }, [ filters.q, onFilterChange ]); + + if (!isActive) { + return null; + } + + return <FilterTagsRow tags={ tags } onClear={ handleClear } onClearAll={ handleClearAll } { ...rest }/>; +}; + +export default React.memo(CrossChainFilterTags); diff --git a/src/features/cross-chain-txs/components/filters/ProtocolFilter.tsx b/src/features/cross-chain-txs/components/filters/ProtocolFilter.tsx new file mode 100644 index 00000000000..3ebae1319fd --- /dev/null +++ b/src/features/cross-chain-txs/components/filters/ProtocolFilter.tsx @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Spinner } from '@chakra-ui/react'; +import { isEqual } from 'es-toolkit'; +import React from 'react'; + +import useApiQuery from 'src/api/hooks/useApiQuery'; + +import config from 'src/config'; +import { getFeaturePayload } from 'src/config/utils/features'; +import ColumnFilterContent from 'src/shared/filters/ColumnFilterContent'; +import ColumnFilterContentSection from 'src/shared/filters/ColumnFilterContentSection'; + +import { Checkbox, CheckboxGroup } from 'src/toolkit/chakra/checkbox'; + +import type { CrossChainColumnFilterField } from './utils'; +import { getProtocolOptions, joinFilterValue, splitFilterValue } from './utils'; + +const FILTER_FIELD: CrossChainColumnFilterField = 'bridge_ids'; + +const CONFIGURED_BRIDGE_IDS: Array<number> = getFeaturePayload(config.features.crossChainTxs)?.bridgeIds ?? []; + +interface Props { + value: string | undefined; + handleFilterChange: (field: CrossChainColumnFilterField, value: string | undefined) => void; +} + +const ProtocolFilter = ({ value, handleFilterChange }: Props) => { + const [ currentValue, setCurrentValue ] = React.useState<Array<string>>(() => splitFilterValue(value)); + + const bridgesQuery = useApiQuery('interchainIndexer:bridges', { queryOptions: { refetchOnMount: false } }); + + const options = React.useMemo( + () => getProtocolOptions(bridgesQuery.data?.items, CONFIGURED_BRIDGE_IDS), + [ bridgesQuery.data?.items ], + ); + + const handleReset = React.useCallback(() => setCurrentValue([]), []); + + const handleFilter = React.useCallback(() => { + handleFilterChange(FILTER_FIELD, joinFilterValue(currentValue)); + }, [ handleFilterChange, currentValue ]); + + return ( + <ColumnFilterContent + isTouched={ !isEqual(currentValue.slice().sort(), splitFilterValue(value).sort()) } + onFilter={ handleFilter } + > + <ColumnFilterContentSection title="Protocol" onReset={ handleReset } isFilled={ currentValue.length > 0 }> + <CheckboxGroup value={ currentValue } onValueChange={ setCurrentValue } orientation="vertical"> + { bridgesQuery.isPending && <Spinner size="md"/> } + { options.map((option) => ( + <Checkbox key={ option.id } value={ option.id }> + { option.name } + </Checkbox> + )) } + </CheckboxGroup> + </ColumnFilterContentSection> + </ColumnFilterContent> + ); +}; + +export default React.memo(ProtocolFilter); diff --git a/src/features/cross-chain-txs/components/filters/utils.spec.ts b/src/features/cross-chain-txs/components/filters/utils.spec.ts new file mode 100644 index 00000000000..c27ce8d9bc7 --- /dev/null +++ b/src/features/cross-chain-txs/components/filters/utils.spec.ts @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { bridgeAmb, bridgeAvalanche, bridgeXdai } from '../../mocks/bridges'; +import { config as chains } from '../../mocks/config'; +import { filterChainOptions, getCrossChainFilterTags, getProtocolOptions, hasActiveColumnFilters, joinFilterValue, splitFilterValue } from './utils'; + +const BRIDGES = [ bridgeAmb, bridgeAvalanche, bridgeXdai ]; + +describe('getProtocolOptions', () => { + it('lists only bridges that are enabled and configured for the deployment', () => { + const disabledBridge = { ...bridgeXdai, enabled: false }; + + expect(getProtocolOptions([ bridgeAmb, bridgeAvalanche, disabledBridge ], [ 1, 3, 99 ])).toEqual([ + { id: '1', name: 'AMB/Omnibridge' }, + ]); + }); + + it('keeps a single configured bridge', () => { + expect(getProtocolOptions(BRIDGES, [ 2 ])).toEqual([ { id: '2', name: 'Avalanche ICTT' } ]); + }); + + it('returns no options before the bridges are loaded', () => { + expect(getProtocolOptions(undefined, [ 1, 2 ])).toEqual([]); + }); +}); + +describe('splitFilterValue / joinFilterValue', () => { + it('round-trips a comma-joined URL value', () => { + expect(splitFilterValue('1,100')).toEqual([ '1', '100' ]); + expect(joinFilterValue([ '1', '100' ])).toBe('1,100'); + }); + + it('treats an absent or empty value as no selection', () => { + expect(splitFilterValue(undefined)).toEqual([]); + expect(splitFilterValue('')).toEqual([]); + expect(joinFilterValue([])).toBeUndefined(); + }); +}); + +describe('filterChainOptions', () => { + it('returns every chain when the search term is blank', () => { + expect(filterChainOptions(chains, '')).toBe(chains); + expect(filterChainOptions(chains, ' ')).toBe(chains); + }); + + it('matches by chain name or chain id, case-insensitively', () => { + expect(filterChainOptions(chains, 'c-CHAIN').map((chain) => chain.id)).toEqual([ '43114' ]); + expect(filterChainOptions(chains, '4311').map((chain) => chain.id)).toEqual([ '43114' ]); + expect(filterChainOptions(chains, 'no such chain')).toEqual([]); + }); + + it('returns no chains before the list is loaded', () => { + expect(filterChainOptions(undefined, 'c')).toEqual([]); + }); +}); + +describe('hasActiveColumnFilters', () => { + it('ignores the search term', () => { + expect(hasActiveColumnFilters({ q: 'foo' })).toBe(false); + expect(hasActiveColumnFilters({ q: 'foo', bridge_ids: '1' })).toBe(true); + expect(hasActiveColumnFilters(undefined)).toBe(false); + }); +}); + +describe('getCrossChainFilterTags', () => { + it('returns no tags when no column filter is set', () => { + expect(getCrossChainFilterTags({ q: 'foo' }, chains, BRIDGES)).toEqual([]); + }); + + it('maps URL ids to chain and bridge names, joined with a comma', () => { + const tags = getCrossChainFilterTags( + { src_chain_ids: '43114,8021', dst_chain_ids: '4444', bridge_ids: '1,3' }, + chains, + BRIDGES, + ); + + expect(tags).toEqual([ + { key: 'src_chain_ids', name: 'Source chain', value: 'C-Chain, Numine', isLoading: false }, + { key: 'dst_chain_ids', name: 'Destination chain', value: 'Duck chain', isLoading: false }, + { key: 'bridge_ids', name: 'Protocol', value: 'AMB/Omnibridge, xDai Bridge', isLoading: false }, + ]); + }); + + it('falls back to the id when a chain or bridge is unknown', () => { + const tags = getCrossChainFilterTags({ src_chain_ids: '7', bridge_ids: '42' }, undefined, undefined); + + expect(tags).toEqual([ + { key: 'src_chain_ids', name: 'Source chain', value: 'Chain 7', isLoading: false }, + { key: 'bridge_ids', name: 'Protocol', value: 'Bridge 42', isLoading: false }, + ]); + }); + + it('marks only the tags whose directory is still pending as loading', () => { + const tags = getCrossChainFilterTags( + { src_chain_ids: '7', dst_chain_ids: '4444', bridge_ids: '1' }, + undefined, + BRIDGES, + { chains: true, bridges: false }, + ); + + expect(tags.map((tag) => [ tag.key, tag.isLoading ])).toEqual([ + [ 'src_chain_ids', true ], + [ 'dst_chain_ids', true ], + [ 'bridge_ids', false ], + ]); + }); +}); diff --git a/src/features/cross-chain-txs/components/filters/utils.ts b/src/features/cross-chain-txs/components/filters/utils.ts new file mode 100644 index 00000000000..016c227e992 --- /dev/null +++ b/src/features/cross-chain-txs/components/filters/utils.ts @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { Bridge, ChainInfo } from '@blockscout/interchain-indexer-types'; +import type { CrossChainFilters } from 'src/features/cross-chain-txs/types/api'; + +import type { FilterTag } from 'src/shared/filters/FilterTagsRow'; + +const COLUMN_FILTER_FIELDS = [ 'src_chain_ids', 'dst_chain_ids', 'bridge_ids' ] as const; + +export type CrossChainColumnFilterField = typeof COLUMN_FILTER_FIELDS[number]; + +export type CrossChainFilterChangeHandler = (filters: CrossChainFilters) => void; + +export interface FilterDirectoriesPending { + readonly chains: boolean; + readonly bridges: boolean; +} + +export interface ProtocolOption { + readonly id: string; + readonly name: string; +} + +const EMPTY_CHAINS: Array<ChainInfo> = []; + +const COLUMN_FILTER_NAMES: Record<CrossChainColumnFilterField, string> = { + src_chain_ids: 'Source chain', + dst_chain_ids: 'Destination chain', + bridge_ids: 'Protocol', +}; + +export function splitFilterValue(value: string | undefined): Array<string> { + return value ? value.split(',').filter(Boolean) : []; +} + +export function joinFilterValue(values: Array<string>): string | undefined { + return values.length > 0 ? values.join(',') : undefined; +} + +export function hasActiveColumnFilters(filters: CrossChainFilters | undefined): boolean { + return COLUMN_FILTER_FIELDS.some((field) => Boolean(filters?.[field])); +} + +export function getProtocolOptions(bridges: Array<Bridge> | undefined, configuredBridgeIds: Array<number>): Array<ProtocolOption> { + if (!bridges) { + return []; + } + + return bridges + .filter((bridge) => bridge.enabled && configuredBridgeIds.includes(bridge.id)) + .map((bridge) => ({ id: String(bridge.id), name: bridge.name })); +} + +export function filterChainOptions(chains: Array<ChainInfo> | undefined, searchTerm: string): Array<ChainInfo> { + if (!chains) { + return EMPTY_CHAINS; + } + + const term = searchTerm.trim().toLowerCase(); + if (!term) { + return chains; + } + + return chains.filter((chain) => chain.name.toLowerCase().includes(term) || chain.id.toLowerCase().includes(term)); +} + +function getChainName(chainId: string, chains: Array<ChainInfo> | undefined): string { + return chains?.find((chain) => chain.id === chainId)?.name || `Chain ${ chainId }`; +} + +function getBridgeName(bridgeId: string, bridges: Array<Bridge> | undefined): string { + return bridges?.find((bridge) => String(bridge.id) === bridgeId)?.name || `Bridge ${ bridgeId }`; +} + +export function getCrossChainFilterTags( + filters: CrossChainFilters | undefined, + chains: Array<ChainInfo> | undefined, + bridges: Array<Bridge> | undefined, + pending: FilterDirectoriesPending = { chains: false, bridges: false }, +): Array<FilterTag<CrossChainColumnFilterField>> { + return COLUMN_FILTER_FIELDS.flatMap((field) => { + const ids = splitFilterValue(filters?.[field]); + + if (ids.length === 0) { + return []; + } + + const isBridgeField = field === 'bridge_ids'; + const names = isBridgeField ? + ids.map((id) => getBridgeName(id, bridges)) : + ids.map((id) => getChainName(id, chains)); + const isLoading = isBridgeField ? pending.bridges : pending.chains; + + return [ { key: field, name: COLUMN_FILTER_NAMES[field], value: names.join(', '), isLoading } ]; + }); +} diff --git a/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainContent.tsx b/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainContent.tsx index c1a3d9bbe3a..40b1f19852b 100644 --- a/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainContent.tsx +++ b/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainContent.tsx @@ -1,16 +1,20 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { InterchainTransfer } from '@blockscout/interchain-indexer-types'; +import type { CrossChainFilters } from 'src/features/cross-chain-txs/types/api'; import type { PaginationParams } from 'src/shared/pagination/types'; import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import DataList, { type Props as DataListProps } from 'src/shared/lists/DataList'; -import TokenTransfersCrossChainList from './TokenTransfersCrossChainList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + +import CrossChainFilterTags from '../filters/CrossChainFilterTags'; +import type { CrossChainFilterChangeHandler } from '../filters/utils'; +import { hasActiveColumnFilters } from '../filters/utils'; import TokenTransfersCrossChainTable from './TokenTransfersCrossChainTable'; interface Props extends Omit<DataListProps, 'children'> { @@ -20,48 +24,46 @@ interface Props extends Omit<DataListProps, 'children'> { currentAddress?: string; tableTop?: number; resetKey?: string; + filters?: CrossChainFilters; + onFilterChange?: CrossChainFilterChangeHandler; } -const TokenTransfersCrossChainContent = ({ items, isLoading, pagination, currentAddress, tableTop, resetKey, ...rest }: Props) => { +const TokenTransfersCrossChainContent = ({ items, isLoading, pagination, currentAddress, tableTop, resetKey, filters, onFilterChange, ...rest }: Props) => { const content = items ? ( - <> - <Box hideFrom="lg"> - <TokenTransfersCrossChainList - items={ items } - isLoading={ isLoading } - currentAddress={ currentAddress } - resetKey={ resetKey } - listItemProps={{ - py: 4, - textStyle: 'sm', - rowGap: '14px', - }} - /> - </Box> - <Box hideBelow="lg"> - <TokenTransfersCrossChainTable - data={ items } - isLoading={ isLoading } - top={ tableTop ?? (pagination?.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0) } - currentAddress={ currentAddress } - resetKey={ resetKey } - /> - </Box> - </> + <TableContainerScrollable> + <TokenTransfersCrossChainTable + data={ items } + isLoading={ isLoading } + top={ tableTop ?? (pagination?.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0) } + currentAddress={ currentAddress } + resetKey={ resetKey } + filters={ filters } + onFilterChange={ onFilterChange } + /> + </TableContainerScrollable> ) : null; + // The sticky action bar pulls itself up by 24px (its own negative top margin) over whatever precedes it. + const tagsRowMarginBottom = rest.actionBar && pagination?.isVisible ? 6 : 3; + return ( - <DataList - itemsNum={ items?.length } - emptyText="There are no cross-chain token transfers." - emptyStateProps={{ - term: 'token transfer', - }} - { ...rest } - > - { content } - </DataList> + <> + { filters && onFilterChange && ( + <CrossChainFilterTags filters={ filters } onFilterChange={ onFilterChange } mb={ tagsRowMarginBottom }/> + ) } + <DataList + itemsNum={ items?.length } + emptyText="There are no cross-chain token transfers." + emptyStateProps={{ + term: 'token transfer', + }} + hasActiveFilters={ hasActiveColumnFilters(filters) } + { ...rest } + > + { content } + </DataList> + </> ); }; diff --git a/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainList.tsx b/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainList.tsx deleted file mode 100644 index 79a01ea724b..00000000000 --- a/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainList.tsx +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { JsxStyleProps } from '@chakra-ui/react'; -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { InterchainTransfer } from '@blockscout/interchain-indexer-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import TokenTransfersCrossChainListItem from './TokenTransfersCrossChainListItem'; -import { getItemKey } from './utils'; - -interface Props { - items: Array<InterchainTransfer>; - isLoading?: boolean; - currentAddress?: string; - resetKey?: string; - listItemProps?: JsxStyleProps; -} - -const TokenTransfersCrossChainList = ({ items, isLoading, currentAddress, resetKey, listItemProps }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <TokenTransfersCrossChainListItem - key={ getItemKey(item, isLoading ? index : undefined) } - data={ item } - isLoading={ isLoading } - currentAddress={ currentAddress } - { ...listItemProps } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(TokenTransfersCrossChainList); diff --git a/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainTable.tsx b/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainTable.tsx index 2a715be0262..d83f8a0c1ef 100644 --- a/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainTable.tsx +++ b/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainTable.tsx @@ -4,6 +4,7 @@ import { Flex } from '@chakra-ui/react'; import React from 'react'; import type { InterchainTransfer } from '@blockscout/interchain-indexer-types'; +import type { CrossChainFilters } from 'src/features/cross-chain-txs/types/api'; import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; @@ -12,6 +13,9 @@ import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; +import type { CrossChainFilterColumn } from '../filters/CrossChainFilterByColumn'; +import CrossChainFilterByColumn from '../filters/CrossChainFilterByColumn'; +import type { CrossChainFilterChangeHandler } from '../filters/utils'; import TokenTransfersCrossChainTableItem from './TokenTransfersCrossChainTableItem'; import { getItemKey } from './utils'; @@ -21,27 +25,50 @@ interface Props { top?: number; currentAddress?: string; resetKey?: string; + filters?: CrossChainFilters; + onFilterChange?: CrossChainFilterChangeHandler; } -const TokenTransfersCrossChainTable = ({ data, isLoading, top, currentAddress, resetKey }: Props) => { +const TokenTransfersCrossChainTable = ({ data, isLoading, top, currentAddress, resetKey, filters, onFilterChange }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const renderFilter = (column: CrossChainFilterColumn) => { + if (!filters || !onFilterChange) { + return null; + } + + return <CrossChainFilterByColumn column={ column } filters={ filters } onFilterChange={ onFilterChange } isLoading={ isLoading }/>; + }; + return ( <AddressHighlightProvider> - <TableRoot tableLayout="auto"> + <TableRoot tableLayout="auto" minW="1100px"> <TableHeaderSticky top={ top }> <TableRow> - <TableColumnHeader w={ currentAddress ? '86px' : '42px' }/> + <TableColumnHeader w={ currentAddress ? '60px' : '42px' }/> <TableColumnHeader>Source token</TableColumnHeader> - <TableColumnHeader/> <TableColumnHeader>Target token</TableColumnHeader> - <TableColumnHeader>Source tx</TableColumnHeader> - <TableColumnHeader>Dest tx</TableColumnHeader> - <TableColumnHeader>Protocol</TableColumnHeader> - <TableColumnHeader>Message</TableColumnHeader> + <TableColumnHeader> + <Flex alignItems="center" columnGap={ 1 }> + Source tx + { renderFilter('source') } + </Flex> + </TableColumnHeader> + <TableColumnHeader> + <Flex alignItems="center" columnGap={ 1 }> + Dest tx + { renderFilter('destination') } + </Flex> + </TableColumnHeader> + <TableColumnHeader> + <Flex alignItems="center" columnGap={ 1 }> + Protocol + { renderFilter('protocol') } + </Flex> + </TableColumnHeader> <TableColumnHeader> <Flex alignItems="center" flexWrap="nowrap"> - Timestamp + Message <TimeFormatToggle/> </Flex> </TableColumnHeader> diff --git a/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainTableItem.tsx b/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainTableItem.tsx index 295bff2d907..8bf954d13ec 100644 --- a/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainTableItem.tsx +++ b/src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainTableItem.tsx @@ -1,12 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { chakra, HStack, VStack } from '@chakra-ui/react'; +import { chakra, VStack } from '@chakra-ui/react'; import React from 'react'; import type { InterchainTransfer } from '@blockscout/interchain-indexer-types'; import AddressEntityInterchain from 'src/slices/address/components/entity/AddressEntityInterchain'; -import AddressFromToIcon from 'src/slices/address/components/from-to/AddressFromToIcon'; import TxEntityInterchain from 'src/slices/tx/components/entity/TxEntityInterchain'; import TokenValueInterchain from 'src/features/cross-chain-txs/components/TokenValueInterchain'; @@ -28,6 +27,12 @@ interface Props { currentAddress?: string; } +const TOKEN_VALUE_PROPS = { + fontWeight: 'semibold', + tokenEntityProps: { fontWeight: 'medium' }, +}; +const ADDRESS_LINK_PROPS = { variant: 'secondary' as const }; + const TokenTransfersCrossChainTableItem = ({ data, isLoading, currentAddress }: Props) => { const dashElement = <chakra.span color="text.secondary" lineHeight="24px">{ mdash }</chakra.span>; @@ -35,7 +40,7 @@ const TokenTransfersCrossChainTableItem = ({ data, isLoading, currentAddress }: return ( <TableRow> <TableCell> - <HStack gap={ 1 }> + <VStack alignItems="start" gap={ 1.5 }> <CrossChainTxsStatusTag status={ data.status } loading={ isLoading }/> { currentAddress && ( <CrossChainFromToTag @@ -45,9 +50,9 @@ const TokenTransfersCrossChainTableItem = ({ data, isLoading, currentAddress }: isLoading={ isLoading } /> ) } - </HStack> + </VStack> </TableCell> - <TableCell maxW="150px"> + <TableCell maxW="200px"> <VStack alignItems="start"> { data.source_token && ( <TokenValueInterchain @@ -56,6 +61,7 @@ const TokenTransfersCrossChainTableItem = ({ data, isLoading, currentAddress }: chain={ data.source_chain } loading={ isLoading } lineHeight="24px" + { ...TOKEN_VALUE_PROPS } /> ) } { @@ -65,6 +71,7 @@ const TokenTransfersCrossChainTableItem = ({ data, isLoading, currentAddress }: address={ data.sender } isLoading={ isLoading } truncation="constant" + link={ ADDRESS_LINK_PROPS } noIcon currentAddress={ currentAddress } textStyle="xs" @@ -73,10 +80,7 @@ const TokenTransfersCrossChainTableItem = ({ data, isLoading, currentAddress }: } </VStack> </TableCell> - <TableCell> - <AddressFromToIcon type="unspecified" isLoading={ isLoading } mt={ 0.5 }/> - </TableCell> - <TableCell maxW="150px"> + <TableCell maxW="200px"> <VStack alignItems="start"> { data.destination_token && ( <TokenValueInterchain @@ -85,6 +89,7 @@ const TokenTransfersCrossChainTableItem = ({ data, isLoading, currentAddress }: chain={ data.destination_chain } loading={ isLoading } lineHeight="24px" + { ...TOKEN_VALUE_PROPS } /> ) } { @@ -94,6 +99,7 @@ const TokenTransfersCrossChainTableItem = ({ data, isLoading, currentAddress }: address={ data.recipient } isLoading={ isLoading } truncation="constant" + link={ ADDRESS_LINK_PROPS } noIcon currentAddress={ currentAddress } textStyle="xs" @@ -144,20 +150,19 @@ const TokenTransfersCrossChainTableItem = ({ data, isLoading, currentAddress }: /> </VStack> </TableCell> - <TableCell> + <TableCell maxW="150px"> <CrossChainBridgeLink data={ data.bridge } isLoading={ isLoading } messageId={ data.message_id } lineHeight="24px"/> </TableCell> <TableCell> - <CrossChainMessageEntity id={ data.message_id } isLoading={ isLoading } lineHeight="24px"/> - </TableCell> - <TableCell> - <TimeWithTooltip - timestamp={ data.send_timestamp || data.receive_timestamp } - isLoading={ isLoading } - color="text.secondary" - lineHeight="24px" - whiteSpace="nowrap" - /> + <VStack alignItems="start"> + <CrossChainMessageEntity id={ data.message_id } bridgeId={ data.bridge?.id } isLoading={ isLoading } lineHeight="24px"/> + <TimeWithTooltip + timestamp={ data.send_timestamp || data.receive_timestamp } + isLoading={ isLoading } + color="text.secondary" + whiteSpace="nowrap" + /> + </VStack> </TableCell> </TableRow> ); diff --git a/src/features/cross-chain-txs/components/token-transfers/utils.ts b/src/features/cross-chain-txs/components/token-transfers/utils.ts index 8e8f7594763..1edd526134c 100644 --- a/src/features/cross-chain-txs/components/token-transfers/utils.ts +++ b/src/features/cross-chain-txs/components/token-transfers/utils.ts @@ -6,11 +6,12 @@ export const getItemKey = (data: InterchainTransfer, index?: number) => { return [ data.message_id, data.sender?.hash, - data.source_token?.address_hash, + // Null for a native token; the symbol keeps the key distinct between two native transfers of one message. + data.source_token?.address_hash ?? data.source_token?.symbol, data.source_amount, data.source_chain?.id, index, ] - .filter((item) => item !== undefined) + .filter((item) => item !== undefined && item !== null) .join('-'); }; diff --git a/src/features/cross-chain-txs/components/txs/TransactionsCrossChainContent.tsx b/src/features/cross-chain-txs/components/txs/TransactionsCrossChainContent.tsx index 1600a1a113c..30e46910bda 100644 --- a/src/features/cross-chain-txs/components/txs/TransactionsCrossChainContent.tsx +++ b/src/features/cross-chain-txs/components/txs/TransactionsCrossChainContent.tsx @@ -1,9 +1,9 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { InterchainMessage } from '@blockscout/interchain-indexer-types'; +import type { CrossChainFilters } from 'src/features/cross-chain-txs/types/api'; import type { PaginationParams } from 'src/shared/pagination/types'; import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; @@ -11,68 +11,70 @@ import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import DataList from 'src/shared/lists/DataList'; import type { Props as DataListProps } from 'src/shared/lists/DataList'; -import TransactionsCrossChainList from './TransactionsCrossChainList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + +import CrossChainFilterTags from '../filters/CrossChainFilterTags'; +import type { CrossChainFilterChangeHandler } from '../filters/utils'; +import { hasActiveColumnFilters } from '../filters/utils'; import TransactionsCrossChainTable from './TransactionsCrossChainTable'; export interface Props extends Omit<DataListProps, 'children'> { items?: Array<InterchainMessage>; isLoading?: boolean; pagination?: PaginationParams; - isTableView?: boolean; stickyHeader?: boolean; currentAddress?: string; resetKey?: string; + filters?: CrossChainFilters; + onFilterChange?: CrossChainFilterChangeHandler; } const TransactionsCrossChainContent = ({ items, isLoading, pagination, - isTableView, stickyHeader = true, currentAddress, resetKey, + filters, + onFilterChange, ...rest }: Props) => { const content = items ? ( - <> - <Box display={{ base: isTableView ? 'none' : 'block', lg: 'none' }}> - <TransactionsCrossChainList - items={ items } - isLoading={ isLoading } - currentAddress={ currentAddress } - resetKey={ resetKey } - /> - </Box> - <Box - display={{ base: isTableView ? 'block' : 'none', lg: 'block' }} - overflowX={{ base: 'scroll', lg: 'initial' }} - mx={{ base: -3, lg: 0 }} - px={{ base: 3, lg: 0 }} - > - <TransactionsCrossChainTable - data={ items } - isLoading={ isLoading } - top={ ACTION_BAR_HEIGHT_DESKTOP } - stickyHeader={ stickyHeader } - currentAddress={ currentAddress } - resetKey={ resetKey } - /> - </Box> - </> + <TableContainerScrollable> + <TransactionsCrossChainTable + data={ items } + isLoading={ isLoading } + top={ ACTION_BAR_HEIGHT_DESKTOP } + stickyHeader={ stickyHeader } + currentAddress={ currentAddress } + resetKey={ resetKey } + filters={ filters } + onFilterChange={ onFilterChange } + /> + </TableContainerScrollable> ) : null; + // The sticky action bar pulls itself up by 24px (its own negative top margin) over whatever precedes it. + const tagsRowMarginBottom = rest.actionBar && pagination?.isVisible ? 6 : 3; + return ( - <DataList - itemsNum={ items?.length } - emptyText="There are no cross-chain transactions." - emptyStateProps={{ - term: 'transaction', - }} - { ...rest } - > - { content } - </DataList> + <> + { filters && onFilterChange && ( + <CrossChainFilterTags filters={ filters } onFilterChange={ onFilterChange } mb={ tagsRowMarginBottom }/> + ) } + <DataList + itemsNum={ items?.length } + emptyText="There are no cross-chain transactions." + emptyStateProps={{ + term: 'transaction', + }} + hasActiveFilters={ hasActiveColumnFilters(filters) } + { ...rest } + > + { content } + </DataList> + </> ); }; diff --git a/src/features/cross-chain-txs/components/txs/TransactionsCrossChainList.tsx b/src/features/cross-chain-txs/components/txs/TransactionsCrossChainList.tsx deleted file mode 100644 index 6f69d72bd34..00000000000 --- a/src/features/cross-chain-txs/components/txs/TransactionsCrossChainList.tsx +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { InterchainMessage } from '@blockscout/interchain-indexer-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import TransactionsCrossChainListItem from './TransactionsCrossChainListItem'; - -interface Props { - items: Array<InterchainMessage>; - isLoading?: boolean; - currentAddress?: string; - resetKey?: string; -} - -const TransactionsCrossChainList = ({ items, isLoading, currentAddress, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <TransactionsCrossChainListItem - key={ item.message_id + (isLoading ? index : '') } - data={ item } - isLoading={ isLoading } - currentAddress={ currentAddress } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(TransactionsCrossChainList); diff --git a/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTable.spec.tsx b/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTable.spec.tsx new file mode 100644 index 00000000000..aa6c3a245d8 --- /dev/null +++ b/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTable.spec.tsx @@ -0,0 +1,47 @@ +// @vitest-environment jsdom +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, render } from 'vitest/lib'; + +import { pending, withUnindexedDestination } from '../../mocks/txs'; +import TransactionsCrossChainTable from './TransactionsCrossChainTable'; + +const SOURCE_CHAIN_NAME = withUnindexedDestination.source_chain.name; +const BRIDGE_NAME = withUnindexedDestination.bridge.name; +const PENDING_DESTINATION_CHAIN_NAME = pending.destination_chain.name; + +function firstRowCellByColumn(container: HTMLElement, header: string): Element { + const headers = Array.from(container.querySelectorAll('thead th')); + const index = headers.findIndex((cell) => cell.textContent?.trim() === header); + + if (index < 0) { + throw new Error(`no "${ header }" column in the table header`); + } + + return container.querySelectorAll('tbody tr:first-child td')[index]; +} + +describe('TransactionsCrossChainTable', () => { + afterEach(cleanup); + + it('renders a message whose destination never resolves as an ordinary row with an empty destination side', () => { + const { container } = render(<TransactionsCrossChainTable data={ [ withUnindexedDestination ] }/>); + + expect(firstRowCellByColumn(container, 'Source tx').textContent).toContain(SOURCE_CHAIN_NAME); + expect(firstRowCellByColumn(container, 'Protocol').textContent).toContain(BRIDGE_NAME); + expect(firstRowCellByColumn(container, 'Dest tx').textContent).toBe(mdash); + expect(firstRowCellByColumn(container, 'Recipient').textContent).toBe(mdash); + }); + + it('leaves the destination tx empty on a row that has no destination hash yet and is not flagged as unindexed', () => { + const { container } = render(<TransactionsCrossChainTable data={ [ pending ] }/>); + + expect(firstRowCellByColumn(container, 'Dest tx').textContent) + .toBe(`${ mdash }${ PENDING_DESTINATION_CHAIN_NAME }`); + }); +}); diff --git a/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTable.tsx b/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTable.tsx index 8b968ab1e26..f11b7810ad9 100644 --- a/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTable.tsx +++ b/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTable.tsx @@ -4,6 +4,7 @@ import { Flex } from '@chakra-ui/react'; import React from 'react'; import type { InterchainMessage } from '@blockscout/interchain-indexer-types'; +import type { CrossChainFilters } from 'src/features/cross-chain-txs/types/api'; import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; @@ -12,6 +13,9 @@ import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; +import type { CrossChainFilterColumn } from '../filters/CrossChainFilterByColumn'; +import CrossChainFilterByColumn from '../filters/CrossChainFilterByColumn'; +import type { CrossChainFilterChangeHandler } from '../filters/utils'; import TransactionsCrossChainTableItem from './TransactionsCrossChainTableItem'; interface Props { @@ -21,33 +25,56 @@ interface Props { stickyHeader?: boolean; currentAddress?: string; resetKey?: string; + filters?: CrossChainFilters; + onFilterChange?: CrossChainFilterChangeHandler; } -const TransactionsCrossChainTable = ({ data, isLoading, top, stickyHeader, currentAddress, resetKey }: Props) => { +const TransactionsCrossChainTable = ({ data, isLoading, top, stickyHeader, currentAddress, resetKey, filters, onFilterChange }: Props) => { const TableHeaderComponent = stickyHeader ? TableHeaderSticky : TableHeader; const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const renderFilter = (column: CrossChainFilterColumn) => { + if (!filters || !onFilterChange) { + return null; + } + + return <CrossChainFilterByColumn column={ column } filters={ filters } onFilterChange={ onFilterChange } isLoading={ isLoading }/>; + }; + return ( <AddressHighlightProvider> - <TableRoot tableLayout="auto"> + <TableRoot tableLayout="auto" minW="1200px"> <TableHeaderComponent top={ stickyHeader ? top : undefined }> <TableRow> - <TableColumnHeader w={ currentAddress ? '86px' : '42px' }/> - <TableColumnHeader>Message</TableColumnHeader> + <TableColumnHeader w={ currentAddress ? '60px' : '42px' }/> <TableColumnHeader> <Flex alignItems="center" flexWrap="nowrap"> - Timestamp + Message <TimeFormatToggle/> </Flex> </TableColumnHeader> <TableColumnHeader>Msg sender</TableColumnHeader> - <TableColumnHeader>Source tx</TableColumnHeader> - <TableColumnHeader>Dest tx</TableColumnHeader> + <TableColumnHeader> + <Flex alignItems="center" columnGap={ 1 }> + Source tx + { renderFilter('source') } + </Flex> + </TableColumnHeader> + <TableColumnHeader> + <Flex alignItems="center" columnGap={ 1 }> + Dest tx + { renderFilter('destination') } + </Flex> + </TableColumnHeader> <TableColumnHeader>Transf</TableColumnHeader> <TableColumnHeader>Sender</TableColumnHeader> - <TableColumnHeader/> <TableColumnHeader>Recipient</TableColumnHeader> - <TableColumnHeader>Protocol</TableColumnHeader> + <TableColumnHeader> + <Flex alignItems="center" columnGap={ 1 }> + Protocol + { renderFilter('protocol') } + </Flex> + </TableColumnHeader> </TableRow> </TableHeaderComponent> <TableBody> diff --git a/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTableItem.tsx b/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTableItem.tsx index 6911708556d..c899aea9123 100644 --- a/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTableItem.tsx +++ b/src/features/cross-chain-txs/components/txs/TransactionsCrossChainTableItem.tsx @@ -1,13 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { chakra, HStack, VStack } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; +import { chakra, VStack } from '@chakra-ui/react'; import React from 'react'; import type { InterchainMessage } from '@blockscout/interchain-indexer-types'; import AddressEntityInterchain from 'src/slices/address/components/entity/AddressEntityInterchain'; -import AddressFromToIcon from 'src/slices/address/components/from-to/AddressFromToIcon'; import TxEntityInterchain from 'src/slices/tx/components/entity/TxEntityInterchain'; import TokenValueInterchain from 'src/features/cross-chain-txs/components/TokenValueInterchain'; @@ -15,6 +13,11 @@ import TokenValueInterchain from 'src/features/cross-chain-txs/components/TokenV import config from 'src/config'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; import ChainLabel from 'src/shared/external-chains/ChainLabel'; +<<<<<<< HEAD +======= +import { route } from 'src/shared/router/routes'; +import TokenValueInterchain from 'src/shared/values/entity/TokenValueInterchain'; +>>>>>>> v2.13.0 import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; @@ -36,6 +39,7 @@ const TransactionsCrossChainTableItem = ({ data, isLoading, currentAddress }: Pr const hasTransfers = data.transfers.length > 0; const firstTransfer = hasTransfers ? data.transfers[0] : null; + const bridgeId = data.bridge?.id; const txHashWithTransfers = (() => { if (!hasTransfers) { return; @@ -55,7 +59,7 @@ const TransactionsCrossChainTableItem = ({ data, isLoading, currentAddress }: Pr return ( <TableRow> <TableCell w="42px"> - <HStack gap={ 1 }> + <VStack alignItems="start" gap={ 1.5 }> <CrossChainTxsStatusTag status={ data.status } loading={ isLoading }/> { currentAddress && ( <CrossChainFromToTagTx @@ -64,22 +68,21 @@ const TransactionsCrossChainTableItem = ({ data, isLoading, currentAddress }: Pr isLoading={ isLoading } /> ) } - </HStack> - </TableCell> - <TableCell> - <CrossChainMessageEntity id={ data.message_id } isLoading={ isLoading } lineHeight="24px" fontWeight={ 700 }/> + </VStack> </TableCell> <TableCell> - <TimeWithTooltip - timestamp={ data.send_timestamp || data.receive_timestamp } - isLoading={ isLoading } - enableIncrement - color="text.secondary" - lineHeight="24px" - whiteSpace="nowrap" - /> + <VStack alignItems="start"> + <CrossChainMessageEntity id={ data.message_id } bridgeId={ bridgeId } isLoading={ isLoading } lineHeight="24px" fontWeight={ 700 }/> + <TimeWithTooltip + timestamp={ data.send_timestamp || data.receive_timestamp } + isLoading={ isLoading } + enableIncrement + color="text.secondary" + whiteSpace="nowrap" + /> + </VStack> </TableCell> - <TableCell maxW="150px"> + <TableCell maxW="130px"> { data.sender ? ( <AddressEntityInterchain chain={ data.source_chain } @@ -156,7 +159,7 @@ const TransactionsCrossChainTableItem = ({ data, isLoading, currentAddress }: Pr </Skeleton> ) } </TableCell> - <TableCell maxW="150px"> + <TableCell maxW="200px"> <VStack alignItems="start"> { hasTransfers && ( <> @@ -184,13 +187,16 @@ const TransactionsCrossChainTableItem = ({ data, isLoading, currentAddress }: Pr color="text.secondary" /> ) } - { data.transfers.length > 1 && ( + { data.transfers.length > 1 && bridgeId !== undefined && ( <Link variant="secondary" textDecorationStyle="dashed" textDecorationLine="underline" mt={ 2 } - href={ route({ pathname: '/cross-chain-tx/[id]', query: { id: data.message_id, tab: 'transfers' } }) } + href={ route({ + pathname: '/bridge/[bridgeId]/cross-chain-tx/[id]', + query: { bridgeId: String(bridgeId), id: data.message_id, tab: 'transfers' }, + }) } textStyle="xs" > View all @@ -200,10 +206,7 @@ const TransactionsCrossChainTableItem = ({ data, isLoading, currentAddress }: Pr ) } </VStack> </TableCell> - <TableCell> - { hasTransfers && <AddressFromToIcon type="unspecified" isLoading={ isLoading } mt={ 0.5 }/> } - </TableCell> - <TableCell maxW="150px"> + <TableCell maxW="200px"> { hasTransfers && ( <VStack alignItems="start"> { @@ -233,7 +236,7 @@ const TransactionsCrossChainTableItem = ({ data, isLoading, currentAddress }: Pr </VStack> ) } </TableCell> - <TableCell> + <TableCell maxW="120px"> <CrossChainBridgeLink data={ data.bridge } isLoading={ isLoading } messageId={ data.message_id } lineHeight="24px"/> </TableCell> </TableRow> diff --git a/src/features/cross-chain-txs/config.ts b/src/features/cross-chain-txs/config.ts index 2038d8b688b..b32c649f978 100644 --- a/src/features/cross-chain-txs/config.ts +++ b/src/features/cross-chain-txs/config.ts @@ -2,16 +2,28 @@ import apis from 'src/api/config'; -import { getEnvValue } from 'src/config/utils/envs'; +import { getEnvValue, parseEnvJson } from 'src/config/utils/envs'; import type { Feature } from 'src/config/utils/features'; const title = 'Cross-chain transactions'; -const config: Feature<{}> = (() => { - if (getEnvValue('NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED') === 'true' && apis.interchainIndexer) { +const bridgeIds = + parseEnvJson<Array<number>>(getEnvValue('NEXT_PUBLIC_CROSS_CHAIN_TXS_BRIDGE_IDS')) ?? []; + +const includeUnindexedChains = + getEnvValue('NEXT_PUBLIC_CROSS_CHAIN_TXS_INCLUDE_UNINDEXED_CHAINS') === 'true'; + +const config: Feature<{ bridgeIds: Array<number>; includeUnindexedChains: boolean }> = (() => { + if ( + getEnvValue('NEXT_PUBLIC_CROSS_CHAIN_TXS_ENABLED') === 'true' && + apis.interchainIndexer && + bridgeIds.length > 0 + ) { return Object.freeze({ title, isEnabled: true, + bridgeIds, + includeUnindexedChains, }); } diff --git a/src/features/cross-chain-txs/hooks/useBridgedTokensQuery.spec.ts b/src/features/cross-chain-txs/hooks/useBridgedTokensQuery.spec.ts new file mode 100644 index 00000000000..641a96ac381 --- /dev/null +++ b/src/features/cross-chain-txs/hooks/useBridgedTokensQuery.spec.ts @@ -0,0 +1,64 @@ +// @vitest-environment jsdom + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { act, cleanup, renderHook, waitFor } from 'vitest/lib'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const responseInit = { + headers: { + 'Content-Type': 'application/json', + }, +}; + +const getRequestedSearchTerms = () => fetchMock.mock.calls + .map(([ input ]) => new URL(String(input))) + .filter((url) => url.pathname.endsWith('/bridged-tokens')) + .map((url) => url.searchParams.get('q')); + +describe('useBridgedTokensQuery (cross-chain)', () => { + beforeEach(() => { + fetchMock.resetMocks(); + fetchMock.mockResponse(JSON.stringify({ items: [], next_page_params: null }), responseInit); + }); + + afterEach(cleanup); + + // withEnvs resets the module registry, so the stand-in must come from the same graph as the hook under test: + // a statically imported one would provide a router context the re-evaluated facade never reads + const loadModules = async() => { + const [ { routerStandIn }, { 'default': useBridgedTokensQuery } ] = await Promise.all([ + import('vitest/utils/routerStandIn'), + import('./useBridgedTokensQuery'), + ]); + return { routerStandIn, useBridgedTokensQuery }; + }; + + it('sends the search term from the URL to the bridged tokens API', async() => { + await withEnvs(ENVS_MAP.crossChainTxs, async() => { + const { routerStandIn, useBridgedTokensQuery } = await loadModules(); + routerStandIn.reset({ pathname: '/tokens', query: { tab: 'bridged', q: 'USDC' } }); + + const { result } = renderHook(() => useBridgedTokensQuery({ enabled: true }), { wrapper: routerStandIn.appWrapper }); + + expect(result.current.searchTerm).toBe('USDC'); + await waitFor(() => expect(getRequestedSearchTerms()).toEqual([ 'USDC' ])); + }); + }); + + it('refetches the bridged tokens with the term typed into the search input', async() => { + await withEnvs(ENVS_MAP.crossChainTxs, async() => { + const { routerStandIn, useBridgedTokensQuery } = await loadModules(); + routerStandIn.reset({ pathname: '/tokens', query: { tab: 'bridged' } }); + + const { result } = renderHook(() => useBridgedTokensQuery({ enabled: true }), { wrapper: routerStandIn.appWrapper }); + await waitFor(() => expect(getRequestedSearchTerms()).toEqual([ null ])); + + act(() => result.current.onSearchTermChange('DAI')); + + await waitFor(() => expect(getRequestedSearchTerms()).toEqual([ null, 'DAI' ])); + expect(result.current.searchTerm).toBe('DAI'); + }); + }); +}); diff --git a/src/features/cross-chain-txs/hooks/useBridgedTokensQuery.ts b/src/features/cross-chain-txs/hooks/useBridgedTokensQuery.ts index 42646d86bbc..2185f02d0bd 100644 --- a/src/features/cross-chain-txs/hooks/useBridgedTokensQuery.ts +++ b/src/features/cross-chain-txs/hooks/useBridgedTokensQuery.ts @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { CrossChainBridgedTokensSorting, CrossChainBridgedTokensSortingField, CrossChainBridgedTokensSortingValue } from '../types/api'; @@ -8,8 +7,8 @@ import type { CrossChainBridgedTokensSorting, CrossChainBridgedTokensSortingFiel import { INTERCHAIN_BRIDGED_TOKEN_ITEM } from 'src/features/cross-chain-txs/stubs/messages'; import config from 'src/config'; -import useDebounce from 'src/shared/hooks/useDebounce'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; @@ -24,39 +23,31 @@ interface Props { } export default function useBridgedTokensQuery({ enabled }: Props) { - const router = useRouter(); - - const q = getQueryParamString(router.query.q); - - const [ searchTerm, setSearchTerm ] = React.useState<string>(q ?? ''); - const [ sort, setSort ] = React.useState<CrossChainBridgedTokensSortingValue>( - getSortValueFromQuery<CrossChainBridgedTokensSortingValue>(router.query, BRIDGED_TOKENS_SORT_OPTIONS) ?? 'default', - ); - - const debouncedSearchTerm = useDebounce(searchTerm, 300); - - const query = useQueryWithPages({ + const query = useApiPaginatedQuery({ resourceName: 'interchainIndexer:bridged_tokens', pathParams: { chainId: config.chain.id, }, - filters: { q: debouncedSearchTerm }, - sorting: getSortParamsFromValue<CrossChainBridgedTokensSortingValue, CrossChainBridgedTokensSortingField, CrossChainBridgedTokensSorting['order']>(sort), options: { enabled, placeholderData: generateListStub<'interchainIndexer:bridged_tokens'>(INTERCHAIN_BRIDGED_TOKEN_ITEM, 10, { next_page_params: { page_token: 'token' } }), }, }); - const onSearchTermChange = React.useCallback((value: string) => { - query.onFilterChange({ q: value }); - setSearchTerm(value); - }, [ query ]); + const searchTerm = getQueryParamString(query.filters.q); + const sort = getSortValueFromQuery<CrossChainBridgedTokensSortingValue>({ ...query.sorting }, BRIDGED_TOKENS_SORT_OPTIONS) ?? 'default'; + + const { onFilterChange, onSortingChange } = query; + + const onSearchTermChange = useDebouncedFilterChange((value) => onFilterChange({ q: value })); const onSortChange: OnValueChangeHandler = React.useCallback(({ value }) => { - setSort(value[0] as CrossChainBridgedTokensSortingValue); - query.onSortingChange(value[0] === 'default' ? undefined : getSortParamsFromValue(value[0] as CrossChainBridgedTokensSortingValue)); - }, [ query ]); + onSortingChange( + getSortParamsFromValue<CrossChainBridgedTokensSortingValue, CrossChainBridgedTokensSortingField, CrossChainBridgedTokensSorting['order']>( + value[0] as CrossChainBridgedTokensSortingValue, + ), + ); + }, [ onSortingChange ]); return React.useMemo(() => ({ query, diff --git a/src/features/cross-chain-txs/hooks/useCrossChainCountersQuery.spec.tsx b/src/features/cross-chain-txs/hooks/useCrossChainCountersQuery.spec.tsx new file mode 100644 index 00000000000..e9e0df91719 --- /dev/null +++ b/src/features/cross-chain-txs/hooks/useCrossChainCountersQuery.spec.tsx @@ -0,0 +1,110 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { describe, it, expect, beforeEach } from 'vitest'; +import { render, renderHook, screen, waitFor, wrapper } from 'vitest/lib'; +import flushPromises from 'vitest/utils/flushPromises'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import { counters } from '../mocks/counters'; + +const STATS_API_HOST = 'https://localhost:3004'; +const MULTICHAIN_STATS_API_HOST = 'http://localhost:3013'; + +const responseInit = { + headers: { + 'Content-Type': 'application/json', + }, +}; + +describe('useCrossChainCountersQuery', () => { + beforeEach(() => { + fetchMock.resetMocks(); + fetchMock.mockResponse(JSON.stringify(counters), responseInit); + }); + + it('reads the interchain counters from the single-chain stats service by id', async() => { + const { useCrossChainCountersQuery } = await import('./useCrossChainCountersQuery'); + + const { result } = renderHook(() => useCrossChainCountersQuery(), { wrapper }); + + expect(result.current.isPlaceholderData).toBe(true); + expect(result.current.data?.totalInterchainMessages).toBeDefined(); + + await waitFor(() => expect(result.current.isPlaceholderData).toBe(false)); + + expect(fetchMock.mock.calls[0][0]).toBe(`${ STATS_API_HOST }/api/v1/counters`); + expect(result.current.data).toEqual({ + totalInterchainMessages: '100', + newMessagesInterchain24h: '42', + totalInterchainTransfers: '101', + newTransfersInterchain24h: '55', + }); + }); + + it('reads the counters from the multichain stats service on a multichain deployment', async() => { + await withEnvs(ENVS_MAP.multichain, async() => { + const { useCrossChainCountersQuery } = await import('./useCrossChainCountersQuery'); + + const { result } = renderHook(() => useCrossChainCountersQuery(), { wrapper }); + + await waitFor(() => expect(result.current.isPlaceholderData).toBe(false)); + + expect(fetchMock.mock.calls[0][0]).toBe(`${ MULTICHAIN_STATS_API_HOST }/api/v1/counters`); + expect(result.current.data?.totalInterchainMessages).toBe('100'); + }); + }); + + it('serves a consumer mounted later on the same page from the already fetched counters without a new request', async() => { + const { useCrossChainCountersQuery } = await import('./useCrossChainCountersQuery'); + + const Consumer = () => { + const { data, fetchStatus } = useCrossChainCountersQuery(); + return <span data-testid="consumer">{ fetchStatus }:{ data?.totalInterchainMessages }</span>; + }; + + const { rerender } = render(<Consumer key="list"/>); + await waitFor(() => expect(screen.getByTestId('consumer').textContent).toBe('idle:100')); + + // a different key unmounts the first consumer and mounts a fresh one under the same QueryClient + rerender(<Consumer key="stats-widget"/>); + await flushPromises(); + + expect(screen.getByTestId('consumer').textContent).toBe('idle:100'); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('leaves every counter undefined when the stats service reports no interchain counters', async() => { + fetchMock.mockResponse(JSON.stringify({ + counters: [ + { id: 'totalBlocks', value: '1000', title: 'Total blocks', description: '' }, + { id: 'averageBlockTime', value: '12', title: 'Average block time', description: '' }, + ], + }), responseInit); + const { useCrossChainCountersQuery } = await import('./useCrossChainCountersQuery'); + + const { result } = renderHook(() => useCrossChainCountersQuery(), { wrapper }); + + await waitFor(() => expect(result.current.isPlaceholderData).toBe(false)); + + expect(result.current.data?.totalInterchainMessages).toBeUndefined(); + expect(result.current.data?.newMessagesInterchain24h).toBeUndefined(); + expect(result.current.data?.totalInterchainTransfers).toBeUndefined(); + expect(result.current.data?.newTransfersInterchain24h).toBeUndefined(); + }); + + it('returns no data and no placeholder when no stats service is configured', async() => { + await withEnvs([ [ 'NEXT_PUBLIC_STATS_API_HOST', '' ] ], async() => { + const { useCrossChainCountersQuery } = await import('./useCrossChainCountersQuery'); + + const { result } = renderHook(() => useCrossChainCountersQuery(), { wrapper }); + + expect(result.current.data).toBeUndefined(); + expect(result.current.isPlaceholderData).toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/features/cross-chain-txs/hooks/useCrossChainCountersQuery.ts b/src/features/cross-chain-txs/hooks/useCrossChainCountersQuery.ts new file mode 100644 index 00000000000..fe2bbbc5fab --- /dev/null +++ b/src/features/cross-chain-txs/hooks/useCrossChainCountersQuery.ts @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type * as stats from '@blockscout/stats-types'; + +import useApiQuery from 'src/api/hooks/useApiQuery'; + +import config from 'src/config'; + +import { CROSS_CHAIN_COUNTERS } from '../stubs/counters'; + +export type CrossChainCounterId = + 'totalInterchainMessages' | + 'totalInterchainTransfers' | + 'newMessagesInterchain24h' | + 'newTransfersInterchain24h'; + +export type CrossChainCounters = Partial<Record<CrossChainCounterId, string>>; + +type ResourceName = 'stats:counters' | 'multichainStats:counters'; + +const RESOURCE_NAME: ResourceName = config.features.multichain.isEnabled ? 'multichainStats:counters' : 'stats:counters'; +const IS_ENABLED = config.features.multichain.isEnabled ? Boolean(config.apis.multichainStats) : Boolean(config.apis.stats); + +function selectCrossChainCounters(data: stats.Counters): CrossChainCounters { + return Object.fromEntries(data.counters.map((counter) => [ counter.id, counter.value ])); +} + +export function useCrossChainCountersQuery() { + return useApiQuery<ResourceName, unknown, CrossChainCounters>(RESOURCE_NAME, { + queryOptions: { + enabled: IS_ENABLED, + placeholderData: IS_ENABLED ? CROSS_CHAIN_COUNTERS : undefined, + refetchOnMount: false, + select: selectCrossChainCounters, + }, + }); +} diff --git a/src/features/cross-chain-txs/hooks/useTxCrossChainTransfersQuery.ts b/src/features/cross-chain-txs/hooks/useTxCrossChainTransfersQuery.ts index a96f85ea811..2f4c7ab4505 100644 --- a/src/features/cross-chain-txs/hooks/useTxCrossChainTransfersQuery.ts +++ b/src/features/cross-chain-txs/hooks/useTxCrossChainTransfersQuery.ts @@ -3,7 +3,7 @@ import { INTERCHAIN_TRANSFER } from 'src/features/cross-chain-txs/stubs/messages'; import config from 'src/config'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; interface Props { @@ -12,7 +12,7 @@ interface Props { } export default function useTxCrossChainTransfersQuery({ hash, enabled = true }: Props) { - return useQueryWithPages({ + return useApiPaginatedQuery({ resourceName: 'interchainIndexer:tx_transfers', pathParams: { hash }, options: { diff --git a/src/features/cross-chain-txs/mocks/bridged-tokens.ts b/src/features/cross-chain-txs/mocks/bridged-tokens.ts new file mode 100644 index 00000000000..f3705b677ed --- /dev/null +++ b/src/features/cross-chain-txs/mocks/bridged-tokens.ts @@ -0,0 +1,64 @@ +import type { GetBridgedTokensResponse, StatsBridgedTokenRow } from '@blockscout/interchain-indexer-types'; +import { TokenInfo_TokenType } from '@blockscout/interchain-indexer-types'; + +import { chainA, chainB } from 'src/features/multichain/mocks/chains'; + +export const bridgedTokenErc20 = { + stats_asset_id: '1', + name: 'Gnosis Token', + symbol: 'GNO', + icon_url: 'https://example.com/gno.png', + input_transfers_count: 4906, + output_transfers_count: 6908, + total_transfers_count: 11814, + tokens: [ + { + chain_id: chainA.id, + token_address: '0x9c58bacc331c9aa871afd802db6379a98e80cedb', + name: 'Gnosis Token on xDai', + symbol: 'GNO', + icon_url: 'https://example.com/gno.png', + decimals: 18, + type: TokenInfo_TokenType.ERC20, + }, + { + chain_id: chainB.id, + token_address: '0x6810e776880c02933d47db1b9fc05908e5386b96', + name: 'Gnosis Token', + symbol: 'GNO', + icon_url: 'https://example.com/gno.png', + decimals: 18, + type: TokenInfo_TokenType.ERC20, + }, + ], +} satisfies StatsBridgedTokenRow; + +export const bridgedTokenNative = { + stats_asset_id: '412', + name: 'xDai', + symbol: 'xDAI', + icon_url: undefined, + input_transfers_count: 1627, + output_transfers_count: 1125, + total_transfers_count: 2752, + tokens: [ + { + chain_id: chainA.id, + token_address: undefined, + name: 'xDai', + symbol: 'xDAI', + icon_url: undefined, + decimals: 18, + type: TokenInfo_TokenType.NATIVE, + }, + ], +} satisfies StatsBridgedTokenRow; + +export const listResponse = { + items: [ + bridgedTokenErc20, + bridgedTokenNative, + ], + next_page_params: undefined, + prev_page_params: undefined, +} satisfies GetBridgedTokensResponse; diff --git a/src/features/cross-chain-txs/mocks/bridges.ts b/src/features/cross-chain-txs/mocks/bridges.ts new file mode 100644 index 00000000000..5365e6d91ed --- /dev/null +++ b/src/features/cross-chain-txs/mocks/bridges.ts @@ -0,0 +1,31 @@ +import type { Bridge } from '@blockscout/interchain-indexer-types'; + +export const bridgeAmb = { + id: 1, + name: 'AMB/Omnibridge', + type: 'amb', + enabled: true, + ui_url: 'https://bridge.gnosischain.com/bridge-explorer/transaction/{{message_id}}', + docs_url: 'https://docs.gnosischain.com/bridges/About%20Token%20Bridges/amb-bridge', + indexed_chain_ids: [ '1', '100' ], +} satisfies Bridge; + +export const bridgeAvalanche = { + id: 2, + name: 'Avalanche ICTT', + type: 'avalanche_native', + enabled: true, + ui_url: undefined, + docs_url: undefined, + indexed_chain_ids: [ '8021', '43114' ], +} satisfies Bridge; + +export const bridgeXdai = { + id: 3, + name: 'xDai Bridge', + type: 'xdai', + enabled: true, + ui_url: 'https://bridge.gnosischain.com/bridge-explorer/transaction/{{message_id}}', + docs_url: 'https://docs.gnosischain.com/bridges/About%20Token%20Bridges/xdai-bridge', + indexed_chain_ids: [ '1', '100' ], +} satisfies Bridge; diff --git a/src/features/cross-chain-txs/mocks/counters.ts b/src/features/cross-chain-txs/mocks/counters.ts new file mode 100644 index 00000000000..068091dfc49 --- /dev/null +++ b/src/features/cross-chain-txs/mocks/counters.ts @@ -0,0 +1,30 @@ +import type * as stats from '@blockscout/stats-types'; + +export const counters: stats.Counters = { + counters: [ + { + id: 'totalInterchainMessages', + value: '100', + title: 'Total interchain messages', + description: 'Total indexed inter-chain messages', + }, + { + id: 'newMessagesInterchain24h', + value: '42', + title: 'New interchain messages (24h)', + description: 'Number of new interchain messages within the last 24 hours', + }, + { + id: 'totalInterchainTransfers', + value: '101', + title: 'Total interchain transfers', + description: 'Total indexed inter-chain transfers', + }, + { + id: 'newTransfersInterchain24h', + value: '55', + title: 'New interchain transfers (24h)', + description: 'Number of new interchain transfers within the last 24 hours', + }, + ], +}; diff --git a/src/features/cross-chain-txs/mocks/transfers.ts b/src/features/cross-chain-txs/mocks/transfers.ts index c5e42944916..3cadc9d60c9 100644 --- a/src/features/cross-chain-txs/mocks/transfers.ts +++ b/src/features/cross-chain-txs/mocks/transfers.ts @@ -1,10 +1,11 @@ import type { GetTransfersResponse, InterchainTransfer } from '@blockscout/interchain-indexer-types'; -import { MessageStatus } from '@blockscout/interchain-indexer-types'; +import { MessageStatus, TokenInfo_TokenType } from '@blockscout/interchain-indexer-types'; import { config } from './config'; export const transferA = { bridge: { + id: 2, name: 'Avalanche ICTT', ui_url: 'https://app.avax.network/', }, @@ -18,6 +19,7 @@ export const transferA = { symbol: 'WAVAX', decimals: '18', icon_url: 'https://app.avax.network/logo.svg', + type: TokenInfo_TokenType.ERC20, }, source_amount: '509700000000000000', source_transaction_hash: '0x866a70cb1c8c33d259c819473d7b419c0de67770755bf07dee14dd2d0c6dc8ab', @@ -31,6 +33,7 @@ export const transferA = { name: 'Wrapped AVAX', symbol: 'WAVAX', decimals: '18', + type: TokenInfo_TokenType.ERC20, }, destination_amount: '509700000000000000', destination_transaction_hash: '0xdbdf690cfde8af2ee855bb90bfa9977a2d8ba36c9ae1a2010c67fe3774832213', @@ -38,6 +41,7 @@ export const transferA = { hash: '0xd7e63822d0e386fb65f28f41e8c1aa8d844ba018', }, receive_timestamp: '2022-01-13T12:06:30.000Z', + has_unindexed_chain: false, } satisfies InterchainTransfer; export const transferB = { @@ -54,18 +58,64 @@ export const transferB = { name: 'Circle USD', symbol: 'USDC', decimals: '6', + type: TokenInfo_TokenType.ERC20, }, destination_transaction_hash: '0xdbdf690cfde8af2ee855bb90bfa9977a2d8ba36c9ae1a2010c67fe3774832214', status: MessageStatus.MESSAGE_STATUS_FAILED, bridge: { + id: 4, name: 'Optimism Superchain', }, } satisfies InterchainTransfer; +export const transferWithUnindexedDestination = { + ...transferA, + message_id: '0x057b42bbbfbb4900e155a554ae67632cb21e6f5a64d815fcad7f33abe552c05c', + status: MessageStatus.MESSAGE_STATUS_INITIATED, + destination_chain: undefined, + destination_token: undefined, + destination_amount: undefined, + destination_transaction_hash: undefined, + recipient: undefined, + receive_timestamp: undefined, + has_unindexed_chain: true, +} satisfies InterchainTransfer; + +export const transferNative = { + ...transferA, + message_id: '0x00000064000000000000000000000000000000000000000000000000000014f4', + bridge: { + id: 3, + name: 'xDai Bridge', + ui_url: 'https://bridge.gnosischain.com/bridge-explorer/transaction/{{message_id}}', + }, + source_transaction_hash: '0x6374f557d67ddef8b2334550fa1ccdcb13f18b3a7476375678eca6b4057a76d1', + source_token: { + address_hash: undefined, + name: 'xDai', + symbol: 'xDAI', + decimals: '18', + icon_url: undefined, + type: TokenInfo_TokenType.NATIVE, + }, + source_amount: '3112500000000000000000', + destination_transaction_hash: '0xa30986ded02f481cb38edd0c20890e1503a11f47e66717d2985c27adcc2eb68e', + destination_token: { + address_hash: '0x6b175474e89094c44da98b954eedeac495271d0f', + name: 'Dai Stablecoin', + symbol: 'DAI', + decimals: '18', + icon_url: 'https://example.com/dai.png', + type: TokenInfo_TokenType.ERC20, + }, + destination_amount: '3112500000000000000000', +} satisfies InterchainTransfer; + export const listResponse = { items: [ transferA, transferB, + transferNative, ], next_page_params: { page_token: 'token', diff --git a/src/features/cross-chain-txs/mocks/txs.ts b/src/features/cross-chain-txs/mocks/txs.ts index 27a4f136c0c..f08628805e6 100644 --- a/src/features/cross-chain-txs/mocks/txs.ts +++ b/src/features/cross-chain-txs/mocks/txs.ts @@ -2,11 +2,12 @@ import type { GetMessagesResponse, InterchainMessage } from '@blockscout/interch import { MessageStatus } from '@blockscout/interchain-indexer-types'; import { config } from './config'; -import { transferA, transferB } from './transfers'; +import { transferA, transferB, transferWithUnindexedDestination } from './transfers'; /* eslint-disable max-len */ export const base = { bridge: { + id: 2, name: 'Avalanche ICTT', ui_url: 'https://app.avax.network/', }, @@ -31,6 +32,7 @@ export const base = { transferA, transferB, ], + has_unindexed_chain: false, } satisfies InterchainMessage; export const pending = { @@ -59,10 +61,25 @@ export const failed = { transferB, ], bridge: { + id: 3, name: 'Goose bridge', }, } satisfies InterchainMessage; +export const withUnindexedDestination = { + ...base, + message_id: '0x057b42bbbfbb4900e155a554ae67632cb21e6f5a64d815fcad7f33abe552c05c', + status: MessageStatus.MESSAGE_STATUS_INITIATED, + destination_chain: undefined, + destination_transaction_hash: undefined, + recipient: undefined, + receive_timestamp: undefined, + has_unindexed_chain: true, + transfers: [ + transferWithUnindexedDestination, + ], +} satisfies InterchainMessage; + export const listResponse = { items: [ base, diff --git a/src/features/cross-chain-txs/pages/address/AddressTxsCrossChain.tsx b/src/features/cross-chain-txs/pages/address/AddressTxsCrossChain.tsx index 010fc724dd6..1ff09c8bb36 100644 --- a/src/features/cross-chain-txs/pages/address/AddressTxsCrossChain.tsx +++ b/src/features/cross-chain-txs/pages/address/AddressTxsCrossChain.tsx @@ -13,21 +13,20 @@ import type { Props } from '../../components/txs/TransactionsCrossChainContent'; const AddressTxsCrossChain = ({ pagination, isLoading, ...rest }: Props) => { const isMobile = useIsMobile(); + const actionBar = isMobile && pagination?.isVisible && ( + <ActionBar> + <Pagination { ...pagination } ml="auto"/> + </ActionBar> + ); + return ( - <> - { isMobile && ( - <ActionBar> - { pagination?.isVisible && <Pagination { ...pagination } ml="auto"/> } - </ActionBar> - ) } - <TransactionsCrossChainContent - pagination={ pagination } - isLoading={ isLoading } - isTableView - stickyHeader={ !isMobile } - { ...rest } - /> - </> + <TransactionsCrossChainContent + pagination={ pagination } + isLoading={ isLoading } + stickyHeader={ !isMobile } + actionBar={ actionBar } + { ...rest } + /> ); }; diff --git a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensIndex.tsx b/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensIndex.tsx index 7555a9305a7..f7d4df8167c 100644 --- a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensIndex.tsx +++ b/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensIndex.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { CrossChainBridgedTokensSortingValue } from '../../types/api'; @@ -8,15 +7,15 @@ import type { CrossChainBridgedTokensSortingValue } from '../../types/api'; import useApiQuery from 'src/api/hooks/useApiQuery'; import DataList from 'src/shared/lists/DataList'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; import type { OnValueChangeHandler } from 'src/toolkit/chakra/select'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import BridgedTokensList from './BridgedTokensList'; import BridgedTokensTable from './BridgedTokensTable'; interface Props { - query: QueryWithPagesResult<'interchainIndexer:bridged_tokens'>; + query: ApiPaginatedQueryResult<'interchainIndexer:bridged_tokens'>; onSortChange: OnValueChangeHandler; sort: CrossChainBridgedTokensSortingValue; actionBar?: React.ReactNode; @@ -37,31 +36,21 @@ const BridgedTokensIndex = ({ query, onSortChange, sort, actionBar, hasActiveFil }} actionBar={ actionBar } hasActiveFilters={ hasActiveFilters } + isTransitioning={ query.isTransitioning } > { query.data?.items ? ( - <> - <Box hideFrom="lg"> - <BridgedTokensList - data={ query.data.items } - page={ query.pagination.page } - chainsData={ chainsQuery.data?.items } - isLoading={ query.isPlaceholderData || chainsQuery.isPlaceholderData } - resetKey={ query.queryHash } - /> - </Box> - <Box hideBelow="lg"> - <BridgedTokensTable - data={ query.data.items } - sort={ sort } - setSorting={ onSortChange } - chainsData={ chainsQuery.data?.items } - isLoading={ query.isPlaceholderData || chainsQuery.isPlaceholderData } - resetKey={ query.queryHash } - page={ query.pagination.page } - top={ tableTop } - /> - </Box> - </> + <TableContainerScrollable> + <BridgedTokensTable + data={ query.data.items } + sort={ sort } + setSorting={ onSortChange } + chainsData={ chainsQuery.data?.items } + isLoading={ query.isInitialLoading || chainsQuery.isPlaceholderData } + resetKey={ query.queryHash } + page={ query.pagination.page } + top={ tableTop } + /> + </TableContainerScrollable> ) : null } </DataList> ); diff --git a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensList.tsx b/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensList.tsx deleted file mode 100644 index ec49477e4a8..00000000000 --- a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensList.tsx +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { ChainInfo, StatsBridgedTokenRow } from '@blockscout/interchain-indexer-types'; - -import config from 'src/config'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import BridgedTokensListItem from './BridgedTokensListItem'; - -interface Props { - data: Array<StatsBridgedTokenRow>; - page: number; - isLoading?: boolean; - resetKey?: string; - chainsData?: Array<ChainInfo>; -} - -const BridgedTokensList = ({ data, page, isLoading, resetKey, chainsData }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => { - const tokenInfo = item.tokens.find((token) => String(token.chain_id) === config.chain.id) || - item.tokens.find((token) => String(token.chain_id) !== config.chain.id); - const chainInfo = chainsData?.find((chain) => chain.id === tokenInfo?.chain_id); - - return ( - <BridgedTokensListItem - key={ String(tokenInfo?.token_address) + (isLoading ? index : '') } - data={ item } - tokenInfo={ tokenInfo } - chainInfo={ chainInfo } - index={ index } - page={ page } - isLoading={ isLoading } - /> - ); - }) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - ); -}; - -export default React.memo(BridgedTokensList); diff --git a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensListItem.tsx b/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensListItem.tsx deleted file mode 100644 index 49ccaf5c557..00000000000 --- a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensListItem.tsx +++ /dev/null @@ -1,97 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Grid, HStack } from '@chakra-ui/react'; -import React from 'react'; - -import type { ChainInfo, StatsBridgedTokenItem, StatsBridgedTokenRow } from '@blockscout/interchain-indexer-types'; - -import AddressEntityInterchain from 'src/slices/address/components/entity/AddressEntityInterchain'; -import TokenEntityInterchain from 'src/slices/token/components/entity/TokenEntityInterchain'; -import { toTokenModel } from 'src/slices/token/utils/model'; - -import getItemIndex from 'src/shared/lists/get-item-index'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - data: StatsBridgedTokenRow; - tokenInfo?: StatsBridgedTokenItem; - chainInfo?: ChainInfo; - index: number; - page: number; - isLoading?: boolean; -} - -const BridgedTokensListItem = ({ data, tokenInfo, chainInfo, index, page, isLoading }: Props) => { - - const tokenModel = React.useMemo(() => { - if (!tokenInfo) { - return; - } - - return toTokenModel({ - ...tokenInfo, - decimals: String(tokenInfo.decimals ?? '0'), - address_hash: tokenInfo.token_address, - type: 'ERC-20', - }); - }, [ tokenInfo ]); - - return ( - <ListItemMobile rowGap={ 3 } alignItems="stretch"> - - <HStack justifyContent="space-between"> - { tokenModel ? ( - <TokenEntityInterchain - token={ tokenModel } - chain={ chainInfo } - isLoading={ isLoading } - jointSymbol - noCopy - w="auto" - textStyle="sm" - fontWeight="700" - /> - ) : <Skeleton loading={ isLoading } w="fit-content"><span>Unknown token</span></Skeleton> } - <Skeleton loading={ isLoading } textStyle="sm" color="text.secondary" minW="24px" textAlign="right"> - <span>{ getItemIndex(index, page) }</span> - </Skeleton> - </HStack> - { tokenModel && ( - <AddressEntityInterchain - address={{ hash: tokenModel.address_hash }} - chain={ chainInfo } - isLoading={ isLoading } - truncation="constant" - link={{ variant: 'secondary' }} - noIcon - ml="28px" - /> - ) } - - <Grid gridTemplateColumns="120px 1fr" columnGap={ 2 } rowGap={ 3 } textStyle="sm"> - <Skeleton loading={ isLoading } fontWeight={ 500 }> - <span>Out transfers</span> - </Skeleton> - <Skeleton loading={ isLoading } color="text.secondary"> - <span>{ Number(data.output_transfers_count).toLocaleString() }</span> - </Skeleton> - <Skeleton loading={ isLoading } fontWeight={ 500 }> - <span>In transfers</span> - </Skeleton> - <Skeleton loading={ isLoading } color="text.secondary"> - <span>{ Number(data.input_transfers_count).toLocaleString() }</span> - </Skeleton> - <Skeleton loading={ isLoading } fontWeight={ 500 }> - <span>Total transfers</span> - </Skeleton> - <Skeleton loading={ isLoading } color="text.secondary"> - <span>{ Number(data.total_transfers_count).toLocaleString() }</span> - </Skeleton> - </Grid> - </ListItemMobile> - ); -}; - -export default React.memo(BridgedTokensListItem); diff --git a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTable.pw.tsx b/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTable.pw.tsx new file mode 100644 index 00000000000..2db27b2db65 --- /dev/null +++ b/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTable.pw.tsx @@ -0,0 +1,29 @@ +import * as bridgedTokensMock from 'src/features/cross-chain-txs/mocks/bridged-tokens'; +import { chainA, chainB } from 'src/features/multichain/mocks/chains'; + +import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; +import { test, expect } from 'playwright/lib'; + +import BridgedTokensTable from './BridgedTokensTable'; + +const noop = () => {}; + +test('base view', async({ render, mockEnvs, mockAssetResponse }) => { + await mockEnvs([ + ...ENVS_MAP.crossChainTxs, + [ 'NEXT_PUBLIC_NETWORK_ID', chainA.id ], + ]); + await mockAssetResponse(bridgedTokensMock.bridgedTokenErc20.icon_url, './playwright/mocks/image_s.jpg'); + + const component = await render( + <BridgedTokensTable + data={ bridgedTokensMock.listResponse.items } + chainsData={ [ chainA, chainB ] } + sort="default" + setSorting={ noop } + page={ 1 } + />, + ); + + await expect(component).toHaveScreenshot(); +}); diff --git a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTable.tsx b/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTable.tsx index e21833b50a0..fe4014acca6 100644 --- a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTable.tsx +++ b/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTable.tsx @@ -7,6 +7,7 @@ import type { ChainInfo, StatsBridgedTokenRow } from '@blockscout/interchain-ind import { BridgedTokensSort } from '@blockscout/interchain-indexer-types'; import config from 'src/config'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import getNextSortValue from 'src/shared/sort/get-next-sort-value'; @@ -26,9 +27,12 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: StatsBridgedTokenRow): string => item.stats_asset_id; + const BridgedTokensTable = ({ data, isLoading, sort, setSorting, page, top, chainsData, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); const onSortToggle = React.useCallback((field: CrossChainBridgedTokensSortingField) => { const value = getNextSortValue<CrossChainBridgedTokensSortingField, CrossChainBridgedTokensSortingValue>(BRIDGED_TOKENS_SORT_SEQUENCE, field)(sort); @@ -36,16 +40,17 @@ const BridgedTokensTable = ({ data, isLoading, sort, setSorting, page, top, chai }, [ sort, setSorting ]); return ( - <TableRoot minW="1100px"> + <TableRoot minW="900px"> <TableHeaderSticky top={ top }> <TableRow> - <TableColumnHeader>Token</TableColumnHeader> + <TableColumnHeader w="55%">Token</TableColumnHeader> <TableColumnHeaderSortable isNumeric sortField={ BridgedTokensSort.INPUT_TRANSFERS_COUNT } sortValue={ sort } onSortToggle={ onSortToggle } disabled={ isLoading } + w="15%" > In transfers </TableColumnHeaderSortable> @@ -55,6 +60,7 @@ const BridgedTokensTable = ({ data, isLoading, sort, setSorting, page, top, chai sortValue={ sort } onSortToggle={ onSortToggle } disabled={ isLoading } + w="15%" > Out transfers </TableColumnHeaderSortable> @@ -64,6 +70,7 @@ const BridgedTokensTable = ({ data, isLoading, sort, setSorting, page, top, chai sortValue={ sort } onSortToggle={ onSortToggle } disabled={ isLoading } + w="15%" > Total transfers </TableColumnHeaderSortable> @@ -77,7 +84,7 @@ const BridgedTokensTable = ({ data, isLoading, sort, setSorting, page, top, chai return ( <BridgedTokensTableItem - key={ String(tokenInfo?.token_address) + (isLoading ? index : '') } + key={ keys[index] } data={ item } tokenInfo={ tokenInfo } chainInfo={ chainInfo } diff --git a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTableItem.tsx b/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTableItem.tsx index 9f246869056..a3d8882644c 100644 --- a/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTableItem.tsx +++ b/src/features/cross-chain-txs/pages/bridged-tokens/BridgedTokensTableItem.tsx @@ -4,11 +4,13 @@ import { Flex } from '@chakra-ui/react'; import React from 'react'; import type { ChainInfo, StatsBridgedTokenItem, StatsBridgedTokenRow } from '@blockscout/interchain-indexer-types'; +import { getTokenTypeName } from 'src/slices/token/utils/token-types'; import AddressEntityInterchain from 'src/slices/address/components/entity/AddressEntityInterchain'; import TokenEntityInterchain from 'src/slices/token/components/entity/TokenEntityInterchain'; import { toTokenModel } from 'src/slices/token/utils/model'; +import { isNativeToken, toCoreTokenType } from 'src/features/cross-chain-txs/utils/token-type'; import TokenAddToWallet from 'src/features/web3-wallet/components/TokenAddToWallet'; import config from 'src/config'; @@ -16,6 +18,7 @@ import getItemIndex from 'src/shared/lists/get-item-index'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; +import { Tag } from 'src/toolkit/chakra/tag'; interface Props { data: StatsBridgedTokenRow; @@ -28,18 +31,22 @@ interface Props { const BridgedTokensTableItem = ({ data, tokenInfo, chainInfo, index, page, isLoading }: Props) => { + const isNative = isNativeToken(tokenInfo?.type); + const tokenType = toCoreTokenType(tokenInfo?.type); + const tokenModel = React.useMemo(() => { if (!tokenInfo) { return undefined; } + // The core token model has no native kind; only the entity (which accepts any kind) gets it. return toTokenModel({ ...tokenInfo, decimals: String(tokenInfo.decimals ?? '0'), address_hash: tokenInfo.token_address, - type: 'ERC-20', + type: tokenType === 'NATIVE' ? undefined : tokenType, }); - }, [ tokenInfo ]); + }, [ tokenInfo, tokenType ]); return ( <TableRow className="group"> @@ -57,36 +64,39 @@ const BridgedTokensTableItem = ({ data, tokenInfo, chainInfo, index, page, isLoa { tokenModel ? ( <Flex overflow="hidden" flexDir="column" rowGap={ 2 }> <TokenEntityInterchain - token={ tokenModel } + token={{ ...tokenModel, type: tokenType }} chain={ chainInfo } isLoading={ isLoading } jointSymbol noCopy - noLink={ !chainInfo } + noLink={ !chainInfo || isNative } textStyle="sm" fontWeight="700" /> - <Flex columnGap={ 2 } py="5px" alignItems="center"> - <AddressEntityInterchain - address={{ hash: tokenModel.address_hash }} - chain={ chainInfo } - isLoading={ isLoading } - noIcon - textStyle="sm" - fontWeight={ 500 } - link={{ variant: 'secondary' }} - noLink={ !chainInfo } - /> - { chainInfo?.id === config.chain.id && ( - <TokenAddToWallet - token={ tokenModel } + { !isNative && ( + <Flex columnGap={ 2 } py="5px" alignItems="center"> + <AddressEntityInterchain + address={{ hash: tokenModel.address_hash }} + chain={ chainInfo } isLoading={ isLoading } - iconSize={ 5 } - opacity={ 0 } - _groupHover={{ opacity: 1 }} + noIcon + textStyle="sm" + fontWeight={ 500 } + link={{ variant: 'secondary' }} + noLink={ !chainInfo } /> - ) } - </Flex> + { chainInfo?.id === config.chain.id && ( + <TokenAddToWallet + token={ tokenModel } + isLoading={ isLoading } + iconSize={ 5 } + opacity={ 0 } + _groupHover={{ opacity: 1 }} + /> + ) } + </Flex> + ) } + <Tag loading={ isLoading } w="fit-content">{ getTokenTypeName(tokenType) }</Tag> </Flex> ) : <Skeleton loading={ isLoading } w="fit-content"><span>Unknown token</span></Skeleton> } </Flex> diff --git a/src/features/cross-chain-txs/pages/bridged-tokens/__screenshots__/BridgedTokensTable.pw.tsx_default_base-view-1.png b/src/features/cross-chain-txs/pages/bridged-tokens/__screenshots__/BridgedTokensTable.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..b374fea5a2d Binary files /dev/null and b/src/features/cross-chain-txs/pages/bridged-tokens/__screenshots__/BridgedTokensTable.pw.tsx_default_base-view-1.png differ diff --git a/src/features/cross-chain-txs/pages/home/LatestCrossChainTxs.tsx b/src/features/cross-chain-txs/pages/home/LatestCrossChainTxs.tsx index 6ede5fffba4..a307fdca164 100644 --- a/src/features/cross-chain-txs/pages/home/LatestCrossChainTxs.tsx +++ b/src/features/cross-chain-txs/pages/home/LatestCrossChainTxs.tsx @@ -1,25 +1,22 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; -import TransactionsCrossChainListItem from 'src/features/cross-chain-txs/components/txs/TransactionsCrossChainListItem'; import { INTERCHAIN_MESSAGE } from 'src/features/cross-chain-txs/stubs/messages'; -import useIsMobile from 'src/shared/hooks/useIsMobile'; import { generateListStub } from 'src/shared/pagination/utils'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; -import { TableBody, TableRoot } from 'src/toolkit/chakra/table'; +import { TableBody, TableContainerScrollable, TableRoot } from 'src/toolkit/chakra/table'; -import LatestCrossChainTxsItemDesktop from './LatestCrossChainTxsItemDesktop'; +import LatestCrossChainTxsTableItem from './LatestCrossChainTxsTableItem'; const LatestCrossChainTxs = () => { - const isMobile = useIsMobile(); - const txsCount = isMobile ? 2 : 5; + const txsCount = 5; const { data, isPlaceholderData, isError } = useApiQuery('interchainIndexer:messages', { queryOptions: { placeholderData: generateListStub<'interchainIndexer:messages'>( @@ -38,34 +35,20 @@ const LatestCrossChainTxs = () => { return ( <> - <Box mb={ 3 } hideFrom="lg" textStyle="sm"> - { data.items.slice(0, txsCount).map(((tx, index) => ( - <TransactionsCrossChainListItem - key={ tx.message_id + (isPlaceholderData ? index : '') } - data={ tx } - isLoading={ isPlaceholderData } - py={ 4 } - textStyle="sm" - rowGap="14px" - _first={{ - borderTopWidth: '0', - paddingTop: '4px', - }} - /> - ))) } - </Box> - <Box mb={ 3 } hideBelow="lg" textStyle="sm"> - <TableRoot minWidth="750px"> - <TableBody> - { data.items.slice(0, txsCount).map(((tx, index) => ( - <LatestCrossChainTxsItemDesktop - key={ tx.message_id + (isPlaceholderData ? index : '') } - data={ tx } - isLoading={ isPlaceholderData } - /> - ))) } - </TableBody> - </TableRoot> + <Box mb={ 3 } textStyle="sm"> + <TableContainerScrollable> + <TableRoot minWidth="750px"> + <TableBody> + { data.items.slice(0, txsCount).map(((tx, index) => ( + <LatestCrossChainTxsTableItem + key={ tx.message_id + (isPlaceholderData ? index : '') } + data={ tx } + isLoading={ isPlaceholderData } + /> + ))) } + </TableBody> + </TableRoot> + </TableContainerScrollable> </Box> <Flex justifyContent="center"> <Link textStyle="sm" href={ route({ pathname: '/txs', query: { tab: 'txs_cross_chain' } }) }>View all transactions</Link> diff --git a/src/features/cross-chain-txs/pages/home/LatestCrossChainTxsItemDesktop.tsx b/src/features/cross-chain-txs/pages/home/LatestCrossChainTxsItemDesktop.tsx deleted file mode 100644 index c519f926d7c..00000000000 --- a/src/features/cross-chain-txs/pages/home/LatestCrossChainTxsItemDesktop.tsx +++ /dev/null @@ -1,91 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { chakra, VStack } from '@chakra-ui/react'; -import React from 'react'; - -import type { InterchainMessage } from '@blockscout/interchain-indexer-types'; - -import TxEntityInterchain from 'src/slices/tx/components/entity/TxEntityInterchain'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ChainLabel from 'src/shared/external-chains/ChainLabel'; - -import { TableCell, TableRow } from 'src/toolkit/chakra/table'; -import { mdash } from 'src/toolkit/utils/htmlEntities'; - -import CrossChainBridgeLink from '../../components/CrossChainBridgeLink'; -import CrossChainMessageEntity from '../../components/CrossChainMessageEntity'; -import CrossChainTxsStatusTag from '../../components/CrossChainTxsStatusTag'; - -interface Props { - data: InterchainMessage; - isLoading?: boolean; -} - -const LatestCrossChainTxsItemDesktop = ({ data, isLoading }: Props) => { - - return ( - <TableRow> - <TableCell w="42px"> - <CrossChainTxsStatusTag status={ data.status } loading={ isLoading }/> - </TableCell> - <TableCell> - <VStack alignItems="start"> - <CrossChainMessageEntity id={ data.message_id } isLoading={ isLoading } lineHeight="24px" fontWeight={ 700 }/> - <TimeWithTooltip timestamp={ data.send_timestamp || data.receive_timestamp } isLoading={ isLoading } color="text.secondary" timeFormat="absolute"/> - </VStack> - </TableCell> - <TableCell> - <VStack alignItems="start"> - { data.source_transaction_hash ? ( - <TxEntityInterchain - chain={ data.source_chain } - hash={ data.source_transaction_hash } - isLoading={ isLoading } - noIcon - noCopy - truncation="constant" - lineHeight="24px" - /> - ) : ( - <chakra.span color="text.secondary">{ mdash }</chakra.span> - ) } - <ChainLabel - data={ data.source_chain } - isLoading={ isLoading } - color="text.secondary" - textStyle="xs" - /> - </VStack> - </TableCell> - <TableCell> - <VStack alignItems="start"> - { data.destination_transaction_hash ? ( - <TxEntityInterchain - chain={ data.destination_chain } - hash={ data.destination_transaction_hash } - isLoading={ isLoading } - noIcon - noCopy - truncation="constant" - lineHeight="24px" - /> - ) : ( - <chakra.span color="text.secondary">{ mdash }</chakra.span> - ) } - <ChainLabel - data={ data.destination_chain } - isLoading={ isLoading } - color="text.secondary" - textStyle="xs" - /> - </VStack> - </TableCell> - <TableCell> - <CrossChainBridgeLink data={ data.bridge } isLoading={ isLoading } messageId={ data.message_id } lineHeight="24px"/> - </TableCell> - </TableRow> - ); -}; - -export default React.memo(LatestCrossChainTxsItemDesktop); diff --git a/src/features/cross-chain-txs/pages/home/LatestCrossChainTxsTableItem.tsx b/src/features/cross-chain-txs/pages/home/LatestCrossChainTxsTableItem.tsx new file mode 100644 index 00000000000..12173563800 --- /dev/null +++ b/src/features/cross-chain-txs/pages/home/LatestCrossChainTxsTableItem.tsx @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { chakra, VStack } from '@chakra-ui/react'; +import React from 'react'; + +import type { InterchainMessage } from '@blockscout/interchain-indexer-types'; + +import TxEntityInterchain from 'src/slices/tx/components/entity/TxEntityInterchain'; + +import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import ChainLabel from 'src/shared/external-chains/ChainLabel'; + +import { TableCell, TableRow } from 'src/toolkit/chakra/table'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import CrossChainBridgeLink from '../../components/CrossChainBridgeLink'; +import CrossChainMessageEntity from '../../components/CrossChainMessageEntity'; +import CrossChainTxsStatusTag from '../../components/CrossChainTxsStatusTag'; + +interface Props { + data: InterchainMessage; + isLoading?: boolean; +} + +const LatestCrossChainTxsTableItem = ({ data, isLoading }: Props) => { + + return ( + <TableRow> + <TableCell w="42px"> + <CrossChainTxsStatusTag status={ data.status } loading={ isLoading }/> + </TableCell> + <TableCell> + <VStack alignItems="start"> + <CrossChainMessageEntity id={ data.message_id } bridgeId={ data.bridge?.id } isLoading={ isLoading } lineHeight="24px" fontWeight={ 700 }/> + <TimeWithTooltip timestamp={ data.send_timestamp || data.receive_timestamp } isLoading={ isLoading } color="text.secondary" timeFormat="absolute"/> + </VStack> + </TableCell> + <TableCell> + <VStack alignItems="start"> + { data.source_transaction_hash ? ( + <TxEntityInterchain + chain={ data.source_chain } + hash={ data.source_transaction_hash } + isLoading={ isLoading } + noIcon + noCopy + truncation="constant" + lineHeight="24px" + /> + ) : ( + <chakra.span color="text.secondary">{ mdash }</chakra.span> + ) } + <ChainLabel + data={ data.source_chain } + isLoading={ isLoading } + color="text.secondary" + textStyle="xs" + /> + </VStack> + </TableCell> + <TableCell> + <VStack alignItems="start"> + { data.destination_transaction_hash ? ( + <TxEntityInterchain + chain={ data.destination_chain } + hash={ data.destination_transaction_hash } + isLoading={ isLoading } + noIcon + noCopy + truncation="constant" + lineHeight="24px" + /> + ) : ( + <chakra.span color="text.secondary">{ mdash }</chakra.span> + ) } + <ChainLabel + data={ data.destination_chain } + isLoading={ isLoading } + color="text.secondary" + textStyle="xs" + /> + </VStack> + </TableCell> + <TableCell> + <CrossChainBridgeLink data={ data.bridge } isLoading={ isLoading } messageId={ data.message_id } lineHeight="24px"/> + </TableCell> + </TableRow> + ); +}; + +export default React.memo(LatestCrossChainTxsTableItem); diff --git a/src/features/cross-chain-txs/pages/ictt-users/IcttUsers.tsx b/src/features/cross-chain-txs/pages/ictt-users/IcttUsers.tsx index 6ac69c82608..349de32d62d 100644 --- a/src/features/cross-chain-txs/pages/ictt-users/IcttUsers.tsx +++ b/src/features/cross-chain-txs/pages/ictt-users/IcttUsers.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, createListCollection } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; +import { createListCollection } from '@chakra-ui/react'; import React from 'react'; import type { CrossChainChainsStatsSorting, CrossChainChainsStatsSortingField, CrossChainChainsStatsSortingValue } from '../../types/api'; @@ -12,15 +11,16 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; import getSortValueFromQuery from 'src/shared/sort/get-sort-value-from-query'; import Sort from 'src/shared/sort/Sort'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import { INTERCHAIN_STATS_CHAINS_ITEM } from '../../stubs/messages'; import { ICTT_USERS_SORT_OPTIONS } from '../../utils/ictt-sort'; -import IcttUsersList from './IcttUsersList'; import IcttUsersTable from './IcttUsersTable'; const sortCollection = createListCollection({ @@ -28,24 +28,23 @@ const sortCollection = createListCollection({ }); const IcttUsers = () => { - const router = useRouter(); const isMobile = useIsMobile(); - const [ sort, setSort ] = React.useState<CrossChainChainsStatsSortingValue>( - getSortValueFromQuery<CrossChainChainsStatsSortingValue>(router.query, ICTT_USERS_SORT_OPTIONS) ?? 'default', - ); - - const { data, isPlaceholderData, isError, onSortingChange, pagination, queryHash } = useQueryWithPages({ + const { data, isInitialLoading, isTransitioning, isError, sorting, onSortingChange, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'interchainIndexer:stats_chains', - sorting: getSortParamsFromValue<CrossChainChainsStatsSortingValue, CrossChainChainsStatsSortingField, CrossChainChainsStatsSorting['order']>(sort), options: { placeholderData: generateListStub<'interchainIndexer:stats_chains'>(INTERCHAIN_STATS_CHAINS_ITEM, 50, { next_page_params: { page_token: 'token' } }), }, }); + const sort = getSortValueFromQuery<CrossChainChainsStatsSortingValue>({ ...sorting }, ICTT_USERS_SORT_OPTIONS) ?? 'default'; + const handleSortChange = React.useCallback(({ value }: { value: Array<string> }) => { - setSort(value[0] as CrossChainChainsStatsSortingValue); - onSortingChange(value[0] === 'default' ? undefined : getSortParamsFromValue(value[0] as CrossChainChainsStatsSortingValue)); + onSortingChange( + getSortParamsFromValue<CrossChainChainsStatsSortingValue, CrossChainChainsStatsSortingField, CrossChainChainsStatsSorting['order']>( + value[0] as CrossChainChainsStatsSortingValue, + ), + ); }, [ onSortingChange ]); const actionBar = isMobile || pagination.isVisible ? ( @@ -55,7 +54,7 @@ const IcttUsers = () => { defaultValue={ [ sort ] } collection={ sortCollection } onValueChange={ handleSortChange } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } hideFrom="lg" /> <Pagination { ...pagination } ml="auto"/> @@ -78,22 +77,18 @@ const IcttUsers = () => { term: 'ICTT user', }} actionBar={ actionBar } + isTransitioning={ isTransitioning } > { data?.items ? ( - <> - <Box hideFrom="lg"> - <IcttUsersList data={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <IcttUsersTable - data={ data.items } - sort={ sort } - setSorting={ handleSortChange } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <IcttUsersTable + data={ data.items } + sort={ sort } + setSorting={ handleSortChange } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null } </DataList> </> diff --git a/src/features/cross-chain-txs/pages/ictt-users/IcttUsersList.tsx b/src/features/cross-chain-txs/pages/ictt-users/IcttUsersList.tsx deleted file mode 100644 index 807f8dfbcdc..00000000000 --- a/src/features/cross-chain-txs/pages/ictt-users/IcttUsersList.tsx +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { StatsChainRow } from '@blockscout/interchain-indexer-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import IcttUsersListItem from './IcttUsersListItem'; - -interface Props { - data: Array<StatsChainRow>; - isLoading?: boolean; - resetKey?: string; -} - -const IcttUsersList = ({ data, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <IcttUsersListItem - key={ String(item.id) + (isLoading ? index : '') } - data={ item } - isLoading={ isLoading } - /> - )) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - ); -}; - -export default React.memo(IcttUsersList); diff --git a/src/features/cross-chain-txs/pages/ictt-users/IcttUsersListItem.tsx b/src/features/cross-chain-txs/pages/ictt-users/IcttUsersListItem.tsx deleted file mode 100644 index 86e43f0264a..00000000000 --- a/src/features/cross-chain-txs/pages/ictt-users/IcttUsersListItem.tsx +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Grid } from '@chakra-ui/react'; -import React from 'react'; - -import type { StatsChainRow } from '@blockscout/interchain-indexer-types'; - -import ChainSnippetList from 'src/shared/external-chains/ChainSnippetList'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - data: StatsChainRow; - isLoading?: boolean; -} - -const IcttUsersListItem = ({ data, isLoading }: Props) => { - const chainInfo = React.useMemo(() => { - return { - name: data.name, - id: String(data.id), - logo: data.logo, - explorer_url: data.explorer_url, - }; - }, [ data.name, data.id, data.logo, data.explorer_url ]); - - return ( - <ListItemMobile rowGap={ 3 } py={ 4 } fontSize="sm" alignItems="stretch"> - <ChainSnippetList data={ chainInfo } isLoading={ isLoading }/> - <Grid gridTemplateColumns="200px 1fr" columnGap={ 2 } rowGap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 }> - <span>Number of unique ICTT users</span> - </Skeleton> - <Skeleton loading={ isLoading }> - <span>{ Number(data.unique_transfer_users_count).toLocaleString() }</span> - </Skeleton> - </Grid> - </ListItemMobile> - ); -}; - -export default React.memo(IcttUsersListItem); diff --git a/src/features/cross-chain-txs/pages/ictt-users/IcttUsersTable.tsx b/src/features/cross-chain-txs/pages/ictt-users/IcttUsersTable.tsx index 2dfebf2c7b6..30c048fff21 100644 --- a/src/features/cross-chain-txs/pages/ictt-users/IcttUsersTable.tsx +++ b/src/features/cross-chain-txs/pages/ictt-users/IcttUsersTable.tsx @@ -8,6 +8,7 @@ import type { StatsChainRow } from '@blockscout/interchain-indexer-types'; import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import getNextSortValue from 'src/shared/sort/get-next-sort-value'; @@ -24,8 +25,11 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: StatsChainRow): string => String(item.id); + const IcttUsersTable = ({ data, isLoading, sort, setSorting, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); const onSortToggle = React.useCallback((field: CrossChainChainsStatsSortingField) => { const value = getNextSortValue<CrossChainChainsStatsSortingField, CrossChainChainsStatsSortingValue>(ICTT_USERS_SORT_SEQUENCE, field)(sort); @@ -33,7 +37,7 @@ const IcttUsersTable = ({ data, isLoading, sort, setSorting, resetKey }: Props) }, [ sort, setSorting ]); return ( - <TableRoot minW="1100px"> + <TableRoot minW="500px"> <TableHeaderSticky top={ ACTION_BAR_HEIGHT_DESKTOP }> <TableRow> <TableColumnHeader width="50%">Chain</TableColumnHeader> @@ -52,7 +56,7 @@ const IcttUsersTable = ({ data, isLoading, sort, setSorting, resetKey }: Props) <TableBody> { data.slice(0, renderedItemsNum).map((item, index) => ( <IcttUsersTableItem - key={ String(item.id) + (isLoading ? index : '') } + key={ keys[index] } data={ item } isLoading={ isLoading } /> diff --git a/src/features/cross-chain-txs/pages/token-transfers/TokenTransfersCrossChain.pw.tsx b/src/features/cross-chain-txs/pages/token-transfers/TokenTransfersCrossChain.pw.tsx index 7d7f24fa650..fc2f1bc5d15 100644 --- a/src/features/cross-chain-txs/pages/token-transfers/TokenTransfersCrossChain.pw.tsx +++ b/src/features/cross-chain-txs/pages/token-transfers/TokenTransfersCrossChain.pw.tsx @@ -1,6 +1,7 @@ import { Box } from '@chakra-ui/react'; import * as crossChainConfigMock from 'src/features/cross-chain-txs/mocks/config'; +import * as crossChainCountersMock from 'src/features/cross-chain-txs/mocks/counters'; import * as crossChainTransfersMock from 'src/features/cross-chain-txs/mocks/transfers'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; @@ -16,12 +17,12 @@ test.describe('txs', () => { [ 'NEXT_PUBLIC_NETWORK_ID', crossChainConfigMock.config[0].id ], ]); await mockApiResponse('interchainIndexer:transfers', crossChainTransfersMock.listResponse); - await mockApiResponse('interchainIndexer:stats_common', { total_messages: 100, total_transfers: 101, timestamp: '2022-01-13T12:00:00.000Z' }); - await mockApiResponse('interchainIndexer:stats_daily', { daily_messages: 42, daily_transfers: 55, date: '2022-01-13' }); + await mockApiResponse('stats:counters', crossChainCountersMock.counters); await mockAssetResponse(crossChainConfigMock.config[0].logo as string, './playwright/mocks/duck.png'); await mockAssetResponse(crossChainConfigMock.config[1].logo as string, './playwright/mocks/goose.png'); await mockAssetResponse(crossChainTransfersMock.transferA.source_token.icon_url as string, './playwright/mocks/image_s.jpg'); + await mockAssetResponse(crossChainTransfersMock.transferNative.destination_token.icon_url, './playwright/mocks/image_md.jpg'); }); test.describe('desktop', () => { @@ -36,14 +37,4 @@ test.describe('txs', () => { await expect(component).toHaveScreenshot(); }); }); - - test.describe('mobile', () => { - test.use({ viewport: pwConfig.viewport.mobile }); - test.slow(); - - test('base view', async({ render }) => { - const component = await render(<TokenTransfersCrossChain/>); - await expect(component).toHaveScreenshot({ timeout: 30_000 }); - }); - }); }); diff --git a/src/features/cross-chain-txs/pages/token-transfers/TokenTransfersCrossChain.tsx b/src/features/cross-chain-txs/pages/token-transfers/TokenTransfersCrossChain.tsx index 713951d5eac..0c3d4a01427 100644 --- a/src/features/cross-chain-txs/pages/token-transfers/TokenTransfersCrossChain.tsx +++ b/src/features/cross-chain-txs/pages/token-transfers/TokenTransfersCrossChain.tsx @@ -2,47 +2,46 @@ import React from 'react'; -import useApiQuery from 'src/api/hooks/useApiQuery'; - import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import TokenTransfersCrossChainContent from '../../components/token-transfers/TokenTransfersCrossChainContent'; -import { INTERCHAIN_STATS_COMMON, INTERCHAIN_TRANSFER } from '../../stubs/messages'; +import { useCrossChainCountersQuery } from '../../hooks/useCrossChainCountersQuery'; +import { INTERCHAIN_TRANSFER } from '../../stubs/messages'; const TokenTransfersCrossChain = () => { - const { data, isPlaceholderData, isError, pagination, queryHash } = useQueryWithPages({ + const { data, isInitialLoading, isTransitioning, isError, pagination, queryHash, filters, onFilterChange } = useApiPaginatedQuery({ resourceName: 'interchainIndexer:transfers', options: { placeholderData: generateListStub<'interchainIndexer:transfers'>(INTERCHAIN_TRANSFER, 50, { next_page_params: { page_token: 'token' } }), }, }); - const statsQuery = useApiQuery('interchainIndexer:stats_common', { - queryOptions: { - placeholderData: INTERCHAIN_STATS_COMMON, - }, - }); + const countersQuery = useCrossChainCountersQuery(); + const total = countersQuery.data?.totalInterchainTransfers; - const actionBarText = ( - <Skeleton loading={ statsQuery.isPlaceholderData || isPlaceholderData }> - A total of { Number(statsQuery.data?.total_transfers).toLocaleString() } cross-chain token transfers found + const actionBarText = total !== undefined ? ( + <Skeleton loading={ countersQuery.isPlaceholderData || isInitialLoading }> + A total of { Number(total).toLocaleString() } cross-chain token transfers found </Skeleton> - ); + ) : null; const actionBar = <StickyPaginationWithText text={ actionBarText } pagination={ pagination }/>; return ( <TokenTransfersCrossChainContent items={ data?.items } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } + isTransitioning={ isTransitioning } pagination={ pagination } isError={ isError } itemsNum={ data?.items.length } actionBar={ actionBar } resetKey={ queryHash } + filters={ filters } + onFilterChange={ onFilterChange } /> ); }; diff --git a/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_dark-color-mode_txs-desktop-base-view-dark-mode-1.png b/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_dark-color-mode_txs-desktop-base-view-dark-mode-1.png index 28c2e225a07..ee686ed1375 100644 Binary files a/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_dark-color-mode_txs-desktop-base-view-dark-mode-1.png and b/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_dark-color-mode_txs-desktop-base-view-dark-mode-1.png differ diff --git a/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_default_txs-desktop-base-view-dark-mode-1.png b/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_default_txs-desktop-base-view-dark-mode-1.png index 3259916b21f..2532e348885 100644 Binary files a/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_default_txs-desktop-base-view-dark-mode-1.png and b/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_default_txs-desktop-base-view-dark-mode-1.png differ diff --git a/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_default_txs-mobile-base-view-1.png b/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_default_txs-mobile-base-view-1.png deleted file mode 100644 index 4e9e23427b9..00000000000 Binary files a/src/features/cross-chain-txs/pages/token-transfers/__screenshots__/TokenTransfersCrossChain.pw.tsx_default_txs-mobile-base-view-1.png and /dev/null differ diff --git a/src/features/cross-chain-txs/pages/tx/TxCrossChain.pw.tsx b/src/features/cross-chain-txs/pages/tx/TxCrossChain.pw.tsx index 13f428122de..8a5851fec11 100644 --- a/src/features/cross-chain-txs/pages/tx/TxCrossChain.pw.tsx +++ b/src/features/cross-chain-txs/pages/tx/TxCrossChain.pw.tsx @@ -7,9 +7,14 @@ import { test, expect } from 'playwright/lib'; import TxCrossChain from './TxCrossChain'; +const bridgeId = String(crossChainTxMock.base.bridge.id); + const hooksConfig = { router: { - query: { id: crossChainTxMock.base.message_id }, + query: { + bridgeId, + id: crossChainTxMock.base.message_id, + }, }, }; @@ -23,6 +28,9 @@ test('successful tx +@mobile', async({ render, mockEnvs, mockApiResponse, mockAs pathParams: { id: crossChainTxMock.base.message_id, }, + queryParams: { + bridge_id: bridgeId, + }, }); await mockAssetResponse(crossChainConfigMock.config[0].logo as string, './playwright/mocks/duck.png'); diff --git a/src/features/cross-chain-txs/pages/tx/TxCrossChain.tsx b/src/features/cross-chain-txs/pages/tx/TxCrossChain.tsx index c95c3c7f6df..3d4365e16da 100644 --- a/src/features/cross-chain-txs/pages/tx/TxCrossChain.tsx +++ b/src/features/cross-chain-txs/pages/tx/TxCrossChain.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -13,22 +12,28 @@ import TextAd from 'src/features/ads/text/components/TextAd'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; import CrossChainMessageEntity from '../../components/CrossChainMessageEntity'; import { INTERCHAIN_MESSAGE } from '../../stubs/messages'; +import { remapBadRequestToInvalidInput } from '../../utils/message-details-error'; import TxCrossChainDetails from './TxCrossChainDetails'; import TxCrossChainTransfers from './TxCrossChainTransfers'; const TxCrossChain = () => { const router = useRouter(); const messageId = getQueryParamString(router.query.id); + const bridgeId = getQueryParamString(router.query.bridgeId); const query = useApiQuery('interchainIndexer:message', { pathParams: { id: messageId, }, + queryParams: { + bridge_id: bridgeId, + }, queryOptions: { placeholderData: INTERCHAIN_MESSAGE, }, @@ -47,11 +52,12 @@ const TxCrossChain = () => { }, ]; - throwOnResourceLoadError(query); + throwOnResourceLoadError(remapBadRequestToInvalidInput(query)); const titleSecondRow = ( <CrossChainMessageEntity id={ messageId } + bridgeId={ query.data?.bridge?.id } isLoading={ query.isPlaceholderData } variant="subheading" truncation="dynamic" diff --git a/src/features/cross-chain-txs/pages/tx/TxCrossChainDetails.tsx b/src/features/cross-chain-txs/pages/tx/TxCrossChainDetails.tsx index a50194b54a8..be2c61a45b0 100644 --- a/src/features/cross-chain-txs/pages/tx/TxCrossChainDetails.tsx +++ b/src/features/cross-chain-txs/pages/tx/TxCrossChainDetails.tsx @@ -73,7 +73,14 @@ const TxCrossChainDetails = ({ data, isLoading }: Props) => { <CrossChainBridgeLink data={ data.bridge } isLoading={ isLoading } messageId={ data.message_id }/> </DetailedInfo.ItemValue> - { data.transfers.length > 0 && <TxCrossChainDetailsTransfers data={ data.transfers } id={ data.message_id } isLoading={ isLoading }/> } + { data.transfers.length > 0 && ( + <TxCrossChainDetailsTransfers + data={ data.transfers } + id={ data.message_id } + bridgeId={ data.bridge?.id } + isLoading={ isLoading } + /> + ) } <DetailedInfo.ItemLabel hint="Current state of the cross-chain operation" diff --git a/src/features/cross-chain-txs/pages/tx/TxCrossChainDetailsTransfers.tsx b/src/features/cross-chain-txs/pages/tx/TxCrossChainDetailsTransfers.tsx index 7ff2f6aafcc..ea9171a4128 100644 --- a/src/features/cross-chain-txs/pages/tx/TxCrossChainDetailsTransfers.tsx +++ b/src/features/cross-chain-txs/pages/tx/TxCrossChainDetailsTransfers.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, Flex, GridItem } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { InterchainTransfer } from '@blockscout/interchain-indexer-types'; @@ -12,6 +11,11 @@ import AddressFromToIcon from 'src/slices/address/components/from-to/AddressFrom import TokenValueInterchain from 'src/features/cross-chain-txs/components/TokenValueInterchain'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; +<<<<<<< HEAD +======= +import { route } from 'src/shared/router/routes'; +import TokenValueInterchain from 'src/shared/values/entity/TokenValueInterchain'; +>>>>>>> v2.13.0 import SpriteIcon from 'src/sprite/SpriteIcon'; import { Link } from 'src/toolkit/chakra/link'; @@ -22,10 +26,11 @@ const MAX_NUM = 5; interface Props { data: Array<InterchainTransfer>; id: string; + bridgeId: number | undefined; isLoading?: boolean; } -const TxCrossChainDetailsTransfers = ({ data, id, isLoading }: Props) => { +const TxCrossChainDetailsTransfers = ({ data, id, bridgeId, isLoading }: Props) => { return ( <> <DetailedInfo.ItemLabel @@ -97,14 +102,17 @@ const TxCrossChainDetailsTransfers = ({ data, id, isLoading }: Props) => { }) } </Flex> </DetailedInfo.ItemValue> - { data.length > MAX_NUM && ( + { data.length > MAX_NUM && bridgeId !== undefined && ( <> <GridItem hideBelow="lg"/> <GridItem fontSize="sm" alignItems="center" display="inline-flex" pl={{ base: '28px', lg: 0 }}> { /* FIXME use non-navigation icon */ } <SpriteIcon name="navigation/tokens" boxSize={ 6 }/> <Link - href={ route({ pathname: '/cross-chain-tx/[id]', query: { id, tab: 'transfers' } }) } + href={ route({ + pathname: '/bridge/[bridgeId]/cross-chain-tx/[id]', + query: { bridgeId: String(bridgeId), id, tab: 'transfers' }, + }) } > View all </Link> diff --git a/src/features/cross-chain-txs/pages/tx/TxCrossChainTransfers.tsx b/src/features/cross-chain-txs/pages/tx/TxCrossChainTransfers.tsx index f4968f8abe3..97900c0c251 100644 --- a/src/features/cross-chain-txs/pages/tx/TxCrossChainTransfers.tsx +++ b/src/features/cross-chain-txs/pages/tx/TxCrossChainTransfers.tsx @@ -1,15 +1,14 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { InterchainTransfer } from '@blockscout/interchain-indexer-types'; import DataList from 'src/shared/lists/DataList'; -import TokenTransfersCrossChainListItem from '../../components/token-transfers/TokenTransfersCrossChainListItem'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import TokenTransfersCrossChainTable from '../../components/token-transfers/TokenTransfersCrossChainTable'; -import { getItemKey } from '../../components/token-transfers/utils'; interface Props { data: Array<InterchainTransfer> | undefined; @@ -19,27 +18,9 @@ interface Props { const TxCrossChainTransfers = ({ data, isLoading, isError }: Props) => { const content = data ? ( - <> - <Box hideFrom="lg"> - { data.map((item, index) => ( - <TokenTransfersCrossChainListItem - key={ getItemKey(item, isLoading ? index : undefined) } - data={ item } - isLoading={ isLoading } - py={ 4 } - textStyle="sm" - rowGap="14px" - _first={{ - borderTopWidth: '0', - paddingTop: '0', - }} - /> - )) } - </Box> - <Box hideBelow="lg"> - <TokenTransfersCrossChainTable data={ data } isLoading={ isLoading }/> - </Box> - </> + <TableContainerScrollable> + <TokenTransfersCrossChainTable data={ data } isLoading={ isLoading }/> + </TableContainerScrollable> ) : null; return ( diff --git a/src/features/cross-chain-txs/pages/tx/TxDetailsCrossChainMessage.tsx b/src/features/cross-chain-txs/pages/tx/TxDetailsCrossChainMessage.tsx index ef23cbb1231..025a3613e2e 100644 --- a/src/features/cross-chain-txs/pages/tx/TxDetailsCrossChainMessage.tsx +++ b/src/features/cross-chain-txs/pages/tx/TxDetailsCrossChainMessage.tsx @@ -27,7 +27,7 @@ const TxDetailsCrossChainMessage = ({ data, isLoading }: Props) => { return ( <HStack columnGap={ 3 } rowGap={ 0 } flexWrap="wrap"> - <CrossChainMessageEntity id={ data.message_id } isLoading={ isLoading }/> + <CrossChainMessageEntity id={ data.message_id } bridgeId={ data.bridge?.id } isLoading={ isLoading }/> <DetailedInfoItemBreakdown.Container loading={ isLoading }> <DetailedInfoItemBreakdown.Row label="Timestamp" diff --git a/src/features/cross-chain-txs/pages/tx/TxDetailsCrossChainTransfers.tsx b/src/features/cross-chain-txs/pages/tx/TxDetailsCrossChainTransfers.tsx index 507eccd9340..584554a527f 100644 --- a/src/features/cross-chain-txs/pages/tx/TxDetailsCrossChainTransfers.tsx +++ b/src/features/cross-chain-txs/pages/tx/TxDetailsCrossChainTransfers.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { route } from 'nextjs-routes'; import React from 'react'; import { useMultichainContext } from 'src/features/multichain/context'; import config from 'src/config'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/features/cross-chain-txs/pages/tx/TxTokenTransferCrossChain.tsx b/src/features/cross-chain-txs/pages/tx/TxTokenTransferCrossChain.tsx index f6b3126548b..3605daa516f 100644 --- a/src/features/cross-chain-txs/pages/tx/TxTokenTransferCrossChain.tsx +++ b/src/features/cross-chain-txs/pages/tx/TxTokenTransferCrossChain.tsx @@ -1,55 +1,57 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { TxQuery } from 'src/slices/tx/hooks/useTxQuery'; import DataList from 'src/shared/lists/DataList'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; -import TokenTransfersCrossChainList from '../../components/token-transfers/TokenTransfersCrossChainList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + +import CrossChainFilterTags from '../../components/filters/CrossChainFilterTags'; +import { hasActiveColumnFilters } from '../../components/filters/utils'; import TokenTransfersCrossChainTable from '../../components/token-transfers/TokenTransfersCrossChainTable'; interface Props { txQuery: TxQuery; - crossChainQuery: QueryWithPagesResult<'interchainIndexer:tx_transfers'>; + crossChainQuery: ApiPaginatedQueryResult<'interchainIndexer:tx_transfers'>; isLoading?: boolean; tableTop?: number; + actionBar?: React.ReactNode; } -const TxTokenTransferCrossChain = ({ txQuery, crossChainQuery, isLoading, tableTop }: Props) => { +const TxTokenTransferCrossChain = ({ txQuery, crossChainQuery, isLoading, tableTop, actionBar }: Props) => { const content = crossChainQuery.data?.items ? ( - <> - <Box hideFrom="lg"> - <TokenTransfersCrossChainList - items={ crossChainQuery.data.items } - isLoading={ isLoading || crossChainQuery.isPlaceholderData } - resetKey={ crossChainQuery.queryHash } - /> - </Box> - <Box hideBelow="lg"> - <TokenTransfersCrossChainTable - data={ crossChainQuery.data.items } - isLoading={ isLoading || crossChainQuery.isPlaceholderData } - top={ tableTop } - resetKey={ crossChainQuery.queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <TokenTransfersCrossChainTable + data={ crossChainQuery.data.items } + isLoading={ isLoading || crossChainQuery.isInitialLoading } + top={ tableTop } + resetKey={ crossChainQuery.queryHash } + filters={ crossChainQuery.filters } + onFilterChange={ crossChainQuery.onFilterChange } + /> + </TableContainerScrollable> ) : null; return ( - <DataList - isError={ txQuery.isError || crossChainQuery.isError } - itemsNum={ crossChainQuery.data?.items.length } - emptyText="There are no cross-chain token transfers." - emptyStateProps={{ - term: 'token transfer', - }} - > - { content } - </DataList> + <> + <CrossChainFilterTags filters={ crossChainQuery.filters } onFilterChange={ crossChainQuery.onFilterChange } mb={ actionBar ? 6 : 3 }/> + <DataList + actionBar={ actionBar } + isError={ txQuery.isError || crossChainQuery.isError } + itemsNum={ crossChainQuery.data?.items.length } + emptyText="There are no cross-chain token transfers." + emptyStateProps={{ + term: 'token transfer', + }} + hasActiveFilters={ hasActiveColumnFilters(crossChainQuery.filters) } + isTransitioning={ crossChainQuery.isTransitioning } + > + { content } + </DataList> + </> ); }; diff --git a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChain.pw.tsx_default_successful-tx-mobile-1.png b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChain.pw.tsx_default_successful-tx-mobile-1.png index 5dc2b0249d4..31667d2bf12 100644 Binary files a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChain.pw.tsx_default_successful-tx-mobile-1.png and b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChain.pw.tsx_default_successful-tx-mobile-1.png differ diff --git a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChain.pw.tsx_mobile_successful-tx-mobile-1.png b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChain.pw.tsx_mobile_successful-tx-mobile-1.png index c2127c26573..2d94b1fbb29 100644 Binary files a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChain.pw.tsx_mobile_successful-tx-mobile-1.png and b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChain.pw.tsx_mobile_successful-tx-mobile-1.png differ diff --git a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_dark-color-mode_successful-tx-mobile-dark-mode-1.png b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_dark-color-mode_successful-tx-mobile-dark-mode-1.png index e7530c26b2f..c0874f47f89 100644 Binary files a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_dark-color-mode_successful-tx-mobile-dark-mode-1.png and b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_dark-color-mode_successful-tx-mobile-dark-mode-1.png differ diff --git a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_failed-on-first-step-1.png b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_failed-on-first-step-1.png index 4fc2fa432e1..8d0c87a4676 100644 Binary files a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_failed-on-first-step-1.png and b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_failed-on-first-step-1.png differ diff --git a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_initiated-tx-1.png b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_initiated-tx-1.png index 6279c4622dd..0610860a764 100644 Binary files a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_initiated-tx-1.png and b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_initiated-tx-1.png differ diff --git a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_successful-tx-mobile-dark-mode-1.png b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_successful-tx-mobile-dark-mode-1.png index acd00225ae5..6f75767e716 100644 Binary files a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_successful-tx-mobile-dark-mode-1.png and b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_default_successful-tx-mobile-dark-mode-1.png differ diff --git a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_mobile_successful-tx-mobile-dark-mode-1.png b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_mobile_successful-tx-mobile-dark-mode-1.png index cbed61d36f3..5d6c9ab8218 100644 Binary files a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_mobile_successful-tx-mobile-dark-mode-1.png and b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxCrossChainDetailsLifecycle.pw.tsx_mobile_successful-tx-mobile-dark-mode-1.png differ diff --git a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png index 044bff42163..09b45bf62f5 100644 Binary files a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png and b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_default_base-view-mobile-dark-mode-1.png b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_default_base-view-mobile-dark-mode-1.png index 1bd9ffcde00..47a62542790 100644 Binary files a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_default_base-view-mobile-dark-mode-1.png and b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_default_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_mobile_base-view-mobile-dark-mode-1.png b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_mobile_base-view-mobile-dark-mode-1.png index aa0a39706c1..d3a7df9e1bf 100644 Binary files a/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_mobile_base-view-mobile-dark-mode-1.png and b/src/features/cross-chain-txs/pages/tx/__screenshots__/TxDetailsCrossChainMessages.pw.tsx_mobile_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/cross-chain-txs/pages/txs/TransactionsCrossChain.pw.tsx b/src/features/cross-chain-txs/pages/txs/TransactionsCrossChain.pw.tsx index 5f04d8abb23..b20bfe490e9 100644 --- a/src/features/cross-chain-txs/pages/txs/TransactionsCrossChain.pw.tsx +++ b/src/features/cross-chain-txs/pages/txs/TransactionsCrossChain.pw.tsx @@ -3,6 +3,7 @@ import { test, expect } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; import * as crossChainConfigMock from '../../mocks/config'; +import * as crossChainCountersMock from '../../mocks/counters'; import * as crossChainTransfersMock from '../../mocks/transfers'; import * as crossChainTxMock from '../../mocks/txs'; import TransactionsCrossChain from './TransactionsCrossChain'; @@ -16,8 +17,7 @@ test.describe('txs', () => { [ 'NEXT_PUBLIC_NETWORK_ID', crossChainConfigMock.config[0].id ], ]); await mockApiResponse('interchainIndexer:messages', crossChainTxMock.listResponse); - await mockApiResponse('interchainIndexer:stats_common', { total_messages: 100, total_transfers: 101, timestamp: '2022-01-13T12:00:00.000Z' }); - await mockApiResponse('interchainIndexer:stats_daily', { daily_messages: 42, daily_transfers: 55, date: '2022-01-13' }); + await mockApiResponse('stats:counters', crossChainCountersMock.counters); await mockAssetResponse(crossChainConfigMock.config[0].logo as string, './playwright/mocks/duck.png'); await mockAssetResponse(crossChainConfigMock.config[1].logo as string, './playwright/mocks/goose.png'); @@ -32,13 +32,4 @@ test.describe('txs', () => { await expect(component).toHaveScreenshot({ timeout: 30_000 }); }); }); - - test.describe('mobile', () => { - test.use({ viewport: pwConfig.viewport.mobile }); - - test('base view', async({ render }) => { - const component = await render(<TransactionsCrossChain/>); - await expect(component).toHaveScreenshot({ timeout: 30_000 }); - }); - }); }); diff --git a/src/features/cross-chain-txs/pages/txs/TransactionsCrossChain.tsx b/src/features/cross-chain-txs/pages/txs/TransactionsCrossChain.tsx index 7635013aa1b..a9b3ce83f21 100644 --- a/src/features/cross-chain-txs/pages/txs/TransactionsCrossChain.tsx +++ b/src/features/cross-chain-txs/pages/txs/TransactionsCrossChain.tsx @@ -2,36 +2,32 @@ import React from 'react'; -import useApiQuery from 'src/api/hooks/useApiQuery'; - import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import TransactionsCrossChainContent from '../../components/txs/TransactionsCrossChainContent'; -import { INTERCHAIN_MESSAGE, INTERCHAIN_STATS_COMMON } from '../../stubs/messages'; +import { useCrossChainCountersQuery } from '../../hooks/useCrossChainCountersQuery'; +import { INTERCHAIN_MESSAGE } from '../../stubs/messages'; import TransactionsCrossChainStats from './TransactionsCrossChainStats'; const TransactionsCrossChain = () => { - const { data, isPlaceholderData, isError, pagination, queryHash } = useQueryWithPages({ + const { data, isInitialLoading, isTransitioning, isError, pagination, queryHash, filters, onFilterChange } = useApiPaginatedQuery({ resourceName: 'interchainIndexer:messages', options: { placeholderData: generateListStub<'interchainIndexer:messages'>(INTERCHAIN_MESSAGE, 50, { next_page_params: { page_token: 'token' } }), }, }); - const statsQuery = useApiQuery('interchainIndexer:stats_common', { - queryOptions: { - placeholderData: INTERCHAIN_STATS_COMMON, - }, - }); + const countersQuery = useCrossChainCountersQuery(); + const total = countersQuery.data?.totalInterchainMessages; - const actionBarText = ( - <Skeleton loading={ statsQuery.isPlaceholderData || isPlaceholderData }> - A total of { Number(statsQuery.data?.total_messages).toLocaleString() } cross-chain transactions found + const actionBarText = total !== undefined ? ( + <Skeleton loading={ countersQuery.isPlaceholderData || isInitialLoading }> + A total of { Number(total).toLocaleString() } cross-chain transactions found </Skeleton> - ); + ) : null; const actionBar = <StickyPaginationWithText text={ actionBarText } pagination={ pagination }/>; @@ -40,11 +36,14 @@ const TransactionsCrossChain = () => { <TransactionsCrossChainStats/> <TransactionsCrossChainContent items={ data?.items } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } + isTransitioning={ isTransitioning } pagination={ pagination } isError={ isError } actionBar={ actionBar } resetKey={ queryHash } + filters={ filters } + onFilterChange={ onFilterChange } /> </> ); diff --git a/src/features/cross-chain-txs/pages/txs/TransactionsCrossChainStats.tsx b/src/features/cross-chain-txs/pages/txs/TransactionsCrossChainStats.tsx index 1abe70fb891..56024a387ef 100644 --- a/src/features/cross-chain-txs/pages/txs/TransactionsCrossChainStats.tsx +++ b/src/features/cross-chain-txs/pages/txs/TransactionsCrossChainStats.tsx @@ -1,43 +1,31 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; -import useApiQuery from 'src/api/hooks/useApiQuery'; - +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; -import { INTERCHAIN_STATS_DAILY } from '../../stubs/messages'; +import { useCrossChainCountersQuery } from '../../hooks/useCrossChainCountersQuery'; interface Props {} const TransactionsCrossChainStats = (props: Props) => { - const { data, isPlaceholderData, isError } = useApiQuery('interchainIndexer:stats_daily', { - queryOptions: { - placeholderData: INTERCHAIN_STATS_DAILY, - }, - }); + const { data, isPlaceholderData, isError } = useCrossChainCountersQuery(); + const value = data?.newMessagesInterchain24h; - if (isError || !data) { + if (isError || value === undefined) { return null; } return ( - <Box - display="grid" - gridTemplateColumns="1fr" - rowGap={ 3 } - columnGap={ 3 } - mb={ 6 } - { ...props } - > + <StatsContainer mb={ 6 } { ...props }> <StatsWidget label="Cross-chain txns" - value={ Number(data.daily_messages).toLocaleString() } + value={ Number(value).toLocaleString() } period="24h" isLoading={ isPlaceholderData } /> - </Box> + </StatsContainer> ); }; diff --git a/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_dark-color-mode_txs-desktop-base-view-dark-mode-1.png b/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_dark-color-mode_txs-desktop-base-view-dark-mode-1.png index b34fca690a5..fa41b71f6e1 100644 Binary files a/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_dark-color-mode_txs-desktop-base-view-dark-mode-1.png and b/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_dark-color-mode_txs-desktop-base-view-dark-mode-1.png differ diff --git a/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_default_txs-desktop-base-view-dark-mode-1.png b/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_default_txs-desktop-base-view-dark-mode-1.png index a270b7fe5c6..991da8bfa5d 100644 Binary files a/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_default_txs-desktop-base-view-dark-mode-1.png and b/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_default_txs-desktop-base-view-dark-mode-1.png differ diff --git a/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_default_txs-mobile-base-view-1.png b/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_default_txs-mobile-base-view-1.png deleted file mode 100644 index 119d0a3b91c..00000000000 Binary files a/src/features/cross-chain-txs/pages/txs/__screenshots__/TransactionsCrossChain.pw.tsx_default_txs-mobile-base-view-1.png and /dev/null differ diff --git a/src/features/cross-chain-txs/stubs/counters.ts b/src/features/cross-chain-txs/stubs/counters.ts new file mode 100644 index 00000000000..38c54b11e72 --- /dev/null +++ b/src/features/cross-chain-txs/stubs/counters.ts @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type * as stats from '@blockscout/stats-types'; + +import type { CrossChainCounterId } from '../hooks/useCrossChainCountersQuery'; + +const COUNTER_IDS = [ + 'totalInterchainMessages', + 'newMessagesInterchain24h', + 'totalInterchainTransfers', + 'newTransfersInterchain24h', +] satisfies Array<CrossChainCounterId>; + +export const CROSS_CHAIN_COUNTERS: stats.Counters = { + counters: COUNTER_IDS.map((id) => ({ id, value: '10823', title: '', description: '' })), +}; diff --git a/src/features/cross-chain-txs/stubs/messages.ts b/src/features/cross-chain-txs/stubs/messages.ts index 3ae4859f063..de9352b2c82 100644 --- a/src/features/cross-chain-txs/stubs/messages.ts +++ b/src/features/cross-chain-txs/stubs/messages.ts @@ -1,13 +1,11 @@ import type { ChainInfo, - GetCommonStatisticsResponse, - GetDailyStatisticsResponse, InterchainMessage, InterchainTransfer, StatsBridgedTokenRow, StatsChainRow, } from '@blockscout/interchain-indexer-types'; -import { MessageStatus } from '@blockscout/interchain-indexer-types'; +import { MessageStatus, TokenInfo_TokenType } from '@blockscout/interchain-indexer-types'; import { ADDRESS_HASH } from 'src/slices/address/stubs/address-params'; import { TX_HASH } from 'src/slices/tx/stubs/tx'; @@ -19,6 +17,7 @@ const TOKEN = { name: 'Wrapped AVAX', symbol: 'WAVAX', decimals: '18', + type: TokenInfo_TokenType.ERC20, }; const CHAIN = { @@ -30,6 +29,7 @@ const CHAIN = { export const INTERCHAIN_TRANSFER = { bridge: { + id: 2, name: 'Avalanche ICTT', }, message_id: MESSAGE_ID, @@ -50,10 +50,12 @@ export const INTERCHAIN_TRANSFER = { hash: ADDRESS_HASH, }, receive_timestamp: '2026-01-07T18:41:53.000Z', + has_unindexed_chain: false, } satisfies InterchainTransfer; export const INTERCHAIN_MESSAGE = { bridge: { + id: 2, name: 'Avalanche ICTT', }, message_id: MESSAGE_ID, @@ -75,20 +77,9 @@ export const INTERCHAIN_MESSAGE = { transfers: [ INTERCHAIN_TRANSFER, ], + has_unindexed_chain: false, } satisfies InterchainMessage; -export const INTERCHAIN_STATS_DAILY = { - date: '2026-01-12', - daily_messages: 75, - daily_transfers: 75, -} satisfies GetDailyStatisticsResponse; - -export const INTERCHAIN_STATS_COMMON = { - timestamp: '2026-01-12T11:49:59.380Z', - total_messages: 10823, - total_transfers: 10822, -} satisfies GetCommonStatisticsResponse; - export const INTERCHAIN_STATS_CHAINS_ITEM = { id: '8021', name: 'NUMINE Mainnet', @@ -113,6 +104,7 @@ export const INTERCHAIN_BRIDGED_TOKEN_ITEM = { symbol: 'WAVAX', icon_url: undefined, decimals: 18, + type: TokenInfo_TokenType.ERC20, }, ], } satisfies StatsBridgedTokenRow; diff --git a/src/features/cross-chain-txs/types/api.ts b/src/features/cross-chain-txs/types/api.ts index 64cff0f036c..b1fe5eb221d 100644 --- a/src/features/cross-chain-txs/types/api.ts +++ b/src/features/cross-chain-txs/types/api.ts @@ -4,6 +4,9 @@ import type * as interchainIndexer from '@blockscout/interchain-indexer-types'; export interface CrossChainFilters { q?: string; + src_chain_ids?: string; + dst_chain_ids?: string; + bridge_ids?: string; } export interface CrossChainChainsStatsSorting { diff --git a/src/features/cross-chain-txs/utils/message-details-error.spec.ts b/src/features/cross-chain-txs/utils/message-details-error.spec.ts new file mode 100644 index 00000000000..04e41871d26 --- /dev/null +++ b/src/features/cross-chain-txs/utils/message-details-error.spec.ts @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { remapBadRequestToInvalidInput } from './message-details-error'; + +const INVALID_INPUT_STATUS = 422; + +const MALFORMED_MESSAGE_ID_ERROR = { + status: 400, + statusText: 'Bad Request', + payload: { code: 3, message: 'invalid message_id' }, +}; + +const WRONG_BRIDGE_ID_ERROR = { + status: 404, + statusText: 'Not Found', + payload: { code: 5, message: 'message not found' }, +}; + +describe('remapBadRequestToInvalidInput', () => { + it('surfaces a malformed message identifier as invalid input', () => { + const state = remapBadRequestToInvalidInput({ isError: true, error: MALFORMED_MESSAGE_ID_ERROR }); + + expect(state).toEqual({ + isError: true, + error: { ...MALFORMED_MESSAGE_ID_ERROR, status: INVALID_INPUT_STATUS }, + }); + }); + + it('leaves any other status untouched', () => { + const state = remapBadRequestToInvalidInput({ isError: true, error: WRONG_BRIDGE_ID_ERROR }); + + expect(state).toEqual({ isError: true, error: WRONG_BRIDGE_ID_ERROR }); + }); + + it('leaves a successful state untouched', () => { + const state = remapBadRequestToInvalidInput({ isError: false, error: null }); + + expect(state).toEqual({ isError: false, error: null }); + }); +}); diff --git a/src/features/cross-chain-txs/utils/message-details-error.ts b/src/features/cross-chain-txs/utils/message-details-error.ts new file mode 100644 index 00000000000..d6c359ae6f7 --- /dev/null +++ b/src/features/cross-chain-txs/utils/message-details-error.ts @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { ResourceError } from 'src/api/resources'; + +const BAD_REQUEST_STATUS = 400; +const INVALID_INPUT_STATUS = 422; + +type MessageDetailsErrorState = + { readonly isError: true; readonly error: ResourceError<unknown> } | + { readonly isError: false; readonly error: null }; + +// the indexer answers a malformed message_id with 400; the app's invalid-input page is keyed on 422 +export function remapBadRequestToInvalidInput(state: MessageDetailsErrorState): MessageDetailsErrorState { + if (!state.isError || state.error.status !== BAD_REQUEST_STATUS) { + return state; + } + + return { isError: true, error: { ...state.error, status: INVALID_INPUT_STATUS } }; +} diff --git a/src/features/cross-chain-txs/utils/token-type.spec.ts b/src/features/cross-chain-txs/utils/token-type.spec.ts new file mode 100644 index 00000000000..ec7a3186ba3 --- /dev/null +++ b/src/features/cross-chain-txs/utils/token-type.spec.ts @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { TokenInfo_TokenType } from '@blockscout/interchain-indexer-types'; + +import { describe, expect, it } from 'vitest'; + +import { isNativeToken, toCoreTokenType } from './token-type'; + +describe('toCoreTokenType', () => { + it('maps every served indexer kind to its core token type', () => { + expect(toCoreTokenType(TokenInfo_TokenType.ERC20)).toBe('ERC-20'); + expect(toCoreTokenType(TokenInfo_TokenType.NATIVE)).toBe('NATIVE'); + expect(toCoreTokenType(TokenInfo_TokenType.ERC721)).toBe('ERC-721'); + expect(toCoreTokenType(TokenInfo_TokenType.ERC1155)).toBe('ERC-1155'); + }); + + it('falls back to ERC-20 for a missing or unknown kind', () => { + expect(toCoreTokenType(undefined)).toBe('ERC-20'); + expect(toCoreTokenType(TokenInfo_TokenType.UNSPECIFIED)).toBe('ERC-20'); + expect(toCoreTokenType(TokenInfo_TokenType.UNRECOGNIZED)).toBe('ERC-20'); + }); +}); + +describe('isNativeToken', () => { + it('is true only for the native kind', () => { + expect(isNativeToken(TokenInfo_TokenType.NATIVE)).toBe(true); + expect(isNativeToken(TokenInfo_TokenType.ERC20)).toBe(false); + expect(isNativeToken(undefined)).toBe(false); + }); +}); diff --git a/src/features/cross-chain-txs/utils/token-type.ts b/src/features/cross-chain-txs/utils/token-type.ts new file mode 100644 index 00000000000..d0378df139c --- /dev/null +++ b/src/features/cross-chain-txs/utils/token-type.ts @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { schemas } from '@blockscout/api-types'; +import { TokenInfo_TokenType } from '@blockscout/interchain-indexer-types'; + +export type CoreTokenType = NonNullable<schemas['Token']['type']> | 'NATIVE'; + +const TOKEN_TYPE_MAP: Partial<Record<TokenInfo_TokenType, CoreTokenType>> = { + [TokenInfo_TokenType.ERC20]: 'ERC-20', + [TokenInfo_TokenType.NATIVE]: 'NATIVE', + [TokenInfo_TokenType.ERC721]: 'ERC-721', + [TokenInfo_TokenType.ERC1155]: 'ERC-1155', +}; + +// ERC-20 is the only kind the indexer served before it reported one, so an unknown kind keeps that behaviour. +export function toCoreTokenType(type: TokenInfo_TokenType | undefined): CoreTokenType { + return (type && TOKEN_TYPE_MAP[type]) ?? 'ERC-20'; +} + +export function isNativeToken(type: TokenInfo_TokenType | undefined): boolean { + return type === TokenInfo_TokenType.NATIVE; +} diff --git a/src/features/csv-export/components/dialog/CsvExportDialog.tsx b/src/features/csv-export/components/dialog/CsvExportDialog.tsx index 36ce9edfb9b..052369d6fdc 100644 --- a/src/features/csv-export/components/dialog/CsvExportDialog.tsx +++ b/src/features/csv-export/components/dialog/CsvExportDialog.tsx @@ -8,7 +8,7 @@ import { FormProvider, useForm } from 'react-hook-form'; import type { FormFields } from './types'; import { useSettingsContext } from 'src/shell/top-bar/settings/context'; -import SettingsLocalTime from 'src/shell/top-bar/settings/time-format/SettingsLocalTime'; +import SettingsLocalTime from 'src/shell/top-bar/settings/fields/time-format/SettingsLocalTime'; import { Button } from 'src/toolkit/chakra/button'; import { DialogBody, DialogContent, DialogHeader, DialogRoot } from 'src/toolkit/chakra/dialog'; diff --git a/src/features/csv-export/components/dialog/CsvExportDialogDescription.tsx b/src/features/csv-export/components/dialog/CsvExportDialogDescription.tsx index a7b6c2e5563..4b9e82b766b 100644 --- a/src/features/csv-export/components/dialog/CsvExportDialogDescription.tsx +++ b/src/features/csv-export/components/dialog/CsvExportDialogDescription.tsx @@ -7,7 +7,8 @@ import type { CsvExportType } from '../../types/client'; import type { ClusterChainConfig } from 'src/features/multichain/types/client'; import ChainIcon from 'src/shared/external-chains/ChainIcon'; -import shortenString from 'src/shared/texts/shorten-string'; + +import { shortenString } from 'src/toolkit/utils/texts'; import getPrefixByFilter from '../../utils/get-prefix-by-filter'; diff --git a/src/features/csv-export/components/downloads/CsvExportDownloadsItem.tsx b/src/features/csv-export/components/downloads/CsvExportDownloadsItem.tsx index cb317f7d24b..cd993f58ec0 100644 --- a/src/features/csv-export/components/downloads/CsvExportDownloadsItem.tsx +++ b/src/features/csv-export/components/downloads/CsvExportDownloadsItem.tsx @@ -12,7 +12,6 @@ import multichainConfig from 'src/features/multichain/chains-config'; import config from 'src/config'; import dayjs from 'src/shared/date-and-time/dayjs'; -import shortenString from 'src/shared/texts/shorten-string'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; @@ -20,6 +19,7 @@ import { DATE_PICKER_DATE_TIME_FORMAT } from 'src/toolkit/chakra/date-picker'; import { Link } from 'src/toolkit/chakra/link'; import { Status } from 'src/toolkit/chakra/status'; import { SECOND } from 'src/toolkit/utils/consts'; +import { shortenString } from 'src/toolkit/utils/texts'; import getPrefixByFilter from '../../utils/get-prefix-by-filter'; import type { StorageItem } from '../../utils/storage'; diff --git a/src/features/csv-export/mocks.ts b/src/features/csv-export/mocks.ts new file mode 100644 index 00000000000..09dfc385d8e --- /dev/null +++ b/src/features/csv-export/mocks.ts @@ -0,0 +1,6 @@ +import type { paths } from '@blockscout/api-types'; + +export const config: paths['/api/v2/config/csv-export']['get'] = { + limit: 10_000, + async_enabled: false, +}; diff --git a/src/features/data-availability/components/SearchBarSuggestBlob.tsx b/src/features/data-availability/components/SearchBarSuggestBlob.tsx index 7dcaa0034cf..0902a1410a7 100644 --- a/src/features/data-availability/components/SearchBarSuggestBlob.tsx +++ b/src/features/data-availability/components/SearchBarSuggestBlob.tsx @@ -8,14 +8,14 @@ import type { ItemsProps } from 'src/slices/search/components/search-bar/SearchB import * as BlobEntity from 'src/features/data-availability/components/entity/BlobEntity'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const SearchBarSuggestBlob = ({ data }: ItemsProps<schemas['SearchResultBlob']>) => { return ( <Flex alignItems="center" minW={ 0 }> <BlobEntity.Icon/> <chakra.mark overflow="hidden" whiteSpace="nowrap" fontWeight={ 700 }> - <HashStringShortenDynamic hash={ data.blob_hash } noTooltip/> + <Truncate value={ data.blob_hash } tooltip={ false }/> </chakra.mark> </Flex> ); diff --git a/src/features/data-availability/components/__screenshots__/BlobDataType.pw.tsx_default_raw-data-1.png b/src/features/data-availability/components/__screenshots__/BlobDataType.pw.tsx_default_raw-data-1.png index c52ecec0d00..618b03a37d5 100644 Binary files a/src/features/data-availability/components/__screenshots__/BlobDataType.pw.tsx_default_raw-data-1.png and b/src/features/data-availability/components/__screenshots__/BlobDataType.pw.tsx_default_raw-data-1.png differ diff --git a/src/features/data-availability/components/entity/BlobEntity.tsx b/src/features/data-availability/components/entity/BlobEntity.tsx index 95a72cb91b7..1ca6a932317 100644 --- a/src/features/data-availability/components/entity/BlobEntity.tsx +++ b/src/features/data-availability/components/entity/BlobEntity.tsx @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as EntityBase from 'src/shared/entities/components'; import { distributeEntityProps } from 'src/shared/entities/utils'; +import { route } from 'src/shared/router/routes'; type LinkProps = EntityBase.LinkBaseProps & Pick<EntityProps, 'hash'>; diff --git a/src/features/data-availability/components/entity/BlobEntityL1.tsx b/src/features/data-availability/components/entity/BlobEntityL1.tsx index 7909f5ce620..771e4121dbc 100644 --- a/src/features/data-availability/components/entity/BlobEntityL1.tsx +++ b/src/features/data-availability/components/entity/BlobEntityL1.tsx @@ -1,10 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; import * as BlobEntity from './BlobEntity'; diff --git a/src/features/data-availability/hooks/useBlockBlobTxsQuery.ts b/src/features/data-availability/hooks/useBlockBlobTxsQuery.ts index 524f993d7d8..c395e84fd1e 100644 --- a/src/features/data-availability/hooks/useBlockBlobTxsQuery.ts +++ b/src/features/data-availability/hooks/useBlockBlobTxsQuery.ts @@ -3,7 +3,7 @@ import type { BlockQuery } from 'src/slices/block/hooks/useBlockQuery'; import { TX_ITEM } from 'src/slices/tx/stubs/tx'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; interface Params { @@ -13,10 +13,10 @@ interface Params { } export default function useBlockBlobTxsQuery({ heightOrHash, blockQuery, tab }: Params) { - const apiQuery = useQueryWithPages({ + const apiQuery = useApiPaginatedQuery({ resourceName: 'core:block_txs', pathParams: { height_or_hash: heightOrHash }, - filters: { type: 'blob_transaction' }, + queryParams: { type: 'blob_transaction' }, options: { enabled: Boolean(tab === 'blob_txs' && !blockQuery.isPlaceholderData && blockQuery.data?.blob_transactions_count), placeholderData: generateListStub<'core:block_txs'>(TX_ITEM, 3, { next_page_params: null }), diff --git a/src/features/data-availability/pages/blob-details/Blob.tsx b/src/features/data-availability/pages/blob-details/Blob.tsx index 443abb33ed4..9da390b175a 100644 --- a/src/features/data-availability/pages/blob-details/Blob.tsx +++ b/src/features/data-availability/pages/blob-details/Blob.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -16,6 +15,7 @@ import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; import isCustomAppError from 'src/shared/errors/is-custom-app-error'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import BlobInfo from './BlobInfo'; diff --git a/src/features/data-availability/pages/blob-details/BlobData.tsx b/src/features/data-availability/pages/blob-details/BlobData.tsx index e0e26e5113a..39930a18879 100644 --- a/src/features/data-availability/pages/blob-details/BlobData.tsx +++ b/src/features/data-availability/pages/blob-details/BlobData.tsx @@ -31,6 +31,9 @@ const FORMATS = [ type Format = typeof FORMATS[number]['value']; +const DEFAULT_IMAGE_FORMAT: Array<Format> = [ 'Image' ]; +const DEFAULT_RAW_FORMAT: Array<Format> = [ 'Raw' ]; + interface Props { data: string; hash: string; @@ -38,7 +41,7 @@ interface Props { } const BlobData = ({ data, isLoading, hash }: Props) => { - const [ format, setFormat ] = React.useState<Array<Format>>([ 'Raw' ]); + const [ selectedFormat, setSelectedFormat ] = React.useState<Array<Format> | null>(null); const guessedType = React.useMemo(() => { if (isLoading) { @@ -55,14 +58,10 @@ const BlobData = ({ data, isLoading, hash }: Props) => { }); }, [ isImage ]); - React.useEffect(() => { - if (isImage) { - setFormat([ 'Image' ]); - } - }, [ isImage ]); + const format = selectedFormat ?? (isImage ? DEFAULT_IMAGE_FORMAT : DEFAULT_RAW_FORMAT); const handleFormatChange = React.useCallback(({ value }: { value: Array<string> }) => { - setFormat(value as Array<Format>); + setSelectedFormat(value as Array<Format>); }, []); const handleDownloadButtonClick = React.useCallback(() => { diff --git a/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png b/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png index 85a275b15e8..c34fc57751a 100644 Binary files a/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png and b/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_default_base-view-mobile-dark-mode-1.png b/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_default_base-view-mobile-dark-mode-1.png index 75a0bace942..d603965c248 100644 Binary files a/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_default_base-view-mobile-dark-mode-1.png and b/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_default_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_default_without-data-1.png b/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_default_without-data-1.png index f29d165c3e7..54743dd27b4 100644 Binary files a/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_default_without-data-1.png and b/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_default_without-data-1.png differ diff --git a/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_mobile_base-view-mobile-dark-mode-1.png b/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_mobile_base-view-mobile-dark-mode-1.png index 2d721eab2c4..2d7aa90bbb8 100644 Binary files a/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_mobile_base-view-mobile-dark-mode-1.png and b/src/features/data-availability/pages/blob-details/__screenshots__/Blob.pw.tsx_mobile_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/data-availability/pages/tx/TxBlobListItem.tsx b/src/features/data-availability/pages/tx/TxBlobListItem.tsx deleted file mode 100644 index 66faac9f2c2..00000000000 --- a/src/features/data-availability/pages/tx/TxBlobListItem.tsx +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import BlobDataType from 'src/features/data-availability/components/BlobDataType'; -import BlobEntity from 'src/features/data-availability/components/entity/BlobEntity'; - -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - data: schemas['BlobResponse']; - isLoading?: boolean; -} - -const TxBlobListItem = ({ data, isLoading }: Props) => { - const size = data.blob_data ? data.blob_data.replace('0x', '').length / 2 : '-'; - - return ( - <ListItemMobileGrid.Container> - <ListItemMobileGrid.Label isLoading={ isLoading }>Blob hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlobEntity hash={ data.hash } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Data type</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { data.blob_data ? <BlobDataType isLoading={ isLoading } data={ data.blob_data }/> : '-' } - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Size, bytes</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - { size.toLocaleString() } - </Skeleton> - </ListItemMobileGrid.Value> - </ListItemMobileGrid.Container> - ); -}; - -export default React.memo(TxBlobListItem); diff --git a/src/features/data-availability/pages/tx/TxBlobs.pw.tsx b/src/features/data-availability/pages/tx/TxBlobs.pw.tsx index 453e89667da..488177becd4 100644 --- a/src/features/data-availability/pages/tx/TxBlobs.pw.tsx +++ b/src/features/data-availability/pages/tx/TxBlobs.pw.tsx @@ -15,7 +15,7 @@ const hooksConfig = { }, }; -test('base view +@mobile', async({ render, mockApiResponse }) => { +test('base view', async({ render, mockApiResponse }) => { await mockApiResponse('core:tx_blobs', blobsMock.txBlobs, { pathParams: { hash: txMock.base.hash } }); const txQuery = { data: txMock.base, diff --git a/src/features/data-availability/pages/tx/TxBlobs.tsx b/src/features/data-availability/pages/tx/TxBlobs.tsx index d30381409bb..f78b691d6b4 100644 --- a/src/features/data-availability/pages/tx/TxBlobs.tsx +++ b/src/features/data-availability/pages/tx/TxBlobs.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -13,7 +12,8 @@ import { TX_BLOB } from 'src/features/data-availability/stubs'; import DataList from 'src/shared/lists/DataList'; -import TxBlobsList from './TxBlobsList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import TxBlobsTable from './TxBlobsTable'; interface Props { @@ -34,14 +34,9 @@ const TxBlobs = ({ txQuery }: Props) => { } const content = data?.items ? ( - <> - <Box hideBelow="lg"> - <TxBlobsTable data={ data.items } isLoading={ isPlaceholderData }/> - </Box> - <Box hideFrom="lg"> - <TxBlobsList data={ data.items } isLoading={ isPlaceholderData }/> - </Box> - </> + <TableContainerScrollable> + <TxBlobsTable data={ data.items } isLoading={ isPlaceholderData }/> + </TableContainerScrollable> ) : null; return ( diff --git a/src/features/data-availability/pages/tx/TxBlobsList.tsx b/src/features/data-availability/pages/tx/TxBlobsList.tsx deleted file mode 100644 index 0e91e3c4893..00000000000 --- a/src/features/data-availability/pages/tx/TxBlobsList.tsx +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import TxBlobListItem from './TxBlobListItem'; - -const TxBlobsList = ({ data, isLoading }: { data: Array<schemas['BlobResponse']>; isLoading?: boolean }) => { - return ( - <Box> - { data.map((item, index) => ( - <TxBlobListItem - key={ item.hash + (isLoading ? index : '') } - data={ item } - isLoading={ isLoading } - /> - )) } - </Box> - ); -}; - -export default TxBlobsList; diff --git a/src/features/data-availability/pages/tx/TxBlobsTable.tsx b/src/features/data-availability/pages/tx/TxBlobsTable.tsx index d3206fc9410..f389bd2e433 100644 --- a/src/features/data-availability/pages/tx/TxBlobsTable.tsx +++ b/src/features/data-availability/pages/tx/TxBlobsTable.tsx @@ -4,6 +4,8 @@ import React from 'react'; import type { schemas } from '@blockscout/api-types'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; + import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; import TxBlobsTableItem from './TxBlobsTableItem'; @@ -13,10 +15,13 @@ interface Props { isLoading?: boolean; } +const getBaseKey = (item: schemas['BlobResponse']): string => item.hash; + const TxBlobsTable = ({ data, isLoading }: Props) => { + const keys = useUniqueKeys(data, getBaseKey); return ( - <TableRoot> + <TableRoot minW="600px"> <TableHeaderSticky> <TableRow> <TableColumnHeader width="60%">Blob hash</TableColumnHeader> @@ -26,7 +31,7 @@ const TxBlobsTable = ({ data, isLoading }: Props) => { </TableHeaderSticky> <TableBody> { data.map((item, index) => ( - <TxBlobsTableItem key={ item.hash + (isLoading ? index : '') } data={ item } isLoading={ isLoading }/> + <TxBlobsTableItem key={ keys[index] } data={ item } isLoading={ isLoading }/> )) } </TableBody> </TableRoot> diff --git a/src/features/data-availability/pages/tx/__screenshots__/TxBlobs.pw.tsx_default_base-view-1.png b/src/features/data-availability/pages/tx/__screenshots__/TxBlobs.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..f2ff218e8d8 Binary files /dev/null and b/src/features/data-availability/pages/tx/__screenshots__/TxBlobs.pw.tsx_default_base-view-1.png differ diff --git a/src/features/data-availability/pages/tx/__screenshots__/TxBlobs.pw.tsx_default_base-view-mobile-1.png b/src/features/data-availability/pages/tx/__screenshots__/TxBlobs.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index ff9431379c3..00000000000 Binary files a/src/features/data-availability/pages/tx/__screenshots__/TxBlobs.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/data-availability/pages/tx/__screenshots__/TxBlobs.pw.tsx_mobile_base-view-mobile-1.png b/src/features/data-availability/pages/tx/__screenshots__/TxBlobs.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 106d961972b..00000000000 Binary files a/src/features/data-availability/pages/tx/__screenshots__/TxBlobs.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/defi-dropdown/components/DeFiDropdown.spec.tsx b/src/features/defi-dropdown/components/DeFiDropdown.spec.tsx index 60f98225821..1e5a0be319a 100644 --- a/src/features/defi-dropdown/components/DeFiDropdown.spec.tsx +++ b/src/features/defi-dropdown/components/DeFiDropdown.spec.tsx @@ -4,7 +4,11 @@ import React from 'react'; import { afterEach, describe, expect, it } from 'vitest'; +<<<<<<< HEAD import { cleanup, render, screen } from 'vitest/lib'; +======= +import { cleanup, screen } from 'vitest/lib'; +>>>>>>> v2.13.0 import withEnvs from 'vitest/utils/mockEnvs'; const ITEMS_ENV: [ string, string ] = [ @@ -14,6 +18,10 @@ const ITEMS_ENV: [ string, string ] = [ async function renderDropdown(envs: Array<[ string, string ]>): Promise<void> { return withEnvs(envs, async() => { +<<<<<<< HEAD +======= + const { render } = await import('vitest/lib'); +>>>>>>> v2.13.0 const { 'default': DeFiDropdown } = await import('./DeFiDropdown'); render(<DeFiDropdown/>); }); diff --git a/src/features/defi-dropdown/components/DeFiDropdown.tsx b/src/features/defi-dropdown/components/DeFiDropdown.tsx index b8589b7f398..5062124e9b9 100644 --- a/src/features/defi-dropdown/components/DeFiDropdown.tsx +++ b/src/features/defi-dropdown/components/DeFiDropdown.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex, chakra } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; -import { route } from 'nextjs-routes'; import React from 'react'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; +import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; @@ -19,10 +19,10 @@ const feature = config.features.deFiDropdown; const DeFiDropdown = () => { const router = useRouter(); - const source = mixpanel.getPageType(router.pathname); + const source = analytics.getPageType(router.pathname); const handleClick = React.useCallback((content: string) => { - mixpanel.logEvent(mixpanel.EventTypes.BUTTON_CLICK, { Content: `DeFi button: ${ content }`, Source: source }); + analytics.logEvent(analytics.EventTypes.BUTTON_CLICK, { Content: `DeFi button: ${ content }`, Source: source }); }, [ source ]); if (!feature.isEnabled) { diff --git a/src/features/defi-dropdown/components/DeFiDropdownItem.tsx b/src/features/defi-dropdown/components/DeFiDropdownItem.tsx index 4af210b9adc..3bad070e42b 100644 --- a/src/features/defi-dropdown/components/DeFiDropdownItem.tsx +++ b/src/features/defi-dropdown/components/DeFiDropdownItem.tsx @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { DeFiDropdownItem as TDeFiDropdownItem } from '../types/client'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/features/dex-pools/components/entity/PoolEntity.tsx b/src/features/dex-pools/components/entity/PoolEntity.tsx index 037524da7b2..7821660b07b 100644 --- a/src/features/dex-pools/components/entity/PoolEntity.tsx +++ b/src/features/dex-pools/components/entity/PoolEntity.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex, chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type * as contractsInfo from '@blockscout/contracts-info-types'; @@ -12,9 +11,9 @@ import { getPoolTitle } from 'src/features/dex-pools/utils/get-pool-title'; import * as EntityBase from 'src/shared/entities/components'; import { distributeEntityProps } from 'src/shared/entities/utils'; +import { route } from 'src/shared/router/routes'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedTextTooltip } from 'src/toolkit/components/truncation/TruncatedTextTooltip'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; type LinkProps = EntityBase.LinkBaseProps & Pick<EntityProps, 'pool'>; @@ -88,18 +87,7 @@ const Content = chakra((props: ContentProps) => { const nameString = getPoolTitle(props.pool); return ( - <TruncatedTextTooltip label={ nameString }> - <Skeleton - loading={ props.isLoading } - display="inline-block" - whiteSpace="nowrap" - overflow="hidden" - textOverflow="ellipsis" - height="fit-content" - > - { nameString } - </Skeleton> - </TruncatedTextTooltip> + <Truncate value={ nameString } type="end" loading={ props.isLoading }/> ); }); diff --git a/src/features/dex-pools/pages/details/Pool.pw.tsx b/src/features/dex-pools/pages/details/Pool.pw.tsx index 9784c45b711..e18510dc225 100644 --- a/src/features/dex-pools/pages/details/Pool.pw.tsx +++ b/src/features/dex-pools/pages/details/Pool.pw.tsx @@ -3,6 +3,7 @@ import React from 'react'; import * as addressMock from 'src/slices/address/mocks/address'; import * as poolMock from 'src/features/dex-pools/mocks/pool'; +import { POOL } from 'src/features/dex-pools/stubs'; import config from 'src/config'; @@ -22,6 +23,8 @@ test('base view +@mobile +@dark-mode', async({ render, mockApiResponse, mockText await mockTextAd(); await mockApiResponse('contractInfo:pool', poolMock.base, { pathParams: { instanceId: config.apis.contractInfo?.instanceId, hash: addressHash } }); await mockApiResponse('core:address', addressMock.contract, { pathParams: { hash: poolMock.base.pool_id } }); + // The page requests the address of the placeholder pool before the pool query resolves + await mockApiResponse('core:address', addressMock.contract, { pathParams: { hash: POOL.pool_id } }); await mockAssetResponse(poolMock.base.quote_token_icon_url as string, './playwright/mocks/image_s.jpg'); await mockAssetResponse(poolMock.base.base_token_icon_url as string, './playwright/mocks/image_md.jpg'); const component = await render(<Pool/>, { hooksConfig }); diff --git a/src/features/dex-pools/pages/details/Pool.tsx b/src/features/dex-pools/pages/details/Pool.tsx index a010c117396..d7b6a0a91e7 100644 --- a/src/features/dex-pools/pages/details/Pool.tsx +++ b/src/features/dex-pools/pages/details/Pool.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -24,13 +23,14 @@ import isCustomAppError from 'src/shared/errors/is-custom-app-error'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import VerifyWith from 'src/shared/links/VerifyWith'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import { Image } from 'src/toolkit/chakra/image'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { Tag } from 'src/toolkit/chakra/tag'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const Pool = () => { const router = useRouter(); @@ -95,7 +95,7 @@ const Pool = () => { return ( <Skeleton loading={ isPlaceholderData } display="flex" alignItems="center" overflow="hidden"> <Flex overflow="hidden"> - <HashStringShortenDynamic hash={ data?.pool_id }/> + <Truncate value={ data?.pool_id }/> </Flex> <CopyToClipboard text={ data?.pool_id }/> </Skeleton> diff --git a/src/features/dex-pools/pages/details/__screenshots__/Pool.pw.tsx_default_base-view-mobile-dark-mode-1.png b/src/features/dex-pools/pages/details/__screenshots__/Pool.pw.tsx_default_base-view-mobile-dark-mode-1.png index 3fb09b5de88..2987bc561ff 100644 Binary files a/src/features/dex-pools/pages/details/__screenshots__/Pool.pw.tsx_default_base-view-mobile-dark-mode-1.png and b/src/features/dex-pools/pages/details/__screenshots__/Pool.pw.tsx_default_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/dex-pools/pages/details/__screenshots__/Pool.pw.tsx_mobile_base-view-mobile-dark-mode-1.png b/src/features/dex-pools/pages/details/__screenshots__/Pool.pw.tsx_mobile_base-view-mobile-dark-mode-1.png index 84257b4ce62..c38f0688095 100644 Binary files a/src/features/dex-pools/pages/details/__screenshots__/Pool.pw.tsx_mobile_base-view-mobile-dark-mode-1.png and b/src/features/dex-pools/pages/details/__screenshots__/Pool.pw.tsx_mobile_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/dex-pools/pages/index/Pools.pw.tsx b/src/features/dex-pools/pages/index/Pools.pw.tsx index 4914c434f1e..8fdb718b81b 100644 --- a/src/features/dex-pools/pages/index/Pools.pw.tsx +++ b/src/features/dex-pools/pages/index/Pools.pw.tsx @@ -4,7 +4,7 @@ import * as poolMock from 'src/features/dex-pools/mocks/pool'; import config from 'src/config'; -import { test, expect, devices } from 'playwright/lib'; +import { test, expect } from 'playwright/lib'; import Pools from './Pools'; @@ -20,20 +20,3 @@ test('base view +@dark-mode', async({ render, mockApiResponse, mockTextAd, mockA const component = await render(<Pools/>); await expect(component).toHaveScreenshot(); }); - -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - - test('base view', async({ render, mockApiResponse, mockTextAd, mockAssetResponse }) => { - await mockTextAd(); - await mockApiResponse( - 'contractInfo:pools', - { items: [ poolMock.base, poolMock.noIcons, poolMock.base ], next_page_params: undefined }, - { pathParams: { instanceId: config.apis.contractInfo?.instanceId } }, - ); - await mockAssetResponse(poolMock.base.quote_token_icon_url as string, './playwright/mocks/image_s.jpg'); - await mockAssetResponse(poolMock.base.base_token_icon_url as string, './playwright/mocks/image_s.jpg'); - const component = await render(<Pools/>); - await expect(component).toHaveScreenshot(); - }); -}); diff --git a/src/features/dex-pools/pages/index/Pools.tsx b/src/features/dex-pools/pages/index/Pools.tsx index 04c680090db..39bb0c8ca0b 100644 --- a/src/features/dex-pools/pages/index/Pools.tsx +++ b/src/features/dex-pools/pages/index/Pools.tsx @@ -1,65 +1,47 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; -import PoolsList from 'src/features/dex-pools/pages/index/PoolsList'; import PoolsTable from 'src/features/dex-pools/pages/index/PoolsTable'; import { POOL } from 'src/features/dex-pools/stubs'; import config from 'src/config'; -import useDebounce from 'src/shared/hooks/useDebounce'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { FilterInput } from 'src/toolkit/components/filters/FilterInput'; const Pools = () => { - const router = useRouter(); - const q = getQueryParamString(router.query.query); - - const [ searchTerm, setSearchTerm ] = React.useState<string>(q ?? ''); - const debouncedSearchTerm = useDebounce(searchTerm, 300); - - const poolsQuery = useQueryWithPages({ + const poolsQuery = useApiPaginatedQuery({ resourceName: 'contractInfo:pools', pathParams: { instanceId: config.apis.contractInfo?.instanceId }, - filters: { query: debouncedSearchTerm }, options: { placeholderData: { items: Array(50).fill(POOL), next_page_params: { page_token: 'a', page_size: 50 } }, }, }); - const handleSearchTermChange = React.useCallback((value: string) => { - poolsQuery.onFilterChange({ query: value }); - setSearchTerm(value); - }, [ poolsQuery ]); + const searchTerm = getQueryParamString(poolsQuery.filters.query); + const { onFilterChange } = poolsQuery; + const handleSearchTermChange = useDebouncedFilterChange((value) => onFilterChange({ query: value })); const content = poolsQuery.data?.items ? ( - <> - <Box hideFrom="lg"> - <PoolsList - items={ poolsQuery.data.items } - isLoading={ poolsQuery.isPlaceholderData } - resetKey={ poolsQuery.queryHash } - /> - </Box> - <Box hideBelow="lg"> - <PoolsTable - items={ poolsQuery.data.items } - top={ poolsQuery.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ poolsQuery.isPlaceholderData } - page={ poolsQuery.pagination.page } - resetKey={ poolsQuery.queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <PoolsTable + items={ poolsQuery.data.items } + top={ poolsQuery.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ poolsQuery.isInitialLoading } + page={ poolsQuery.pagination.page } + resetKey={ poolsQuery.queryHash } + /> + </TableContainerScrollable> ) : null; const filter = ( @@ -100,10 +82,11 @@ const Pools = () => { itemsNum={ poolsQuery.data?.items.length } emptyText="There are no pools." actionBar={ actionBar } - hasActiveFilters={ Boolean(debouncedSearchTerm) } + hasActiveFilters={ Boolean(searchTerm) } emptyStateProps={{ term: 'pool', }} + isTransitioning={ poolsQuery.isTransitioning } > { content } </DataList> diff --git a/src/features/dex-pools/pages/index/PoolsList.tsx b/src/features/dex-pools/pages/index/PoolsList.tsx deleted file mode 100644 index dec546ac8bf..00000000000 --- a/src/features/dex-pools/pages/index/PoolsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type * as contractsInfo from '@blockscout/contracts-info-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import PoolsListItem from './PoolsListItem'; - -interface Props { - items: Array<contractsInfo.Pool>; - isLoading?: boolean; - resetKey?: string; -} - -const PoolsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <PoolsListItem - key={ item.pool_id + (isLoading ? index : '') } - isLoading={ isLoading } - item={ item } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(PoolsList); diff --git a/src/features/dex-pools/pages/index/PoolsListItem.tsx b/src/features/dex-pools/pages/index/PoolsListItem.tsx deleted file mode 100644 index d449620d705..00000000000 --- a/src/features/dex-pools/pages/index/PoolsListItem.tsx +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type * as contractsInfo from '@blockscout/contracts-info-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import PoolEntity from 'src/features/dex-pools/components/entity/PoolEntity'; -import getPoolLinks from 'src/features/dex-pools/utils/get-pool-links'; - -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShorten from 'src/shared/texts/HashStringShorten'; - -import { Image } from 'src/toolkit/chakra/image'; -import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - item: contractsInfo.Pool; - isLoading?: boolean; -}; - -const PoolsListItem = ({ item, isLoading }: Props) => { - const externalLinks = getPoolLinks(item); - return ( - <ListItemMobileGrid.Container gridTemplateColumns="100px auto"> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Pool</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <PoolEntity pool={ item } fontWeight={ 700 } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - { item.is_contract && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Contract</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity address={{ hash: item.pool_id }} noIcon link={{ variant: 'secondary' }} isLoading={ isLoading } truncation="constant_long"/> - </ListItemMobileGrid.Value> - </> - ) } - - { !item.is_contract && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Pool ID</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <HashStringShorten hash={ item.pool_id } type="long"/> - <CopyToClipboard text={ item.pool_id }/> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Liquidity</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - ${ Number(item.liquidity).toLocaleString(undefined, { maximumFractionDigits: 2, notation: 'compact' }) } - </Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>View in</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - { externalLinks.map((link) => ( - <Link external href={ link.url } key={ link.url } display="inline-flex"> - <Image src={ link.image } alt={ link.title } boxSize={ 5 } mr={ 2 }/> - { link.title } - </Link> - )) } - </Skeleton> - </ListItemMobileGrid.Value> - </ListItemMobileGrid.Container> - ); -}; - -export default PoolsListItem; diff --git a/src/features/dex-pools/pages/index/PoolsTable.tsx b/src/features/dex-pools/pages/index/PoolsTable.tsx index db235dd7150..f04c86994d9 100644 --- a/src/features/dex-pools/pages/index/PoolsTable.tsx +++ b/src/features/dex-pools/pages/index/PoolsTable.tsx @@ -6,6 +6,7 @@ import type * as contractsInfo from '@blockscout/contracts-info-types'; import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -20,11 +21,14 @@ interface Props { resetKey?: string; }; +const getBaseKey = (item: contractsInfo.Pool): string => item.pool_id; + const PoolsTable = ({ items, page, isLoading, top, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( - <TableRoot minWidth="900px"> + <TableRoot minWidth="700px"> <TableHeaderSticky top={ top ?? ACTION_BAR_HEIGHT_DESKTOP }> <TableRow> <TableColumnHeader width="70%">Pool</TableColumnHeader> @@ -35,7 +39,7 @@ const PoolsTable = ({ items, page, isLoading, top, resetKey }: Props) => { </TableHeaderSticky> <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( - <PoolsTableItem key={ item.pool_id + (isLoading ? index : '') } item={ item } index={ index } page={ page } isLoading={ isLoading }/> + <PoolsTableItem key={ keys[index] } item={ item } index={ index } page={ page } isLoading={ isLoading }/> )) } <TableRow ref={ cutRef }/> </TableBody> diff --git a/src/features/dex-pools/pages/index/PoolsTableItem.tsx b/src/features/dex-pools/pages/index/PoolsTableItem.tsx index cac6aee8334..3827d077ddd 100644 --- a/src/features/dex-pools/pages/index/PoolsTableItem.tsx +++ b/src/features/dex-pools/pages/index/PoolsTableItem.tsx @@ -12,13 +12,13 @@ import getPoolLinks from 'src/features/dex-pools/utils/get-pool-links'; import getItemIndex from 'src/shared/lists/get-item-index'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShorten from 'src/shared/texts/HashStringShorten'; import { Image } from 'src/toolkit/chakra/image'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props { item: contractsInfo.Pool; @@ -54,7 +54,7 @@ const PoolsTableItem = ({ /> ) : ( <Flex color="text.secondary" alignItems="center"> - <HashStringShorten hash={ item.pool_id } type="long"/> + <Truncate value={ item.pool_id } type="middle-static" maxSymbols={ 16 }/> <CopyToClipboard text={ item.pool_id }/> </Flex> ) } diff --git a/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_dark-color-mode_base-view-dark-mode-1.png index 1c94f4b652a..e2d5fd1acf3 100644 Binary files a/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and b/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_default_base-view-dark-mode-1.png b/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_default_base-view-dark-mode-1.png index 9d5b6b75b28..e044b06a59c 100644 Binary files a/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_default_base-view-dark-mode-1.png and b/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_default_mobile-base-view-1.png b/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_default_mobile-base-view-1.png deleted file mode 100644 index 90cfb4e2f93..00000000000 Binary files a/src/features/dex-pools/pages/index/__screenshots__/Pools.pw.tsx_default_mobile-base-view-1.png and /dev/null differ diff --git a/src/features/fhe-operations/pages/tx/TxFheOperations.tsx b/src/features/fhe-operations/pages/tx/TxFheOperations.tsx index 6a722cfc9e1..11703ac3e21 100644 --- a/src/features/fhe-operations/pages/tx/TxFheOperations.tsx +++ b/src/features/fhe-operations/pages/tx/TxFheOperations.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -13,7 +12,6 @@ import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; import DataList from 'src/shared/lists/DataList'; import { FHE_OPERATIONS_RESPONSE } from '../../stubs'; -import TxFHEOperationsList from './TxFheOperationsList'; import TxFHEOperationsStats from './TxFheOperationsStats'; import TxFHEOperationsTable from './TxFheOperationsTable'; @@ -50,10 +48,7 @@ const TxFHEOperations = ({ txQuery }: Props) => { operationCount={ data.operation_count } isLoading={ isPlaceholderData } /> - <Box> - <TxFHEOperationsTable data={ data.items } isLoading={ isPlaceholderData } resetKey={ hash }/> - <TxFHEOperationsList data={ data.items } isLoading={ isPlaceholderData } resetKey={ hash }/> - </Box> + <TxFHEOperationsTable data={ data.items } isLoading={ isPlaceholderData } resetKey={ hash }/> </> ) : null; diff --git a/src/features/fhe-operations/pages/tx/TxFheOperationsList.tsx b/src/features/fhe-operations/pages/tx/TxFheOperationsList.tsx deleted file mode 100644 index 582dcf3f3fb..00000000000 --- a/src/features/fhe-operations/pages/tx/TxFheOperationsList.tsx +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import TxFHEOperationsListItem from './TxFheOperationsListItem'; - -interface Props { - data: Array<schemas['FheOperation']>; - isLoading?: boolean; - resetKey?: string; -} - -const TxFHEOperationsList = ({ data, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <Box hideFrom="lg"> - { data.slice(0, renderedItemsNum).map((item) => ( - <TxFHEOperationsListItem - key={ item.log_index } - data={ item } - isLoading={ isLoading } - /> - )) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - ); -}; - -export default React.memo(TxFHEOperationsList); diff --git a/src/features/fhe-operations/pages/tx/TxFheOperationsListItem.tsx b/src/features/fhe-operations/pages/tx/TxFheOperationsListItem.tsx deleted file mode 100644 index f5eb0ec945f..00000000000 --- a/src/features/fhe-operations/pages/tx/TxFheOperationsListItem.tsx +++ /dev/null @@ -1,78 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box, Flex, Grid, Text } from '@chakra-ui/react'; -import { capitalize } from 'es-toolkit'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Badge } from 'src/toolkit/chakra/badge'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -import { getTypeColor } from '../../utils/utils'; - -interface Props { - data: schemas['FheOperation']; - isLoading?: boolean; -} - -const TxFHEOperationsListItem = (props: Props) => { - const { data, isLoading } = props; - - return ( - <ListItemMobile> - <Flex gap={ 2 } flexWrap="wrap" alignItems="center"> - <Badge colorPalette={ getTypeColor(data.type) } loading={ isLoading }> - { capitalize(data.type) } - </Badge> - <Badge colorPalette="gray" loading={ isLoading }> - { data.fhe_type } - </Badge> - <Badge colorPalette="gray" loading={ isLoading }> - { data.is_scalar ? 'Scalar' : 'Non-scalar' } - </Badge> - </Flex> - - <Grid templateColumns="110px 1fr" rowGap={ 2 } columnGap={ 2 }> - <Text fontWeight="medium">Index</Text> - <Skeleton loading={ isLoading } color="text.secondary"> - { data.log_index } - </Skeleton> - - <Text fontWeight="medium">Operation</Text> - <Skeleton loading={ isLoading } color="text.secondary"> - { data.operation } - </Skeleton> - - <Text fontWeight="medium">HCU cost</Text> - <Skeleton loading={ isLoading } color="text.secondary"> - { data.hcu_cost.toLocaleString() } - </Skeleton> - - <Text fontWeight="medium">HCU depth</Text> - <Skeleton loading={ isLoading } color="text.secondary"> - { data.hcu_depth.toLocaleString() } - </Skeleton> - - <Text fontWeight="medium">Caller</Text> - <Box minW={ 0 }> - { data.caller && data.caller.hash ? ( - <AddressEntity - address={ data.caller } - truncation="constant" - isLoading={ isLoading } - /> - ) : ( - <Text color="text.secondary">—</Text> - ) } - </Box> - </Grid> - </ListItemMobile> - ); -}; - -export default React.memo(TxFHEOperationsListItem); diff --git a/src/features/fhe-operations/pages/tx/TxFheOperationsStats.tsx b/src/features/fhe-operations/pages/tx/TxFheOperationsStats.tsx index 1d62e5ba4be..3224163346d 100644 --- a/src/features/fhe-operations/pages/tx/TxFheOperationsStats.tsx +++ b/src/features/fhe-operations/pages/tx/TxFheOperationsStats.tsx @@ -1,8 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; interface Props { @@ -14,12 +14,7 @@ interface Props { const TxFHEOperationsStats = ({ totalHcu, maxDepthHcu, operationCount, isLoading }: Props) => { return ( - <Box - display="grid" - gridTemplateColumns={{ base: '1fr', lg: 'repeat(3, calc(33.333% - 8px))' }} - gap={ 3 } - mb={ 6 } - > + <StatsContainer mb={ 6 }> <StatsWidget label="Total HCU" hint="Sum of all Homomorphic Computation Units consumed by FHE operations in this transaction" @@ -38,7 +33,7 @@ const TxFHEOperationsStats = ({ totalHcu, maxDepthHcu, operationCount, isLoading value={ operationCount.toLocaleString() } isLoading={ isLoading } /> - </Box> + </StatsContainer> ); }; diff --git a/src/features/fhe-operations/pages/tx/TxFheOperationsTable.tsx b/src/features/fhe-operations/pages/tx/TxFheOperationsTable.tsx index d703c037fe4..befa8a99288 100644 --- a/src/features/fhe-operations/pages/tx/TxFheOperationsTable.tsx +++ b/src/features/fhe-operations/pages/tx/TxFheOperationsTable.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -9,7 +8,7 @@ import { AddressHighlightProvider } from 'src/slices/address/contexts/address-hi import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; -import { TableBody, TableColumnHeader, TableHeader, TableRoot, TableRow } from 'src/toolkit/chakra/table'; +import { TableBody, TableColumnHeader, TableContainerScrollable, TableHeader, TableRoot, TableRow } from 'src/toolkit/chakra/table'; import TxFHEOperationsTableItem from './TxFheOperationsTableItem'; @@ -24,7 +23,7 @@ const TxFHEOperationsTable = ({ data, isLoading, resetKey }: Props) => { return ( <AddressHighlightProvider> - <Box maxW="100%" overflowX="auto" hideBelow="lg"> + <TableContainerScrollable> <TableRoot tableLayout="fixed" minWidth="900px" w="100%"> <TableHeader> <TableRow> @@ -49,7 +48,7 @@ const TxFHEOperationsTable = ({ data, isLoading, resetKey }: Props) => { <TableRow ref={ cutRef }/> </TableBody> </TableRoot> - </Box> + </TableContainerScrollable> </AddressHighlightProvider> ); }; diff --git a/src/features/flashblocks/hooks/useFlashblocksSocketData.ts b/src/features/flashblocks/hooks/useFlashblocksSocketData.ts index 5e095b2b4af..aeb0bec2476 100644 --- a/src/features/flashblocks/hooks/useFlashblocksSocketData.ts +++ b/src/features/flashblocks/hooks/useFlashblocksSocketData.ts @@ -75,12 +75,8 @@ export default function useFlashblocksSocketData() { if (isPausedRef.current) { setNewItemsNum((prev) => (prev ?? 0) + newItems.length); } else { - setItems((prev) => { - if (prev.length === 0) { - setInitialTs(now); - } - return [ ...newItems, ...prev ].slice(0, MAX_FLASHBLOCKS_COUNT); - }); + setInitialTs((prev) => prev ?? now); + setItems((prev) => [ ...newItems, ...prev ].slice(0, MAX_FLASHBLOCKS_COUNT)); } setItemsNum((prev) => prev + newItems.length); diff --git a/src/features/flashblocks/pages/index/Flashblocks.tsx b/src/features/flashblocks/pages/index/Flashblocks.tsx index 1c59b763cee..060cff02378 100644 --- a/src/features/flashblocks/pages/index/Flashblocks.tsx +++ b/src/features/flashblocks/pages/index/Flashblocks.tsx @@ -8,9 +8,9 @@ import useFlashblocksSocketData from 'src/features/flashblocks/hooks/useFlashblo import config from 'src/config'; import { Switch } from 'src/toolkit/chakra/switch'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { Hint } from 'src/toolkit/components/Hint/Hint'; -import FlashblocksList from './FlashblocksList'; import FlashblocksStats from './FlashblocksStats'; import FlashblocksTable from './FlashblocksTable'; @@ -53,22 +53,14 @@ const Flashblocks = () => { label={ `Real-time ${ flashblocksFeature.name }s show the latest ${ flashblocksFeature.name }s with real-time updates in the chronological order. ` } /> </HStack> - <Box hideBelow="lg"> + <TableContainerScrollable> <FlashblocksTable items={ items } newItemsNum={ newItemsNum } onAlertLinkClick={ handleAlertLinkClick } showAlertError={ showAlertError } /> - </Box> - <Box hideFrom="lg"> - <FlashblocksList - data={ items } - newItemsNum={ newItemsNum } - onAlertLinkClick={ handleAlertLinkClick } - showAlertError={ showAlertError } - /> - </Box> + </TableContainerScrollable> </Box> ); }; diff --git a/src/features/flashblocks/pages/index/FlashblocksList.tsx b/src/features/flashblocks/pages/index/FlashblocksList.tsx deleted file mode 100644 index 470e99f9e50..00000000000 --- a/src/features/flashblocks/pages/index/FlashblocksList.tsx +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { FlashblockItem } from 'src/features/flashblocks/types/client'; - -import * as SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; - -import FlashblocksListItem from './FlashblocksListItem'; - -interface Props { - data: Array<FlashblockItem>; - newItemsNum: number | undefined; - showAlertError?: boolean; - onAlertLinkClick?: () => void; -} - -const FlashblocksList = ({ data, newItemsNum, showAlertError, onAlertLinkClick }: Props) => { - return ( - <Box> - { (newItemsNum !== undefined || showAlertError) && ( - <SocketNewItemsNotice.Mobile - type="flashblock" - num={ newItemsNum } - showErrorAlert={ showAlertError } - onLinkClick={ onAlertLinkClick } - /> - ) } - { data.map((item) => ( - <FlashblocksListItem - key={ `${ item.block_number }-${ item.index }` } - data={ item } - /> - )) } - </Box> - ); -}; - -export default React.memo(FlashblocksList); diff --git a/src/features/flashblocks/pages/index/FlashblocksListItem.tsx b/src/features/flashblocks/pages/index/FlashblocksListItem.tsx deleted file mode 100644 index 084c5f679b5..00000000000 --- a/src/features/flashblocks/pages/index/FlashblocksListItem.tsx +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; -import React from 'react'; - -import type { FlashblockItem } from 'src/features/flashblocks/types/client'; - -import FlashblockEntity from 'src/features/flashblocks/components/FlashblockEntity'; - -import Time from 'src/shared/date-and-time/Time'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Link } from 'src/toolkit/chakra/link'; - -interface Props { - data: FlashblockItem; -} - -const FlashblocksListItem = ({ data }: Props) => { - return ( - <ListItemMobile rowGap={ 3 }> - <Flex justifyContent="space-between" w="100%"> - { data.block_number ? ( - <FlashblockEntity - number={ data.block_number } - index={ data.index } - fontWeight={ 600 } - /> - ) : <Text color="text.secondary">N/A</Text> } - </Flex> - { data.timestamp && ( - <Flex columnGap={ 2 }> - <Text fontWeight={ 500 }>Timestamp</Text> - <Time color="text.secondary" timestamp={ data.timestamp } format="DD MMM, HH:mm:ss.SSS"/> - </Flex> - ) } - <Flex columnGap={ 2 }> - <Text fontWeight={ 500 }>Txn</Text> - { data.transactions_count > 0 ? ( - <Link href={ route({ - pathname: '/block/[height_or_hash]', - query: { height_or_hash: String(data.block_number), tab: 'txs' }, - }) }> - { data.transactions_count } - </Link> - ) : - <Text color="text.secondary">{ data.transactions_count }</Text> - } - </Flex> - <Flex columnGap={ 2 }> - <Text fontWeight={ 500 }>Gas used</Text> - <Text color="text.secondary">{ data.gas_used.toLocaleString() }</Text> - </Flex> - </ListItemMobile> - ); -}; - -export default FlashblocksListItem; diff --git a/src/features/flashblocks/pages/index/FlashblocksStats.tsx b/src/features/flashblocks/pages/index/FlashblocksStats.tsx index 723d40c4a0d..c7ef2d8fd00 100644 --- a/src/features/flashblocks/pages/index/FlashblocksStats.tsx +++ b/src/features/flashblocks/pages/index/FlashblocksStats.tsx @@ -1,10 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import { upperFirst } from 'es-toolkit'; import React from 'react'; import config from 'src/config'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; import { SECOND } from 'src/toolkit/utils/consts'; @@ -26,12 +26,7 @@ const FlashblocksStats = ({ itemsNum, txsNum, initialTs }: Props) => { } return ( - <Box - display="grid" - gridTemplateColumns={{ base: '1fr', lg: `repeat(3, calc(${ 100 / 3 }% - 9px))` }} - gap={{ base: 1, lg: 3 }} - mb={ 6 } - > + <StatsContainer mb={ 6 }> <StatsWidget label={ `${ upperFirst(flashblocksFeature.name) }s (sec)` } value={ timeElapsed ? Number(itemsNum / (timeElapsed / SECOND)).toLocaleString(undefined, { maximumFractionDigits: 0 }) : '-' } @@ -48,7 +43,7 @@ const FlashblocksStats = ({ itemsNum, txsNum, initialTs }: Props) => { '-' } /> - </Box> + </StatsContainer> ); }; diff --git a/src/features/flashblocks/pages/index/FlashblocksTable.tsx b/src/features/flashblocks/pages/index/FlashblocksTable.tsx index 1760679b6dd..1abfb63fad8 100644 --- a/src/features/flashblocks/pages/index/FlashblocksTable.tsx +++ b/src/features/flashblocks/pages/index/FlashblocksTable.tsx @@ -18,8 +18,11 @@ interface Props { } const FlashblocksTable = ({ items, newItemsNum, showAlertError, onAlertLinkClick }: Props) => { + + const hasTimestamp = items.some(item => item.timestamp !== undefined); + return ( - <TableRoot> + <TableRoot minW={ hasTimestamp ? '600px' : '300px' }> <TableHeaderSticky top={ 0 }> <TableRow> <TableColumnHeader width="50%"> diff --git a/src/features/flashblocks/pages/index/FlashblocksTableItem.tsx b/src/features/flashblocks/pages/index/FlashblocksTableItem.tsx index bd0c18a8f49..272b25a7a9a 100644 --- a/src/features/flashblocks/pages/index/FlashblocksTableItem.tsx +++ b/src/features/flashblocks/pages/index/FlashblocksTableItem.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { HStack, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { FlashblockItem } from 'src/features/flashblocks/types/client'; @@ -9,6 +8,7 @@ import type { FlashblockItem } from 'src/features/flashblocks/types/client'; import FlashblockEntity from 'src/features/flashblocks/components/FlashblockEntity'; import Time from 'src/shared/date-and-time/Time'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; diff --git a/src/features/gas-tracker/components/GasTrackerChart.tsx b/src/features/gas-tracker/components/GasTrackerChart.tsx index af162a3907b..2a05e08425d 100644 --- a/src/features/gas-tracker/components/GasTrackerChart.tsx +++ b/src/features/gas-tracker/components/GasTrackerChart.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex, chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -10,6 +9,7 @@ import ChartWidgetContainer from 'src/features/chain-stats/components/ChartWidge import { CHAIN_STATS_CHARTS_SECTION_GAS } from 'src/features/chain-stats/stubs/charts'; import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { ContentLoader } from 'src/toolkit/components/loaders/ContentLoader'; diff --git a/src/features/gas-tracker/components/__screenshots__/GasTrackerPriceSnippet.pw.tsx_default_loading-state-1.png b/src/features/gas-tracker/components/__screenshots__/GasTrackerPriceSnippet.pw.tsx_default_loading-state-1.png index 44dd9e4b1bd..f2000fc2b94 100644 Binary files a/src/features/gas-tracker/components/__screenshots__/GasTrackerPriceSnippet.pw.tsx_default_loading-state-1.png and b/src/features/gas-tracker/components/__screenshots__/GasTrackerPriceSnippet.pw.tsx_default_loading-state-1.png differ diff --git a/src/features/gas-tracker/pages/index/__screenshots__/GasTracker.pw.tsx_mobile_base-view-dark-mode-mobile-1.png b/src/features/gas-tracker/pages/index/__screenshots__/GasTracker.pw.tsx_mobile_base-view-dark-mode-mobile-1.png index 4626f518464..050358c5203 100644 Binary files a/src/features/gas-tracker/pages/index/__screenshots__/GasTracker.pw.tsx_mobile_base-view-dark-mode-mobile-1.png and b/src/features/gas-tracker/pages/index/__screenshots__/GasTracker.pw.tsx_mobile_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/get-gas-button/components/GetGasButton.tsx b/src/features/get-gas-button/components/GetGasButton.tsx index a9120a0d4d3..da9bd29e2d7 100644 --- a/src/features/get-gas-button/components/GetGasButton.tsx +++ b/src/features/get-gas-button/components/GetGasButton.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; import { Image } from 'src/toolkit/chakra/image'; import { Link } from 'src/toolkit/chakra/link'; @@ -16,7 +16,7 @@ const GetGasButton = () => { const isMobile = useIsMobile(); const onGetGasClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.BUTTON_CLICK, { Content: 'Get gas', Source: 'address' }); + analytics.logEvent(analytics.EventTypes.BUTTON_CLICK, { Content: 'Get gas', Source: 'address' }); }, []); if (getGasFeature.isEnabled && !isMobile) { diff --git a/src/features/hot-contracts/pages/index/HotContracts.pw.tsx b/src/features/hot-contracts/pages/index/HotContracts.pw.tsx index b3b0c2e19ee..607de46b5be 100644 --- a/src/features/hot-contracts/pages/index/HotContracts.pw.tsx +++ b/src/features/hot-contracts/pages/index/HotContracts.pw.tsx @@ -9,7 +9,7 @@ import { test, expect } from 'playwright/lib'; import HotContracts from './HotContracts'; -test('base view +@mobile', async({ render, mockTextAd, mockApiResponse, mockEnvs }) => { +test('base view', async({ render, mockTextAd, mockApiResponse, mockEnvs }) => { test.slow(); await mockEnvs([ [ 'NEXT_PUBLIC_VIEWS_TOKEN_SCAM_TOGGLE_ENABLED', 'true' ] ]); await mockTextAd(); diff --git a/src/features/hot-contracts/pages/index/HotContracts.tsx b/src/features/hot-contracts/pages/index/HotContracts.tsx index 2893481c02e..a6069fee41d 100644 --- a/src/features/hot-contracts/pages/index/HotContracts.tsx +++ b/src/features/hot-contracts/pages/index/HotContracts.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, createListCollection, Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; +import { createListCollection, Flex } from '@chakra-ui/react'; import React from 'react'; import type { HotContractsInterval, HotContractsSorting, HotContractsSortingField, HotContractsSortingValue } from 'src/features/hot-contracts/types/api'; @@ -12,34 +11,32 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import useStatsQuery from 'src/slices/chain/stats/useStatsQuery'; import HotContractsIntervalSelect from 'src/features/hot-contracts/pages/index/HotContractsIntervalSelect'; -import HotContractsList from 'src/features/hot-contracts/pages/index/HotContractsList'; import HotContractsTable from 'src/features/hot-contracts/pages/index/HotContractsTable'; import { HOT_CONTRACTS } from 'src/features/hot-contracts/stubs'; import { getIntervalValueFromQuery, SORT_OPTIONS } from 'src/features/hot-contracts/utils'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { usePaginationParams } from 'src/shared/pagination/usePaginationParams'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; import getSortValueFromQuery from 'src/shared/sort/get-sort-value-from-query'; import Sort from 'src/shared/sort/Sort'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; const sortCollection = createListCollection({ items: SORT_OPTIONS, }); const HotContracts = () => { - const router = useRouter(); - const [ interval, setInterval ] = React.useState<HotContractsInterval>(getIntervalValueFromQuery(router.query.scale)); - const [ sort, setSort ] = - React.useState<HotContractsSortingValue>(getSortValueFromQuery<HotContractsSortingValue>(router.query, SORT_OPTIONS) ?? 'default'); + const { filters } = usePaginationParams('core:stats_hot_contracts'); + const interval = getIntervalValueFromQuery(filters.scale); - const { data, isError, isPlaceholderData, pagination, onSortingChange, onFilterChange, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, sorting, onSortingChange, onFilterChange, queryHash } = useApiPaginatedQuery({ resourceName: 'core:stats_hot_contracts', - filters: { scale: interval }, - sorting: getSortParamsFromValue<HotContractsSortingValue, HotContractsSortingField, HotContractsSorting['order']>(sort), + queryParams: { scale: interval }, options: { placeholderData: { items: Array(50).fill(HOT_CONTRACTS), @@ -50,39 +47,30 @@ const HotContracts = () => { const statsQuery = useStatsQuery(); - const isLoading = isPlaceholderData || statsQuery.isPlaceholderData; + const sort = getSortValueFromQuery<HotContractsSortingValue>({ ...sorting }, SORT_OPTIONS) ?? 'default'; + const isLoading = isInitialLoading || statsQuery.isPlaceholderData; const handleSortChange = React.useCallback(({ value }: { value: Array<string> }) => { - setSort(value[0] as HotContractsSortingValue); - onSortingChange(value[0] === 'default' ? undefined : getSortParamsFromValue(value[0] as HotContractsSortingValue)); + onSortingChange( + getSortParamsFromValue<HotContractsSortingValue, HotContractsSortingField, HotContractsSorting['order']>(value[0] as HotContractsSortingValue), + ); }, [ onSortingChange ]); const handleIntervalChange = React.useCallback((newInterval: HotContractsInterval) => { - setInterval(newInterval); onFilterChange({ scale: newInterval }); }, [ onFilterChange ]); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <HotContractsList - items={ data.items } - isLoading={ isLoading } - exchangeRate={ statsQuery.data?.coin_price ?? null } - resetKey={ queryHash } - /> - </Box> - <Box hideBelow="lg"> - <HotContractsTable - items={ data.items } - isLoading={ isLoading } - sort={ sort } - setSorting={ handleSortChange } - exchangeRate={ statsQuery.data?.coin_price ?? null } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <HotContractsTable + items={ data.items } + isLoading={ isLoading } + sort={ sort } + setSorting={ handleSortChange } + exchangeRate={ statsQuery.data?.coin_price ?? null } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const actionBar = ( @@ -127,6 +115,7 @@ const HotContracts = () => { emptyStateProps={{ term: 'hot contract', }} + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/hot-contracts/pages/index/HotContractsList.tsx b/src/features/hot-contracts/pages/index/HotContractsList.tsx deleted file mode 100644 index 17a8e6f09ea..00000000000 --- a/src/features/hot-contracts/pages/index/HotContractsList.tsx +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import HotContractsListItem from './HotContractsListItem'; - -interface Props { - items: Array<schemas['HotContract']>; - isLoading?: boolean; - exchangeRate: string | null; - resetKey?: string; -} - -const HotContractsList = ({ items, isLoading, exchangeRate, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <HotContractsListItem - key={ item.contract_address.hash + (isLoading ? index : '') } - isLoading={ isLoading } - data={ item } - exchangeRate={ exchangeRate } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(HotContractsList); diff --git a/src/features/hot-contracts/pages/index/HotContractsListItem.tsx b/src/features/hot-contracts/pages/index/HotContractsListItem.tsx deleted file mode 100644 index 1bfc399869f..00000000000 --- a/src/features/hot-contracts/pages/index/HotContractsListItem.tsx +++ /dev/null @@ -1,69 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { HStack } from '@chakra-ui/react'; -import BigNumber from 'bignumber.js'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import { Reputation } from 'src/slices/token/components/entity/TokenEntity'; - -import MetadataTags from 'src/features/address-metadata/components/tag/MetadataTags'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - data: schemas['HotContract']; - isLoading?: boolean; - exchangeRate: string | null; -} - -const HotContractsListItem = ({ data, isLoading, exchangeRate }: Props) => { - const protocolTags = data?.contract_address?.metadata?.tags?.filter(tag => tag.tagType === 'protocol'); - - return ( - <ListItemMobile rowGap={ 3 } py={ 4 } textStyle="sm"> - <HStack justifyContent="space-between" width="100%"> - <AddressEntity - address={ data.contract_address } - isLoading={ isLoading } - /> - <Reputation value={ data.contract_address.reputation ?? null }/> - </HStack> - { protocolTags && protocolTags.length > 0 && ( - <MetadataTags - isLoading={ isLoading } - tags={ protocolTags } - noColors - /> - ) } - <HStack> - <Skeleton loading={ isLoading } fontWeight={ 500 } w="100px">Txn count</Skeleton> - <Skeleton loading={ isLoading }> - <span>{ Number(data.transactions_count).toLocaleString() }</span> - </Skeleton> - </HStack> - <HStack> - <Skeleton loading={ isLoading } fontWeight={ 500 } w="100px">Gas used</Skeleton> - <Skeleton loading={ isLoading }> - <span>{ BigNumber(data.total_gas_used || 0).toFormat() }</span> - </Skeleton> - </HStack> - <HStack alignItems="flex-start"> - <Skeleton loading={ isLoading } fontWeight={ 500 } w="100px">Balance</Skeleton> - <NativeCoinValue - amount={ data.balance } - loading={ isLoading } - exchangeRate={ exchangeRate } - flexWrap="wrap" - /> - </HStack> - </ListItemMobile> - ); -}; - -export default React.memo(HotContractsListItem); diff --git a/src/features/hot-contracts/pages/index/HotContractsTable.tsx b/src/features/hot-contracts/pages/index/HotContractsTable.tsx index e56fcfcd153..598149b8e92 100644 --- a/src/features/hot-contracts/pages/index/HotContractsTable.tsx +++ b/src/features/hot-contracts/pages/index/HotContractsTable.tsx @@ -9,6 +9,7 @@ import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import { currencyUnits } from 'src/slices/chain/units'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import getNextSortValue from 'src/shared/sort/get-next-sort-value'; @@ -26,6 +27,8 @@ interface Props { resetKey?: string; }; +const getBaseKey = (item: schemas['HotContract']): string => item.contract_address.hash; + const HotContractsTable = ({ items, isLoading, sort, setSorting, exchangeRate, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); @@ -34,6 +37,8 @@ const HotContractsTable = ({ items, isLoading, sort, setSorting, exchangeRate, r setSorting({ value: [ value ] }); }, [ sort, setSorting ]); + const keys = useUniqueKeys(items, getBaseKey); + return ( <TableRoot minWidth="900px"> <TableHeaderSticky top={ ACTION_BAR_HEIGHT_DESKTOP }> @@ -64,7 +69,12 @@ const HotContractsTable = ({ items, isLoading, sort, setSorting, exchangeRate, r </TableHeaderSticky> <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( - <HotContractsTableItem key={ index } isLoading={ isLoading } data={ item } exchangeRate={ exchangeRate }/> + <HotContractsTableItem + key={ keys[index] } + isLoading={ isLoading } + data={ item } + exchangeRate={ exchangeRate } + /> )) } <TableRow ref={ cutRef }/> </TableBody> diff --git a/src/features/hot-contracts/pages/index/HotContractsTableItem.tsx b/src/features/hot-contracts/pages/index/HotContractsTableItem.tsx index 03134f0a2f2..86398524b50 100644 --- a/src/features/hot-contracts/pages/index/HotContractsTableItem.tsx +++ b/src/features/hot-contracts/pages/index/HotContractsTableItem.tsx @@ -10,11 +10,12 @@ import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import { Reputation } from 'src/slices/token/components/entity/TokenEntity'; import MetadataTags from 'src/features/address-metadata/components/tag/MetadataTags'; +import { getVisibleProtocolTags } from 'src/features/address-metadata/utils/get-visible-protocol-tags'; import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props { isLoading?: boolean; @@ -27,7 +28,7 @@ const HotContractsTableItem = ({ data, exchangeRate, }: Props) => { - const protocolTags = data?.contract_address?.metadata?.tags?.filter(tag => tag.tagType === 'protocol'); + const protocolTags = getVisibleProtocolTags(data?.contract_address?.metadata?.tags); return ( <TableRow> @@ -39,7 +40,7 @@ const HotContractsTableItem = ({ /> <Reputation value={ data.contract_address.reputation ?? null } ml={ 0 }/> </HStack> - { protocolTags && protocolTags.length > 0 && ( + { protocolTags.length > 0 && ( <MetadataTags isLoading={ isLoading } tags={ protocolTags } @@ -49,10 +50,10 @@ const HotContractsTableItem = ({ ) } </TableCell> <TableCell isNumeric> - <TruncatedText text={ Number(data.transactions_count).toLocaleString() } loading={ isLoading } maxW="100%"/> + <Truncate value={ Number(data.transactions_count).toLocaleString() } type="end" loading={ isLoading } maxW="100%"/> </TableCell> <TableCell isNumeric> - <TruncatedText text={ BigNumber(data.total_gas_used || 0).toFormat() } loading={ isLoading } maxW="100%"/> + <Truncate value={ BigNumber(data.total_gas_used || 0).toFormat() } type="end" loading={ isLoading } maxW="100%"/> </TableCell> <TableCell isNumeric> <NativeCoinValue diff --git a/src/features/hot-contracts/pages/index/__screenshots__/HotContracts.pw.tsx_default_base-view-1.png b/src/features/hot-contracts/pages/index/__screenshots__/HotContracts.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..9545133ee90 Binary files /dev/null and b/src/features/hot-contracts/pages/index/__screenshots__/HotContracts.pw.tsx_default_base-view-1.png differ diff --git a/src/features/hot-contracts/pages/index/__screenshots__/HotContracts.pw.tsx_default_base-view-mobile-1.png b/src/features/hot-contracts/pages/index/__screenshots__/HotContracts.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index eba40b752c3..00000000000 Binary files a/src/features/hot-contracts/pages/index/__screenshots__/HotContracts.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/hot-contracts/pages/index/__screenshots__/HotContracts.pw.tsx_mobile_base-view-mobile-1.png b/src/features/hot-contracts/pages/index/__screenshots__/HotContracts.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 3b479dbc0e3..00000000000 Binary files a/src/features/hot-contracts/pages/index/__screenshots__/HotContracts.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/marketplace/components/MarketplaceAppIframe.tsx b/src/features/marketplace/components/MarketplaceAppIframe.tsx index 6a3b156312c..84a3acd4fa8 100644 --- a/src/features/marketplace/components/MarketplaceAppIframe.tsx +++ b/src/features/marketplace/components/MarketplaceAppIframe.tsx @@ -2,11 +2,9 @@ import { Center, chakra } from '@chakra-ui/react'; import { DappscoutIframeProvider, useDappscoutIframe } from 'dappscout-iframe'; -import React, { useCallback, useEffect, useState, useMemo } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import Web3Boundary from 'src/features/connect-wallet/components/Web3Boundary'; -import useWeb3Wallet from 'src/features/connect-wallet/hooks/useWallet'; -import essentialDappsChainsConfig from 'src/features/marketplace/chains-config/essential-dapps'; import config from 'src/config'; @@ -25,17 +23,14 @@ type ContentProps = { appUrl?: string; address?: string; message?: Record<string, unknown>; - isEssentialDapp?: boolean; className?: string; }; -const Content = chakra(({ appUrl, address, message, isEssentialDapp, className }: ContentProps) => { +const Content = chakra(({ appUrl, address, message, className }: ContentProps) => { const { iframeRef, isReady } = useDappscoutIframe(); - const web3Wallet = useWeb3Wallet({ source: 'Essential dapps' }); const [ iframeKey, setIframeKey ] = useState(0); const [ isFrameLoading, setIsFrameLoading ] = useState(true); - const [ iframeHeight, setIframeHeight ] = useState(0); useEffect(() => { setIsFrameLoading(true); @@ -52,31 +47,9 @@ const Content = chakra(({ appUrl, address, message, isEssentialDapp, className } } }, [ isFrameLoading, appUrl, iframeRef, message ]); - useEffect(() => { - const handleMessage = (event: MessageEvent) => { - try { - if (event.origin !== new URL(appUrl ?? '').origin || !isEssentialDapp) { - return; - } - switch (event.data?.type) { - case 'window-height': - setIframeHeight(Number(event.data.height)); - break; - case 'connect-wallet': - web3Wallet.connect(); - break; - } - } catch {} - }; - - window.addEventListener('message', handleMessage); - return () => window.removeEventListener('message', handleMessage); - }, [ appUrl, isEssentialDapp, web3Wallet ]); - return ( <Center flexGrow={ 1 } - minH={ isEssentialDapp ? `${ iframeHeight }px` : undefined } minW="100%" className={ className } > @@ -108,43 +81,26 @@ type Props = { appId: string; appUrl?: string; message?: Record<string, unknown>; - isEssentialDapp?: boolean; className?: string; }; const MarketplaceAppIframeContent = ({ - appId, appUrl, message, isEssentialDapp, className, + appId, appUrl, message, className, }: Props) => { const { address, - chainId: connectedChainId, sendTransaction, signMessage, signTypedData, switchChain, - } = useMarketplaceWallet(appId, isEssentialDapp); - - const [ chainId, rpcUrl ] = useMemo(() => { - let data: [ number?, string? ] = [ Number(config.chain.id), config.chain.rpcUrls[0] ]; - - if (isEssentialDapp) { - const chainConfig = essentialDappsChainsConfig()?.chains.find( - (chain) => chain.id === String(connectedChainId), - ); - if (chainConfig?.app_config?.chain?.rpcUrls[0]) { - data = [ connectedChainId, chainConfig.app_config.chain.rpcUrls[0] ]; - } - } - - return data; - }, [ isEssentialDapp, connectedChainId ]); + } = useMarketplaceWallet(appId); return ( <DappscoutIframeProvider address={ address } appUrl={ appUrl } - chainId={ chainId } - rpcUrl={ rpcUrl } + chainId={ Number(config.chain.id) } + rpcUrl={ config.chain.rpcUrls[0] } sendTransaction={ sendTransaction } signMessage={ signMessage } signTypedData={ signTypedData } @@ -154,7 +110,6 @@ const MarketplaceAppIframeContent = ({ appUrl={ appUrl } address={ address } message={ message } - isEssentialDapp={ isEssentialDapp } className={ className } /> </DappscoutIframeProvider> diff --git a/src/features/marketplace/components/MarketplaceDisclaimerModal.tsx b/src/features/marketplace/components/MarketplaceDisclaimerModal.tsx index 9a944fe16c5..a936537ed93 100644 --- a/src/features/marketplace/components/MarketplaceDisclaimerModal.tsx +++ b/src/features/marketplace/components/MarketplaceDisclaimerModal.tsx @@ -1,10 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; import { Button } from 'src/toolkit/chakra/button'; import { DialogBody, DialogContent, DialogFooter, DialogHeader, DialogRoot } from 'src/toolkit/chakra/dialog'; diff --git a/src/features/marketplace/components/SearchBarSuggestApp.tsx b/src/features/marketplace/components/SearchBarSuggestApp.tsx index a265dca4c97..cc34c174cff 100644 --- a/src/features/marketplace/components/SearchBarSuggestApp.tsx +++ b/src/features/marketplace/components/SearchBarSuggestApp.tsx @@ -1,13 +1,13 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { MarketplaceDapp } from '@blockscout/admin-rs-types'; import SearchBarSuggestItemLink from 'src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestItemLink'; +import { route } from 'src/shared/router/routes'; import highlightText from 'src/shared/texts/highlight-text'; import SpriteIcon from 'src/sprite/SpriteIcon'; diff --git a/src/features/marketplace/components/rating/MarketplaceRating.tsx b/src/features/marketplace/components/rating/MarketplaceRating.tsx index 62761b92439..7224ce3f2c3 100644 --- a/src/features/marketplace/components/rating/MarketplaceRating.tsx +++ b/src/features/marketplace/components/rating/MarketplaceRating.tsx @@ -6,7 +6,7 @@ import React from 'react'; import useIsAuth from 'src/features/account/hooks/useIsAuth'; import config from 'src/config'; -import type { EventTypes, EventPayload } from 'src/services/mixpanel'; +import type { EventTypes, EventPayload } from 'src/shared/analytics'; import type { PopoverContentProps } from 'src/toolkit/chakra/popover'; import { PopoverBody, PopoverContent, PopoverRoot } from 'src/toolkit/chakra/popover'; @@ -50,8 +50,8 @@ const MarketplaceRating = ({ { fullView && ( <> <RatingComponent defaultValue={ Math.floor(rating || 0) } readOnly key={ rating }/> - { rating && <Text fontSize="md" ml={ 2 }>{ rating }</Text> } - { ratingsTotalCount && <Text color="text.secondary" textStyle="md" ml={ 1 }>({ ratingsTotalCount })</Text> } + { Boolean(rating) && <Text fontSize="md" ml={ 2 }>{ rating }</Text> } + { Boolean(ratingsTotalCount) && <Text color="text.secondary" textStyle="md" ml={ 1 }>({ ratingsTotalCount })</Text> } </> ) } <PopoverRoot positioning={{ placement: 'bottom' }}> diff --git a/src/features/marketplace/components/rating/MarketplaceRatingPopoverContent.tsx b/src/features/marketplace/components/rating/MarketplaceRatingPopoverContent.tsx index 80ccd783bf9..a8dbafe8c3c 100644 --- a/src/features/marketplace/components/rating/MarketplaceRatingPopoverContent.tsx +++ b/src/features/marketplace/components/rating/MarketplaceRatingPopoverContent.tsx @@ -7,8 +7,8 @@ import React from 'react'; import useApiFetch from 'src/api/hooks/useApiFetch'; import config from 'src/config'; -import type { EventTypes, EventPayload } from 'src/services/mixpanel'; -import * as mixpanel from 'src/services/mixpanel'; +import type { EventTypes, EventPayload } from 'src/shared/analytics'; +import * as analytics from 'src/shared/analytics'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Rating } from 'src/toolkit/chakra/rating'; @@ -48,8 +48,8 @@ const MarketplaceRatingPopoverContent = ({ appId, userRating, source }: Props) = description: 'Your rating improves the service', }); - mixpanel.logEvent( - mixpanel.EventTypes.APP_FEEDBACK, + analytics.logEvent( + analytics.EventTypes.APP_FEEDBACK, { Action: 'Rating', Source: source, AppId: appId, Score: value }, ); } catch (error) { @@ -74,7 +74,7 @@ const MarketplaceRatingPopoverContent = ({ appId, userRating, source }: Props) = return ( <> <Flex alignItems="center" h="30px"> - { ratingValue && ( + { Boolean(ratingValue) && ( // FIXME use non-navigation icon <SpriteIcon name="navigation/verified_contracts" color="green.400" boxSize="30px" mr={ 1 } ml="-5px"/> ) } diff --git a/src/features/marketplace/context.tsx b/src/features/marketplace/context.tsx index 0872e7eede9..a94ac1d1535 100644 --- a/src/features/marketplace/context.tsx +++ b/src/features/marketplace/context.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; -import React, { createContext, useContext, useEffect, useState, useMemo } from 'react'; +import React, { createContext, useContext, useState, useMemo } from 'react'; type Props = { children: React.ReactNode; @@ -18,21 +17,8 @@ export const MarketplaceContext = createContext<TMarketplaceContext>({ }); export function MarketplaceContextProvider({ children }: Props) { - const router = useRouter(); const [ isAutoConnectDisabled, setIsAutoConnectDisabled ] = useState(false); - useEffect(() => { - const handleRouteChange = () => { - setIsAutoConnectDisabled(false); - }; - - router.events.on('routeChangeStart', handleRouteChange); - - return () => { - router.events.off('routeChangeStart', handleRouteChange); - }; - }, [ router.events ]); - const value = useMemo(() => ({ isAutoConnectDisabled, setIsAutoConnectDisabled, diff --git a/src/features/marketplace/hooks/useAutoConnectWallet.ts b/src/features/marketplace/hooks/useAutoConnectWallet.ts new file mode 100644 index 00000000000..81afd37a0d0 --- /dev/null +++ b/src/features/marketplace/hooks/useAutoConnectWallet.ts @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { useEffect, useRef } from 'react'; + +import useWeb3Wallet from 'src/features/connect-wallet/hooks/useWallet'; + +import removeQueryParam from 'src/shared/router/remove-query-param'; +import updateQueryParam from 'src/shared/router/update-query-param'; +import { useRouter } from 'src/shared/router/useRouter'; + +export default function useAutoConnectWallet() { + const router = useRouter(); + const web3Wallet = useWeb3Wallet({ source: 'Swap button' }); + const isConnectionStarted = useRef(false); + + useEffect(() => { + if (router.query.action !== 'connect') { + return; + } + + let timer: ReturnType<typeof setTimeout>; + + if (!web3Wallet.isConnected && !web3Wallet.isOpen) { + if (!isConnectionStarted.current) { + timer = setTimeout(() => { + if (!web3Wallet.isConnected) { + web3Wallet.connect(); + isConnectionStarted.current = true; + } + }, 500); + } else { + isConnectionStarted.current = false; + updateQueryParam(router, 'action', 'tooltip'); + } + } else if (web3Wallet.isConnected) { + isConnectionStarted.current = false; + removeQueryParam(router, 'action'); + } + + return () => clearTimeout(timer); + }, [ router, web3Wallet ]); +} diff --git a/src/features/marketplace/hooks/useAutoConnectWallet.tsx b/src/features/marketplace/hooks/useAutoConnectWallet.tsx deleted file mode 100644 index 3fcebcefb71..00000000000 --- a/src/features/marketplace/hooks/useAutoConnectWallet.tsx +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useRouter } from 'next/router'; -import { useEffect, useRef } from 'react'; - -import useWeb3Wallet from 'src/features/connect-wallet/hooks/useWallet'; - -import removeQueryParam from 'src/shared/router/remove-query-param'; -import updateQueryParam from 'src/shared/router/update-query-param'; - -export default function useAutoConnectWallet() { - const router = useRouter(); - const web3Wallet = useWeb3Wallet({ source: 'Swap button' }); - const isConnectionStarted = useRef(false); - - useEffect(() => { - if (router.query.action !== 'connect') { - return; - } - - let timer: ReturnType<typeof setTimeout>; - - if (!web3Wallet.isConnected && !web3Wallet.isOpen) { - if (!isConnectionStarted.current) { - timer = setTimeout(() => { - if (!web3Wallet.isConnected) { - web3Wallet.connect(); - isConnectionStarted.current = true; - } - }, 500); - } else { - isConnectionStarted.current = false; - updateQueryParam(router, 'action', 'tooltip'); - } - } else if (web3Wallet.isConnected) { - isConnectionStarted.current = false; - removeQueryParam(router, 'action'); - } - - return () => clearTimeout(timer); - }, [ router, web3Wallet ]); -} diff --git a/src/features/marketplace/hooks/useExternalDappRedirect.spec.ts b/src/features/marketplace/hooks/useExternalDappRedirect.spec.ts new file mode 100644 index 00000000000..c50b8f79c07 --- /dev/null +++ b/src/features/marketplace/hooks/useExternalDappRedirect.spec.ts @@ -0,0 +1,41 @@ +// @vitest-environment jsdom + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { renderHook } from 'vitest/lib'; + +import { useExternalDappRedirect } from './useExternalDappRedirect'; + +const DAPP_URL = 'https://app.uniswap.org/?utm_source=Blockscout'; + +const replace = vi.fn(); + +beforeEach(() => { + vi.stubGlobal('location', { ...window.location, replace }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + replace.mockReset(); +}); + +describe('useExternalDappRedirect', () => { + it('sends the user to the dapp URL when the dapp is external', () => { + renderHook(() => useExternalDappRedirect(DAPP_URL, true)); + + expect(replace).toHaveBeenCalledWith(DAPP_URL); + }); + + it('keeps the user on the page when the dapp is embedded', () => { + renderHook(() => useExternalDappRedirect(DAPP_URL, false)); + + expect(replace).not.toHaveBeenCalled(); + }); + + it('waits for the dapp URL before redirecting', () => { + const { rerender } = renderHook(({ url }) => useExternalDappRedirect(url, true), { initialProps: { url: undefined as string | undefined } }); + expect(replace).not.toHaveBeenCalled(); + + rerender({ url: DAPP_URL }); + expect(replace).toHaveBeenCalledWith(DAPP_URL); + }); +}); diff --git a/src/features/marketplace/hooks/useExternalDappRedirect.ts b/src/features/marketplace/hooks/useExternalDappRedirect.ts new file mode 100644 index 00000000000..c00218fde89 --- /dev/null +++ b/src/features/marketplace/hooks/useExternalDappRedirect.ts @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { useEffect } from 'react'; + +export function useExternalDappRedirect(appUrl: string | undefined, isExternal: boolean): void { + useEffect(() => { + if (isExternal && appUrl) { + window.location.replace(appUrl); + } + }, [ appUrl, isExternal ]); +} diff --git a/src/features/marketplace/hooks/useFavoriteApps.ts b/src/features/marketplace/hooks/useFavoriteApps.ts index b01afa95e40..6c4e1c16f3c 100644 --- a/src/features/marketplace/hooks/useFavoriteApps.ts +++ b/src/features/marketplace/hooks/useFavoriteApps.ts @@ -2,7 +2,7 @@ import React from 'react'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; const STORAGE_KEY = 'favoriteApps'; @@ -18,7 +18,7 @@ export default function useFavoriteApps() { const [ favoriteApps, setFavoriteApps ] = React.useState<Array<string>>(getFavoriteApps()); const onFavoriteClick = React.useCallback((id: string, isFavorite: boolean, source: 'Discovery view' | 'App page' | 'Banner') => { - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { Type: 'Favorite app', Info: id, Source: source }); + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Favorite app', Info: id, Source: source }); const favoriteApps = getFavoriteApps(); diff --git a/src/features/marketplace/hooks/useGraphLinks.tsx b/src/features/marketplace/hooks/useGraphLinks.ts similarity index 100% rename from src/features/marketplace/hooks/useGraphLinks.tsx rename to src/features/marketplace/hooks/useGraphLinks.ts diff --git a/src/features/marketplace/hooks/useMarketplace.ts b/src/features/marketplace/hooks/useMarketplace.ts new file mode 100644 index 00000000000..985a6e37a3d --- /dev/null +++ b/src/features/marketplace/hooks/useMarketplace.ts @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { MarketplaceCategory } from 'src/features/marketplace/types/client'; + +import * as analytics from 'src/shared/analytics'; +import useDebounce from 'src/shared/hooks/useDebounce'; +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; + +import useFavoriteApps from './useFavoriteApps'; +import useMarketplaceApps from './useMarketplaceApps'; +import useMarketplaceCategories from './useMarketplaceCategories'; + +export default function useMarketplace() { + const router = useRouter(); + const defaultCategoryId = getQueryParamString(router.query.category); + const defaultFilterQuery = getQueryParamString(router.query.filter); + + const [ selectedAppId, setSelectedAppId ] = React.useState<string | null>(null); + const [ selectedCategoryId, setSelectedCategoryId ] = React.useState<string>(MarketplaceCategory.ALL); + const [ filterQuery, setFilterQuery ] = React.useState(defaultFilterQuery); + const [ isDisclaimerModalOpen, setIsDisclaimerModalOpen ] = React.useState<boolean>(false); + + const { favoriteApps, onFavoriteClick } = useFavoriteApps(); + + const showDisclaimer = React.useCallback((id: string) => { + setSelectedAppId(id); + setIsDisclaimerModalOpen(true); + }, []); + + const debouncedFilterQuery = useDebounce(filterQuery, 500); + const clearSelectedAppId = React.useCallback(() => { + setSelectedAppId(null); + setIsDisclaimerModalOpen(false); + }, []); + + const handleCategoryChange = React.useCallback((newCategory: string) => { + analytics.logEvent(analytics.EventTypes.FILTERS, { Source: 'Marketplace', 'Filter name': newCategory }); + setSelectedCategoryId(newCategory); + }, []); + + const { + isPlaceholderData, isError, error, data, displayedApps, sorting, setSorting, refetch, + } = useMarketplaceApps(debouncedFilterQuery, selectedCategoryId, favoriteApps); + const { + isPlaceholderData: isCategoriesPlaceholderData, data: categories, + } = useMarketplaceCategories(data, isPlaceholderData); + + React.useEffect(() => { + if (!isPlaceholderData && !isError) { + const isValidDefaultCategory = categories.map(c => c.name).includes(defaultCategoryId); + isValidDefaultCategory && setSelectedCategoryId(defaultCategoryId); + } + // run only when data is loaded + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ isPlaceholderData ]); + + React.useEffect(() => { + const appId = getQueryParamString(router.query.selectedAppId); + if (appId) { + router.replace({ pathname: '/apps/[id]/info', query: { id: appId } }); + } + }, [ router.query.selectedAppId, router ]); + + React.useEffect(() => { + if (isPlaceholderData) { + return; + } + + const { query } = router; + const newQuery = { ...query }; + + if (selectedCategoryId !== MarketplaceCategory.ALL) { + newQuery.category = selectedCategoryId; + } else { + delete newQuery.category; + } + + if (debouncedFilterQuery) { + newQuery.filter = debouncedFilterQuery; + } else { + delete newQuery.filter; + } + + if (debouncedFilterQuery.length > 0) { + analytics.logEvent(analytics.EventTypes.LOCAL_SEARCH, { Source: 'Marketplace', 'Search query': debouncedFilterQuery }); + } + + router.replace({ pathname: '/apps', query: newQuery }, { shallow: true }); + // omit router in the deps because router.push() somehow modifies it + // and we get infinite re-renders then + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ debouncedFilterQuery, selectedCategoryId, isPlaceholderData ]); + + return React.useMemo(() => ({ + selectedCategoryId, + onCategoryChange: handleCategoryChange, + filterQuery: debouncedFilterQuery, + onSearchInputChange: setFilterQuery, + isPlaceholderData, + isError, + error, + categories, + apps: data, + displayedApps, + selectedAppId, + clearSelectedAppId, + favoriteApps, + onFavoriteClick, + isDisclaimerModalOpen, + showDisclaimer, + appsTotal: data?.length || 0, + isCategoriesPlaceholderData, + sorting, + setSorting, + refetch, + }), [ + selectedCategoryId, + categories, + clearSelectedAppId, + selectedAppId, + data, + displayedApps, + error, + favoriteApps, + handleCategoryChange, + onFavoriteClick, + isError, + isPlaceholderData, + debouncedFilterQuery, + isDisclaimerModalOpen, + showDisclaimer, + isCategoriesPlaceholderData, + sorting, + setSorting, + refetch, + ]); +} diff --git a/src/features/marketplace/hooks/useMarketplace.tsx b/src/features/marketplace/hooks/useMarketplace.tsx deleted file mode 100644 index 1f1b99f8043..00000000000 --- a/src/features/marketplace/hooks/useMarketplace.tsx +++ /dev/null @@ -1,144 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useRouter } from 'next/router'; -import React from 'react'; - -import { MarketplaceCategory } from 'src/features/marketplace/types/client'; - -import * as mixpanel from 'src/services/mixpanel'; -import useDebounce from 'src/shared/hooks/useDebounce'; -import getQueryParamString from 'src/shared/router/get-query-param-string'; - -import useFavoriteApps from './useFavoriteApps'; -import useMarketplaceApps from './useMarketplaceApps'; -import useMarketplaceCategories from './useMarketplaceCategories'; - -export default function useMarketplace() { - const router = useRouter(); - const defaultCategoryId = getQueryParamString(router.query.category); - const defaultFilterQuery = getQueryParamString(router.query.filter); - - const [ selectedAppId, setSelectedAppId ] = React.useState<string | null>(null); - const [ selectedCategoryId, setSelectedCategoryId ] = React.useState<string>(MarketplaceCategory.ALL); - const [ filterQuery, setFilterQuery ] = React.useState(defaultFilterQuery); - const [ isDisclaimerModalOpen, setIsDisclaimerModalOpen ] = React.useState<boolean>(false); - - const { favoriteApps, onFavoriteClick } = useFavoriteApps(); - - const showDisclaimer = React.useCallback((id: string) => { - setSelectedAppId(id); - setIsDisclaimerModalOpen(true); - }, []); - - const debouncedFilterQuery = useDebounce(filterQuery, 500); - const clearSelectedAppId = React.useCallback(() => { - setSelectedAppId(null); - setIsDisclaimerModalOpen(false); - }, []); - - const handleCategoryChange = React.useCallback((newCategory: string) => { - mixpanel.logEvent(mixpanel.EventTypes.FILTERS, { Source: 'Marketplace', 'Filter name': newCategory }); - setSelectedCategoryId(newCategory); - }, []); - - const { - isPlaceholderData, isError, error, data, displayedApps, sorting, setSorting, refetch, - } = useMarketplaceApps(debouncedFilterQuery, selectedCategoryId, favoriteApps); - const { - isPlaceholderData: isCategoriesPlaceholderData, data: categories, - } = useMarketplaceCategories(data, isPlaceholderData); - - React.useEffect(() => { - if (!isPlaceholderData && !isError) { - const isValidDefaultCategory = categories.map(c => c.name).includes(defaultCategoryId); - isValidDefaultCategory && setSelectedCategoryId(defaultCategoryId); - } - // run only when data is loaded - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ isPlaceholderData ]); - - React.useEffect(() => { - const appId = getQueryParamString(router.query.selectedAppId); - if (appId) { - router.replace({ pathname: '/apps/[id]/info', query: { id: appId } }); - } - }, [ router.query.selectedAppId, router ]); - - React.useEffect(() => { - if (isPlaceholderData) { - return; - } - - const { query } = router; - const newQuery = { ...query }; - - if (selectedCategoryId !== MarketplaceCategory.ALL) { - newQuery.category = selectedCategoryId; - } else { - delete newQuery.category; - } - - if (debouncedFilterQuery) { - newQuery.filter = debouncedFilterQuery; - } else { - delete newQuery.filter; - } - - if (debouncedFilterQuery.length > 0) { - mixpanel.logEvent(mixpanel.EventTypes.LOCAL_SEARCH, { Source: 'Marketplace', 'Search query': debouncedFilterQuery }); - } - - router.replace( - { pathname: '/apps', query: newQuery }, - undefined, - { shallow: true }, - ); - // omit router in the deps because router.push() somehow modifies it - // and we get infinite re-renders then - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ debouncedFilterQuery, selectedCategoryId, isPlaceholderData ]); - - return React.useMemo(() => ({ - selectedCategoryId, - onCategoryChange: handleCategoryChange, - filterQuery: debouncedFilterQuery, - onSearchInputChange: setFilterQuery, - isPlaceholderData, - isError, - error, - categories, - apps: data, - displayedApps, - selectedAppId, - clearSelectedAppId, - favoriteApps, - onFavoriteClick, - isDisclaimerModalOpen, - showDisclaimer, - appsTotal: data?.length || 0, - isCategoriesPlaceholderData, - sorting, - setSorting, - refetch, - }), [ - selectedCategoryId, - categories, - clearSelectedAppId, - selectedAppId, - data, - displayedApps, - error, - favoriteApps, - handleCategoryChange, - onFavoriteClick, - isError, - isPlaceholderData, - debouncedFilterQuery, - isDisclaimerModalOpen, - showDisclaimer, - isCategoriesPlaceholderData, - sorting, - setSorting, - refetch, - ]); -} diff --git a/src/features/marketplace/hooks/useMarketplaceApps.ts b/src/features/marketplace/hooks/useMarketplaceApps.ts new file mode 100644 index 00000000000..d637a889bc3 --- /dev/null +++ b/src/features/marketplace/hooks/useMarketplaceApps.ts @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { useQuery } from '@tanstack/react-query'; +import React from 'react'; + +import type { MarketplaceDapp } from '@blockscout/admin-rs-types'; +import { MarketplaceCategory } from 'src/features/marketplace/types/client'; + +import useApiFetch from 'src/api/hooks/useApiFetch'; +import useFetch from 'src/api/hooks/useFetch'; +import type { ResourceError } from 'src/api/resources'; + +import useIsAuth from 'src/features/account/hooks/useIsAuth'; +import { MARKETPLACE_APP } from 'src/features/marketplace/stubs'; + +import config from 'src/config'; + +import type { SortValue } from '../utils/sort'; + +const feature = config.features.marketplace; + +const EMPTY_ARRAY: Array<string> = []; + +export const MARKETPLACE_APPS_PLACEHOLDER_COUNT = 20; + +function isAppNameMatches(q: string, app: MarketplaceDapp) { + return app.title.toLowerCase().includes(q.toLowerCase()); +} + +function isAppCategoryMatches(category: string, app: MarketplaceDapp, favoriteApps: Array<string> = []) { + return category === MarketplaceCategory.ALL || + (category === MarketplaceCategory.FAVORITES && favoriteApps.includes(app.id)) || + app.categories.includes(category); +} + +function sortApps(apps: Array<MarketplaceDapp>, favoriteApps: Array<string> = [], sorting: SortValue | undefined) { + return apps.sort((a, b) => { + const priorityA = a.priority || 0; + const priorityB = b.priority || 0; + // First, sort by favorite apps + if (favoriteApps.includes(a.id) !== favoriteApps.includes(b.id)) { + return favoriteApps.includes(a.id) ? -1 : 1; + } + if (sorting === 'rating_score') { + return (b.rating || 0) - (a.rating || 0); + } + if (sorting === 'rating_count') { + return (b.ratingsTotalCount || 0) - (a.ratingsTotalCount || 0); + } + // Then sort by priority (descending) + if (priorityB !== priorityA) { + return priorityB - priorityA; + } + // If priority is the same, sort by internalWallet (true first) + if (a.internalWallet !== b.internalWallet) { + return a.internalWallet ? -1 : 1; + } + // If internalWallet is also the same, sort by external (false first) + if (a.external !== b.external) { + return a.external ? 1 : -1; + } + // If all criteria are the same, keep original order (stable sort) + return 0; + }); +} + +export default function useMarketplaceApps( + filter: string, + selectedCategoryId: string = MarketplaceCategory.ALL, + favoriteApps: Array<string> = EMPTY_ARRAY, +) { + const fetch = useFetch(); + const apiFetch = useApiFetch(); + const isAuth = useIsAuth(); + + const [ sorting, setSorting ] = React.useState<SortValue>(); + // Use a ref to keep initial favorite apps and sorting while favorite / un-favorite apps + const favoriteAppsRef = React.useRef(favoriteApps); + + const { + isPlaceholderData, isError, error, data, refetch, + } = useQuery<unknown, ResourceError<unknown>, Array<MarketplaceDapp>>({ + queryKey: [ 'marketplace-dapps', { isAuth } ], + queryFn: async() => { + if (!feature.isEnabled) { + return []; + } else if ('configUrl' in feature) { + return fetch<Array<MarketplaceDapp>, unknown>(feature.configUrl, undefined, { resource: 'marketplace-dapps' }); + } else { + return apiFetch('admin:marketplace_dapps', { pathParams: { instanceId: config.apis.admin?.instanceId } }); + } + }, + select: (data) => sortApps(data as Array<MarketplaceDapp>, favoriteAppsRef.current, sorting), + placeholderData: feature.isEnabled ? Array(MARKETPLACE_APPS_PLACEHOLDER_COUNT).fill(MARKETPLACE_APP) : undefined, + staleTime: Infinity, + enabled: feature.isEnabled, + }); + + const displayedApps = React.useMemo(() => { + if (isPlaceholderData) { + return data || []; + } + + return data?.filter(app => isAppNameMatches(filter, app) && isAppCategoryMatches(selectedCategoryId, app, favoriteApps)) || []; + }, [ selectedCategoryId, data, filter, favoriteApps, isPlaceholderData ]); + + return React.useMemo(() => ({ + data, + displayedApps, + error, + isError, + isPlaceholderData, + sorting, + setSorting, + refetch, + }), [ + data, + displayedApps, + error, + isError, + isPlaceholderData, + sorting, + setSorting, + refetch, + ]); +} diff --git a/src/features/marketplace/hooks/useMarketplaceApps.tsx b/src/features/marketplace/hooks/useMarketplaceApps.tsx deleted file mode 100644 index 47224f5df96..00000000000 --- a/src/features/marketplace/hooks/useMarketplaceApps.tsx +++ /dev/null @@ -1,130 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useQuery } from '@tanstack/react-query'; -import React from 'react'; - -import type { MarketplaceDapp } from '@blockscout/admin-rs-types'; -import { MarketplaceCategory } from 'src/features/marketplace/types/client'; - -import useApiFetch from 'src/api/hooks/useApiFetch'; -import useFetch from 'src/api/hooks/useFetch'; -import type { ResourceError } from 'src/api/resources'; - -import useIsAuth from 'src/features/account/hooks/useIsAuth'; -import { MARKETPLACE_APP } from 'src/features/marketplace/stubs'; - -import config from 'src/config'; - -import type { SortValue } from '../utils/sort'; - -const feature = config.features.marketplace; - -const EMPTY_ARRAY: Array<string> = []; - -export const MARKETPLACE_APPS_PLACEHOLDER_COUNT = 20; - -function isAppNameMatches(q: string, app: MarketplaceDapp) { - return app.title.toLowerCase().includes(q.toLowerCase()); -} - -function isAppCategoryMatches(category: string, app: MarketplaceDapp, favoriteApps: Array<string> = []) { - return category === MarketplaceCategory.ALL || - (category === MarketplaceCategory.FAVORITES && favoriteApps.includes(app.id)) || - app.categories.includes(category); -} - -function sortApps(apps: Array<MarketplaceDapp>, favoriteApps: Array<string> = [], sorting: SortValue | undefined) { - return apps.sort((a, b) => { - const priorityA = a.priority || 0; - const priorityB = b.priority || 0; - // First, sort by favorite apps - if (favoriteApps.includes(a.id) !== favoriteApps.includes(b.id)) { - return favoriteApps.includes(a.id) ? -1 : 1; - } - if (sorting === 'rating_score') { - return (b.rating || 0) - (a.rating || 0); - } - if (sorting === 'rating_count') { - return (b.ratingsTotalCount || 0) - (a.ratingsTotalCount || 0); - } - // Then sort by priority (descending) - if (priorityB !== priorityA) { - return priorityB - priorityA; - } - // If priority is the same, sort by internalWallet (true first) - if (a.internalWallet !== b.internalWallet) { - return a.internalWallet ? -1 : 1; - } - // If internalWallet is also the same, sort by external (false first) - if (a.external !== b.external) { - return a.external ? 1 : -1; - } - // If all criteria are the same, keep original order (stable sort) - return 0; - }); -} - -export default function useMarketplaceApps( - filter: string, - selectedCategoryId: string = MarketplaceCategory.ALL, - favoriteApps: Array<string> = EMPTY_ARRAY, -) { - const fetch = useFetch(); - const apiFetch = useApiFetch(); - const isAuth = useIsAuth(); - - const [ sorting, setSorting ] = React.useState<SortValue>(); - // Use a ref to keep initial favorite apps and sorting while favorite / un-favorite apps - const favoriteAppsRef = React.useRef(favoriteApps); - - const { - isPlaceholderData, isError, error, data, refetch, - } = useQuery<unknown, ResourceError<unknown>, Array<MarketplaceDapp>>({ - queryKey: [ 'marketplace-dapps' ], - queryFn: async() => { - if (!feature.isEnabled) { - return []; - } else if ('configUrl' in feature) { - return fetch<Array<MarketplaceDapp>, unknown>(feature.configUrl, undefined, { resource: 'marketplace-dapps' }); - } else { - return apiFetch('admin:marketplace_dapps', { pathParams: { instanceId: config.apis.admin?.instanceId } }); - } - }, - select: (data) => sortApps(data as Array<MarketplaceDapp>, favoriteAppsRef.current, sorting), - placeholderData: feature.isEnabled ? Array(MARKETPLACE_APPS_PLACEHOLDER_COUNT).fill(MARKETPLACE_APP) : undefined, - staleTime: Infinity, - enabled: feature.isEnabled, - }); - - React.useEffect(() => { - refetch(); - }, [ isAuth, refetch ]); - - const displayedApps = React.useMemo(() => { - if (isPlaceholderData) { - return data || []; - } - - return data?.filter(app => isAppNameMatches(filter, app) && isAppCategoryMatches(selectedCategoryId, app, favoriteApps)) || []; - }, [ selectedCategoryId, data, filter, favoriteApps, isPlaceholderData ]); - - return React.useMemo(() => ({ - data, - displayedApps, - error, - isError, - isPlaceholderData, - sorting, - setSorting, - refetch, - }), [ - data, - displayedApps, - error, - isError, - isPlaceholderData, - sorting, - setSorting, - refetch, - ]); -} diff --git a/src/features/marketplace/hooks/useMarketplaceCategories.tsx b/src/features/marketplace/hooks/useMarketplaceCategories.ts similarity index 100% rename from src/features/marketplace/hooks/useMarketplaceCategories.tsx rename to src/features/marketplace/hooks/useMarketplaceCategories.ts diff --git a/src/features/marketplace/hooks/useMarketplaceWallet.ts b/src/features/marketplace/hooks/useMarketplaceWallet.ts new file mode 100644 index 00000000000..5beed79bc15 --- /dev/null +++ b/src/features/marketplace/hooks/useMarketplaceWallet.ts @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { TypedData } from 'abitype'; +import { useCallback } from 'react'; +import type { Account, SignTypedDataParameters } from 'viem'; +import { useAccount, useSendTransaction, useSwitchChain, useSignMessage, useSignTypedData } from 'wagmi'; + +import config from 'src/config'; + +import { useMarketplaceWalletActivity } from './useMarketplaceWalletActivity'; + +type SendTransactionArgs = { + chainId?: number; + mode?: 'prepared'; + to: `0x${ string }` | null; +}; + +export type SignTypedDataArgs< + TTypedData extends + | TypedData | + { + [key: string]: unknown; + } = TypedData, + TPrimaryType extends string = string, +> = SignTypedDataParameters<TTypedData, TPrimaryType, Account>; + +export default function useMarketplaceWallet(appId: string) { + const { address, chainId } = useAccount(); + const { sendTransactionAsync } = useSendTransaction(); + const { signMessageAsync } = useSignMessage(); + const { signTypedDataAsync } = useSignTypedData(); + const { switchChainAsync } = useSwitchChain(); + const { trackTransaction, logEvent } = useMarketplaceWalletActivity(appId); + + const switchChain = useCallback( + (chainId: number) => switchChainAsync({ chainId }), + [ switchChainAsync ], + ); + + const checkAndSwitchChain = useCallback(async() => { + if (Number(config.chain.id) !== chainId) { + await switchChain(Number(config.chain.id)); + } + }, [ chainId, switchChain ]); + + const sendTransaction = useCallback(async(transaction: SendTransactionArgs) => { + await checkAndSwitchChain(); + return trackTransaction(transaction.to ?? '', () => sendTransactionAsync(transaction)); + }, [ sendTransactionAsync, trackTransaction, checkAndSwitchChain ]); + + const signMessage = useCallback(async(message: string) => { + await checkAndSwitchChain(); + const signature = await signMessageAsync({ message }); + logEvent('Sign Message'); + return signature; + }, [ signMessageAsync, logEvent, checkAndSwitchChain ]); + + const signTypedData = useCallback(async(typedData: SignTypedDataArgs) => { + await checkAndSwitchChain(); + if (typedData.domain) { + typedData.domain.chainId = Number(typedData.domain.chainId); + } + const signature = await signTypedDataAsync(typedData); + logEvent('Sign Typed Data'); + return signature; + }, [ signTypedDataAsync, logEvent, checkAndSwitchChain ]); + + return { + address, + sendTransaction, + signMessage, + signTypedData, + switchChain, + }; +} diff --git a/src/features/marketplace/hooks/useMarketplaceWallet.tsx b/src/features/marketplace/hooks/useMarketplaceWallet.tsx deleted file mode 100644 index 035ae1f73a7..00000000000 --- a/src/features/marketplace/hooks/useMarketplaceWallet.tsx +++ /dev/null @@ -1,100 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { TypedData } from 'abitype'; -import { useCallback } from 'react'; -import type { Account, SignTypedDataParameters } from 'viem'; -import { useAccount, useSendTransaction, useSwitchChain, useSignMessage, useSignTypedData } from 'wagmi'; - -import useRewardsActivity from 'src/features/rewards/hooks/useRewardsActivity'; - -import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; - -type SendTransactionArgs = { - chainId?: number; - mode?: 'prepared'; - to: `0x${ string }` | null; -}; - -export type SignTypedDataArgs< - TTypedData extends - | TypedData | - { - [key: string]: unknown; - } = TypedData, - TPrimaryType extends string = string, -> = SignTypedDataParameters<TTypedData, TPrimaryType, Account>; - -export default function useMarketplaceWallet(appId: string, isEssentialDapp = false) { - const { address, chainId } = useAccount(); - const { sendTransactionAsync } = useSendTransaction(); - const { signMessageAsync } = useSignMessage(); - const { signTypedDataAsync } = useSignTypedData(); - const { switchChainAsync } = useSwitchChain(); - const { trackTransaction, trackTransactionConfirm } = useRewardsActivity(); - - const logEvent = useCallback((event: mixpanel.EventPayload<mixpanel.EventTypes.WALLET_ACTION>['Action']) => { - mixpanel.logEvent(mixpanel.EventTypes.WALLET_ACTION, { - Action: event, - Address: address, - AppId: appId, - Source: isEssentialDapp ? 'Essential dapps' : 'Dappscout', - ChainId: isEssentialDapp ? String(chainId) : undefined, - }); - }, [ address, appId, chainId, isEssentialDapp ]); - - const switchChain = useCallback( - (chainId: number) => switchChainAsync({ chainId }), - [ switchChainAsync ], - ); - - const checkAndSwitchChain = useCallback(async() => { - if (!isEssentialDapp && Number(config.chain.id) !== chainId) { - await switchChain(Number(config.chain.id)); - } - }, [ chainId, switchChain, isEssentialDapp ]); - - const sendTransaction = useCallback(async(transaction: SendTransactionArgs) => { - await checkAndSwitchChain(); - const activityResponse = await trackTransaction( - address ?? '', - transaction.to ?? '', - isEssentialDapp ? String(chainId) : undefined, - ); - const tx = await sendTransactionAsync(transaction); - if (activityResponse?.token) { - await trackTransactionConfirm(tx, activityResponse.token); - } - logEvent('Send Transaction'); - return tx; - }, [ - sendTransactionAsync, logEvent, trackTransaction, trackTransactionConfirm, - address, checkAndSwitchChain, chainId, isEssentialDapp, - ]); - - const signMessage = useCallback(async(message: string) => { - await checkAndSwitchChain(); - const signature = await signMessageAsync({ message }); - logEvent('Sign Message'); - return signature; - }, [ signMessageAsync, logEvent, checkAndSwitchChain ]); - - const signTypedData = useCallback(async(typedData: SignTypedDataArgs) => { - await checkAndSwitchChain(); - if (typedData.domain) { - typedData.domain.chainId = Number(typedData.domain.chainId); - } - const signature = await signTypedDataAsync(typedData); - logEvent('Sign Typed Data'); - return signature; - }, [ signTypedDataAsync, logEvent, checkAndSwitchChain ]); - - return { - address, - chainId, - sendTransaction, - signMessage, - signTypedData, - switchChain, - }; -} diff --git a/src/features/marketplace/hooks/useMarketplaceWalletActivity.spec.tsx b/src/features/marketplace/hooks/useMarketplaceWalletActivity.spec.tsx new file mode 100644 index 00000000000..52bb8956c15 --- /dev/null +++ b/src/features/marketplace/hooks/useMarketplaceWalletActivity.spec.tsx @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import mixpanel from 'mixpanel-browser'; +import React from 'react'; +import { http } from 'viem'; +import { createConfig, mock, WagmiProvider } from 'wagmi'; +import { connect } from 'wagmi/actions'; +import { optimism } from 'wagmi/chains'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, renderHook, waitFor } from 'vitest/lib'; +import withEnvs from 'vitest/utils/mockEnvs'; + +vi.mock('mixpanel-browser', () => ({ 'default': { init: vi.fn(), track: vi.fn() } })); + +const ACCOUNT = '0x1111111111111111111111111111111111111111'; +const RECIPIENT = '0x2222222222222222222222222222222222222222'; +const TX_HASH = `0x${ 'ab'.repeat(32) }`; +const REWARDS_ORIGIN = 'https://rewards.test'; +const REWARDS_TOKEN = 'test-rewards-token'; +const ACTIVITY_TOKEN = 'test-activity-token'; +const ENV_OVERRIDES: Array<[ string, string ]> = [ + [ 'NEXT_PUBLIC_REWARDS_SERVICE_API_HOST', REWARDS_ORIGIN ], + [ 'NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID', 'test-project' ], + [ 'NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY', 'test-captcha' ], + [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', 'test-mixpanel' ], +]; + +afterEach(() => { + cleanup(); + document.cookie = 'rewards_api_token=; Max-Age=0; path=/'; + vi.clearAllMocks(); +}); + +describe('marketplace transaction activity', () => { + it.each([ 'success', 'rejection', 'rewards unavailable', 'non-string result' ])('preserves wallet behavior and rewards for %s', async(outcome) => { + await withEnvs(ENV_OVERRIDES, async() => { + const { useMarketplaceWalletActivity } = await import('./useMarketplaceWalletActivity'); + const { RewardsContextProvider, useRewardsContext } = await import('src/features/rewards/context'); + const { getResourceKey } = await import('src/api/hooks/useApiQuery'); + const { init } = await import('src/shared/analytics/queue'); + const { getEnabledProviders } = await import('src/shared/analytics/providers'); + await init(getEnabledProviders().map((provider) => ({ provider, options: { debug: false } })), () => {}); + + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + queryClient.setQueryData(getResourceKey('core:user_info'), { address_hash: ACCOUNT }); + queryClient.setQueryData(getResourceKey('rewards:user_check_activity_pass', { queryParams: { address: ACCOUNT } }), { is_valid: true }); + const walletConfig = createConfig({ + chains: [ optimism ], + connectors: [ mock({ accounts: [ ACCOUNT ] }) ], + transports: { [optimism.id]: http() }, + storage: null, + }); + await connect(walletConfig, { connector: walletConfig.connectors[0] }); + const activityRequests: Array<{ path: string; body: unknown }> = []; + fetchMock.resetMocks(); + fetchMock.mockResponse(async(request) => { + const path = new URL(request.url).pathname; + if (path.includes('/track/transaction')) { + activityRequests.push({ path, body: JSON.parse(await request.text()) }); + if (outcome === 'rewards unavailable') { + return { status: 503, body: '{}' }; + } + return { body: JSON.stringify({ token: ACTIVITY_TOKEN }), headers: { 'content-type': 'application/json' } }; + } + return { body: JSON.stringify({ is_valid: true }), headers: { 'content-type': 'application/json' } }; + }); + + const WalletProvider = ({ children }: React.PropsWithChildren) => ( + <QueryClientProvider client={ queryClient }> + <WagmiProvider config={ walletConfig } reconnectOnMount={ false }> + <RewardsContextProvider>{ children }</RewardsContextProvider> + </WagmiProvider> + </QueryClientProvider> + ); + const { result, unmount } = renderHook(() => ({ + activity: useMarketplaceWalletActivity('swap', true), + rewards: useRewardsContext(), + }), { wrapper: WalletProvider }); + act(() => result.current.rewards.onLoginSuccess(REWARDS_TOKEN)); + await waitFor(() => expect(result.current.rewards.isAuth).toBe(true)); + + const send = outcome === 'rejection' ? + async() => { + throw new Error('Wallet rejected transaction'); + } : + async() => outcome === 'non-string result' ? { hash: TX_HASH } : TX_HASH; + if (outcome === 'rejection') { + await expect(result.current.activity.trackTransaction(RECIPIENT, send)).rejects.toThrow('Wallet rejected transaction'); + } else { + expect(await result.current.activity.trackTransaction(RECIPIENT, send)).toEqual( + outcome === 'non-string result' ? { hash: TX_HASH } : TX_HASH, + ); + } + + expect(activityRequests[0]).toEqual({ + path: '/api/v1/user/activity/track/transaction', + body: { from_address: ACCOUNT, to_address: RECIPIENT, chain_id: '10' }, + }); + if (outcome === 'success') { + expect(activityRequests[1]).toEqual({ + path: '/api/v1/activity/track/transaction/confirm', + body: { tx_hash: TX_HASH, token: ACTIVITY_TOKEN }, + }); + } else { + expect(activityRequests).toHaveLength(1); + } + if (outcome === 'rejection') { + expect(mixpanel.track).not.toHaveBeenCalled(); + } else { + expect(mixpanel.track).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ + Action: 'Send Transaction', Address: ACCOUNT, AppId: 'swap', Source: 'Essential dapps', ChainId: '10', + }), undefined); + } + unmount(); + queryClient.clear(); + }); + }); +}); diff --git a/src/features/marketplace/hooks/useMarketplaceWalletActivity.ts b/src/features/marketplace/hooks/useMarketplaceWalletActivity.ts new file mode 100644 index 00000000000..0000f7f1a02 --- /dev/null +++ b/src/features/marketplace/hooks/useMarketplaceWalletActivity.ts @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { useCallback } from 'react'; +import { useAccount } from 'wagmi'; + +import useRewardsActivity from 'src/features/rewards/hooks/useRewardsActivity'; + +import * as analytics from 'src/shared/analytics'; + +type WalletAction = analytics.EventPayload<analytics.EventTypes.WALLET_ACTION>['Action']; + +interface WalletActivity { + readonly logEvent: (action: WalletAction) => void; + readonly prepareTransaction: (to: string) => Promise<(hash: string) => Promise<void>>; + readonly trackTransaction: <TResult>(to: string, send: () => Promise<TResult>) => Promise<TResult>; +} + +export function useMarketplaceWalletActivity(appId: string, isEssentialDapp = false): WalletActivity { + const { address, chainId } = useAccount(); + const { trackTransaction, trackTransactionConfirm } = useRewardsActivity(); + + const logEvent = useCallback((action: WalletAction) => { + analytics.logEvent(analytics.EventTypes.WALLET_ACTION, { + Action: action, + Address: address, + AppId: appId, + Source: isEssentialDapp ? 'Essential dapps' : 'Dappscout', + ChainId: isEssentialDapp ? String(chainId) : undefined, + }); + }, [ address, appId, chainId, isEssentialDapp ]); + + const prepareTransaction = useCallback(async(to: string) => { + const activity = await trackTransaction(address ?? '', to, isEssentialDapp ? String(chainId) : undefined); + return async(hash: string) => { + if (activity?.token) { + await trackTransactionConfirm(hash, activity.token); + } + }; + }, [ address, chainId, isEssentialDapp, trackTransaction, trackTransactionConfirm ]); + + const sendTrackedTransaction = useCallback(async<TResult>(to: string, send: () => Promise<TResult>): Promise<TResult> => { + const confirmTransaction = await prepareTransaction(to); + const result = await send(); + if (typeof result === 'string') { + await confirmTransaction(result); + } + logEvent('Send Transaction'); + return result; + }, [ prepareTransaction, logEvent ]); + + return { logEvent, prepareTransaction, trackTransaction: sendTrackedTransaction }; +} diff --git a/src/features/marketplace/pages/dapp-info/MarketplaceAppInfoPage.tsx b/src/features/marketplace/pages/dapp-info/MarketplaceAppInfoPage.tsx index 3f891880f92..155bfe1f77e 100644 --- a/src/features/marketplace/pages/dapp-info/MarketplaceAppInfoPage.tsx +++ b/src/features/marketplace/pages/dapp-info/MarketplaceAppInfoPage.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex, HStack, Text } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import type { MouseEvent } from 'react'; import React from 'react'; @@ -14,6 +13,7 @@ import throwOnAbsentParamError from 'src/shared/errors/throw-on-absent-param-err import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import type { IconName } from 'src/sprite/SpriteIcon'; import SpriteIcon from 'src/sprite/SpriteIcon'; diff --git a/src/features/marketplace/pages/dapp-info/__screenshots__/MarketplaceAppInfoPage.pw.tsx_default_base-view-mobile-1.png b/src/features/marketplace/pages/dapp-info/__screenshots__/MarketplaceAppInfoPage.pw.tsx_default_base-view-mobile-1.png index 52ed04a5069..5cd8f1e57e0 100644 Binary files a/src/features/marketplace/pages/dapp-info/__screenshots__/MarketplaceAppInfoPage.pw.tsx_default_base-view-mobile-1.png and b/src/features/marketplace/pages/dapp-info/__screenshots__/MarketplaceAppInfoPage.pw.tsx_default_base-view-mobile-1.png differ diff --git a/src/features/marketplace/pages/dapp-info/__screenshots__/MarketplaceAppInfoPage.pw.tsx_mobile_base-view-mobile-1.png b/src/features/marketplace/pages/dapp-info/__screenshots__/MarketplaceAppInfoPage.pw.tsx_mobile_base-view-mobile-1.png index 358fccd2dde..ff3d6d147b5 100644 Binary files a/src/features/marketplace/pages/dapp-info/__screenshots__/MarketplaceAppInfoPage.pw.tsx_mobile_base-view-mobile-1.png and b/src/features/marketplace/pages/dapp-info/__screenshots__/MarketplaceAppInfoPage.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/features/marketplace/pages/dapp/MarketplaceApp.pw.tsx b/src/features/marketplace/pages/dapp/MarketplaceApp.pw.tsx index b2076c03ba7..cbf68c8b541 100644 --- a/src/features/marketplace/pages/dapp/MarketplaceApp.pw.tsx +++ b/src/features/marketplace/pages/dapp/MarketplaceApp.pw.tsx @@ -11,10 +11,11 @@ import { test, expect, devices } from 'playwright/lib'; import MarketplaceApp from './MarketplaceApp'; +const embeddedApp = { ...appsMock[0], external: false }; + const hooksConfig = { router: { - query: { id: appsMock[0].id }, - isReady: true, + query: { id: embeddedApp.id }, }, }; @@ -22,8 +23,8 @@ const testFn = async({ render, mockAssetResponse, mockEnvs, mockRpcResponse, moc await mockEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_ENABLED', 'true' ], ]); - await mockApiResponse('admin:marketplace_dapp', appsMock[0], { pathParams: { instanceId: config.apis.admin?.instanceId, dappId: appsMock[0].id } }); - await mockAssetResponse(appsMock[0].url, './src/features/marketplace/mocks/dapps.html'); + await mockApiResponse('admin:marketplace_dapp', embeddedApp, { pathParams: { instanceId: config.apis.admin?.instanceId, dappId: embeddedApp.id } }); + await mockAssetResponse(embeddedApp.url, './src/features/marketplace/mocks/dapps.html'); await mockRpcResponse([ { Method: 'eth_chainId', ReturnType: numberToHex(Number(config.chain.id)), diff --git a/src/features/marketplace/pages/dapp/MarketplaceApp.tsx b/src/features/marketplace/pages/dapp/MarketplaceApp.tsx index 5a1039db73a..a057fa652db 100644 --- a/src/features/marketplace/pages/dapp/MarketplaceApp.tsx +++ b/src/features/marketplace/pages/dapp/MarketplaceApp.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React, { useEffect, useMemo } from 'react'; import * as metadata from 'src/shell/metadata'; @@ -14,12 +13,14 @@ import config from 'src/config'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import { useColorMode } from 'src/toolkit/chakra/color-mode'; import MarketplaceAppIframe from '../../components/MarketplaceAppIframe'; import useAppQuery from '../../hooks/useAppQuery'; import useAutoConnectWallet from '../../hooks/useAutoConnectWallet'; +import { useExternalDappRedirect } from '../../hooks/useExternalDappRedirect'; import { getAppUrl } from '../../utils/dapp'; import MarketplaceAppTopBar from './MarketplaceAppTopBar'; @@ -46,6 +47,9 @@ export default function MarketplaceApp() { [ data?.url, isPlaceholderData, router ], ); + const isExternal = !isPlaceholderData && Boolean(data?.external); + useExternalDappRedirect(appUrl, isExternal); + const message = useMemo(() => ({ blockscoutColorMode: colorMode, blockscoutRootUrl: route({ pathname: '/' }, { absolute: true }), @@ -67,6 +71,8 @@ export default function MarketplaceApp() { } }, [ data, isPlaceholderData, setIsAutoConnectDisabled ]); + useEffect(() => () => setIsAutoConnectDisabled(false), [ setIsAutoConnectDisabled ]); + throwOnResourceLoadError(query); return ( @@ -78,7 +84,7 @@ export default function MarketplaceApp() { /> <MarketplaceAppIframe appId={ id } - appUrl={ appUrl } + appUrl={ isExternal ? undefined : appUrl } message={ message } mx={{ base: -4, lg: -6 }} /> diff --git a/src/features/marketplace/pages/dapp/MarketplaceAppTopBar.tsx b/src/features/marketplace/pages/dapp/MarketplaceAppTopBar.tsx index 4eafbfe3a7b..b5f3d9cb03d 100644 --- a/src/features/marketplace/pages/dapp/MarketplaceAppTopBar.tsx +++ b/src/features/marketplace/pages/dapp/MarketplaceAppTopBar.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, Flex } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { MarketplaceDapp } from '@blockscout/admin-rs-types'; @@ -14,8 +13,9 @@ import UserProfileDesktop from 'src/features/account/components/user-profile/Use import RewardsButton from 'src/features/rewards/components/RewardsButton'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { BackToButton } from 'src/toolkit/components/buttons/BackToButton'; @@ -42,7 +42,7 @@ const MarketplaceAppTopBar = ({ appId, data, isLoading }: Props) => { }, [ appProps.referrer ]); const handleBackToClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.BUTTON_CLICK, { Content: 'Back to', Source: mixpanel.PAGE_TYPE_DICT['/apps/[id]'] }); + analytics.logEvent(analytics.EventTypes.BUTTON_CLICK, { Content: 'Back to', Source: analytics.PAGE_TYPE_DICT['/apps/[id]'] }); }, []); return ( diff --git a/src/features/marketplace/pages/dapp/__screenshots__/MarketplaceApp.pw.tsx_default_base-view-1.png b/src/features/marketplace/pages/dapp/__screenshots__/MarketplaceApp.pw.tsx_default_base-view-1.png index 87d7c00aa41..aff319dca7d 100644 Binary files a/src/features/marketplace/pages/dapp/__screenshots__/MarketplaceApp.pw.tsx_default_base-view-1.png and b/src/features/marketplace/pages/dapp/__screenshots__/MarketplaceApp.pw.tsx_default_base-view-1.png differ diff --git a/src/features/marketplace/pages/dapp/__screenshots__/MarketplaceApp.pw.tsx_default_mobile-base-view-1.png b/src/features/marketplace/pages/dapp/__screenshots__/MarketplaceApp.pw.tsx_default_mobile-base-view-1.png index 939fcdd26a2..5aa6d1d3b61 100644 Binary files a/src/features/marketplace/pages/dapp/__screenshots__/MarketplaceApp.pw.tsx_default_mobile-base-view-1.png and b/src/features/marketplace/pages/dapp/__screenshots__/MarketplaceApp.pw.tsx_default_mobile-base-view-1.png differ diff --git a/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_dark-color-mode_base-view-dark-mode-1.png index 9e0195fa4b0..39d3ea4ff82 100644 Binary files a/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and b/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_default_base-view-dark-mode-1.png b/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_default_base-view-dark-mode-1.png index 86533d1de37..d415b59ad3b 100644 Binary files a/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_default_base-view-dark-mode-1.png and b/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_default_mobile-base-view-1.png b/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_default_mobile-base-view-1.png index 543b2b81f94..a77226cc34d 100644 Binary files a/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_default_mobile-base-view-1.png and b/src/features/marketplace/pages/dapp/info/__screenshots__/MarketplaceAppInfo.pw.tsx_default_mobile-base-view-1.png differ diff --git a/src/features/marketplace/pages/essential-dapp/MarketplaceEssentialDapp.tsx b/src/features/marketplace/pages/essential-dapp/MarketplaceEssentialDapp.tsx index 348d38e6380..2eb326f946c 100644 --- a/src/features/marketplace/pages/essential-dapp/MarketplaceEssentialDapp.tsx +++ b/src/features/marketplace/pages/essential-dapp/MarketplaceEssentialDapp.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { EssentialDappsConfig } from 'src/features/marketplace/types/client'; @@ -12,6 +11,7 @@ import { ensureLoaded as ensureWeb3Runtime } from 'src/features/connect-wallet/u import config from 'src/config'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import useAutoConnectWallet from '../../hooks/useAutoConnectWallet'; import Multisend from './multisend/Multisend'; diff --git a/src/features/marketplace/pages/essential-dapp/multisend/Multisend.pw.tsx b/src/features/marketplace/pages/essential-dapp/multisend/Multisend.pw.tsx index 951519b4dfd..c9b736d416a 100644 --- a/src/features/marketplace/pages/essential-dapp/multisend/Multisend.pw.tsx +++ b/src/features/marketplace/pages/essential-dapp/multisend/Multisend.pw.tsx @@ -1,5 +1,7 @@ import React from 'react'; +import * as rpcMock from 'src/slices/block/mocks/rpc'; + import type { TestFnArgs } from 'playwright/lib'; import { test, expect } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; @@ -10,16 +12,34 @@ const ESSENTIAL_DAPPS_CONFIG = JSON.stringify({ multisend: { chains: [ '1' ] }, }); -test('base view +@dark-mode +@mobile', async({ render, mockEnvs, page }: TestFnArgs) => { +test('base view +@dark-mode +@mobile', async({ render, mockEnvs, mockRpcResponse, page }: TestFnArgs) => { await mockEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_ENABLED', 'true' ], [ 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG', ESSENTIAL_DAPPS_CONFIG ], ]); + await mockRpcResponse([ + { + Method: 'eth_getBlockByNumber', + Parameters: [ 'latest', false ], + ReturnType: rpcMock.rpcBlockBase, + }, + { + Method: 'eth_gasPrice', + ReturnType: '0x1', + }, + ]); + + // the widget mounts after the lazy wallet stack and shows a loader in the token input until its + // chains-info request settles; an explicit error answers faster and more predictably than the abort + await page.route('https://api.multisender.app/chain-info/chains', (route) => route.fulfill({ status: 500 })); const component = await render(<Multisend/>); + await expect(component.getByPlaceholder('Select a token or enter token address')).toBeVisible(); + await expect(component.locator('.mantine-Loader-root')).toBeHidden(); + // the CSV editor is CodeMirror, whose placeholder settles its font a frame or two after mount await expect(component).toHaveScreenshot({ - mask: [ page.locator(pwConfig.adsBannerSelector) ], + mask: [ page.locator(pwConfig.adsBannerSelector), component.locator('.cm-editor') ], maskColor: pwConfig.maskColor, }); }); diff --git a/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png b/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png index 4d9f4aae946..e9f25203450 100644 Binary files a/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png and b/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_default_base-view-dark-mode-mobile-1.png b/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_default_base-view-dark-mode-mobile-1.png index 4d4eda750fb..d0263992d6f 100644 Binary files a/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_default_base-view-dark-mode-mobile-1.png and b/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_default_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_mobile_base-view-dark-mode-mobile-1.png b/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_mobile_base-view-dark-mode-mobile-1.png index a9a234e17a5..d2413d4ebc9 100644 Binary files a/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_mobile_base-view-dark-mode-mobile-1.png and b/src/features/marketplace/pages/essential-dapp/multisend/__screenshots__/Multisend.pw.tsx_mobile_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/marketplace/pages/essential-dapp/revoke/Revoke.pw.tsx b/src/features/marketplace/pages/essential-dapp/revoke/Revoke.pw.tsx index 557f8b7b812..e4396937fdf 100644 --- a/src/features/marketplace/pages/essential-dapp/revoke/Revoke.pw.tsx +++ b/src/features/marketplace/pages/essential-dapp/revoke/Revoke.pw.tsx @@ -1,5 +1,7 @@ import React from 'react'; +import * as statsMock from 'src/slices/chain/stats/mocks'; + import * as chainDataMock from 'src/features/multichain/mocks/chains'; import { test, expect } from 'playwright/lib'; @@ -10,13 +12,16 @@ const ESSENTIAL_DAPPS_CONFIG = JSON.stringify({ revoke: { chains: [ chainDataMock.chainA.id ] }, }); -test('base view +@dark-mode +@mobile', async({ render, mockEnvs, mockEssentialDappsChainsConfig, mockAssetResponse }) => { +test('base view +@dark-mode +@mobile', async({ render, mockEnvs, mockEssentialDappsChainsConfig, mockAssetResponse, mockApiResponse }) => { await mockEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_ENABLED', 'true' ], [ 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG', ESSENTIAL_DAPPS_CONFIG ], ]); await mockEssentialDappsChainsConfig(); await mockAssetResponse(chainDataMock.chainA.logo as string, './playwright/mocks/image_s.jpg'); + // No wallet is connected, so the balance hook asks for an empty address + await mockApiResponse('core:address', null as never, { pathParams: { hash: '' }, chainConfig: chainDataMock.chainA, status: 404 }); + await mockApiResponse('core:stats', statsMock.base, { chainConfig: chainDataMock.chainA }); const component = await render(<Revoke/>); diff --git a/src/features/marketplace/pages/essential-dapp/revoke/Revoke.tsx b/src/features/marketplace/pages/essential-dapp/revoke/Revoke.tsx index 44cf0138904..f13af4be6e8 100644 --- a/src/features/marketplace/pages/essential-dapp/revoke/Revoke.tsx +++ b/src/features/marketplace/pages/essential-dapp/revoke/Revoke.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex, Text } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React, { useMemo, useCallback, useEffect, useState } from 'react'; import { isAddress } from 'viem'; import type { PublicClient } from 'viem'; @@ -14,10 +13,11 @@ import useWeb3Wallet from 'src/features/connect-wallet/hooks/useWallet'; import essentialDappsChainsConfig from 'src/features/marketplace/chains-config/essential-dapps'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { useQueryParams } from 'src/shared/router/useQueryParams'; +import { useRouter } from 'src/shared/router/useRouter'; import { Button } from 'src/toolkit/chakra/button'; import { EmptyState } from 'src/toolkit/chakra/empty-state'; @@ -74,7 +74,7 @@ const RevokeContent = () => { const handleChainValueChange = useCallback(({ value }: { value: Array<string> }) => { setSelectedChainId(value); setApprovalsPage(1); - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Chain switch', Info: value[0], Source: 'Revoke essential dapp', diff --git a/src/features/marketplace/pages/essential-dapp/revoke/__screenshots__/Revoke.pw.tsx_mobile_base-view-dark-mode-mobile-1.png b/src/features/marketplace/pages/essential-dapp/revoke/__screenshots__/Revoke.pw.tsx_mobile_base-view-dark-mode-mobile-1.png index 312569993f7..2165c8f4fe5 100644 Binary files a/src/features/marketplace/pages/essential-dapp/revoke/__screenshots__/Revoke.pw.tsx_mobile_base-view-dark-mode-mobile-1.png and b/src/features/marketplace/pages/essential-dapp/revoke/__screenshots__/Revoke.pw.tsx_mobile_base-view-dark-mode-mobile-1.png differ diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/Approvals.tsx b/src/features/marketplace/pages/essential-dapp/revoke/components/Approvals.tsx index 805df7656f0..5d9fdb4726e 100644 --- a/src/features/marketplace/pages/essential-dapp/revoke/components/Approvals.tsx +++ b/src/features/marketplace/pages/essential-dapp/revoke/components/Approvals.tsx @@ -12,8 +12,9 @@ import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import { APPROVALS_STICKY_SUMMARY_BOTTOM_PADDING, APPROVALS_STICKY_SUMMARY_HEIGHT } from '../constants'; -import ApprovalsList from './ApprovalsList'; import ApprovalsTable from './ApprovalsTable'; type Props = { @@ -55,29 +56,17 @@ export default function Approvals({ ) : null; const content = ( - <> - <Box hideFrom="lg"> - <ApprovalsList - selectedChain={ selectedChain } - approvals={ approvals } - isLoading={ isLoading } - isAddressMatch={ isAddressMatch } - hideApproval={ hideApproval } - resetKey={ resetKey } - /> - </Box> - <Box hideBelow="lg"> - <ApprovalsTable - selectedChain={ selectedChain } - approvals={ approvals } - isLoading={ isLoading } - isAddressMatch={ isAddressMatch } - hideApproval={ hideApproval } - tableHeaderTop={ tableHeaderTop } - resetKey={ resetKey } - /> - </Box> - </> + <TableContainerScrollable> + <ApprovalsTable + selectedChain={ selectedChain } + approvals={ approvals } + isLoading={ isLoading } + isAddressMatch={ isAddressMatch } + hideApproval={ hideApproval } + tableHeaderTop={ tableHeaderTop } + resetKey={ resetKey } + /> + </TableContainerScrollable> ); return ( diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/ApprovalsList.tsx b/src/features/marketplace/pages/essential-dapp/revoke/components/ApprovalsList.tsx deleted file mode 100644 index 9c3196c08be..00000000000 --- a/src/features/marketplace/pages/essential-dapp/revoke/components/ApprovalsList.tsx +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box, Flex } from '@chakra-ui/react'; -import React from 'react'; - -import type { AllowanceType } from '../types'; -import type { EssentialDappsChainConfig } from 'src/features/marketplace/types/client'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ApprovalsListItem from './ApprovalsListItem'; - -type Props = { - selectedChain: EssentialDappsChainConfig | undefined; - approvals: Array<AllowanceType>; - isLoading?: boolean; - isAddressMatch?: boolean; - hideApproval: (approval: AllowanceType) => void; - resetKey?: string; -}; - -export default function ApprovalsList({ - selectedChain, - approvals, - isLoading, - isAddressMatch, - hideApproval, - resetKey, -}: Props) { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: approvals, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Flex flexDirection="column"> - { approvals.slice(0, renderedItemsNum).map((approval, index) => ( - <ApprovalsListItem - key={ index } - selectedChain={ selectedChain } - approval={ approval } - isLoading={ isLoading } - isAddressMatch={ isAddressMatch } - hideApproval={ hideApproval } - /> - )) } - </Flex> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -} diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/ApprovalsListItem.tsx b/src/features/marketplace/pages/essential-dapp/revoke/components/ApprovalsListItem.tsx deleted file mode 100644 index b89ea9217d7..00000000000 --- a/src/features/marketplace/pages/essential-dapp/revoke/components/ApprovalsListItem.tsx +++ /dev/null @@ -1,140 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Text } from '@chakra-ui/react'; -import { useCallback, useState } from 'react'; - -import type { AllowanceType } from '../types'; -import type { EssentialDappsChainConfig } from 'src/features/marketplace/types/client'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; - -import dayjs from 'src/shared/date-and-time/dayjs'; -import Time from 'src/shared/date-and-time/Time'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import NumberEntity from 'src/shared/numbers/NumberEntity'; - -import { Button } from 'src/toolkit/chakra/button'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -import useRevoke from '../hooks/useRevoke'; -import formatAllowance, { getAllowancePostfix } from '../lib/formatAllowance'; -import formatUsdValue from '../lib/formatUsdValue'; - -type Props = { - selectedChain: EssentialDappsChainConfig | undefined; - approval: AllowanceType; - isLoading?: boolean; - isAddressMatch?: boolean; - hideApproval: (approval: AllowanceType) => void; -}; - -export default function ApprovalsListItem({ - selectedChain, - approval, - isLoading, - isAddressMatch, - hideApproval, -}: Props) { - const revoke = useRevoke(selectedChain); - const [ isPending, setIsPending ] = useState(false); - - const allowance = formatAllowance(approval); - const allowancePostfix = getAllowancePostfix(approval, allowance); - const valueAtRiskUsd = formatUsdValue(approval.valueAtRiskUsd); - - const handleRevoke = useCallback(async() => { - setIsPending(true); - const success = await revoke(approval); - if (success) { - hideApproval(approval); - } - setIsPending(false); - }, [ revoke, hideApproval, approval ]); - - return ( - <ListItemMobileGrid.Container - gridTemplateColumns="minmax(0, 1fr) minmax(0, 1fr)" - fontWeight="500" - _first={{ - borderTop: 0, - paddingTop: 0, - }} - _last={{ - borderBottom: 0, - paddingBottom: 0, - }} - > - <ListItemMobileGrid.Label isLoading={ isLoading }>Token</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value display="flex" flexDir="column" gap={ 2 } color="inherit"> - <TokenEntity - token={{ - address_hash: approval.address, - type: approval.type, - symbol: approval.symbol || null, - name: approval.name || null, - icon_url: approval.tokenIcon || null, - reputation: approval.tokenReputation, - }} - isLoading={ isLoading } - noCopy - jointSymbol - chain={ selectedChain } - link={{ noIcon: true, external: true }} - /> - <AddressEntity - address={{ hash: approval.address }} - truncation="constant" - noIcon - isLoading={ isLoading } - chain={ selectedChain } - link={{ noIcon: true, external: true }} - /> - </ListItemMobileGrid.Value> - <ListItemMobileGrid.Label isLoading={ isLoading }>Approved spender</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity - address={{ hash: approval.spender }} - truncation="constant" - noIcon - isLoading={ isLoading } - chain={ selectedChain } - link={{ noIcon: true, external: true }} - /> - </ListItemMobileGrid.Value> - <ListItemMobileGrid.Label isLoading={ isLoading }>Approved amount</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value color="inherit"> - <Skeleton loading={ isLoading }> - <NumberEntity - value={ allowance } - postfix={ allowancePostfix } - /> - </Skeleton> - </ListItemMobileGrid.Value> - <ListItemMobileGrid.Label isLoading={ isLoading }>Value at risk</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value color="inherit"> - <Skeleton loading={ isLoading }> - { valueAtRiskUsd || '-' } - </Skeleton> - </ListItemMobileGrid.Value> - <ListItemMobileGrid.Label isLoading={ isLoading }>Last updated</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value color="inherit"> - <Skeleton loading={ isLoading } display="flex" flexDir="column" rowGap={ 2 }> - <Time timestamp={ approval.timestamp }/> - <Text>{ dayjs(approval.timestamp).fromNow() }</Text> - </Skeleton> - </ListItemMobileGrid.Value> - { isAddressMatch && ( - <Button - size="sm" - variant="outline" - loading={ isLoading || isPending } - onClick={ handleRevoke } - gridColumn="span 2" - > - Revoke - </Button> - ) } - </ListItemMobileGrid.Container> - ); -} diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/ApprovalsTable.tsx b/src/features/marketplace/pages/essential-dapp/revoke/components/ApprovalsTable.tsx index 284849ef5fb..029e63b4925 100644 --- a/src/features/marketplace/pages/essential-dapp/revoke/components/ApprovalsTable.tsx +++ b/src/features/marketplace/pages/essential-dapp/revoke/components/ApprovalsTable.tsx @@ -34,7 +34,7 @@ export default function ApprovalsTable({ const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: approvals, isEnabled: !isLoading, resetKey }); return ( - <TableRoot> + <TableRoot minW="1000px"> <TableHeaderSticky top={ tableHeaderTop }> <TableRow> <TableColumnHeader w="30%">Token</TableColumnHeader> diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/Content.pw.tsx b/src/features/marketplace/pages/essential-dapp/revoke/components/Content.pw.tsx index de8d32bc6bd..f7ee7416988 100644 --- a/src/features/marketplace/pages/essential-dapp/revoke/components/Content.pw.tsx +++ b/src/features/marketplace/pages/essential-dapp/revoke/components/Content.pw.tsx @@ -23,7 +23,7 @@ const approvalsQueryDataWithPagination = { total: APPROVALS_PAGE_SIZE + 1, }; -test('base view +@dark-mode +@mobile', async({ render, mockAssetResponse }: TestFnArgs) => { +test('base view with responsive summary +@dark-mode +@mobile', async({ render, mockAssetResponse }: TestFnArgs) => { const props = { selectedChain: chainDataMock.chainA, searchAddress: addressHash, diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png deleted file mode 100644 index cb00b8e1408..00000000000 Binary files a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_dark-color-mode_base-view-dark-mode-mobile-1.png and /dev/null differ diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_dark-color-mode_base-view-with-responsive-summary-dark-mode-mobile-1.png b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_dark-color-mode_base-view-with-responsive-summary-dark-mode-mobile-1.png new file mode 100644 index 00000000000..4338c7807f0 Binary files /dev/null and b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_dark-color-mode_base-view-with-responsive-summary-dark-mode-mobile-1.png differ diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_default_base-view-dark-mode-mobile-1.png b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_default_base-view-dark-mode-mobile-1.png deleted file mode 100644 index eed8c1228d4..00000000000 Binary files a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_default_base-view-dark-mode-mobile-1.png and /dev/null differ diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_default_base-view-with-responsive-summary-dark-mode-mobile-1.png b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_default_base-view-with-responsive-summary-dark-mode-mobile-1.png new file mode 100644 index 00000000000..29b9def7514 Binary files /dev/null and b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_default_base-view-with-responsive-summary-dark-mode-mobile-1.png differ diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_default_with-pagination-1.png b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_default_with-pagination-1.png index b5427412400..7520a34b06b 100644 Binary files a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_default_with-pagination-1.png and b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_default_with-pagination-1.png differ diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_mobile_base-view-dark-mode-mobile-1.png b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_mobile_base-view-dark-mode-mobile-1.png deleted file mode 100644 index 1f23510a2ed..00000000000 Binary files a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_mobile_base-view-dark-mode-mobile-1.png and /dev/null differ diff --git a/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_mobile_base-view-with-responsive-summary-dark-mode-mobile-1.png b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_mobile_base-view-with-responsive-summary-dark-mode-mobile-1.png new file mode 100644 index 00000000000..2ed56793459 Binary files /dev/null and b/src/features/marketplace/pages/essential-dapp/revoke/components/__screenshots__/Content.pw.tsx_mobile_base-view-with-responsive-summary-dark-mode-mobile-1.png differ diff --git a/src/features/marketplace/pages/essential-dapp/revoke/hooks/useApprovalsQuery.ts b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useApprovalsQuery.ts new file mode 100644 index 00000000000..0b355fa3488 --- /dev/null +++ b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useApprovalsQuery.ts @@ -0,0 +1,316 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import ERC20Artifact from '@openzeppelin/contracts/build/contracts/ERC20.json'; +import NftArtifact from '@openzeppelin/contracts/build/contracts/ERC721.json'; +import { useQuery } from '@tanstack/react-query'; +import { useCallback, useMemo, useState } from 'react'; +import { formatUnits, getAbiItem, getAddress, isAddress } from 'viem'; +import type { GetLogsParameters, PublicClient } from 'viem'; +import { usePublicClient } from 'wagmi'; + +import type { AllowanceType, ApprovalsQueryData, BaseAllowanceType } from '../types'; +import type { schemas } from '@blockscout/api-types'; +import type { EssentialDappsChainConfig } from 'src/features/marketplace/types/client'; + +import useApiFetch from 'src/api/hooks/useApiFetch'; + +import { PUBLIC_RPC_BLOCK_BATCH_SIZE } from '../constants'; +import { filterHiddenBaseAllowances, getApprovalHiddenKey, getPageBaseAllowances } from '../lib/approvalKeys'; +import createRevokeBlockscoutClient from '../lib/createRevokeBlockscoutClient'; +import { getTotalValueAtRiskUsd } from '../lib/erc20ValueAtRisk'; +import type { TokenBalanceInfo } from '../lib/erc20ValueAtRisk'; +import { shouldRethrowLocalError, shouldRetryRevokeQuery } from '../lib/errors'; +import getLogs from '../lib/getLogs'; +import { retryOnHttp429 } from '../lib/retry'; +import runParallelBatches from '../lib/runParallelBatches'; +import { ALLOWANCES } from '../stubs'; +import useGetBlockTimestamp from './useGetBlockTimestamp'; +import useSearchErc20Allowances from './useSearchErc20Allowances'; +import useSearchNftAllowances from './useSearchNftAllowances'; + +const PLACEHOLDER_DATA: ApprovalsQueryData = { + items: ALLOWANCES, + total: ALLOWANCES.length, + totalValueAtRiskUsd: 0, +}; + +function throwIfAborted(signal?: AbortSignal) { + if (signal?.aborted) { + throw new DOMException('Aborted', 'AbortError'); + } +} + +function formatErc20Allowance( + allowance: bigint, + decimals: number = 18, + totalSupply: bigint | undefined, +): string { + if (totalSupply && allowance > totalSupply) { + return 'Unlimited'; + } + + return formatUnits(allowance, decimals); +} + +function formatRecordAllowance(record: BaseAllowanceType, decimals?: number, totalSupply?: bigint): string | undefined { + if (!record.allowance) return undefined; + + if (record.type === 'ERC-20') { + return formatErc20Allowance(record.allowance, decimals, totalSupply); + } + + return record.allowance === BigInt(-1) ? 'Unlimited' : record.allowance.toString(); +} + +function sortBaseAllowances(records: Array<BaseAllowanceType>): Array<BaseAllowanceType> { + return records.sort((a, b) => { + const valueAtRiskDiff = (b.valueAtRiskUsd ?? 0) - (a.valueAtRiskUsd ?? 0); + if (valueAtRiskDiff !== 0) return valueAtRiskDiff; + + const exchangeRateDiff = parseFloat(b.exchangeRate ?? '0') - parseFloat(a.exchangeRate ?? '0'); + if (exchangeRateDiff !== 0) return exchangeRateDiff; + + if (b.blockNumber < a.blockNumber) return -1; + if (b.blockNumber > a.blockNumber) return 1; + return 0; + }); +} + +function getTokenBalanceInfo(response: Array<schemas['TokenBalance']>): Map<`0x${ string }`, TokenBalanceInfo> { + const balances = new Map<`0x${ string }`, TokenBalanceInfo>(); + + response.forEach((entry) => { + if (!entry.token?.address_hash) return; + + const tokenAddress = getAddress(entry.token.address_hash as `0x${ string }`); + + balances.set(tokenAddress, { + balance: entry.value ? BigInt(entry.value) : undefined, + exchangeRate: entry.token.exchange_rate || undefined, + decimals: entry.token.decimals === undefined || entry.token.decimals === null ? undefined : Number(entry.token.decimals), + symbol: entry.token.symbol || undefined, + name: entry.token.name || undefined, + tokenIcon: entry.token.icon_url || undefined, + tokenReputation: entry.token.reputation, + totalSupply: entry.token.total_supply ? BigInt(entry.token.total_supply) : undefined, + }); + }); + + return balances; +} + +async function getTokenBalances( + apiFetch: ReturnType<typeof useApiFetch>, + ownerAddress: string, + chain: EssentialDappsChainConfig | undefined, + signal?: AbortSignal, +): Promise<Map<`0x${ string }`, TokenBalanceInfo>> { + const response = await retryOnHttp429( + () => apiFetch('core:address_token_balances', { + pathParams: { hash: ownerAddress }, + chain, + fetchParams: { + signal, + }, + }) as Promise<Array<schemas['TokenBalance']>>, + signal, + ); + + return getTokenBalanceInfo(response); +} + +async function getTokenData( + apiFetch: ReturnType<typeof useApiFetch>, + tokenAddress: `0x${ string }`, + chain: EssentialDappsChainConfig | undefined, + signal?: AbortSignal, +): Promise<schemas['Token'] | undefined> { + try { + return await retryOnHttp429( + () => apiFetch('core:token', { + pathParams: { hash: tokenAddress }, + chain, + fetchParams: { + signal, + }, + }) as Promise<schemas['Token']>, + signal, + ); + } catch (error) { + if (shouldRethrowLocalError(error)) { + throw error; + } + + return undefined; + } +} + +function buildAllowance(record: BaseAllowanceType, tokenData: schemas['Token'] | undefined, timestamp: number): AllowanceType { + const decimals = tokenData?.decimals ? Number(tokenData.decimals) : record.decimals; + const totalSupply = tokenData?.total_supply ? BigInt(tokenData.total_supply) : record.totalSupply; + + return { + type: record.type, + address: record.address, + transactionId: record.transactionId, + tokenId: record.tokenId, + tokenIcon: tokenData?.icon_url || record.tokenIcon, + tokenReputation: tokenData?.reputation ?? record.tokenReputation ?? null, + allowance: formatRecordAllowance(record, decimals, totalSupply), + price: tokenData?.exchange_rate || record.exchangeRate, + balance: record.balance?.toString(), + valueAtRiskUsd: record.valueAtRiskUsd, + decimals, + spender: record.spender, + symbol: tokenData?.symbol || record.symbol, + name: tokenData?.name || record.name, + totalSupply, + timestamp, + }; +} + +const EMPTY_KEYS: Array<string> = []; + +interface HiddenApprovalKeysScope { + readonly scopeKey: string; + readonly keys: Array<string>; +} + +export default function useApprovalsQuery(chain: EssentialDappsChainConfig | undefined, userAddress: string, page: number) { + const apiFetch = useApiFetch(); + const getBlockTimestamp = useGetBlockTimestamp(); + const searchErc20Allowances = useSearchErc20Allowances(); + const searchNftAllowances = useSearchNftAllowances(); + const scopeKey = `${ chain?.id }:${ userAddress }`; + const [ hiddenApprovalKeysScope, setHiddenApprovalKeysScope ] = useState<HiddenApprovalKeysScope>({ scopeKey, keys: EMPTY_KEYS }); + const hiddenApprovalKeys = hiddenApprovalKeysScope.scopeKey === scopeKey ? hiddenApprovalKeysScope.keys : EMPTY_KEYS; + const chainId = chain?.id ? Number(chain.id) : undefined; + const publicClient = usePublicClient({ chainId }) as PublicClient | undefined; + + const blockscoutClient = useMemo( + () => createRevokeBlockscoutClient(chain?.id), + [ chain?.id ], + ); + + const isQueryEnabled = Boolean(userAddress) && isAddress(userAddress) && Boolean(publicClient && blockscoutClient); + const hiddenApprovalKeysKey = hiddenApprovalKeys.join(':'); + + const hideApproval = useCallback((approval: AllowanceType) => { + const key = getApprovalHiddenKey(approval); + + setHiddenApprovalKeysScope((prev) => { + const keys = prev.scopeKey === scopeKey ? prev.keys : EMPTY_KEYS; + return keys.includes(key) ? prev : { scopeKey, keys: [ ...keys, key ] }; + }); + }, [ scopeKey ]); + + const searchBaseAllowances = useCallback(async(signal?: AbortSignal): Promise<Array<BaseAllowanceType>> => { + throwIfAborted(signal); + + if (!publicClient) { + throw new Error('Public client not found'); + } + + if (!blockscoutClient) { + throw new Error('Blockscout client not found'); + } + + const latestBlockNumber = await publicClient.getBlockNumber(); + + const approvalFilter = { + event: getAbiItem({ abi: ERC20Artifact.abi, name: 'Approval' }), + args: { owner: userAddress }, + } as unknown as GetLogsParameters; + + const approvalForAllFilter = { + event: getAbiItem({ abi: NftArtifact.abi, name: 'ApprovalForAll' }), + args: { owner: userAddress }, + } as unknown as GetLogsParameters; + + const tokenBalancesPromise = getTokenBalances(apiFetch, userAddress, chain, signal); + void tokenBalancesPromise.catch(() => undefined); + + const [ approvalEvents, approvalForAllEvents ] = await Promise.all([ + getLogs(blockscoutClient, approvalFilter, BigInt(0), latestBlockNumber, signal), + getLogs(blockscoutClient, approvalForAllFilter, BigInt(0), latestBlockNumber, signal), + ]); + + const [ erc20Allowances, nftAllowances ] = await Promise.all([ + searchErc20Allowances(userAddress, approvalEvents, tokenBalancesPromise, publicClient, signal), + searchNftAllowances(userAddress, approvalEvents, approvalForAllEvents, publicClient, signal), + ]); + + return sortBaseAllowances([ ...erc20Allowances, ...nftAllowances ]); + }, [ apiFetch, blockscoutClient, chain, publicClient, searchErc20Allowances, searchNftAllowances, userAddress ]); + + const baseQuery = useQuery({ + queryKey: [ 'revoke:approvals:base', chain?.id, userAddress ], + queryFn: ({ signal }) => searchBaseAllowances(signal), + enabled: isQueryEnabled, + retry: shouldRetryRevokeQuery, + throwOnError: false, + }); + + const visibleBaseAllowances = useMemo(() => { + return filterHiddenBaseAllowances(baseQuery.data ?? [], hiddenApprovalKeys); + }, [ baseQuery.data, hiddenApprovalKeys ]); + + const enrichApprovals = useCallback(async(records: Array<BaseAllowanceType>, signal?: AbortSignal): Promise<ApprovalsQueryData> => { + throwIfAborted(signal); + + const pageRecords = getPageBaseAllowances(records, page); + const tokenDataPromise = Promise.all( + pageRecords.map((record) => getTokenData(apiFetch, record.address, chain, signal)), + ); + const timestampsPromise = runParallelBatches( + pageRecords, + PUBLIC_RPC_BLOCK_BATCH_SIZE, + (record) => getBlockTimestamp(chain, publicClient, record.blockNumber, signal), + ); + const [ tokenData, timestamps ] = await Promise.all([ tokenDataPromise, timestampsPromise ]); + const items = pageRecords.map((record, index) => buildAllowance(record, tokenData[index], timestamps[index] as number)); + + return { + items, + total: records.length, + totalValueAtRiskUsd: getTotalValueAtRiskUsd(records), + }; + }, [ apiFetch, chain, getBlockTimestamp, page, publicClient ]); + + const pageQuery = useQuery({ + queryKey: [ 'revoke:approvals:page', chain?.id, userAddress, page, baseQuery.dataUpdatedAt, hiddenApprovalKeysKey ], + queryFn: ({ signal }) => enrichApprovals(visibleBaseAllowances, signal), + enabled: isQueryEnabled && Boolean(baseQuery.data) && !baseQuery.isError, + staleTime: Infinity, + retry: shouldRetryRevokeQuery, + throwOnError: false, + }); + + const data = useMemo<ApprovalsQueryData>(() => { + if (pageQuery.data) { + return pageQuery.data; + } + + if (baseQuery.data) { + return { + items: PLACEHOLDER_DATA.items, + total: visibleBaseAllowances.length, + totalValueAtRiskUsd: getTotalValueAtRiskUsd(visibleBaseAllowances), + }; + } + + return PLACEHOLDER_DATA; + }, [ baseQuery.data, pageQuery.data, visibleBaseAllowances ]); + + return useMemo(() => ({ + ...pageQuery, + data, + hideApproval, + error: baseQuery.error || pageQuery.error, + isError: baseQuery.isError || pageQuery.isError, + isFetching: baseQuery.isFetching || pageQuery.isFetching, + isLoading: baseQuery.isLoading || pageQuery.isLoading, + isPending: baseQuery.isPending || pageQuery.isPending, + isPlaceholderData: baseQuery.isLoading || pageQuery.isLoading || !pageQuery.data, + }), [ baseQuery, data, hideApproval, pageQuery ]); +} diff --git a/src/features/marketplace/pages/essential-dapp/revoke/hooks/useApprovalsQuery.tsx b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useApprovalsQuery.tsx deleted file mode 100644 index 4478f932d76..00000000000 --- a/src/features/marketplace/pages/essential-dapp/revoke/hooks/useApprovalsQuery.tsx +++ /dev/null @@ -1,308 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import ERC20Artifact from '@openzeppelin/contracts/build/contracts/ERC20.json'; -import NftArtifact from '@openzeppelin/contracts/build/contracts/ERC721.json'; -import { useQuery } from '@tanstack/react-query'; -import { useCallback, useEffect, useMemo, useState } from 'react'; -import { formatUnits, getAbiItem, getAddress, isAddress } from 'viem'; -import type { GetLogsParameters, PublicClient } from 'viem'; -import { usePublicClient } from 'wagmi'; - -import type { AllowanceType, ApprovalsQueryData, BaseAllowanceType } from '../types'; -import type { schemas } from '@blockscout/api-types'; -import type { EssentialDappsChainConfig } from 'src/features/marketplace/types/client'; - -import useApiFetch from 'src/api/hooks/useApiFetch'; - -import { PUBLIC_RPC_BLOCK_BATCH_SIZE } from '../constants'; -import { filterHiddenBaseAllowances, getApprovalHiddenKey, getPageBaseAllowances } from '../lib/approvalKeys'; -import createRevokeBlockscoutClient from '../lib/createRevokeBlockscoutClient'; -import { getTotalValueAtRiskUsd } from '../lib/erc20ValueAtRisk'; -import type { TokenBalanceInfo } from '../lib/erc20ValueAtRisk'; -import { shouldRethrowLocalError, shouldRetryRevokeQuery } from '../lib/errors'; -import getLogs from '../lib/getLogs'; -import { retryOnHttp429 } from '../lib/retry'; -import runParallelBatches from '../lib/runParallelBatches'; -import { ALLOWANCES } from '../stubs'; -import useGetBlockTimestamp from './useGetBlockTimestamp'; -import useSearchErc20Allowances from './useSearchErc20Allowances'; -import useSearchNftAllowances from './useSearchNftAllowances'; - -const PLACEHOLDER_DATA: ApprovalsQueryData = { - items: ALLOWANCES, - total: ALLOWANCES.length, - totalValueAtRiskUsd: 0, -}; - -function throwIfAborted(signal?: AbortSignal) { - if (signal?.aborted) { - throw new DOMException('Aborted', 'AbortError'); - } -} - -function formatErc20Allowance( - allowance: bigint, - decimals: number = 18, - totalSupply: bigint | undefined, -): string { - if (totalSupply && allowance > totalSupply) { - return 'Unlimited'; - } - - return formatUnits(allowance, decimals); -} - -function formatRecordAllowance(record: BaseAllowanceType, decimals?: number, totalSupply?: bigint): string | undefined { - if (!record.allowance) return undefined; - - if (record.type === 'ERC-20') { - return formatErc20Allowance(record.allowance, decimals, totalSupply); - } - - return record.allowance === BigInt(-1) ? 'Unlimited' : record.allowance.toString(); -} - -function sortBaseAllowances(records: Array<BaseAllowanceType>): Array<BaseAllowanceType> { - return records.sort((a, b) => { - const valueAtRiskDiff = (b.valueAtRiskUsd ?? 0) - (a.valueAtRiskUsd ?? 0); - if (valueAtRiskDiff !== 0) return valueAtRiskDiff; - - const exchangeRateDiff = parseFloat(b.exchangeRate ?? '0') - parseFloat(a.exchangeRate ?? '0'); - if (exchangeRateDiff !== 0) return exchangeRateDiff; - - if (b.blockNumber < a.blockNumber) return -1; - if (b.blockNumber > a.blockNumber) return 1; - return 0; - }); -} - -function getTokenBalanceInfo(response: Array<schemas['TokenBalance']>): Map<`0x${ string }`, TokenBalanceInfo> { - const balances = new Map<`0x${ string }`, TokenBalanceInfo>(); - - response.forEach((entry) => { - if (!entry.token?.address_hash) return; - - const tokenAddress = getAddress(entry.token.address_hash as `0x${ string }`); - - balances.set(tokenAddress, { - balance: entry.value ? BigInt(entry.value) : undefined, - exchangeRate: entry.token.exchange_rate || undefined, - decimals: entry.token.decimals === undefined || entry.token.decimals === null ? undefined : Number(entry.token.decimals), - symbol: entry.token.symbol || undefined, - name: entry.token.name || undefined, - tokenIcon: entry.token.icon_url || undefined, - tokenReputation: entry.token.reputation, - totalSupply: entry.token.total_supply ? BigInt(entry.token.total_supply) : undefined, - }); - }); - - return balances; -} - -async function getTokenBalances( - apiFetch: ReturnType<typeof useApiFetch>, - ownerAddress: string, - chain: EssentialDappsChainConfig | undefined, - signal?: AbortSignal, -): Promise<Map<`0x${ string }`, TokenBalanceInfo>> { - const response = await retryOnHttp429( - () => apiFetch('core:address_token_balances', { - pathParams: { hash: ownerAddress }, - chain, - fetchParams: { - signal, - }, - }) as Promise<Array<schemas['TokenBalance']>>, - signal, - ); - - return getTokenBalanceInfo(response); -} - -async function getTokenData( - apiFetch: ReturnType<typeof useApiFetch>, - tokenAddress: `0x${ string }`, - chain: EssentialDappsChainConfig | undefined, - signal?: AbortSignal, -): Promise<schemas['Token'] | undefined> { - try { - return await retryOnHttp429( - () => apiFetch('core:token', { - pathParams: { hash: tokenAddress }, - chain, - fetchParams: { - signal, - }, - }) as Promise<schemas['Token']>, - signal, - ); - } catch (error) { - if (shouldRethrowLocalError(error)) { - throw error; - } - - return undefined; - } -} - -function buildAllowance(record: BaseAllowanceType, tokenData: schemas['Token'] | undefined, timestamp: number): AllowanceType { - const decimals = tokenData?.decimals ? Number(tokenData.decimals) : record.decimals; - const totalSupply = tokenData?.total_supply ? BigInt(tokenData.total_supply) : record.totalSupply; - - return { - type: record.type, - address: record.address, - transactionId: record.transactionId, - tokenId: record.tokenId, - tokenIcon: tokenData?.icon_url || record.tokenIcon, - tokenReputation: tokenData?.reputation ?? record.tokenReputation ?? null, - allowance: formatRecordAllowance(record, decimals, totalSupply), - price: tokenData?.exchange_rate || record.exchangeRate, - balance: record.balance?.toString(), - valueAtRiskUsd: record.valueAtRiskUsd, - decimals, - spender: record.spender, - symbol: tokenData?.symbol || record.symbol, - name: tokenData?.name || record.name, - totalSupply, - timestamp, - }; -} - -export default function useApprovalsQuery(chain: EssentialDappsChainConfig | undefined, userAddress: string, page: number) { - const apiFetch = useApiFetch(); - const getBlockTimestamp = useGetBlockTimestamp(); - const searchErc20Allowances = useSearchErc20Allowances(); - const searchNftAllowances = useSearchNftAllowances(); - const [ hiddenApprovalKeys, setHiddenApprovalKeys ] = useState<Array<string>>([]); - const chainId = chain?.id ? Number(chain.id) : undefined; - const publicClient = usePublicClient({ chainId }) as PublicClient | undefined; - - const blockscoutClient = useMemo( - () => createRevokeBlockscoutClient(chain?.id), - [ chain?.id ], - ); - - const isQueryEnabled = Boolean(userAddress) && isAddress(userAddress) && Boolean(publicClient && blockscoutClient); - const hiddenApprovalKeysKey = hiddenApprovalKeys.join(':'); - - useEffect(() => { - setHiddenApprovalKeys([]); - }, [ chain?.id, userAddress ]); - - const hideApproval = useCallback((approval: AllowanceType) => { - const key = getApprovalHiddenKey(approval); - - setHiddenApprovalKeys((prev) => prev.includes(key) ? prev : [ ...prev, key ]); - }, []); - - const searchBaseAllowances = useCallback(async(signal?: AbortSignal): Promise<Array<BaseAllowanceType>> => { - throwIfAborted(signal); - - if (!publicClient) { - throw new Error('Public client not found'); - } - - if (!blockscoutClient) { - throw new Error('Blockscout client not found'); - } - - const latestBlockNumber = await publicClient.getBlockNumber(); - - const approvalFilter = { - event: getAbiItem({ abi: ERC20Artifact.abi, name: 'Approval' }), - args: { owner: userAddress }, - } as unknown as GetLogsParameters; - - const approvalForAllFilter = { - event: getAbiItem({ abi: NftArtifact.abi, name: 'ApprovalForAll' }), - args: { owner: userAddress }, - } as unknown as GetLogsParameters; - - const tokenBalancesPromise = getTokenBalances(apiFetch, userAddress, chain, signal); - void tokenBalancesPromise.catch(() => undefined); - - const [ approvalEvents, approvalForAllEvents ] = await Promise.all([ - getLogs(blockscoutClient, approvalFilter, BigInt(0), latestBlockNumber, signal), - getLogs(blockscoutClient, approvalForAllFilter, BigInt(0), latestBlockNumber, signal), - ]); - - const [ erc20Allowances, nftAllowances ] = await Promise.all([ - searchErc20Allowances(userAddress, approvalEvents, tokenBalancesPromise, publicClient, signal), - searchNftAllowances(userAddress, approvalEvents, approvalForAllEvents, publicClient, signal), - ]); - - return sortBaseAllowances([ ...erc20Allowances, ...nftAllowances ]); - }, [ apiFetch, blockscoutClient, chain, publicClient, searchErc20Allowances, searchNftAllowances, userAddress ]); - - const baseQuery = useQuery({ - queryKey: [ 'revoke:approvals:base', chain?.id, userAddress ], - queryFn: ({ signal }) => searchBaseAllowances(signal), - enabled: isQueryEnabled, - retry: shouldRetryRevokeQuery, - throwOnError: false, - }); - - const visibleBaseAllowances = useMemo(() => { - return filterHiddenBaseAllowances(baseQuery.data ?? [], hiddenApprovalKeys); - }, [ baseQuery.data, hiddenApprovalKeys ]); - - const enrichApprovals = useCallback(async(records: Array<BaseAllowanceType>, signal?: AbortSignal): Promise<ApprovalsQueryData> => { - throwIfAborted(signal); - - const pageRecords = getPageBaseAllowances(records, page); - const tokenDataPromise = Promise.all( - pageRecords.map((record) => getTokenData(apiFetch, record.address, chain, signal)), - ); - const timestampsPromise = runParallelBatches( - pageRecords, - PUBLIC_RPC_BLOCK_BATCH_SIZE, - (record) => getBlockTimestamp(chain, publicClient, record.blockNumber, signal), - ); - const [ tokenData, timestamps ] = await Promise.all([ tokenDataPromise, timestampsPromise ]); - const items = pageRecords.map((record, index) => buildAllowance(record, tokenData[index], timestamps[index] as number)); - - return { - items, - total: records.length, - totalValueAtRiskUsd: getTotalValueAtRiskUsd(records), - }; - }, [ apiFetch, chain, getBlockTimestamp, page, publicClient ]); - - const pageQuery = useQuery({ - queryKey: [ 'revoke:approvals:page', chain?.id, userAddress, page, baseQuery.dataUpdatedAt, hiddenApprovalKeysKey ], - queryFn: ({ signal }) => enrichApprovals(visibleBaseAllowances, signal), - enabled: isQueryEnabled && Boolean(baseQuery.data) && !baseQuery.isError, - staleTime: Infinity, - retry: shouldRetryRevokeQuery, - throwOnError: false, - }); - - const data = useMemo<ApprovalsQueryData>(() => { - if (pageQuery.data) { - return pageQuery.data; - } - - if (baseQuery.data) { - return { - items: PLACEHOLDER_DATA.items, - total: visibleBaseAllowances.length, - totalValueAtRiskUsd: getTotalValueAtRiskUsd(visibleBaseAllowances), - }; - } - - return PLACEHOLDER_DATA; - }, [ baseQuery.data, pageQuery.data, visibleBaseAllowances ]); - - return useMemo(() => ({ - ...pageQuery, - data, - hideApproval, - error: baseQuery.error || pageQuery.error, - isError: baseQuery.isError || pageQuery.isError, - isFetching: baseQuery.isFetching || pageQuery.isFetching, - isLoading: baseQuery.isLoading || pageQuery.isLoading, - isPending: baseQuery.isPending || pageQuery.isPending, - isPlaceholderData: baseQuery.isLoading || pageQuery.isLoading || !pageQuery.data, - }), [ baseQuery, data, hideApproval, pageQuery ]); -} diff --git a/src/features/marketplace/pages/essential-dapp/revoke/hooks/useCoinBalanceQuery.tsx b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useCoinBalanceQuery.ts similarity index 100% rename from src/features/marketplace/pages/essential-dapp/revoke/hooks/useCoinBalanceQuery.tsx rename to src/features/marketplace/pages/essential-dapp/revoke/hooks/useCoinBalanceQuery.ts diff --git a/src/features/marketplace/pages/essential-dapp/revoke/hooks/useGetBlockTimestamp.tsx b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useGetBlockTimestamp.ts similarity index 100% rename from src/features/marketplace/pages/essential-dapp/revoke/hooks/useGetBlockTimestamp.tsx rename to src/features/marketplace/pages/essential-dapp/revoke/hooks/useGetBlockTimestamp.ts diff --git a/src/features/marketplace/pages/essential-dapp/revoke/hooks/useRevoke.spec.ts b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useRevoke.spec.ts new file mode 100644 index 00000000000..f8fb43755c2 --- /dev/null +++ b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useRevoke.spec.ts @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import type * as viemActions from 'viem/actions'; +import type * as wagmi from 'wagmi'; + +import type { AllowanceType } from '../types'; +import type { EssentialDappsChainConfig } from 'src/features/marketplace/types/client'; + +import { toaster } from 'src/toolkit/chakra/toaster'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { renderHook, wrapper } from 'vitest/lib'; + +import useRevoke from './useRevoke'; + +const USER_ADDRESS = '0x1111111111111111111111111111111111111111'; +const TOKEN_ADDRESS = '0x2222222222222222222222222222222222222222'; +const SPENDER_ADDRESS = '0x3333333333333333333333333333333333333333'; +const TX_HASH = `0x${ 'ab'.repeat(32) }`; +const CHAIN: EssentialDappsChainConfig = { id: '10', name: 'OP Mainnet' }; +const ERC20_APPROVAL: AllowanceType = { + type: 'ERC-20', + address: TOKEN_ADDRESS, + spender: SPENDER_ADDRESS, + transactionId: null, + tokenReputation: null, + timestamp: 0, +}; + +const walletState = vi.hoisted(() => ({ + address: undefined as string | undefined, + publicClient: undefined as object | undefined, + switchChainAsync: vi.fn(), + writeContractAsync: vi.fn(), + waitForTransactionReceipt: vi.fn(), +})); + +vi.mock('wagmi', async(importOriginal) => ({ + ...await importOriginal<typeof wagmi>(), + useAccount: () => ({ address: walletState.address }), + useSwitchChain: () => ({ switchChainAsync: walletState.switchChainAsync }), + useWriteContract: () => ({ writeContractAsync: walletState.writeContractAsync }), + usePublicClient: () => walletState.publicClient, +})); + +vi.mock('viem/actions', async(importOriginal) => ({ + ...await importOriginal<typeof viemActions>(), + waitForTransactionReceipt: walletState.waitForTransactionReceipt, +})); + +function renderRevoke(chain: EssentialDappsChainConfig = CHAIN) { + return renderHook(() => useRevoke(chain), { wrapper }).result.current; +} + +describe('useRevoke', () => { + beforeEach(() => { + walletState.address = USER_ADDRESS; + walletState.publicClient = {}; + walletState.switchChainAsync.mockResolvedValue(undefined); + walletState.writeContractAsync.mockResolvedValue(TX_HASH); + walletState.waitForTransactionReceipt.mockResolvedValue({ status: 'success' }); + vi.spyOn(toaster, 'success'); + vi.spyOn(toaster, 'error'); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.resetAllMocks(); + }); + + it('should revoke an ERC-20 approval on the approval chain and report success', async() => { + const revoke = renderRevoke(); + + await expect(revoke(ERC20_APPROVAL)).resolves.toBe(true); + + expect(walletState.switchChainAsync).toHaveBeenCalledWith({ chainId: 10 }); + expect(walletState.writeContractAsync).toHaveBeenCalledWith(expect.objectContaining({ + account: USER_ADDRESS, + address: TOKEN_ADDRESS, + functionName: 'approve', + args: [ SPENDER_ADDRESS, 0 ], + chainId: 10, + })); + expect(toaster.success).toHaveBeenCalledWith(expect.objectContaining({ title: 'Success' })); + }); + + it('should do nothing when no wallet is connected', async() => { + walletState.address = undefined; + const revoke = renderRevoke(); + + await expect(revoke(ERC20_APPROVAL)).resolves.toBeUndefined(); + + expect(walletState.writeContractAsync).not.toHaveBeenCalled(); + }); + + it.each([ + { + condition: 'the chain has no id', + setup: () => {}, + chain: { ...CHAIN, id: '' }, + message: 'Chain not found', + }, + { + condition: 'no public client is available', + setup: () => { + walletState.publicClient = undefined; + }, + chain: CHAIN, + message: 'Public client not found', + }, + { + condition: 'the transaction is reverted', + setup: () => { + walletState.waitForTransactionReceipt.mockResolvedValue({ status: 'reverted' }); + }, + chain: CHAIN, + message: 'Failed to revoke approval.', + }, + { + condition: 'the wallet rejects with a short message', + setup: () => { + walletState.writeContractAsync.mockRejectedValue({ shortMessage: 'User rejected the request.' }); + }, + chain: CHAIN, + message: 'User rejected the request.', + }, + { + condition: 'the error carries no message', + setup: () => { + walletState.switchChainAsync.mockRejectedValue({}); + }, + chain: CHAIN, + message: 'Something went wrong. Try again later.', + }, + ])('should report failure when $condition', async({ setup, chain, message }) => { + setup(); + const revoke = renderRevoke(chain); + + await expect(revoke(ERC20_APPROVAL)).resolves.toBe(false); + + expect(toaster.error).toHaveBeenCalledWith(expect.objectContaining({ description: message })); + }); +}); diff --git a/src/features/marketplace/pages/essential-dapp/revoke/hooks/useRevoke.tsx b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useRevoke.tsx index 6b84df33f73..5fc06206adf 100644 --- a/src/features/marketplace/pages/essential-dapp/revoke/hooks/useRevoke.tsx +++ b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useRevoke.tsx @@ -13,7 +13,7 @@ import TxEntity from 'src/slices/tx/components/entity/TxEntity'; import useRewardsActivity from 'src/features/rewards/hooks/useRewardsActivity'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { toaster } from 'src/toolkit/chakra/toaster'; @@ -44,7 +44,7 @@ export default function useRevoke(chain?: EssentialDappsChainConfig) { chainId: Number(chain?.id), }); - mixpanel.logEvent(mixpanel.EventTypes.WALLET_ACTION, { + analytics.logEvent(analytics.EventTypes.WALLET_ACTION, { Action: 'Send Transaction', Address: userAddress, AppId: 'revoke', diff --git a/src/features/marketplace/pages/essential-dapp/revoke/hooks/useSearchErc20Allowances.tsx b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useSearchErc20Allowances.ts similarity index 100% rename from src/features/marketplace/pages/essential-dapp/revoke/hooks/useSearchErc20Allowances.tsx rename to src/features/marketplace/pages/essential-dapp/revoke/hooks/useSearchErc20Allowances.ts diff --git a/src/features/marketplace/pages/essential-dapp/revoke/hooks/useSearchNftAllowances.tsx b/src/features/marketplace/pages/essential-dapp/revoke/hooks/useSearchNftAllowances.ts similarity index 100% rename from src/features/marketplace/pages/essential-dapp/revoke/hooks/useSearchNftAllowances.tsx rename to src/features/marketplace/pages/essential-dapp/revoke/hooks/useSearchNftAllowances.ts diff --git a/src/features/marketplace/pages/essential-dapp/swap/Swap.tsx b/src/features/marketplace/pages/essential-dapp/swap/Swap.tsx index 8d91fc9a37b..7d7d6fb2002 100644 --- a/src/features/marketplace/pages/essential-dapp/swap/Swap.tsx +++ b/src/features/marketplace/pages/essential-dapp/swap/Swap.tsx @@ -1,9 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Flex, useToken } from '@chakra-ui/react'; +import { Center, Flex, useToken } from '@chakra-ui/react'; import React, { useMemo } from 'react'; import AdBanner from 'src/features/ads/banner/components/AdBanner'; +import Web3Boundary from 'src/features/connect-wallet/components/Web3Boundary'; +import useWeb3Wallet from 'src/features/connect-wallet/hooks/useWallet'; import essentialDappsChainsConfig from 'src/features/marketplace/chains-config/essential-dapps'; import config from 'src/config'; @@ -11,54 +13,67 @@ import { getFeaturePayload } from 'src/config/utils/features'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import { useColorMode } from 'src/toolkit/chakra/color-mode'; +import { ContentLoader } from 'src/toolkit/components/loaders/ContentLoader'; import { BODY_TYPEFACE } from 'src/toolkit/theme/foundations/typography'; -import MarketplaceAppIframe from '../../../components/MarketplaceAppIframe'; +import { SWAP_WIDGET_MIN_HEIGHT } from './consts'; +import SwapWidgetIframe from './SwapWidgetIframe'; +import { useSwapWallet } from './useSwapWallet'; +import { getSwapWidgetConfig } from './widget-config'; const feature = getFeaturePayload(config.features.marketplace); const dappConfig = feature?.essentialDapps?.swap; -const defaultChainId = Number( - dappConfig?.chains.includes(config.chain.id as string) ? - config.chain.id : - dappConfig?.chains[0], -); +const widgetConfig = dappConfig ? getSwapWidgetConfig(dappConfig, config.chain.id, essentialDappsChainsConfig()?.chains ?? []) : undefined; -function getExplorerUrls() { - return Object.fromEntries(dappConfig?.chains.map((chainId) => { - const chainConfig = essentialDappsChainsConfig()?.chains.find( - (chain) => chain.id === chainId, - ); - return [ Number(chainId), [ chainConfig?.explorer_url ] ]; - }) || []); -} - -export default function Swap() { - const isMobile = useIsMobile(); +const SwapWidget = () => { const { colorMode } = useColorMode(); const [ mainColor ] = useToken('colors', 'blue.600'); const [ borderColor ] = useToken('colors', colorMode === 'light' ? 'blackAlpha.100' : 'whiteAlpha.100'); + const [ borderRadius, borderRadiusSecondary ] = useToken('radii', [ 'md', 'base' ]); + const wallet = useWeb3Wallet({ source: 'Essential dapps' }); + const handler = useSwapWallet(); + const handlers = useMemo(() => [ handler ], [ handler ]); + const themedConfig = useMemo(() => widgetConfig && ({ + ...widgetConfig, + // The iframe's CSS color-scheme follows our theme, including changes during an active swap. + appearance: 'system' as const, + // widget-light omits these serializable MUI fields from its types; the hosted widget forwards them unchanged. + theme: { + typography: { fontFamily: BODY_TYPEFACE }, + colorSchemes: { + light: { palette: { primary: { main: mainColor }, secondary: { main: mainColor } } }, + dark: { palette: { primary: { main: mainColor }, secondary: { main: mainColor } } }, + }, + shape: { + borderRadius: Number.parseInt(borderRadius, 10), + borderRadiusSecondary: Number.parseInt(borderRadiusSecondary, 10), + }, + container: { height: 'fit-content', border: `1px solid ${ borderColor }`, borderRadius }, + }, + }), [ mainColor, borderColor, borderRadius, borderRadiusSecondary ]); + + if (!themedConfig) { + return null; + } + + return ( + <SwapWidgetIframe + config={ themedConfig } + handlers={ handlers } + onConnect={ wallet.connect } + /> + ); +}; - const message = useMemo(() => ({ - type: 'config', - integrator: dappConfig?.integrator, - fee: Number(dappConfig?.fee), - chains: dappConfig?.chains.map((chainId) => Number(chainId)), - explorerUrls: getExplorerUrls(), - mainColor, - borderColor, - fontFamily: BODY_TYPEFACE, - defaultChainId, - }), [ mainColor, borderColor ]); +export default function Swap() { + const isMobile = useIsMobile(); return ( <Flex flex="1" flexDir="column" justifyContent="space-between" gap={ 6 }> - <MarketplaceAppIframe - appId="swap" - appUrl={ dappConfig?.url } - message={ message } - isEssentialDapp - /> + <Web3Boundary fallback={ <Center h={ SWAP_WIDGET_MIN_HEIGHT }><ContentLoader/></Center> }> + <SwapWidget/> + </Web3Boundary> { (feature?.essentialDappsAdEnabled && !isMobile) && ( <AdBanner format="mobile" diff --git a/src/features/marketplace/pages/essential-dapp/swap/SwapWidgetIframe.spec.tsx b/src/features/marketplace/pages/essential-dapp/swap/SwapWidgetIframe.spec.tsx new file mode 100644 index 00000000000..34d711dfbd2 --- /dev/null +++ b/src/features/marketplace/pages/essential-dapp/swap/SwapWidgetIframe.spec.tsx @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import React from 'react'; + +import { SECOND } from 'src/toolkit/utils/consts'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen } from 'vitest/lib'; + +import SwapWidgetIframe from './SwapWidgetIframe'; + +const WIDGET_ORIGIN = 'https://widget.li.fi'; +const CONFIG = { integrator: 'blockscout' }; + +function sendMessage(iframe: HTMLIFrameElement, data: Record<string, unknown>, origin = WIDGET_ORIGIN, source: Window | null = iframe.contentWindow): void { + act(() => { + window.dispatchEvent(new MessageEvent('message', { origin, source, data: { source: 'widget-light', ...data } })); + }); +} + +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +describe('Swap iframe loading', () => { + it('keeps the unstyled iframe hidden until its configured page renders', () => { + const { container } = render(<React.StrictMode><SwapWidgetIframe config={ CONFIG }/></React.StrictMode>); + const iframe = container.querySelector('iframe')!; + expect(window.getComputedStyle(iframe).visibility).toBe('hidden'); + expect(iframe.parentElement?.getAttribute('aria-busy')).toBe('true'); + + fireEvent.load(iframe); + sendMessage(iframe, { type: 'READY' }); + expect(window.getComputedStyle(iframe).visibility).toBe('hidden'); + + const ready = { type: 'WIDGET_EVENT', event: 'pageEntered', data: '/' }; + sendMessage(iframe, ready, 'https://untrusted.test'); + sendMessage(iframe, ready, WIDGET_ORIGIN, window); + expect(window.getComputedStyle(iframe).visibility).toBe('hidden'); + + sendMessage(iframe, ready); + expect(window.getComputedStyle(iframe).visibility).toBe('visible'); + expect(iframe.parentElement?.getAttribute('aria-busy')).toBe('false'); + }); + + it('keeps an active iframe when its config changes and waits again after leaving the page', () => { + const { container, rerender, unmount } = render(<SwapWidgetIframe config={ CONFIG }/>); + const iframe = container.querySelector('iframe')!; + sendMessage(iframe, { type: 'READY' }); + sendMessage(iframe, { type: 'WIDGET_EVENT', event: 'pageEntered', data: '/' }); + + rerender(<SwapWidgetIframe config={{ ...CONFIG, appearance: 'light' }}/>); + expect(container.querySelector('iframe')).toBe(iframe); + expect(window.getComputedStyle(iframe).visibility).toBe('visible'); + unmount(); + + const nextRender = render(<SwapWidgetIframe config={ CONFIG }/>); + const nextIframe = nextRender.container.querySelector('iframe')!; + expect(window.getComputedStyle(nextIframe).visibility).toBe('hidden'); + sendMessage(nextIframe, { type: 'READY' }); + sendMessage(nextIframe, { type: 'WIDGET_EVENT', event: 'pageEntered', data: '/' }); + expect(window.getComputedStyle(nextIframe).visibility).toBe('visible'); + }); + + it('offers a fresh attempt when the widget never becomes ready', () => { + vi.useFakeTimers(); + const { container } = render(<SwapWidgetIframe config={ CONFIG }/>); + const iframe = container.querySelector('iframe')!; + const widget = iframe.parentElement!; + sendMessage(iframe, { type: 'READY' }); + act(() => vi.advanceTimersByTime(30 * SECOND)); + + expect(screen.getByRole('alert').textContent).toContain('Unable to load the swap widget'); + expect(container.querySelector('iframe')).toBeNull(); + expect(widget.getAttribute('aria-busy')).toBe('false'); + fireEvent.click(screen.getByRole('button', { name: 'Try again' })); + + const nextIframe = container.querySelector('iframe')!; + expect(nextIframe).not.toBe(iframe); + expect(window.getComputedStyle(nextIframe).visibility).toBe('hidden'); + expect(screen.queryByRole('alert')).toBeNull(); + sendMessage(iframe, { type: 'WIDGET_EVENT', event: 'pageEntered', data: '/' }); + expect(window.getComputedStyle(nextIframe).visibility).toBe('hidden'); + sendMessage(nextIframe, { type: 'READY' }); + sendMessage(nextIframe, { type: 'WIDGET_EVENT', event: 'pageEntered', data: '/' }); + act(() => vi.advanceTimersByTime(30 * SECOND)); + expect(window.getComputedStyle(nextIframe).visibility).toBe('visible'); + expect(screen.queryByRole('alert')).toBeNull(); + }); +}); diff --git a/src/features/marketplace/pages/essential-dapp/swap/SwapWidgetIframe.tsx b/src/features/marketplace/pages/essential-dapp/swap/SwapWidgetIframe.tsx new file mode 100644 index 00000000000..48adde1d089 --- /dev/null +++ b/src/features/marketplace/pages/essential-dapp/swap/SwapWidgetIframe.tsx @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Box, Center, Text, chakra } from '@chakra-ui/react'; +import { LiFiWidgetLight, useWidgetLightEvents, WidgetLightEvent, type WidgetLightIframeProps } from '@lifi/widget-light'; +import React, { useCallback, useEffect, useState } from 'react'; + +import { Button } from 'src/toolkit/chakra/button'; +import { useColorMode } from 'src/toolkit/chakra/color-mode'; +import { ContentLoader } from 'src/toolkit/components/loaders/ContentLoader'; + +import { SWAP_WIDGET_LOAD_TIMEOUT, SWAP_WIDGET_MIN_HEIGHT } from './consts'; + +const StyledLiFiWidget = chakra(LiFiWidgetLight); + +type Props = Pick<WidgetLightIframeProps, 'config' | 'handlers' | 'onConnect'>; + +export default function SwapWidgetIframe(props: Props) { + const { colorMode } = useColorMode(); + const [ status, setStatus ] = useState<'loading' | 'ready' | 'error'>('loading'); + const events = useWidgetLightEvents(); + + useEffect(() => { + if (status !== 'loading') return; + const timeout = window.setTimeout(() => setStatus('error'), SWAP_WIDGET_LOAD_TIMEOUT); + // READY only starts configuration; PageEntered means the configured widget has rendered. + const handleReady = () => { + window.clearTimeout(timeout); + setStatus('ready'); + }; + events.on(WidgetLightEvent.PageEntered, handleReady); + return () => { + window.clearTimeout(timeout); + events.off(WidgetLightEvent.PageEntered, handleReady); + }; + }, [ events, status ]); + + const handleRetry = useCallback(() => setStatus('loading'), []); + + return ( + <Box position="relative" minH={ SWAP_WIDGET_MIN_HEIGHT } bg="bg.primary" aria-busy={ status === 'loading' }> + { status !== 'error' && ( + <StyledLiFiWidget + { ...props } + autoResize + w="full" + minH={ SWAP_WIDGET_MIN_HEIGHT } + display="block" + visibility={ status === 'ready' ? 'visible' : 'hidden' } + css={{ + colorScheme: colorMode, + // LI.FI reports body.offsetHeight, which excludes the hosted page's 8px top and bottom margins. + '--lifi-iframe-height-offset': '16px', + }} + /> + ) } + { status === 'loading' && <Center position="absolute" inset={ 0 }><ContentLoader/></Center> } + { status === 'error' && ( + <Center position="absolute" inset={ 0 } flexDir="column" gap={ 4 }> + <Text role="alert">Unable to load the swap widget. Please try again.</Text> + <Button onClick={ handleRetry }>Try again</Button> + </Center> + ) } + </Box> + ); +} diff --git a/src/features/marketplace/pages/essential-dapp/swap/consts.ts b/src/features/marketplace/pages/essential-dapp/swap/consts.ts new file mode 100644 index 00000000000..a52783acc38 --- /dev/null +++ b/src/features/marketplace/pages/essential-dapp/swap/consts.ts @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { SECOND } from 'src/toolkit/utils/consts'; + +export const SWAP_WIDGET_MIN_HEIGHT = '500px'; +export const SWAP_WIDGET_LOAD_TIMEOUT = 30 * SECOND; diff --git a/src/features/marketplace/pages/essential-dapp/swap/useSwapWallet.spec.tsx b/src/features/marketplace/pages/essential-dapp/swap/useSwapWallet.spec.tsx new file mode 100644 index 00000000000..d619dcc8ab6 --- /dev/null +++ b/src/features/marketplace/pages/essential-dapp/swap/useSwapWallet.spec.tsx @@ -0,0 +1,473 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import { LiFiWidgetLight, type IframeEcosystemHandler } from '@lifi/widget-light'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import mixpanel from 'mixpanel-browser'; +import React, { useMemo } from 'react'; +import { http, UserRejectedRequestError, type EIP1193Parameters, type EIP1193Provider, type WalletRpcSchema } from 'viem'; +import { createConfig, mock, WagmiProvider, type Config } from 'wagmi'; +import { connect, disconnect } from 'wagmi/actions'; +import { mainnet, optimism } from 'wagmi/chains'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, render, renderHook, waitFor } from 'vitest/lib'; +import withEnvs from 'vitest/utils/mockEnvs'; + +vi.mock('mixpanel-browser', () => ({ 'default': { init: vi.fn(), track: vi.fn() } })); + +const ACCOUNT = '0x1111111111111111111111111111111111111111'; +const OTHER_ACCOUNT = '0x2222222222222222222222222222222222222222'; +const TX_HASH = `0x${ 'ab'.repeat(32) }`; +const SIGNATURE = `0x${ 'cd'.repeat(65) }`; +const ETHEREUM_RPC = 'https://ethereum-rpc.test'; +const OPTIMISM_RPC = 'https://optimism-rpc.test'; +const WIDGET_ORIGIN = 'https://widget.li.fi'; +const WIDGET_CONFIG = { integrator: 'blockscout' }; +const BATCH_ID = 'wallet-batch-id'; +const APPROVAL_HASH = `0x${ 'ef'.repeat(32) }`; +const REWARDS_ORIGIN = 'https://rewards.test'; +const ACTIVITY_TOKEN = 'batch-activity-token'; +const ENV_OVERRIDES: Array<[ string, string ]> = [ + [ 'NEXT_PUBLIC_REWARDS_SERVICE_API_HOST', REWARDS_ORIGIN ], + [ 'NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID', 'test-project' ], + [ 'NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY', 'test-captcha' ], + [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', 'test-mixpanel' ], +]; +const BATCH_PARAMS = [ { + chainId: '0x1', from: ACCOUNT, version: '2.0.0', + calls: [ { to: ACCOUNT, data: '0x1234' }, { to: OTHER_ACCOUNT, data: '0x5678' } ], +} ]; + +interface BatchTestState { + batchResult: unknown; + status: unknown; + reject: boolean; +} + +async function renderTrackedSwap(): Promise<{ + readonly result: { readonly current: { readonly wallet: IframeEcosystemHandler } }; + readonly state: BatchTestState; + readonly activityRequests: Array<{ path: string; body: unknown }>; +}> { + const { useSwapWallet } = await import('./useSwapWallet'); + const { RewardsContextProvider, useRewardsContext } = await import('src/features/rewards/context'); + const { getResourceKey } = await import('src/api/hooks/useApiQuery'); + const { init } = await import('src/shared/analytics/queue'); + const { getEnabledProviders } = await import('src/shared/analytics/providers'); + await init(getEnabledProviders().map((provider) => ({ provider, options: { debug: false } })), () => {}); + queryClient.setQueryData(getResourceKey('core:user_info'), { address_hash: ACCOUNT }); + queryClient.setQueryData(getResourceKey('rewards:user_check_activity_pass', { queryParams: { address: ACCOUNT } }), { is_valid: true }); + + const state: BatchTestState = { batchResult: { id: BATCH_ID }, status: { status: 100, receipts: [] }, reject: false }; + const connector = walletConfig.connectors[0]; + const getProvider = connector.getProvider.bind(connector); + vi.spyOn(connector, 'getProvider').mockImplementation(async(options) => { + const provider = await getProvider(options) as EIP1193Provider; + const request = async(args: EIP1193Parameters<WalletRpcSchema>): Promise<unknown> => { + if (args.method === 'wallet_sendCalls') { + if (state.reject) { + throw new UserRejectedRequestError(new Error('User rejected the batch.')); + } + return state.batchResult; + } + if (args.method === 'wallet_getCallsStatus') { + return state.status; + } + return provider.request(args); + }; + return { ...provider, request: request as typeof provider.request }; + }); + + const activityRequests: Array<{ path: string; body: unknown }> = []; + fetchMock.mockResponse(async(request) => { + if (new URL(request.url).origin !== REWARDS_ORIGIN) { + const { id, method } = JSON.parse(await request.text()) as { readonly id: number; readonly method: string }; + let result: unknown = [ ACCOUNT ]; + if (method === 'eth_sendTransaction') result = TX_HASH; + if (method === 'eth_sign' || method === 'eth_signTypedData_v4') result = SIGNATURE; + return JSON.stringify({ jsonrpc: '2.0', id, result }); + } + const path = new URL(request.url).pathname; + if (path.includes('/track/transaction')) { + activityRequests.push({ path, body: JSON.parse(await request.text()) }); + return { body: JSON.stringify({ token: ACTIVITY_TOKEN }), headers: { 'content-type': 'application/json' } }; + } + return { body: JSON.stringify({ is_valid: true }), headers: { 'content-type': 'application/json' } }; + }); + const TrackedWalletProvider = ({ children }: React.PropsWithChildren) => ( + <WalletProvider><RewardsContextProvider>{ children }</RewardsContextProvider></WalletProvider> + ); + const { result } = renderHook(() => ({ wallet: useSwapWallet(), rewards: useRewardsContext() }), { wrapper: TrackedWalletProvider }); + act(() => result.current.rewards.onLoginSuccess('test-rewards-token')); + await waitFor(() => expect(result.current.rewards.isAuth).toBe(true)); + return { result, state, activityRequests }; +} + +function createWalletConfig(): Config { + return createConfig({ + chains: [ + { ...mainnet, rpcUrls: { 'default': { http: [ ETHEREUM_RPC ] } } }, + { ...optimism, rpcUrls: { 'default': { http: [ OPTIMISM_RPC ] } } }, + ], + connectors: [ mock({ accounts: [ ACCOUNT ], features: { reconnect: true } }) ], + transports: { [mainnet.id]: http(ETHEREUM_RPC), [optimism.id]: http(OPTIMISM_RPC) }, + syncConnectedChain: false, + storage: null, + }); +} + +let walletConfig: ReturnType<typeof createWalletConfig>; +let queryClient: QueryClient; +let rejectTransaction = false; +const sentTransactions: Array<unknown> = []; +const walletRpcUrls: Array<string> = []; + +const WalletProvider = ({ children }: React.PropsWithChildren) => ( + <QueryClientProvider client={ queryClient }> + <WagmiProvider config={ walletConfig } reconnectOnMount={ false }>{ children }</WagmiProvider> + </QueryClientProvider> +); + +beforeEach(async() => { + walletConfig = createWalletConfig(); + queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); + rejectTransaction = false; + sentTransactions.length = 0; + walletRpcUrls.length = 0; + fetchMock.resetMocks(); + fetchMock.mockResponse(async(request) => { + const { id, method, params } = JSON.parse(await request.text()) as { + readonly id: number; + readonly method: string; + readonly params: Array<unknown>; + }; + let result: unknown; + switch (method) { + case 'eth_accounts': result = [ ACCOUNT ]; break; + case 'eth_getBalance': result = new URL(request.url).origin === OPTIMISM_RPC ? '0x20' : '0x10'; break; + case 'eth_sendTransaction': + walletRpcUrls.push(request.url); + if (rejectTransaction) { + return JSON.stringify({ jsonrpc: '2.0', id, error: { code: 4001, message: 'User rejected the request.' } }); + } + sentTransactions.push(params[0]); + result = TX_HASH; + break; + case 'eth_sign': + case 'eth_signTypedData_v4': + walletRpcUrls.push(request.url); + result = SIGNATURE; + break; + default: throw new Error(`Unexpected RPC: ${ method }`); + } + return JSON.stringify({ jsonrpc: '2.0', id, result }); + }); + await connect(walletConfig, { connector: walletConfig.connectors[0] }); +}); + +afterEach(() => { + cleanup(); + queryClient.clear(); + document.cookie = 'rewards_api_token=; Max-Age=0; path=/'; + vi.clearAllMocks(); + vi.restoreAllMocks(); +}); + +describe('Swap wallet with wagmi v2', () => { + it('exposes the existing connection and publishes account changes and disconnects', async() => { + const { useSwapWallet } = await import('./useSwapWallet'); + const { result } = renderHook(useSwapWallet, { wrapper: WalletProvider }); + expect(result.current.getInitState()).toMatchObject({ chainType: 'EVM', state: { accounts: [ ACCOUNT ], chainId: mainnet.id } }); + const emit = vi.fn(); + const unsubscribe = result.current.subscribe(emit); + + act(() => walletConfig.connectors[0].onAccountsChanged([ OTHER_ACCOUNT ])); + await waitFor(() => expect(emit).toHaveBeenCalledWith('accountsChanged', [ OTHER_ACCOUNT ])); + await act(async() => { + await disconnect(walletConfig); + }); + expect(await result.current.handleRequest('accounts', 'eth_accounts')).toEqual([]); + expect(emit).toHaveBeenCalledWith('accountsChanged', []); + unsubscribe(); + }); + + it('switches chains and reads from the connected chain even when the explorer stays on Ethereum', async() => { + const { useSwapWallet } = await import('./useSwapWallet'); + const { result } = renderHook(useSwapWallet, { wrapper: WalletProvider }); + await act(async() => { + await result.current.handleRequest('switch', 'wallet_switchEthereumChain', [ { chainId: '0xa' } ]); + }); + expect(walletConfig.state.chainId).toBe(mainnet.id); + await waitFor(() => expect(result.current.getInitState()).toMatchObject({ state: { chainId: optimism.id } })); + expect(await result.current.handleRequest('balance', 'eth_getBalance', [ ACCOUNT, 'latest' ])).toBe('0x20'); + await waitFor(() => expect(queryClient.isFetching()).toBe(0)); + expect(await result.current.handleRequest('send', 'eth_sendTransaction', [ { to: OTHER_ACCOUNT, value: '0x0' } ])).toBe(TX_HASH); + }); + + it('can read the account and switch away from a wallet chain outside the configuration', async() => { + const { useSwapWallet } = await import('./useSwapWallet'); + const { result } = renderHook(useSwapWallet, { wrapper: WalletProvider }); + act(() => walletConfig.connectors[0].onChainChanged('0x89')); + + expect(await result.current.handleRequest('chain', 'eth_chainId')).toBe('0x89'); + expect(await result.current.handleRequest('accounts', 'eth_accounts')).toEqual([ ACCOUNT ]); + await act(async() => { + expect(await result.current.handleRequest('switch', 'wallet_switchEthereumChain', [ { chainId: '0xa' } ])).toBeNull(); + }); + expect(await result.current.handleRequest('chain', 'eth_chainId')).toBe('0xa'); + expect(await result.current.handleRequest('balance', 'eth_getBalance', [ ACCOUNT, 'latest' ])).toBe('0x20'); + }); + + it.each([ + { method: 'eth_sendTransaction', params: [ { to: OTHER_ACCOUNT, value: '0x0' } ], expected: TX_HASH }, + { method: 'personal_sign', params: [ '0x1234', ACCOUNT ], expected: SIGNATURE }, + ])('uses the new chain immediately after switching for $method', async({ method, params, expected }) => { + const { useSwapWallet } = await import('./useSwapWallet'); + const { result } = renderHook(useSwapWallet, { wrapper: WalletProvider }); + await waitFor(() => expect(queryClient.isFetching()).toBe(0)); + const emit = vi.fn(); + result.current.subscribe(emit); + await act(async() => { + await result.current.handleRequest('switch', 'wallet_switchEthereumChain', [ { chainId: '0xa' } ]); + }); + await waitFor(() => expect(emit).toHaveBeenCalledWith('chainChanged', '0xa')); + + expect(await result.current.handleRequest('after-switch', method, params)).toEqual(expected); + expect(walletRpcUrls).toEqual([ `${ OPTIMISM_RPC }/` ]); + }); + + it('preserves transaction fields and returns wallet signatures', async() => { + const { useSwapWallet } = await import('./useSwapWallet'); + const { result } = renderHook(useSwapWallet, { wrapper: WalletProvider }); + await waitFor(() => expect(queryClient.isFetching()).toBe(0)); + expect(await result.current.handleRequest('send', 'eth_sendTransaction', [ { + to: OTHER_ACCOUNT, value: '0x123456789abcdef', gas: '0x5208', data: '0x1234', + } ])).toBe(TX_HASH); + expect(sentTransactions).toEqual([ expect.objectContaining({ + from: ACCOUNT, to: OTHER_ACCOUNT, value: '0x123456789abcdef', gas: '0x5208', data: '0x1234', + }) ]); + expect(await result.current.handleRequest('sign', 'personal_sign', [ '0x1234', ACCOUNT ])).toBe(SIGNATURE); + expect(await result.current.handleRequest('typed', 'eth_signTypedData_v4', [ ACCOUNT, JSON.stringify({ + domain: { chainId: mainnet.id }, types: { Message: [ { name: 'value', type: 'string' } ] }, primaryType: 'Message', message: { value: 'test' }, + }) ])).toBe(SIGNATURE); + }); + + it('propagates a rejected transaction without reporting a successful send', async() => { + const { useSwapWallet } = await import('./useSwapWallet'); + const { result } = renderHook(useSwapWallet, { wrapper: WalletProvider }); + await waitFor(() => expect(queryClient.isFetching()).toBe(0)); + rejectTransaction = true; + await expect(result.current.handleRequest('send', 'eth_sendTransaction', [ { to: OTHER_ACCOUNT, value: '0x0' } ])) + .rejects.toThrow('User rejected the request'); + expect(sentTransactions).toEqual([]); + }); + + it('bridges iframe requests and ignores messages from a different origin', async() => { + const { useSwapWallet } = await import('./useSwapWallet'); + const Widget = () => { + const handler = useSwapWallet(); + const handlers = useMemo(() => [ handler ], [ handler ]); + return <LiFiWidgetLight config={ WIDGET_CONFIG } handlers={ handlers }/>; + }; + const { container } = render(<WalletProvider><Widget/></WalletProvider>); + const iframe = container.querySelector('iframe'); + expect(iframe?.src).toBe(`${ WIDGET_ORIGIN }/`); + const frameWindow = iframe!.contentWindow!; + const postMessage = vi.spyOn(frameWindow, 'postMessage'); + const dispatch = (origin: string) => window.dispatchEvent(new MessageEvent('message', { + origin, source: frameWindow, data: { source: 'widget-light', type: 'READY' }, + })); + act(() => { + dispatch('https://untrusted.test'); + }); + expect(postMessage).not.toHaveBeenCalled(); + act(() => { + dispatch(WIDGET_ORIGIN); + }); + expect(postMessage).toHaveBeenCalledWith(expect.objectContaining({ + type: 'INIT', ecosystems: [ expect.objectContaining({ chainType: 'EVM', state: expect.objectContaining({ accounts: [ ACCOUNT ] }) }) ], + }), WIDGET_ORIGIN); + + act(() => { + window.dispatchEvent(new MessageEvent('message', { + origin: WIDGET_ORIGIN, source: frameWindow, + data: { source: 'widget-light', type: 'RPC_REQUEST', chainType: 'EVM', id: 'accounts', method: 'eth_accounts' }, + })); + }); + await waitFor(() => expect(postMessage).toHaveBeenCalledWith(expect.objectContaining({ + type: 'RPC_RESPONSE', id: 'accounts', result: [ ACCOUNT ], + }), WIDGET_ORIGIN)); + + act(() => walletConfig.connectors[0].onAccountsChanged([ OTHER_ACCOUNT ])); + await waitFor(() => expect(postMessage).toHaveBeenCalledWith(expect.objectContaining({ + type: 'EVENT', event: 'accountsChanged', data: [ OTHER_ACCOUNT ], + }), WIDGET_ORIGIN)); + }); +}); + +describe('Swap batch activity', () => { + it.each([ + { name: 'atomic', batchResult: { id: BATCH_ID }, status: 200, hashes: [ TX_HASH ] }, + { name: 'multiple receipts', batchResult: { id: BATCH_ID }, status: 200, hashes: [ APPROVAL_HASH, TX_HASH ] }, + { name: 'legacy wallet response', batchResult: BATCH_ID, status: 'CONFIRMED', hashes: [ TX_HASH ] }, + ])('confirms the swap receipt once for $name', async({ batchResult, status, hashes }) => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result, state, activityRequests } = await renderTrackedSwap(); + state.batchResult = batchResult; + expect(await result.current.wallet.handleRequest('send-batch', 'wallet_sendCalls', BATCH_PARAMS)).toEqual(batchResult); + expect(activityRequests).toEqual([ { + path: '/api/v1/user/activity/track/transaction', + body: { from_address: ACCOUNT, to_address: OTHER_ACCOUNT, chain_id: '1' }, + } ]); + + await result.current.wallet.handleRequest('pending', 'wallet_getCallsStatus', [ BATCH_ID ]); + expect(activityRequests).toHaveLength(1); + await act(async() => { + await result.current.wallet.handleRequest('switch', 'wallet_switchEthereumChain', [ { chainId: '0xa' } ]); + }); + state.status = { status, receipts: hashes.map((transactionHash) => ({ status: '0x1', transactionHash })) }; + const responses = await Promise.all([ + result.current.wallet.handleRequest('poll-1', 'wallet_getCallsStatus', [ BATCH_ID ]), + result.current.wallet.handleRequest('poll-2', 'wallet_getCallsStatus', [ BATCH_ID ]), + ]); + expect(responses).toEqual([ state.status, state.status ]); + await result.current.wallet.handleRequest('poll-3', 'wallet_getCallsStatus', [ BATCH_ID ]); + expect(activityRequests).toHaveLength(2); + expect(activityRequests[1]).toEqual({ + path: '/api/v1/activity/track/transaction/confirm', body: { tx_hash: TX_HASH, token: ACTIVITY_TOKEN }, + }); + expect(mixpanel.track).toHaveBeenCalledTimes(1); + expect(mixpanel.track).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ + Action: 'Send Transaction', Address: ACCOUNT, AppId: 'swap', Source: 'Essential dapps', ChainId: '1', + }), undefined); + }); + }); + + it('does not report a batch that the wallet rejects', async() => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result, state, activityRequests } = await renderTrackedSwap(); + state.reject = true; + await expect(result.current.wallet.handleRequest('reject-batch', 'wallet_sendCalls', BATCH_PARAMS)).rejects.toThrow('User rejected'); + state.status = { status: 200, receipts: [ { status: '0x1', transactionHash: TX_HASH } ] }; + await result.current.wallet.handleRequest('poll', 'wallet_getCallsStatus', [ BATCH_ID ]); + expect(activityRequests).toHaveLength(1); + expect(mixpanel.track).not.toHaveBeenCalled(); + }); + }); + + it.each([ + { status: 300, receipts: [ { status: '0x1', transactionHash: TX_HASH } ] }, + { status: 400, receipts: [] }, + { status: 500, receipts: [ { status: '0x0', transactionHash: TX_HASH } ] }, + { status: 200, receipts: [ { status: '0x0', transactionHash: TX_HASH } ] }, + { status: 200, receipts: [ { status: '0x1', transactionHash: BATCH_ID } ] }, + { status: 200, receipts: [] }, + ])('does not confirm failed or missing transaction receipts: %j', async(response) => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result, state, activityRequests } = await renderTrackedSwap(); + await result.current.wallet.handleRequest('send-batch', 'wallet_sendCalls', BATCH_PARAMS); + state.status = response; + await result.current.wallet.handleRequest('poll', 'wallet_getCallsStatus', [ BATCH_ID ]); + expect(activityRequests).toHaveLength(1); + expect(mixpanel.track).toHaveBeenCalledTimes(1); + }); + }); + + it.each([ [ {} ], [ { calls: [] } ] ])('forwards a batch without swap calls without tracking it: %j', async(params) => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result, activityRequests } = await renderTrackedSwap(); + expect(await result.current.wallet.handleRequest('send-batch', 'wallet_sendCalls', params)).toEqual({ id: BATCH_ID }); + expect(activityRequests).toEqual([]); + expect(mixpanel.track).not.toHaveBeenCalled(); + }); + }); + + it('does not retain or log an invalid batch ID', async() => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result, state, activityRequests } = await renderTrackedSwap(); + state.batchResult = 42; + expect(await result.current.wallet.handleRequest('send-batch', 'wallet_sendCalls', BATCH_PARAMS)).toBe(42); + expect(activityRequests).toHaveLength(1); + expect(mixpanel.track).not.toHaveBeenCalled(); + state.status = { status: 200, receipts: [ { status: '0x1', transactionHash: TX_HASH } ] }; + await result.current.wallet.handleRequest('poll', 'wallet_getCallsStatus', [ BATCH_ID ]); + expect(activityRequests).toHaveLength(1); + }); + }); + + it('ignores a status response without a valid batch ID', async() => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result, state, activityRequests } = await renderTrackedSwap(); + await result.current.wallet.handleRequest('send-batch', 'wallet_sendCalls', BATCH_PARAMS); + state.status = { status: 200, receipts: [ { status: '0x1', transactionHash: TX_HASH } ] }; + expect(await result.current.wallet.handleRequest('poll', 'wallet_getCallsStatus', { '0': BATCH_ID })).toEqual(state.status); + expect(activityRequests).toHaveLength(1); + }); + }); + + it.each([ 100, 199, 'PENDING' ])('does not confirm an unfinished batch with status %s', async(status) => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result, state, activityRequests } = await renderTrackedSwap(); + await result.current.wallet.handleRequest('send-batch', 'wallet_sendCalls', BATCH_PARAMS); + state.status = { status, receipts: [ { status: '0x1', transactionHash: TX_HASH } ] }; + await result.current.wallet.handleRequest('poll', 'wallet_getCallsStatus', [ BATCH_ID ]); + expect(activityRequests).toHaveLength(1); + state.status = { status: 200, receipts: [ { status: '0x1', transactionHash: TX_HASH } ] }; + await result.current.wallet.handleRequest('confirmed', 'wallet_getCallsStatus', [ BATCH_ID ]); + expect(activityRequests).toHaveLength(2); + }); + }); + + it('forgets a failed batch even if a later poll reports success', async() => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result, state, activityRequests } = await renderTrackedSwap(); + await result.current.wallet.handleRequest('send-batch', 'wallet_sendCalls', BATCH_PARAMS); + state.status = { status: 300, receipts: [ { status: '0x1', transactionHash: TX_HASH } ] }; + await result.current.wallet.handleRequest('failed', 'wallet_getCallsStatus', [ BATCH_ID ]); + state.status = { status: 200, receipts: [ { status: '0x1', transactionHash: TX_HASH } ] }; + await result.current.wallet.handleRequest('later', 'wallet_getCallsStatus', [ BATCH_ID ]); + expect(activityRequests).toHaveLength(1); + }); + }); + + it('requires every receipt to succeed before confirming the last swap hash', async() => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result, state, activityRequests } = await renderTrackedSwap(); + await result.current.wallet.handleRequest('send-batch', 'wallet_sendCalls', BATCH_PARAMS); + state.status = { status: 200, receipts: [ + { status: '0x0', transactionHash: APPROVAL_HASH }, + { status: '0x1', transactionHash: TX_HASH }, + ] }; + await result.current.wallet.handleRequest('poll', 'wallet_getCallsStatus', [ BATCH_ID ]); + expect(activityRequests).toHaveLength(1); + }); + }); + + it('tracks a single transaction with its recipient and confirms its returned hash', async() => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result, activityRequests } = await renderTrackedSwap(); + expect(await result.current.wallet.handleRequest('send', 'eth_sendTransaction', [ { to: OTHER_ACCOUNT, value: '0x1' } ])).toBe(TX_HASH); + expect(activityRequests).toEqual([ + { path: '/api/v1/user/activity/track/transaction', body: { from_address: ACCOUNT, to_address: OTHER_ACCOUNT, chain_id: '1' } }, + { path: '/api/v1/activity/track/transaction/confirm', body: { tx_hash: TX_HASH, token: ACTIVITY_TOKEN } }, + ]); + expect(mixpanel.track).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ Action: 'Send Transaction' }), undefined); + }); + }); + + it.each([ + { method: 'personal_sign', params: [ '0x1234', ACCOUNT ], action: 'Sign Message' }, + { method: 'eth_sign', params: [ ACCOUNT, '0x1234' ], action: 'Sign Message' }, + { method: 'eth_signTypedData_v4', params: [ ACCOUNT, JSON.stringify({ + domain: { chainId: mainnet.id }, types: { Message: [ { name: 'value', type: 'string' } ] }, + primaryType: 'Message', message: { value: 'test' }, + }) ], action: 'Sign Typed Data' }, + ])('logs $action for $method', async({ method, params, action }) => { + await withEnvs(ENV_OVERRIDES, async() => { + const { result } = await renderTrackedSwap(); + await result.current.wallet.handleRequest('sign', method, params); + expect(mixpanel.track).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ Action: action }), undefined); + }); + }); +}); diff --git a/src/features/marketplace/pages/essential-dapp/swap/useSwapWallet.ts b/src/features/marketplace/pages/essential-dapp/swap/useSwapWallet.ts new file mode 100644 index 00000000000..f399b5e4cec --- /dev/null +++ b/src/features/marketplace/pages/essential-dapp/swap/useSwapWallet.ts @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { IframeEcosystemHandler } from '@lifi/widget-light'; +import { useEthereumIframeHandler } from '@lifi/widget-light/ethereum'; +import { useCallback, useMemo, useRef } from 'react'; +import * as v from 'valibot'; +import { isHash } from 'viem'; + +import { useMarketplaceWalletActivity } from '../../../hooks/useMarketplaceWalletActivity'; + +const BATCH_SUCCESS_STATUS = 200; +const BATCH_FAILURE_STATUS = 300; +type ConfirmTransaction = (hash: string) => Promise<void>; +const transactionRequestSchema = v.tuple([ v.object({ to: v.optional(v.string()) }) ]); +const batchRequestSchema = v.tuple([ v.object({ calls: v.array(v.object({ to: v.optional(v.string()) })) }) ]); +const batchStatusRequestSchema = v.tuple([ v.string() ]); +const batchIdSchema = v.union([ v.string(), v.object({ id: v.string() }) ]); +const batchStatusSchema = v.object({ + status: v.union([ v.number(), v.literal('CONFIRMED'), v.literal('PENDING') ]), + receipts: v.optional(v.array(v.object({ status: v.string(), transactionHash: v.string() }))), +}); + +export function useSwapWallet(): IframeEcosystemHandler { + const handler = useEthereumIframeHandler(); + const { prepareTransaction, trackTransaction, logEvent } = useMarketplaceWalletActivity('swap', true); + const pendingBatches = useRef(new Map<string, ConfirmTransaction>()); + + const sendCalls = useCallback<IframeEcosystemHandler['handleRequest']>(async(id, method, params) => { + const request = v.safeParse(batchRequestSchema, params); + if (!request.success || !request.output[0].calls.length) { + return handler.handleRequest(id, method, params); + } + // LI.FI appends the swap call after approvals and uses the last receipt for its transaction hash. + const confirm = await prepareTransaction(request.output[0].calls.at(-1)?.to ?? ''); + const result = await handler.handleRequest(id, method, params); + const parsedId = v.safeParse(batchIdSchema, result); + if (parsedId.success) { + const batchId = typeof parsedId.output === 'string' ? parsedId.output : parsedId.output.id; + pendingBatches.current.set(batchId, confirm); + logEvent('Send Transaction'); + } + return result; + }, [ handler, prepareTransaction, logEvent ]); + + const confirmCalls = useCallback(async(params: unknown, result: unknown) => { + const request = v.safeParse(batchStatusRequestSchema, params); + if (!request.success) { + return; + } + const [ batchId ] = request.output; + const confirm = pendingBatches.current.get(batchId); + const response = v.safeParse(batchStatusSchema, result); + if (!confirm || !response.success) { + return; + } + const { status, receipts } = response.output; + // The parsed status is numeric or one of two words; Number maps the words to NaN. + const numericStatus = Number(status); + if (numericStatus >= BATCH_FAILURE_STATUS) { + pendingBatches.current.delete(batchId); + return; + } + const isConfirmed = status === 'CONFIRMED' || numericStatus >= BATCH_SUCCESS_STATUS; + const hash = receipts?.at(-1)?.transactionHash; + if (!isConfirmed || !hash || !isHash(hash) || !receipts?.every((receipt) => receipt.status === '0x1')) { + return; + } + pendingBatches.current.delete(batchId); + await confirm(hash); + }, []); + + const handleRequest = useCallback<IframeEcosystemHandler['handleRequest']>(async(id, method, params) => { + if (method === 'wallet_sendCalls') { + return sendCalls(id, method, params); + } + if (method === 'eth_sendTransaction') { + const request = v.safeParse(transactionRequestSchema, params); + const to = request.success ? request.output[0].to ?? '' : ''; + return trackTransaction(to, () => handler.handleRequest(id, method, params)); + } + + const result = await handler.handleRequest(id, method, params); + if (method === 'wallet_getCallsStatus') { + await confirmCalls(params, result); + } else if (method === 'personal_sign' || method === 'eth_sign') { + logEvent('Sign Message'); + } else if (method === 'eth_signTypedData_v4') { + logEvent('Sign Typed Data'); + } + return result; + }, [ handler, trackTransaction, logEvent, sendCalls, confirmCalls ]); + + return useMemo(() => ({ ...handler, handleRequest }), [ handler, handleRequest ]); +} diff --git a/src/features/marketplace/pages/essential-dapp/swap/widget-config.spec.ts b/src/features/marketplace/pages/essential-dapp/swap/widget-config.spec.ts new file mode 100644 index 00000000000..5153754c9b7 --- /dev/null +++ b/src/features/marketplace/pages/essential-dapp/swap/widget-config.spec.ts @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getSwapWidgetConfig } from './widget-config'; + +const SWAP_CONFIG = { chains: [ '1', '10' ], fee: '0.004', integrator: 'blockscout' }; + +describe('getSwapWidgetConfig', () => { + it('keeps the integrator fee and limits both sides of a swap to configured chains', () => { + expect(getSwapWidgetConfig(SWAP_CONFIG, '10', [])).toMatchObject({ + integrator: 'blockscout', + feeConfig: { fee: 0.004 }, + chains: { allow: [ 1, 10 ] }, + fromChain: 10, + fromToken: '0x0000000000000000000000000000000000000000', + hiddenUI: { appearance: true, language: true, gasRefuelMessage: true }, + }); + }); + + it.each([ '137', undefined ])('defaults to the first allowed chain when the explorer chain is %s', (chainId) => { + expect(getSwapWidgetConfig(SWAP_CONFIG, chainId, [])).toMatchObject({ fromChain: 1 }); + }); + + it('only sends available explorer URLs for allowed chains', () => { + const result = getSwapWidgetConfig(SWAP_CONFIG, '1', [ + { id: '1', name: 'Ethereum', explorer_url: 'https://eth.blockscout.com' }, + { id: '10', name: 'Optimism' }, + { id: '137', name: 'Polygon', explorer_url: 'https://polygon.blockscout.com' }, + ]); + expect(result.explorerUrls).toEqual({ '1': [ 'https://eth.blockscout.com' ] }); + expect(JSON.parse(JSON.stringify(result))).toEqual(result); + }); +}); diff --git a/src/features/marketplace/pages/essential-dapp/swap/widget-config.ts b/src/features/marketplace/pages/essential-dapp/swap/widget-config.ts new file mode 100644 index 00000000000..1617f3267a3 --- /dev/null +++ b/src/features/marketplace/pages/essential-dapp/swap/widget-config.ts @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { WidgetLightConfig } from '@lifi/widget-light'; +import { zeroAddress } from 'viem'; + +import type { EssentialDappsChainConfig, EssentialDappsConfig } from 'src/features/marketplace/types/client'; + +export function getSwapWidgetConfig( + swap: NonNullable<EssentialDappsConfig['swap']>, + chainId: string | undefined, + chainConfigs: Array<EssentialDappsChainConfig>, +): WidgetLightConfig { + const chains = swap.chains.map(Number); + const explorerUrls = Object.fromEntries(chainConfigs.flatMap((chain) => + swap.chains.includes(chain.id) && chain.explorer_url ? [ [ Number(chain.id), [ chain.explorer_url ] ] ] : [], + )); + + return { + integrator: swap.integrator, + feeConfig: { fee: Number(swap.fee) }, + chains: { allow: chains }, + fromChain: chains.includes(Number(chainId)) ? Number(chainId) : chains[0], + fromToken: zeroAddress, + explorerUrls, + variant: 'compact', + mode: 'default', + hiddenUI: { appearance: true, language: true, gasRefuelMessage: true }, + }; +} diff --git a/src/features/marketplace/pages/index/Marketplace.pw.tsx b/src/features/marketplace/pages/index/Marketplace.pw.tsx index 465cb8d7df5..f7463204d50 100644 --- a/src/features/marketplace/pages/index/Marketplace.pw.tsx +++ b/src/features/marketplace/pages/index/Marketplace.pw.tsx @@ -5,6 +5,7 @@ import { apps as appsMock } from 'src/features/marketplace/mocks/dapps'; import config from 'src/config'; +import type { TestFnArgs } from 'playwright/lib'; import { test, expect, devices } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; @@ -19,15 +20,19 @@ const ESSENTIAL_DAPPS_CONFIG = JSON.stringify({ const MARKETPLACE_BANNER_CONTENT_URL = 'https://localhost/marketplace-banner.html'; const MARKETPLACE_BANNER_LINK_URL = 'https://example.com'; -test.beforeEach(async({ mockEnvs, mockAssetResponse, mockApiResponse }) => { +const mockDapps = (mockApiResponse: TestFnArgs['mockApiResponse']) => { + return mockApiResponse('admin:marketplace_dapps', appsMock, { pathParams: { instanceId: config.apis.admin?.instanceId } }); +}; + +test.beforeEach(async({ mockEnvs, mockAssetResponse }) => { await mockEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_ENABLED', 'true' ], ]); - await mockApiResponse('admin:marketplace_dapps', appsMock, { pathParams: { instanceId: config.apis.admin?.instanceId } }); await Promise.all(appsMock.map(app => mockAssetResponse(app.logo, './playwright/mocks/image_s.jpg'))); }); -test('base view +@dark-mode', async({ render, page }) => { +test('base view +@dark-mode', async({ render, page, mockApiResponse }) => { + await mockDapps(mockApiResponse); await page.evaluate(() => window.localStorage.setItem('favoriteApps', '["hop-exchange"]')); const component = await render(<Marketplace/>); @@ -35,10 +40,11 @@ test('base view +@dark-mode', async({ render, page }) => { await expect(component).toHaveScreenshot(); }); -test('with featured app +@dark-mode', async({ render, mockEnvs, page }) => { +test('with featured app +@dark-mode', async({ render, mockEnvs, mockApiResponse, page }) => { await mockEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_FEATURED_APP', 'hop-exchange' ], ]); + await mockDapps(mockApiResponse); await page.evaluate(() => window.localStorage.setItem('favoriteApps', '["hop-exchange"]')); const component = await render(<Marketplace/>); @@ -49,11 +55,12 @@ test('with featured app +@dark-mode', async({ render, mockEnvs, page }) => { }); }); -test('with banner +@dark-mode', async({ render, mockEnvs, mockConfigResponse, page }) => { +test('with banner +@dark-mode', async({ render, mockEnvs, mockApiResponse, mockConfigResponse, page }) => { await mockEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL', MARKETPLACE_BANNER_CONTENT_URL ], [ 'NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL', MARKETPLACE_BANNER_LINK_URL ], ]); + await mockDapps(mockApiResponse); await mockConfigResponse('MARKETPLACE_BANNER_CONTENT_URL', MARKETPLACE_BANNER_CONTENT_URL, './playwright/mocks/page.html', true); const component = await render(<Marketplace/>); @@ -63,12 +70,13 @@ test('with banner +@dark-mode', async({ render, mockEnvs, mockConfigResponse, pa }); }); -test('with essential dapps +@dark-mode', async({ render, mockEnvs, mockConfigResponse, page }) => { +test('with essential dapps +@dark-mode', async({ render, mockEnvs, mockApiResponse, mockConfigResponse, page }) => { await mockEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG', ESSENTIAL_DAPPS_CONFIG ], [ 'NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL', MARKETPLACE_BANNER_CONTENT_URL ], [ 'NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL', MARKETPLACE_BANNER_LINK_URL ], ]); + await mockDapps(mockApiResponse); await mockConfigResponse('MARKETPLACE_BANNER_CONTENT_URL', MARKETPLACE_BANNER_CONTENT_URL, './playwright/mocks/page.html', true); const component = await render(<Marketplace/>); await expect(component).toHaveScreenshot({ @@ -82,7 +90,8 @@ test('with essential dapps +@dark-mode', async({ render, mockEnvs, mockConfigRes test.describe('mobile', () => { test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - test('base view', async({ render, page }) => { + test('base view', async({ render, page, mockApiResponse }) => { + await mockDapps(mockApiResponse); await page.evaluate(() => window.localStorage.setItem('favoriteApps', '["hop-exchange"]')); const component = await render( <Box> @@ -97,33 +106,36 @@ test.describe('mobile', () => { await expect(component).toHaveScreenshot(); }); - test('with featured app', async({ render, mockEnvs, page }) => { + test('with featured app', async({ render, mockEnvs, mockApiResponse, page }) => { await mockEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_FEATURED_APP', 'hop-exchange' ], ]); + await mockDapps(mockApiResponse); await page.evaluate(() => window.localStorage.setItem('favoriteApps', '["hop-exchange"]')); const component = await render(<Marketplace/>); await expect(component).toHaveScreenshot(); }); - test('with banner', async({ render, mockEnvs, mockConfigResponse }) => { + test('with banner', async({ render, mockEnvs, mockApiResponse, mockConfigResponse }) => { await mockEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL', MARKETPLACE_BANNER_CONTENT_URL ], [ 'NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL', MARKETPLACE_BANNER_LINK_URL ], ]); + await mockDapps(mockApiResponse); await mockConfigResponse('MARKETPLACE_BANNER_CONTENT_URL', MARKETPLACE_BANNER_CONTENT_URL, './playwright/mocks/page.html', true); const component = await render(<Marketplace/>); await expect(component).toHaveScreenshot(); }); - test('with essential dapps', async({ render, mockEnvs, mockConfigResponse }) => { + test('with essential dapps', async({ render, mockEnvs, mockApiResponse, mockConfigResponse }) => { await mockEnvs([ [ 'NEXT_PUBLIC_MARKETPLACE_ESSENTIAL_DAPPS_CONFIG', ESSENTIAL_DAPPS_CONFIG ], [ 'NEXT_PUBLIC_MARKETPLACE_BANNER_CONTENT_URL', MARKETPLACE_BANNER_CONTENT_URL ], [ 'NEXT_PUBLIC_MARKETPLACE_BANNER_LINK_URL', MARKETPLACE_BANNER_LINK_URL ], ]); + await mockDapps(mockApiResponse); await mockConfigResponse('MARKETPLACE_BANNER_CONTENT_URL', MARKETPLACE_BANNER_CONTENT_URL, './playwright/mocks/page.html', true); const component = await render(<Marketplace/>); await expect(component).toHaveScreenshot(); diff --git a/src/features/marketplace/pages/index/MarketplaceAppCard.tsx b/src/features/marketplace/pages/index/MarketplaceAppCard.tsx index 563792f0723..19c635dc079 100644 --- a/src/features/marketplace/pages/index/MarketplaceAppCard.tsx +++ b/src/features/marketplace/pages/index/MarketplaceAppCard.tsx @@ -6,7 +6,7 @@ import React, { useCallback } from 'react'; import type { MarketplaceDapp } from '@blockscout/admin-rs-types'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { route } from 'src/shared/router/routes'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; @@ -54,7 +54,7 @@ const MarketplaceAppCard = ({ const categoriesLabel = categories.join(', '); const handleInfoClick = useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { Type: 'More button', Info: id, Source: 'Discovery view' }); + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'More button', Info: id, Source: 'Discovery view' }); }, [ id ]); const handleFavoriteClick = useCallback(() => { diff --git a/src/features/marketplace/pages/index/MarketplaceAppCardLink.tsx b/src/features/marketplace/pages/index/MarketplaceAppCardLink.tsx index cb38e25d1b5..ac9e029fe3f 100644 --- a/src/features/marketplace/pages/index/MarketplaceAppCardLink.tsx +++ b/src/features/marketplace/pages/index/MarketplaceAppCardLink.tsx @@ -1,10 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { MouseEvent } from 'react'; +import { route } from 'src/shared/router/routes'; + import { LinkOverlay } from 'src/toolkit/chakra/link'; type Props = { diff --git a/src/features/marketplace/pages/index/MarketplaceList.tsx b/src/features/marketplace/pages/index/MarketplaceList.tsx index 265e714a3fc..534a8c5a022 100644 --- a/src/features/marketplace/pages/index/MarketplaceList.tsx +++ b/src/features/marketplace/pages/index/MarketplaceList.tsx @@ -7,6 +7,7 @@ import type { MouseEvent } from 'react'; import type { MarketplaceDapp } from '@blockscout/admin-rs-types'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { MARKETPLACE_APPS_PLACEHOLDER_COUNT } from '../../hooks/useMarketplaceApps'; @@ -24,6 +25,8 @@ type Props = { resetKey?: string; }; +const getBaseKey = (app: MarketplaceDapp): string => app.id; + const MarketplaceList = ({ apps, favoriteApps, onFavoriteClick, isLoading, selectedCategoryId, onAppClick, graphLinksQuery, resetKey, @@ -40,6 +43,8 @@ const MarketplaceList = ({ onFavoriteClick(id, isFavorite, 'Discovery view'); }, [ onFavoriteClick ]); + const keys = useUniqueKeys(apps, getBaseKey); + return apps.length > 0 ? ( <> <Grid @@ -50,7 +55,7 @@ const MarketplaceList = ({ > { apps.slice(0, renderedItemsNum).map((app, index) => ( <MarketplaceAppCard - key={ app.id + (isLoading ? index : '') } + key={ keys[index] } id={ app.id } external={ app.external } url={ app.url } diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_base-view-dark-mode-1.png index 9f811a13741..192a2c6ddf4 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-banner-dark-mode-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-banner-dark-mode-1.png index 7af998dd443..49b90bd5448 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-banner-dark-mode-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-banner-dark-mode-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-essential-dapps-dark-mode-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-essential-dapps-dark-mode-1.png index f469283ee87..d3db8018302 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-essential-dapps-dark-mode-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-essential-dapps-dark-mode-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-featured-app-dark-mode-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-featured-app-dark-mode-1.png index af591d13868..cf436522cfe 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-featured-app-dark-mode-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_dark-color-mode_with-featured-app-dark-mode-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_base-view-dark-mode-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_base-view-dark-mode-1.png index ffc20ed5b80..ffaff2575c1 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_base-view-dark-mode-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-base-view-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-base-view-1.png index 90f7d9b7199..2f916b83e65 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-base-view-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-base-view-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-banner-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-banner-1.png index bed853bc58b..94f4ae62ca2 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-banner-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-banner-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-essential-dapps-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-essential-dapps-1.png index e194014e7df..ca309df771f 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-essential-dapps-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-essential-dapps-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-featured-app-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-featured-app-1.png index 787ac079134..76bfb9bdd16 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-featured-app-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_mobile-with-featured-app-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-banner-dark-mode-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-banner-dark-mode-1.png index 295d68b2cdf..3f1ea7e0e36 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-banner-dark-mode-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-banner-dark-mode-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-essential-dapps-dark-mode-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-essential-dapps-dark-mode-1.png index 4832f9bc6e3..60ff1145824 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-essential-dapps-dark-mode-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-essential-dapps-dark-mode-1.png differ diff --git a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-featured-app-dark-mode-1.png b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-featured-app-dark-mode-1.png index 78e42b59794..c75f4e56ae2 100644 Binary files a/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-featured-app-dark-mode-1.png and b/src/features/marketplace/pages/index/__screenshots__/Marketplace.pw.tsx_default_with-featured-app-dark-mode-1.png differ diff --git a/src/features/marketplace/pages/index/banner/FeaturedApp.tsx b/src/features/marketplace/pages/index/banner/FeaturedApp.tsx index 29f9fcd188c..12a4cd1b95e 100644 --- a/src/features/marketplace/pages/index/banner/FeaturedApp.tsx +++ b/src/features/marketplace/pages/index/banner/FeaturedApp.tsx @@ -1,14 +1,14 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import type { MouseEvent } from 'react'; import React, { useCallback } from 'react'; import type { MarketplaceDapp } from '@blockscout/admin-rs-types'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; import { useColorModeValue } from 'src/toolkit/chakra/color-mode'; import { Heading } from 'src/toolkit/chakra/heading'; @@ -41,7 +41,7 @@ const FeaturedApp = ({ const categoriesLabel = categories.join(', '); const handleInfoClick = useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { Type: 'More button', Info: id, Source: 'Banner' }); + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'More button', Info: id, Source: 'Banner' }); }, [ id ]); const handleFavoriteClick = useCallback(() => { diff --git a/src/features/marketplace/pages/index/banner/FeaturedAppMobile.tsx b/src/features/marketplace/pages/index/banner/FeaturedAppMobile.tsx index d0c89a78472..50928c9c362 100644 --- a/src/features/marketplace/pages/index/banner/FeaturedAppMobile.tsx +++ b/src/features/marketplace/pages/index/banner/FeaturedAppMobile.tsx @@ -1,12 +1,13 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import type { MouseEvent } from 'react'; import React from 'react'; import type { MarketplaceDapp } from '@blockscout/admin-rs-types'; +import { route } from 'src/shared/router/routes'; + import { useColorModeValue } from 'src/toolkit/chakra/color-mode'; import { Heading } from 'src/toolkit/chakra/heading'; import { IconButton } from 'src/toolkit/chakra/icon-button'; diff --git a/src/features/marketplace/pages/index/banner/IframeBanner.tsx b/src/features/marketplace/pages/index/banner/IframeBanner.tsx index 0541ddc227e..1a8c13687b6 100644 --- a/src/features/marketplace/pages/index/banner/IframeBanner.tsx +++ b/src/features/marketplace/pages/index/banner/IframeBanner.tsx @@ -3,7 +3,7 @@ import { chakra } from '@chakra-ui/react'; import React, { useCallback, useState } from 'react'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; @@ -16,7 +16,7 @@ const IframeBanner = ({ contentUrl, linkUrl }: { contentUrl: string; linkUrl: st }, []); const handleClick = useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.PROMO_BANNER, { Source: 'Marketplace', Link: linkUrl }); + analytics.logEvent(analytics.EventTypes.PROMO_BANNER, { Source: 'Marketplace', Link: linkUrl }); }, [ linkUrl ]); return ( diff --git a/src/features/marketplace/pages/index/essential-dapps/EssentialDappCard.tsx b/src/features/marketplace/pages/index/essential-dapps/EssentialDappCard.tsx index 4323982cc99..23d97d846d9 100644 --- a/src/features/marketplace/pages/index/essential-dapps/EssentialDappCard.tsx +++ b/src/features/marketplace/pages/index/essential-dapps/EssentialDappCard.tsx @@ -1,7 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; + +import { route } from 'src/shared/router/routes'; import { Button } from 'src/toolkit/chakra/button'; import { useColorModeValue } from 'src/toolkit/chakra/color-mode'; diff --git a/src/features/marketplace/types/client.ts b/src/features/marketplace/types/client.ts index 5583efe11bb..c731e00bb13 100644 --- a/src/features/marketplace/types/client.ts +++ b/src/features/marketplace/types/client.ts @@ -20,7 +20,6 @@ export interface EssentialDappsChainConfig extends ExternalChain { export type EssentialDappsConfig = { swap?: { - url: string; chains: Array<string>; fee: string; integrator: string; diff --git a/src/features/marketplace/utils/dapp.spec.ts b/src/features/marketplace/utils/dapp.spec.ts index d2e4f45b345..cee4929f9be 100644 --- a/src/features/marketplace/utils/dapp.spec.ts +++ b/src/features/marketplace/utils/dapp.spec.ts @@ -1,11 +1,13 @@ -import type { NextRouter } from 'next/router'; +import type { Router } from 'src/shared/router/useRouter'; import { describe, it, expect, beforeEach, vi } from 'vitest'; import { getAppUrl } from './dapp'; +type MutableRouter = { -readonly [K in keyof Router]: Router[K] }; + describe('getAppUrl', () => { - let router: NextRouter; + let router: MutableRouter; beforeEach(() => { router = { @@ -13,7 +15,7 @@ describe('getAppUrl', () => { asPath: '/current/path?someParam=value', query: {}, replace: vi.fn(), - } as unknown as NextRouter; + } as unknown as MutableRouter; }); it('should return undefined if url is undefined', () => { @@ -31,7 +33,7 @@ describe('getAppUrl', () => { router.query.url = 'https://different.com/custom-path?query=value'; const result = getAppUrl('https://example.com/app', router); expect(result).toBe('https://example.com/app?someParam=value'); - expect(router.replace).toHaveBeenCalledWith({ pathname: '/current/path', query: {}, hash: '' }, undefined, { shallow: true }); + expect(router.replace).toHaveBeenCalledWith({ pathname: '/current/path', query: {}, hash: '' }, { shallow: true }); }); it('should construct the new url with custom params and hash', () => { diff --git a/src/features/marketplace/utils/dapp.ts b/src/features/marketplace/utils/dapp.ts index 341e3363873..5356aedc65a 100644 --- a/src/features/marketplace/utils/dapp.ts +++ b/src/features/marketplace/utils/dapp.ts @@ -1,11 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { NextRouter } from 'next/router'; - import getQueryParamString from 'src/shared/router/get-query-param-string'; import removeQueryParam from 'src/shared/router/remove-query-param'; +import type { Router } from 'src/shared/router/useRouter'; -export function getAppUrl(url: string | undefined, router: NextRouter) { +export function getAppUrl(url: string | undefined, router: Router) { if (!url) { return; } diff --git a/src/features/metasuites/hooks/useNotifyOnNavigation.ts b/src/features/metasuites/hooks/useNotifyOnNavigation.ts new file mode 100644 index 00000000000..4243dcda666 --- /dev/null +++ b/src/features/metasuites/hooks/useNotifyOnNavigation.ts @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import config from 'src/config'; +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { usePathname } from 'src/shared/router/usePathname'; +import { useRouter } from 'src/shared/router/useRouter'; + +export default function useNotifyOnNavigation() { + const router = useRouter(); + const pathname = usePathname(); + const tab = getQueryParamString(router.query.tab); + + React.useEffect(() => { + if (config.features.metasuites.isEnabled) { + window.postMessage({ source: 'APP_ROUTER', type: 'PATHNAME_CHANGED' }, window.location.origin); + } + }, [ pathname ]); + + React.useEffect(() => { + if (config.features.metasuites.isEnabled) { + window.postMessage({ source: 'APP_ROUTER', type: 'TAB_CHANGED' }, window.location.origin); + } + }, [ tab ]); +} diff --git a/src/features/metasuites/hooks/useNotifyOnNavigation.tsx b/src/features/metasuites/hooks/useNotifyOnNavigation.tsx deleted file mode 100644 index 572353a6472..00000000000 --- a/src/features/metasuites/hooks/useNotifyOnNavigation.tsx +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { usePathname } from 'next/navigation'; -import { useRouter } from 'next/router'; -import React from 'react'; - -import config from 'src/config'; -import getQueryParamString from 'src/shared/router/get-query-param-string'; - -export default function useNotifyOnNavigation() { - const router = useRouter(); - const pathname = usePathname(); - const tab = getQueryParamString(router.query.tab); - - React.useEffect(() => { - if (config.features.metasuites.isEnabled) { - window.postMessage({ source: 'APP_ROUTER', type: 'PATHNAME_CHANGED' }, window.location.origin); - } - }, [ pathname ]); - - React.useEffect(() => { - if (config.features.metasuites.isEnabled) { - window.postMessage({ source: 'APP_ROUTER', type: 'TAB_CHANGED' }, window.location.origin); - } - }, [ tab ]); -} diff --git a/src/features/multichain-button/config.ts b/src/features/multichain-button/config.ts index 5c9cb3a8163..4ff1f3642f3 100644 --- a/src/features/multichain-button/config.ts +++ b/src/features/multichain-button/config.ts @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { MultichainProviderConfig, MultichainProviderConfigParsed } from 'src/features/multichain-button/types/client'; +import type { MultichainProviderConfig } from 'src/features/multichain-button/types/client'; import marketplace from 'src/features/marketplace/config'; @@ -11,20 +11,18 @@ const value = parseEnvJson<Array<MultichainProviderConfig>>(getEnvValue('NEXT_PU const title = 'Multichain balance'; -const config: Feature<{ providers: Array<MultichainProviderConfigParsed> }> = (() => { +const config: Feature<{ providers: Array<MultichainProviderConfig> }> = (() => { if (value) { return Object.freeze({ title, isEnabled: true, - providers: value - .map((provider) => ({ - name: provider.name, - logoUrl: provider.logo, - urlTemplate: provider.url_template, - dappId: marketplace.isEnabled ? provider.dapp_id : undefined, - promo: provider.promo, - })) - .sort((_, b) => (b.promo ? 1 : -1)), + providers: value.map((provider) => ({ + name: provider.name, + logo: provider.logo, + url_template: provider.url_template, + dapp_id: marketplace.isEnabled ? provider.dapp_id : undefined, + view: provider.view, + })), }); } diff --git a/src/features/multichain-button/pages/address/AddressMultichainButton.module.css b/src/features/multichain-button/pages/address/AddressMultichainButton.module.css deleted file mode 100644 index 77b15a1c6cb..00000000000 --- a/src/features/multichain-button/pages/address/AddressMultichainButton.module.css +++ /dev/null @@ -1,119 +0,0 @@ -/* Animation source - https://codepen.io/ARS/pen/vEwEPP */ -.promo { - position: relative; - z-index: 1; - - &::after { - position: absolute; - top: -2px; - left: -2px; - right: -2px; - bottom: -2px; - margin: auto; - z-index: -1; - border-radius: 6px; - - content: ""; - background: linear-gradient(120deg, #e15eff, #fffb22, #e15eff); - background-size: 400% 400%; - clip-path: polygon( - 0% 100%, - 4px 100%, - 4px 4px, - 20px 4px, - 20px 20px, - 4px 20px, - 4px 100%, - 100% 100%, - 100% 0%, - 0% 0% - ); - animation: gradient 3s ease-in-out 0.5s infinite, border 5s ease-in-out; - } -} - -@keyframes gradient { - 0% { - background-position: 14% 0%; - } - 50% { - background-position: 87% 100%; - } - 100% { - background-position: 14% 0%; - } -} - -@keyframes border { - 0% { - clip-path: polygon( - 0% 100%, - 4px 100%, - 4px 100%, - 4px 100%, - 4px 100%, - 4px 100%, - 4px 100%, - 4px 100%, - 4px 100%, - 0% 100% - ); - } - 5% { - clip-path: polygon( - 0% 100%, - 4px 100%, - 4px 4px, - 4px 4px, - 4px 4px, - 4px 4px, - 4px 4px, - 4px 4px, - 4px 0%, - 0% 0% - ); - } - 10% { - clip-path: polygon( - 0% 100%, - 4px 100%, - 4px 4px, - 20px 4px, - 20px 4px, - 20px 4px, - 20px 4px, - 20px 4px, - 100% 0%, - 0% 0% - ); - } - 15% { - clip-path: polygon( - 0% 100%, - 4px 100%, - 4px 4px, - 20px 4px, - 20px 20px, - 20px 20px, - 20px 100%, - 100% 100%, - 100% 0%, - 0% 0% - ); - } - 20%, - 100% { - clip-path: polygon( - 0% 100%, - 4px 100%, - 4px 4px, - 20px 4px, - 20px 20px, - 4px 20px, - 4px 100%, - 100% 100%, - 100% 0%, - 0% 0% - ); - } -} \ No newline at end of file diff --git a/src/features/multichain-button/pages/address/AddressMultichainButton.tsx b/src/features/multichain-button/pages/address/AddressMultichainButton.tsx index 591f35d1535..b82324d1b55 100644 --- a/src/features/multichain-button/pages/address/AddressMultichainButton.tsx +++ b/src/features/multichain-button/pages/address/AddressMultichainButton.tsx @@ -1,47 +1,43 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { upperFirst } from 'es-toolkit'; -import { route } from 'nextjs-routes'; import React from 'react'; -import type { MultichainProviderConfigParsed } from 'src/features/multichain-button/types/client'; +import type { MultichainProviderConfig } from 'src/features/multichain-button/types/client'; -import TextSeparator from 'src/shared/texts/TextSeparator'; +import { route } from 'src/shared/router/routes'; import { Image } from 'src/toolkit/chakra/image'; import { Link } from 'src/toolkit/chakra/link'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; -import styles from './AddressMultichainButton.module.css'; - const TEMPLATE_ADDRESS = '{address}'; -type Props = { - item: MultichainProviderConfigParsed; +interface Props { + item: MultichainProviderConfig; addressHash: string; onClick?: () => void; - isFirst?: boolean; - isLast?: boolean; }; -const AddressMultichainButton = ({ item, addressHash, onClick, isFirst, isLast }: Props) => { +const AddressMultichainButton = ({ item, addressHash, onClick }: Props) => { - const isOnlyOne = isFirst && isLast; + const isFullView = (item.view ?? 'full') === 'full'; const buttonIcon = ( <Image - src={ item.logoUrl } + src={ item.logo } alt={ item.name } boxSize={ 5 } - mr={ isOnlyOne ? { base: 1, lg: 2 } : 0 } + mr={ isFullView ? { base: 1, lg: 2 } : 0 } borderRadius="4px" overflow="hidden" + flexShrink={ 0 } /> ); const name = upperFirst(item.name.replaceAll('_', ' ')); - const buttonContent = isOnlyOne ? ( + const buttonContent = isFullView ? ( <> { buttonIcon } { name } @@ -51,29 +47,25 @@ const AddressMultichainButton = ({ item, addressHash, onClick, isFirst, isLast } ); try { - const portfolioUrlString = item.urlTemplate.replace(TEMPLATE_ADDRESS, addressHash); + const portfolioUrlString = item.url_template.replace(TEMPLATE_ADDRESS, addressHash); const portfolioUrl = new URL(portfolioUrlString); portfolioUrl.searchParams.append('utm_source', 'blockscout'); portfolioUrl.searchParams.append('utm_medium', 'address'); - const dappId = item.dappId; + const dappId = item.dapp_id; const isExternal = typeof dappId !== 'string'; return ( - <> - <Link - className={ item.promo ? styles.promo : undefined } - external={ isExternal } - href={ isExternal ? portfolioUrl.toString() : route({ pathname: '/apps/[id]', query: { id: dappId, url: portfolioUrl.toString() } }) } - variant={ isOnlyOne ? 'underlaid' : undefined } - textStyle="sm" - fontWeight="medium" - onClick={ onClick } - noIcon={ !isOnlyOne } - > - { buttonContent } - </Link> - { item.promo && isFirst && !isLast && <TextSeparator mx={ 0 }/> } - </> + <Link + external={ isExternal } + href={ isExternal ? portfolioUrl.toString() : route({ pathname: '/apps/[id]', query: { id: dappId, url: portfolioUrl.toString() } }) } + variant="underlaid" + textStyle="sm" + fontWeight="medium" + onClick={ onClick } + noIcon={ !isFullView } + > + { buttonContent } + </Link> ); } catch (error) {} diff --git a/src/features/multichain-button/pages/address/AddressMultichainInfoButton.tsx b/src/features/multichain-button/pages/address/AddressMultichainInfoButton.tsx deleted file mode 100644 index b3270db043e..00000000000 --- a/src/features/multichain-button/pages/address/AddressMultichainInfoButton.tsx +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import config from 'src/config'; - -import type { LinkProps } from 'src/toolkit/chakra/link'; -import { Link } from 'src/toolkit/chakra/link'; - -const feature = config.features.multichainButton; - -interface Props extends LinkProps { - addressData?: schemas['AddressResponse']; -} - -const AddressMultichainInfoButton = ({ addressData, ...rest }: Props) => { - if (!feature.isEnabled) { - return null; - } - - const promotedProvider = feature.providers.find((provider) => provider.promo); - - if (!promotedProvider) { - return null; - } - - if (!addressData || (addressData.is_contract && addressData.proxy_type !== 'eip7702')) { - return null; - } - - const url = (() => { - try { - const url = new URL(promotedProvider.urlTemplate.replace('{address}', addressData.hash)); - url.searchParams.append('utm_source', 'blockscout'); - url.searchParams.append('utm_medium', 'address'); - return url.toString(); - } catch (error) {} - return null; - })(); - - if (!url) { - return null; - } - - return ( - <Link - href={ url } - variant="underlaid" - external={ promotedProvider.dappId ? false : true } - flexShrink={ 0 } - { ...rest } - > - Multichain info - </Link> - ); -}; - -export default React.memo(AddressMultichainInfoButton); diff --git a/src/features/multichain-button/types/client.ts b/src/features/multichain-button/types/client.ts index 3b64dc045d6..9256f766c5b 100644 --- a/src/features/multichain-button/types/client.ts +++ b/src/features/multichain-button/types/client.ts @@ -1,17 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -export type MultichainProviderConfig = { +export type MultichainProviderView = 'full' | 'icon'; + +export interface MultichainProviderConfig { name: string; dapp_id?: string; url_template: string; logo: string; - promo?: boolean; -}; - -export type MultichainProviderConfigParsed = { - name: string; - logoUrl: string; - urlTemplate: string; - dappId?: string; - promo?: boolean; + view?: MultichainProviderView; }; diff --git a/src/features/multichain/components/ListCounterText.tsx b/src/features/multichain/components/ListCounterText.tsx index ff251e58385..dd3bd7b19bd 100644 --- a/src/features/multichain/components/ListCounterText.tsx +++ b/src/features/multichain/components/ListCounterText.tsx @@ -4,7 +4,7 @@ import React from 'react'; import useIsInitialLoading from 'src/shared/hooks/useIsInitialLoading'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props { value: string | undefined; @@ -23,15 +23,12 @@ const ListCounterText = ({ isLoading, value, type }: Props) => { const text = `A total of ${ valueNum.toLocaleString() } ${ valueNum === 1 ? type : `${ type }s` } found`; return ( - <TruncatedText - text={ text } - loading={ isInitialLoading } + <Truncate value={ text } type="end" loading={ isInitialLoading } textStyle={{ base: 'md', lg: 'sm' }} color="text.secondary" ml={{ base: 0, lg: 6 }} mr={{ base: 0, lg: 8 }} - mb={{ base: 4, lg: 0 }} - /> + mb={{ base: 4, lg: 0 }}/> ); }; diff --git a/src/features/multichain/context.tsx b/src/features/multichain/context.tsx index 6cd6519fb8e..f7a2b7c1336 100644 --- a/src/features/multichain/context.tsx +++ b/src/features/multichain/context.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { ClusterChainConfig } from 'src/features/multichain/types/client'; @@ -8,6 +7,7 @@ import type { ClusterChainConfig } from 'src/features/multichain/types/client'; import multichainConfig from 'src/features/multichain/chains-config'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import getChainIdFromSlugOrId from './utils/get-chain-id-from-slug-or-id'; diff --git a/src/features/multichain/hooks/useChainValue.spec.ts b/src/features/multichain/hooks/useChainValue.spec.ts new file mode 100644 index 00000000000..4c665041266 --- /dev/null +++ b/src/features/multichain/hooks/useChainValue.spec.ts @@ -0,0 +1,160 @@ +// @vitest-environment jsdom + +import { chainA, chainB } from 'src/features/multichain/mocks/chains'; + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { renderHook, act, cleanup } from 'vitest/lib'; +import { routerStandIn } from 'vitest/utils/routerStandIn'; + +const { mockScrollToTop } = vi.hoisted(() => ({ + mockScrollToTop: vi.fn(), +})); + +vi.mock('react-scroll', () => ({ animateScroll: { scrollToTop: mockScrollToTop } })); +vi.mock('src/features/multichain/chains-config', () => ({ + 'default': () => ({ chains: [ chainA, chainB ] }), +})); + +import { useChainValue } from './useChainValue'; + +const ENCODED_CURSOR = encodeURIComponent(JSON.stringify({ block_number: 11, index: 12, items_count: 13 })); + +beforeEach(() => { + mockScrollToTop.mockClear(); + routerStandIn.reset({ pathname: '/address/[hash]', query: { hash: '0x1' } }); +}); + +afterEach(cleanup); + +describe('useChainValue', () => { + describe('derives the value from the URL', () => { + it('reads chain_id and resolves its config', () => { + routerStandIn.setQuery({ hash: '0x1', chain_id: chainB.id }); + + const { result } = renderHook(() => useChainValue(), { wrapper: routerStandIn.wrapper }); + + expect(result.current.chainValue).toEqual([ chainB.id ]); + expect(result.current.chain).toBe(chainB); + }); + + it('falls back to the first configured chain when the URL names none', () => { + const { result } = renderHook(() => useChainValue(), { wrapper: routerStandIn.wrapper }); + + expect(result.current.chainValue).toEqual([ chainA.id ]); + expect(result.current.chain).toBe(chainA); + }); + + it('falls back to the first available chain when chainIds restrict the choice', () => { + const { result } = renderHook(() => useChainValue({ chainIds: [ chainB.id ] }), { wrapper: routerStandIn.wrapper }); + + expect(result.current.chainValue).toEqual([ chainB.id ]); + expect(result.current.chain).toBe(chainB); + }); + + it('ignores a chain_id that is not configured', () => { + routerStandIn.setQuery({ hash: '0x1', chain_id: '999' }); + + const { result } = renderHook(() => useChainValue(), { wrapper: routerStandIn.wrapper }); + + expect(result.current.chainValue).toEqual([ chainA.id ]); + }); + + it('selects "all" with no chain config when the all option is allowed and the URL names no chain', () => { + const { result } = renderHook(() => useChainValue({ withAllOption: true }), { wrapper: routerStandIn.wrapper }); + + expect(result.current.chainValue).toEqual([ 'all' ]); + expect(result.current.chain).toBeUndefined(); + }); + + it('follows an external URL change without a handler call', () => { + const { result } = renderHook(() => useChainValue(), { wrapper: routerStandIn.wrapper }); + + act(() => { + routerStandIn.setQuery({ hash: '0x1', chain_id: chainB.id }); + }); + + expect(result.current.chainValue).toEqual([ chainB.id ]); + expect(result.current.chain).toBe(chainB); + }); + }); + + describe('onChainValueChange', () => { + it('pushes chain_id, strips the page params and keeps the rest of the query', async() => { + routerStandIn.setQuery({ hash: '0x1', tab: 'txs', filter: 'from', page: '3', next_page_params: ENCODED_CURSOR }); + const { result } = renderHook(() => useChainValue(), { wrapper: routerStandIn.wrapper }); + + await act(async() => { + result.current.onChainValueChange({ value: [ chainB.id ] }); + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(1); + expect(routerStandIn.push).toHaveBeenCalledWith(expect.anything(), { shallow: true }); + expect(routerStandIn.query).toEqual({ hash: '0x1', tab: 'txs', filter: 'from', chain_id: chainB.id }); + expect(result.current.chainValue).toEqual([ chainB.id ]); + expect(result.current.chain).toBe(chainB); + }); + + it('scrolls to the top when leaving a deeper page', async() => { + routerStandIn.setQuery({ hash: '0x1', page: '3', next_page_params: ENCODED_CURSOR }); + const { result } = renderHook(() => useChainValue(), { wrapper: routerStandIn.wrapper }); + + await act(async() => { + result.current.onChainValueChange({ value: [ chainB.id ] }); + }); + + expect(mockScrollToTop).toHaveBeenCalledTimes(1); + }); + + it('does not scroll when already on the first page', async() => { + const { result } = renderHook(() => useChainValue(), { wrapper: routerStandIn.wrapper }); + + await act(async() => { + result.current.onChainValueChange({ value: [ chainB.id ] }); + }); + + expect(mockScrollToTop).not.toHaveBeenCalled(); + }); + + it('scrolls to the given element instead of the window', async() => { + routerStandIn.setQuery({ hash: '0x1', page: '2', next_page_params: ENCODED_CURSOR }); + const scrollIntoView = vi.fn(); + const scrollRef = { current: { scrollIntoView } as unknown as HTMLDivElement }; + const { result } = renderHook(() => useChainValue({ scrollRef }), { wrapper: routerStandIn.wrapper }); + + await act(async() => { + result.current.onChainValueChange({ value: [ chainB.id ] }); + }); + + expect(scrollIntoView).toHaveBeenCalledTimes(1); + expect(mockScrollToTop).not.toHaveBeenCalled(); + }); + }); + + describe('referential stability', () => { + it('keeps the result and handler across a re-render with the same URL', () => { + const { result, rerender } = renderHook(() => useChainValue(), { wrapper: routerStandIn.wrapper }); + const before = result.current; + + rerender(); + + expect(result.current).toBe(before); + }); + + it('keeps the handler when the chain changes and reads the latest router from it', async() => { + const { result } = renderHook(() => useChainValue(), { wrapper: routerStandIn.wrapper }); + const handlerBefore = result.current.onChainValueChange; + + await act(async() => { + routerStandIn.setQuery({ hash: '0x1', tab: 'logs' }); + }); + expect(result.current.onChainValueChange).toBe(handlerBefore); + + await act(async() => { + handlerBefore({ value: [ chainB.id ] }); + }); + + expect(routerStandIn.query).toEqual({ hash: '0x1', tab: 'logs', chain_id: chainB.id }); + expect(result.current.onChainValueChange).toBe(handlerBefore); + }); + }); +}); diff --git a/src/features/multichain/hooks/useChainValue.ts b/src/features/multichain/hooks/useChainValue.ts new file mode 100644 index 00000000000..43d76b2aaf0 --- /dev/null +++ b/src/features/multichain/hooks/useChainValue.ts @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { omit } from 'es-toolkit'; +import React from 'react'; + +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +import multichainConfig from 'src/features/multichain/chains-config'; +import getChainValueFromQuery from 'src/features/multichain/utils/get-chain-value-from-query'; + +import { scrollListToTop } from 'src/shared/pagination/usePaginationActions'; +import { getPageFromQuery, PAGE_FIELDS } from 'src/shared/pagination/usePaginationParams'; +import { useRouter } from 'src/shared/router/useRouter'; +import type { Router } from 'src/shared/router/useRouter'; + +export interface ChainValueParams { + readonly chainIds?: Array<string>; + readonly withAllOption?: boolean; + readonly scrollRef?: React.RefObject<HTMLDivElement | null>; +} + +export interface ChainValue { + readonly chainValue: Array<string>; + readonly chain: ClusterChainConfig | undefined; + readonly onChainValueChange: ({ value }: { value: Array<string> }) => void; +} + +interface LatestInputs { + readonly router: Router; + readonly scrollRef: React.RefObject<HTMLDivElement | null> | undefined; +} + +const NO_CHAIN_VALUE: Array<string> = []; + +export function useChainValue({ chainIds, withAllOption, scrollRef }: ChainValueParams = {}): ChainValue { + const router = useRouter(); + const chainId = getChainValueFromQuery(router.query, chainIds, withAllOption); + + const chainValue = React.useMemo(() => (chainId ? [ chainId ] : NO_CHAIN_VALUE), [ chainId ]); + const chain = React.useMemo(() => multichainConfig()?.chains.find((item) => item.id === chainId), [ chainId ]); + + const latest = React.useRef<LatestInputs>({ router, scrollRef }); + latest.current = { router, scrollRef }; + + const onChainValueChange = React.useCallback(({ value }: { value: Array<string> }) => { + const { router: { pathname, query, push }, scrollRef } = latest.current; + if (getPageFromQuery(query) !== 1) { + scrollListToTop(scrollRef, false); + } + push({ pathname, query: { ...omit(query, PAGE_FIELDS), chain_id: value[0] } }, { shallow: true }); + }, []); + + return React.useMemo(() => ({ chainValue, chain, onChainValueChange }), [ chainValue, chain, onChainValueChange ]); +} diff --git a/src/features/multichain/hooks/useRoutedChainSelect.ts b/src/features/multichain/hooks/useRoutedChainSelect.ts index 6456e859fd4..22b763055bc 100644 --- a/src/features/multichain/hooks/useRoutedChainSelect.ts +++ b/src/features/multichain/hooks/useRoutedChainSelect.ts @@ -1,11 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { pickBy } from 'es-toolkit'; -import { useRouter } from 'next/router'; import React from 'react'; import getChainValueFromQuery from 'src/features/multichain/utils/get-chain-value-from-query'; +import { useRouter } from 'src/shared/router/useRouter'; + interface Props { persistedParams?: Array<string>; isLoading?: boolean; diff --git a/src/features/multichain/mocks/chains.ts b/src/features/multichain/mocks/chains.ts index de09a805b0b..6f478e001a4 100644 --- a/src/features/multichain/mocks/chains.ts +++ b/src/features/multichain/mocks/chains.ts @@ -86,7 +86,7 @@ export const chainB = { ...chainA.app_config?.slices, token: { ...chainA.app_config?.slices?.token, - additionalTypes: [ { id: 'ERC-7984', name: 'ERC-7984' } ], + additionalTypes: [ { id: 'ERC-7984', name: 'ERC-7984' }, { id: 'ERC-8056', name: 'ERC-8056' } ], }, }, apis: { diff --git a/src/features/multichain/mocks/tokens.ts b/src/features/multichain/mocks/tokens.ts index 76d705ccf8b..8864d97ffac 100644 --- a/src/features/multichain/mocks/tokens.ts +++ b/src/features/multichain/mocks/tokens.ts @@ -25,6 +25,9 @@ export const tokenAA: AddressTokenItem = { }, }, reputation: null, + ui_multiplier: null, + new_ui_multiplier: null, + ui_multiplier_effective_at: null, }, token_instance: null, token_id: null, @@ -55,6 +58,9 @@ export const tokenAB: AddressTokenItem = { }, }, reputation: null, + ui_multiplier: null, + new_ui_multiplier: null, + ui_multiplier_effective_at: null, }, token_id: null, value: '32115625288281011210', @@ -136,3 +142,31 @@ export const tokenDA: AddressTokenItem = { exchange_rate: null, }, }; + +export const tokenBC: AddressTokenItem = { + ...tokenAA, + token: { + ...tokenAA.token, + address_hash: '0x7336D3B609bAc510842d7F7Ceb61bcB6910f501D', + name: 'Caterpillar Inc 3.7% 2028', + symbol: '14913UBF6', + decimals: '18', + type: 'ERC-8056', + exchange_rate: '1.02', + ui_multiplier: '1250000000000000000', + new_ui_multiplier: null, + ui_multiplier_effective_at: null, + chain_infos: { + [chainB.id]: { + holders_count: '4', + total_supply: '9692016594070863347712', + is_verified: false, + contract_name: undefined, + }, + }, + }, + value: '4987401008000000000000', + chain_values: { + [chainB.id]: '4987401008000000000000', + }, +}; diff --git a/src/features/multichain/pages/address/MultichainAddress.pw.tsx b/src/features/multichain/pages/address/MultichainAddress.pw.tsx index a7dd869fadb..c941a11e827 100644 --- a/src/features/multichain/pages/address/MultichainAddress.pw.tsx +++ b/src/features/multichain/pages/address/MultichainAddress.pw.tsx @@ -34,7 +34,7 @@ test('base view', async({ mockApiResponse, render, page, mockMultichainConfig, m await mockApiResponse('multichainAggregator:address_tokens', { items: [ tokensMock.tokenAA, tokensMock.tokenAB, tokensMock.tokenBA, tokensMock.tokenCA, tokensMock.tokenDA ], next_page_params: { page_token: '1', page_size: 10 }, - }, { pathParams: { hash: CURRENT_ADDRESS }, queryParams: { type: 'ERC-20,NATIVE,ERC-7984', include_poor_reputation_tokens: false } }); + }, { pathParams: { hash: CURRENT_ADDRESS }, queryParams: { type: 'ERC-20,NATIVE,ERC-7984,ERC-8056', include_poor_reputation_tokens: false } }); await mockAssetResponse(chainDataMock.chainA.logo as string, './playwright/mocks/image_s.jpg'); await mockAssetResponse(chainDataMock.chainB.logo as string, './playwright/mocks/image_md.jpg'); diff --git a/src/features/multichain/pages/address/MultichainAddress.tsx b/src/features/multichain/pages/address/MultichainAddress.tsx index e564a95b3c8..7e7e6403972 100644 --- a/src/features/multichain/pages/address/MultichainAddress.tsx +++ b/src/features/multichain/pages/address/MultichainAddress.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -24,6 +23,7 @@ import EnsEntity from 'src/features/name-services/domains/components/EnsEntity'; import config from 'src/config'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; diff --git a/src/features/multichain/pages/address/MultichainAddressInternalTxs.tsx b/src/features/multichain/pages/address/MultichainAddressInternalTxs.tsx index 46518570f7a..0776379265e 100644 --- a/src/features/multichain/pages/address/MultichainAddressInternalTxs.tsx +++ b/src/features/multichain/pages/address/MultichainAddressInternalTxs.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type * as multichain from '@blockscout/multichain-aggregator-types'; @@ -9,17 +8,18 @@ import ActionBar from 'src/shell/page/action-bar/ActionBar'; import useAddressInternalTxsQuery from 'src/slices/address/pages/details/internal-txs/useAddressInternalTxsQuery'; import AddressTxsFilter from 'src/slices/address/pages/details/txs/AddressTxsFilter'; -import InternalTxsList from 'src/slices/internal-tx/components/InternalTxsList'; import InternalTxsTable from 'src/slices/internal-tx/components/InternalTxsTable'; import CsvExport from 'src/features/csv-export/components/CsvExport'; -import multichainConfig from 'src/features/multichain/chains-config'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; import { MultichainProvider } from 'src/features/multichain/context'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import getAvailableChainIds from './get-available-chain-ids'; interface Props { @@ -29,31 +29,23 @@ interface Props { const MultichainAddressInternalTxs = ({ addressData, isLoading }: Props) => { const chainIds = React.useMemo(() => getAvailableChainIds(addressData), [ addressData ]); + const { chainValue, chain: chainData, onChainValueChange } = useChainValue({ chainIds }); const { hash, query, filterValue, onFilterChange } = useAddressInternalTxsQuery({ enabled: !isLoading && chainIds.length > 0, - isMultichain: true, - chainIds, + chain: chainData, }); - const { data, isPlaceholderData, isError, pagination, chainValue, onChainValueChange } = query; - - const chainData = React.useMemo(() => { - const config = multichainConfig(); - return config?.chains.find(({ id }) => id === chainValue?.[0]); - }, [ chainValue ]); + const { data, isInitialLoading, isError, pagination } = query; if (chainIds.length === 0) { return <p>There are no internal transactions.</p>; } const content = data?.items ? ( - <MultichainProvider chainId={ chainValue?.[0] }> - <Box hideFrom="lg"> - <InternalTxsList data={ data.items } currentAddress={ hash } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> - </Box> - <Box hideBelow="lg"> - <InternalTxsTable data={ data.items } currentAddress={ hash } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> - </Box> + <MultichainProvider chainId={ chainData?.id }> + <TableContainerScrollable> + <InternalTxsTable data={ data.items } currentAddress={ hash } isLoading={ isInitialLoading } resetKey={ query.queryHash }/> + </TableContainerScrollable> </MultichainProvider> ) : null ; @@ -100,6 +92,7 @@ const MultichainAddressInternalTxs = ({ addressData, isLoading }: Props) => { showActionBarIfEmpty showActionBarIfError actionBar={ actionBar } + isTransitioning={ query.isTransitioning } > { content } </DataList> diff --git a/src/features/multichain/pages/address/MultichainAddressLogs.tsx b/src/features/multichain/pages/address/MultichainAddressLogs.tsx index dce543d5c49..be783c7ec7f 100644 --- a/src/features/multichain/pages/address/MultichainAddressLogs.tsx +++ b/src/features/multichain/pages/address/MultichainAddressLogs.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type * as multichain from '@blockscout/multichain-aggregator-types'; @@ -11,17 +10,18 @@ import LogItem from 'src/slices/log/components/LogItem'; import { LOG } from 'src/slices/log/stubs/log'; import CsvExport from 'src/features/csv-export/components/CsvExport'; -import multichainConfig from 'src/features/multichain/chains-config'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; import { MultichainProvider } from 'src/features/multichain/context'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import getAvailableChainIds from './get-available-chain-ids'; @@ -36,10 +36,11 @@ interface Props { const MultichainAddressLogs = ({ addressData, isLoading }: Props) => { const router = useRouter(); const chainIds = React.useMemo(() => getAvailableChainIds(addressData), [ addressData ]); + const { chainValue, chain: chainData, onChainValueChange } = useChainValue({ chainIds }); const isMobile = useIsMobile(); const hash = getQueryParamString(router.query.hash); - const { data, isPlaceholderData, isError, pagination, chainValue, onChainValueChange, queryHash } = useQueryWithPages({ + const { data, isInitialLoading, isTransitioning, isError, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:address_logs', pathParams: { hash }, options: { @@ -51,22 +52,16 @@ const MultichainAddressLogs = ({ addressData, isLoading }: Props) => { } }), enabled: !isLoading, }, - isMultichain: true, - chainIds, + chain: chainData, }); const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data?.items, - isEnabled: !isPlaceholderData, + isEnabled: !isInitialLoading, minItemsNum: INITIAL_RENDERED_ITEMS_NUM, resetKey: queryHash, }); - const chainData = React.useMemo(() => { - const config = multichainConfig(); - return config?.chains.find(({ id }) => id === chainValue?.[0]); - }, [ chainValue ]); - const actionBar = ( <ActionBar mt={ -6 }> <ChainSelect @@ -95,7 +90,7 @@ const MultichainAddressLogs = ({ addressData, isLoading }: Props) => { key={ index } data={ item } type="address" - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } chainData={ chainData } /> )); @@ -115,8 +110,9 @@ const MultichainAddressLogs = ({ addressData, isLoading }: Props) => { showActionBarIfEmpty showActionBarIfError actionBar={ actionBar } + isTransitioning={ isTransitioning } > - <MultichainProvider chainId={ chainValue?.[0] }> + <MultichainProvider chainId={ chainData?.id }> { content } </MultichainProvider> </DataList> diff --git a/src/features/multichain/pages/address/MultichainAddressPortfolio.pw.tsx b/src/features/multichain/pages/address/MultichainAddressPortfolio.pw.tsx index 280afb1b2a7..99181d8b6fd 100644 --- a/src/features/multichain/pages/address/MultichainAddressPortfolio.pw.tsx +++ b/src/features/multichain/pages/address/MultichainAddressPortfolio.pw.tsx @@ -32,7 +32,7 @@ test.describe('nfts', () => { await mockApiResponse( 'core:address_collections', { ...tokensMock.collections, items: [ tokensMock.collections.items[2] ] }, - { pathParams: { hash: CURRENT_ADDRESS }, queryParams: { type: [] }, chainConfig: chainDataMock.chainA }, + { pathParams: { hash: CURRENT_ADDRESS }, chainConfig: chainDataMock.chainA }, ); await mockAssetResponse(chainDataMock.chainA.logo as string, './playwright/mocks/image_s.jpg'); diff --git a/src/features/multichain/pages/address/MultichainAddressPortfolio.tsx b/src/features/multichain/pages/address/MultichainAddressPortfolio.tsx index 6b2be749f70..84d1296cc04 100644 --- a/src/features/multichain/pages/address/MultichainAddressPortfolio.tsx +++ b/src/features/multichain/pages/address/MultichainAddressPortfolio.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type * as multichain from '@blockscout/multichain-aggregator-types'; @@ -15,10 +14,12 @@ import useAddressNftQuery from 'src/slices/token/pages/address/useAddressNftQuer import ChainSelect from 'src/features/multichain/components/ChainSelect'; import { MultichainProvider } from 'src/features/multichain/context'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -54,21 +55,15 @@ const MultichainAddressPortfolio = ({ addressData, isLoading }: Props) => { const tab = getQueryParamString(router.query.tab) as typeof ADDRESS_OP_PORTFOLIO_TAB_IDS[number] | 'portfolio' | undefined; const hash = getQueryParamString(router.query.hash); const chainIds = React.useMemo(() => getAvailableChainIds(addressData), [ addressData ]); + const { chainValue, chain, onChainValueChange } = useChainValue({ chainIds, scrollRef }); const { nftsQuery, collectionsQuery, displayType: nftDisplayType, tokenTypes: nftTokenTypes, onDisplayTypeChange, onTokenTypesChange } = useAddressNftQuery({ scrollRef, enabled: !isLoading && tab === 'portfolio_nfts' && chainIds.length > 0, addressHash: hash, - isMultichain: true, - chainIds, + chain, }); - const handleChainChange = React.useCallback((chainId: string | null) => { - const chainValue = chainId ? [ chainId ] : [ chainIds[0] ]; - nftsQuery.onChainValueChange({ value: chainValue }); - collectionsQuery.onChainValueChange({ value: chainValue }); - }, [ nftsQuery, collectionsQuery, chainIds ]); - const hasActiveFilters = (() => { if (tab === 'portfolio_nfts') { return Boolean(nftTokenTypes?.length); @@ -83,15 +78,15 @@ const MultichainAddressPortfolio = ({ addressData, isLoading }: Props) => { const chainSelect = ( <ChainSelect loading={ query.pagination.isLoading } - value={ query.chainValue } - onValueChange={ query.onChainValueChange } + value={ chainValue } + onValueChange={ onChainValueChange } chainIds={ chainIds } /> ); const hasData = - (!nftsQuery.isPlaceholderData && nftsQuery.data?.items.length) || - (!collectionsQuery.isPlaceholderData && collectionsQuery.data?.items.length); + Boolean(!nftsQuery.isPlaceholderData && nftsQuery.data?.items.length) || + Boolean(!collectionsQuery.isPlaceholderData && collectionsQuery.data?.items.length); return ( <> @@ -113,17 +108,17 @@ const MultichainAddressPortfolio = ({ addressData, isLoading }: Props) => { { id: 'portfolio_tokens', title: 'Tokens', - component: <MultichainAddressPortfolioTokens addressData={ addressData } isLoading={ isLoading } onChainChange={ handleChainChange }/>, + component: <MultichainAddressPortfolioTokens addressData={ addressData } isLoading={ isLoading }/>, }, { id: 'portfolio_nfts', - title: 'NFT', + title: 'NFTs', component: nftDisplayType === 'list' ? ( - <MultichainProvider chainId={ nftsQuery.chainValue?.[0] }> + <MultichainProvider chainId={ chain?.id }> <AddressNfts tokensQuery={ nftsQuery } tokenTypes={ nftTokenTypes } onTokenTypesChange={ onTokenTypesChange }/> </MultichainProvider> ) : ( - <MultichainProvider chainId={ collectionsQuery.chainValue?.[0] }> + <MultichainProvider chainId={ chain?.id }> <AddressNftsCollections collectionsQuery={ collectionsQuery } address={ hash } diff --git a/src/features/multichain/pages/address/MultichainAddressTokenTransfers.pw.tsx b/src/features/multichain/pages/address/MultichainAddressTokenTransfers.pw.tsx index 8258c2c7308..94891583963 100644 --- a/src/features/multichain/pages/address/MultichainAddressTokenTransfers.pw.tsx +++ b/src/features/multichain/pages/address/MultichainAddressTokenTransfers.pw.tsx @@ -5,6 +5,7 @@ import React from 'react'; import * as countersMock from 'src/slices/address/mocks/counters'; import * as tokenTransferMock from 'src/slices/token-transfer/mocks'; +import * as csvExportMock from 'src/features/csv-export/mocks'; import * as addressMock from 'src/features/multichain/mocks/address'; import * as chainDataMock from 'src/features/multichain/mocks/chains'; @@ -32,13 +33,14 @@ test.describe('local transfers', () => { await mockApiResponse( 'core:address_token_transfers', { items: [ tokenTransferMock.erc20 ], next_page_params: DEFAULT_PAGINATION }, - { pathParams: { hash: CURRENT_ADDRESS }, queryParams: { type: [] }, chainConfig: chainDataMock.chainA }, + { pathParams: { hash: CURRENT_ADDRESS }, chainConfig: chainDataMock.chainA }, ); await mockApiResponse( 'core:address_counters', countersMock.forAddress, { pathParams: { hash: CURRENT_ADDRESS }, chainConfig: chainDataMock.chainA }, ); + await mockApiResponse('core:config_csv_export', csvExportMock.config, { chainConfig: chainDataMock.chainA }); await mockAssetResponse(chainDataMock.chainA.logo as string, './playwright/mocks/image_s.jpg'); component = await render( diff --git a/src/features/multichain/pages/address/MultichainAddressTokenTransfers.tsx b/src/features/multichain/pages/address/MultichainAddressTokenTransfers.tsx index f9a225ab5aa..045838637a3 100644 --- a/src/features/multichain/pages/address/MultichainAddressTokenTransfers.tsx +++ b/src/features/multichain/pages/address/MultichainAddressTokenTransfers.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type * as multichain from '@blockscout/multichain-aggregator-types'; @@ -16,6 +15,7 @@ import useAddressCountersQuery from 'src/slices/address/hooks/useAddressCounters import AddressTokenTransfersLocal from 'src/slices/address/pages/details/token-transfers/AddressTokenTransfersLocal'; import useAddressTokenTransfersQuery from 'src/slices/address/pages/details/token-transfers/useAddressTokenTransfersQuery'; import TokenTransferFilter from 'src/slices/token-transfer/components/TokenTransferFilter'; +import { useTokenTransferColumns } from 'src/slices/token-transfer/hooks/useTokenTransferColumns'; import { getTokenFilterValue } from 'src/slices/token/utils/list-utils'; import AddressAdvancedFilterLink from 'src/features/advanced-filter/components/AddressAdvancedFilterLink'; @@ -26,13 +26,16 @@ import multichainConfig from 'src/features/multichain/chains-config'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; import ListCounterText from 'src/features/multichain/components/ListCounterText'; import { MultichainProvider } from 'src/features/multichain/context'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import ColumnsButton from 'src/shared/lists/columns/ColumnsButton'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { EmptyState } from 'src/toolkit/chakra/empty-state'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -68,8 +71,10 @@ const MultichainAddressTokenTransfers = ({ addressData, isLoading }: Props) => { const isLocalTab = tab === 'token_transfers_local' || tab === 'token_transfers'; const chainIds = React.useMemo(() => getAvailableChainIds(addressData), [ addressData ]); + const { chainValue, chain: chainData, onChainValueChange } = useChainValue({ chainIds }); + const chainId = chainData?.id; - const transfersQueryCrossChain = useQueryWithPages({ + const transfersQueryCrossChain = useApiPaginatedQuery({ resourceName: 'interchainIndexer:address_transfers', pathParams: { hash }, options: { @@ -81,22 +86,19 @@ const MultichainAddressTokenTransfers = ({ addressData, isLoading }: Props) => { const transfersQueryLocal = useAddressTokenTransfersQuery({ currentAddress: hash, enabled: isLocalTab && !isLoading && chainIds.length > 0, - isMultichain: true, - chainIds, + chain: chainData, }); - - const chainId = transfersQueryLocal.query.chainValue?.[0]; - const chainData = multichainConfig()?.chains.find(chain => chain.id === chainId); + const columnsState = useTokenTransferColumns('address', { typeFilter: transfersQueryLocal.filters.type, chainConfig: chainData?.app_config }); const countersQueryLocal = useAddressCountersQuery({ hash, - isLoading: transfersQueryLocal.query.isPlaceholderData, + isLoading: transfersQueryLocal.query.isInitialLoading, isEnabled: isLocalTab && !isLoading && chainIds.length > 0, chain: chainData, }); const handleChainValueChange = React.useCallback(({ value }: { value: Array<string> }) => { - transfersQueryLocal.query.onChainValueChange({ value }); + onChainValueChange({ value }); const chainConfig = multichainConfig()?.chains.find(chain => chain.id === value[0]); const tokenTypes = getTokenFilterValue(router.query.type, chainConfig?.app_config); if (tokenTypes) { @@ -105,7 +107,7 @@ const MultichainAddressTokenTransfers = ({ addressData, isLoading }: Props) => { transfersQueryLocal.onTypeFilterChange(chainsTokenTypes); } } - }, [ transfersQueryLocal, router.query.type ]); + }, [ onChainValueChange, transfersQueryLocal, router.query.type ]); const countersText = (() => { if (isLocalTab) { @@ -113,7 +115,7 @@ const MultichainAddressTokenTransfers = ({ addressData, isLoading }: Props) => { <ListCounterText key={ chainId } value={ countersQueryLocal.data?.token_transfers_count } - isLoading={ countersQueryLocal.isPlaceholderData || transfersQueryLocal.query.isPlaceholderData } + isLoading={ countersQueryLocal.isPlaceholderData || transfersQueryLocal.query.isInitialLoading } type="transfer" /> ); @@ -131,7 +133,7 @@ const MultichainAddressTokenTransfers = ({ addressData, isLoading }: Props) => { const chainSelect = ( <ChainSelect loading={ transfersQueryLocal.query.pagination.isLoading } - value={ transfersQueryLocal.query.chainValue } + value={ chainValue } onValueChange={ handleChainValueChange } chainIds={ chainIds } /> @@ -151,9 +153,18 @@ const MultichainAddressTokenTransfers = ({ addressData, isLoading }: Props) => { withAddressFilter onAddressFilterChange={ transfersQueryLocal.onAddressFilterChange } defaultAddressFilter={ transfersQueryLocal.filters.filter } - isLoading={ transfersQueryLocal.query.isPlaceholderData } + isLoading={ transfersQueryLocal.query.isInitialLoading } chainConfig={ chainData?.app_config } /> + <ColumnsButton + tableColumns={ columnsState.selectableColumns } + columns={ columnsState.checkedColumns } + onChange={ columnsState.onColumnsChange } + onOrderChange={ columnsState.onColumnsReorder } + selected={ columnsState.isCustomized } + onReset={ columnsState.onColumnsReset } + isLoading={ transfersQueryLocal.query.isInitialLoading } + /> { chainSelect } <CsvExport type="address_token_transfers" @@ -167,7 +178,7 @@ const MultichainAddressTokenTransfers = ({ addressData, isLoading }: Props) => { loadingInitial={ transfersQueryLocal.query.pagination.isLoading } /> <AddressAdvancedFilterLink - isLoading={ transfersQueryLocal.query.isPlaceholderData } + isLoading={ transfersQueryLocal.query.isInitialLoading } address={ hash } typeFilter={ transfersQueryLocal.filters.type } directionFilter={ transfersQueryLocal.filters.filter } @@ -192,28 +203,30 @@ const MultichainAddressTokenTransfers = ({ addressData, isLoading }: Props) => { id: 'token_transfers_cross_chain', title: 'Cross-chain', component: config.features.crossChainTxs.isEnabled ? ( - <> - { isMobile && !isLocalTab && transfersQueryCrossChain.pagination.isVisible && ( + <TokenTransfersCrossChainContent + items={ transfersQueryCrossChain.data?.items } + isLoading={ transfersQueryCrossChain.isInitialLoading } + isTransitioning={ transfersQueryCrossChain.isTransitioning } + isError={ transfersQueryCrossChain.isError } + pagination={ transfersQueryCrossChain.pagination } + tableTop={ ACTION_BAR_HEIGHT_DESKTOP } + currentAddress={ hash } + resetKey={ transfersQueryCrossChain.queryHash } + filters={ transfersQueryCrossChain.filters } + onFilterChange={ transfersQueryCrossChain.onFilterChange } + actionBar={ isMobile && !isLocalTab && transfersQueryCrossChain.pagination.isVisible && ( <ActionBar> <Pagination ml="auto" { ...transfersQueryCrossChain.pagination }/> </ActionBar> ) } - <TokenTransfersCrossChainContent - items={ transfersQueryCrossChain.data?.items } - isLoading={ transfersQueryCrossChain.isPlaceholderData } - isError={ transfersQueryCrossChain.isError } - pagination={ transfersQueryCrossChain.pagination } - tableTop={ ACTION_BAR_HEIGHT_DESKTOP } - currentAddress={ hash } - /> - </> + /> ) : <EmptyState type="coming_soon"/>, }, { id: [ 'token_transfers_local', 'token_transfers' ], title: 'Local', component: chainIds.length > 0 ? ( - <MultichainProvider chainId={ transfersQueryLocal.query.chainValue?.[0] }> + <MultichainProvider chainId={ chainId }> <SocketProvider url={ getSocketUrl(chainData?.app_config) }> { isMobile && countersText } <AddressTokenTransfersLocal @@ -222,6 +235,7 @@ const MultichainAddressTokenTransfers = ({ addressData, isLoading }: Props) => { onTypeFilterChange={ transfersQueryLocal.onTypeFilterChange } onAddressFilterChange={ transfersQueryLocal.onAddressFilterChange } addressHash={ hash } + columnsState={ columnsState } /> </SocketProvider> </MultichainProvider> diff --git a/src/features/multichain/pages/address/MultichainAddressTxs.pw.tsx b/src/features/multichain/pages/address/MultichainAddressTxs.pw.tsx index ed895189cdd..df98a3b46e2 100644 --- a/src/features/multichain/pages/address/MultichainAddressTxs.pw.tsx +++ b/src/features/multichain/pages/address/MultichainAddressTxs.pw.tsx @@ -5,12 +5,12 @@ import React from 'react'; import * as countersMock from 'src/slices/address/mocks/counters'; import * as txMock from 'src/slices/tx/mocks/list'; +import * as csvExportMock from 'src/features/csv-export/mocks'; import * as addressMock from 'src/features/multichain/mocks/address'; import * as chainDataMock from 'src/features/multichain/mocks/chains'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; import { test, expect } from 'playwright/lib'; -import * as pwConfig from 'playwright/utils/config'; import MultichainAddressTxs from './MultichainAddressTxs'; @@ -39,6 +39,7 @@ test.describe('local txs', () => { countersMock.forContract, { pathParams: { hash: CURRENT_ADDRESS }, chainConfig: chainDataMock.chainA }, ); + await mockApiResponse('core:config_csv_export', csvExportMock.config, { chainConfig: chainDataMock.chainA }); await mockAssetResponse(chainDataMock.chainA.logo as string, './playwright/mocks/image_s.jpg'); component = await render( @@ -54,12 +55,4 @@ test.describe('local txs', () => { test('base view', async() => { await expect(component).toHaveScreenshot(); }); - - test.describe('mobile', () => { - test.use({ viewport: pwConfig.viewport.mobile }); - - test('base view', async() => { - await expect(component).toHaveScreenshot(); - }); - }); }); diff --git a/src/features/multichain/pages/address/MultichainAddressTxs.tsx b/src/features/multichain/pages/address/MultichainAddressTxs.tsx index 2a913070df7..0608be574bf 100644 --- a/src/features/multichain/pages/address/MultichainAddressTxs.tsx +++ b/src/features/multichain/pages/address/MultichainAddressTxs.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex, HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type * as multichain from '@blockscout/multichain-aggregator-types'; @@ -20,17 +19,18 @@ import TxsWithApiSorting from 'src/slices/tx/pages/index/list/TxsWithApiSorting' import TransactionsCrossChainContent from 'src/features/cross-chain-txs/components/txs/TransactionsCrossChainContent'; import { INTERCHAIN_MESSAGE } from 'src/features/cross-chain-txs/stubs/messages'; import CsvExport from 'src/features/csv-export/components/CsvExport'; -import multichainConfig from 'src/features/multichain/chains-config'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; import ListCounterText from 'src/features/multichain/components/ListCounterText'; import { MultichainProvider } from 'src/features/multichain/context'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { EmptyState } from 'src/toolkit/chakra/empty-state'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -66,8 +66,10 @@ const MultichainAddressTxs = ({ addressData, isLoading }: Props) => { const isLocalTab = tab === 'txs_local' || tab === 'txs'; const chainIds = React.useMemo(() => getAvailableChainIds(addressData), [ addressData ]); + const { chainValue, chain: chainData, onChainValueChange } = useChainValue({ chainIds }); + const chainId = chainData?.id; - const txsQueryCrossChain = useQueryWithPages({ + const txsQueryCrossChain = useApiPaginatedQuery({ resourceName: 'interchainIndexer:address_messages', pathParams: { hash }, options: { @@ -79,16 +81,12 @@ const MultichainAddressTxs = ({ addressData, isLoading }: Props) => { const txsQueryLocal = useAddressTxsQuery({ addressHash: hash, enabled: !isLoading && isLocalTab && chainIds.length > 0, - isMultichain: true, - chainIds, + chain: chainData, }); - const chainId = txsQueryLocal.query.chainValue?.[0]; - const chainData = multichainConfig()?.chains.find(chain => chain.id === chainId); - const countersQueryLocal = useAddressCountersQuery({ hash, - isLoading: txsQueryLocal.query.isPlaceholderData || isLoading, + isLoading: txsQueryLocal.query.isInitialLoading || isLoading, isEnabled: !isLoading && isLocalTab && chainIds.length > 0, chain: chainData, }); @@ -108,7 +106,7 @@ const MultichainAddressTxs = ({ addressData, isLoading }: Props) => { <ListCounterText key={ chainId } value={ countersQueryLocal.data?.transactions_count } - isLoading={ countersQueryLocal.isPlaceholderData || txsQueryLocal.query.isPlaceholderData } + isLoading={ countersQueryLocal.isPlaceholderData || txsQueryLocal.query.isInitialLoading } type="transaction" /> ); @@ -120,8 +118,8 @@ const MultichainAddressTxs = ({ addressData, isLoading }: Props) => { const chainSelect = ( <ChainSelect loading={ txsQueryLocal.query.pagination.isLoading } - value={ txsQueryLocal.query.chainValue } - onValueChange={ txsQueryLocal.query.onChainValueChange } + value={ chainValue } + onValueChange={ onChainValueChange } chainIds={ chainIds } /> ); @@ -173,21 +171,23 @@ const MultichainAddressTxs = ({ addressData, isLoading }: Props) => { id: 'txs_cross_chain', title: 'Cross-chain', component: config.features.crossChainTxs.isEnabled ? ( - <> - { isMobile && !isLocalTab && txsQueryCrossChain.pagination.isVisible && ( + <TransactionsCrossChainContent + items={ txsQueryCrossChain.data?.items } + pagination={ txsQueryCrossChain.pagination } + isLoading={ txsQueryCrossChain.isInitialLoading } + isTransitioning={ txsQueryCrossChain.isTransitioning } + isError={ txsQueryCrossChain.isError } + stickyHeader + currentAddress={ hash } + resetKey={ txsQueryCrossChain.queryHash } + filters={ txsQueryCrossChain.filters } + onFilterChange={ txsQueryCrossChain.onFilterChange } + actionBar={ isMobile && !isLocalTab && txsQueryCrossChain.pagination.isVisible && ( <ActionBar> <Pagination ml="auto" { ...txsQueryCrossChain.pagination }/> </ActionBar> ) } - <TransactionsCrossChainContent - items={ txsQueryCrossChain.data?.items } - pagination={ txsQueryCrossChain.pagination } - isLoading={ txsQueryCrossChain.isPlaceholderData } - isError={ txsQueryCrossChain.isError } - stickyHeader - currentAddress={ hash } - /> - </> + /> ) : <EmptyState type="coming_soon"/>, }, { @@ -206,8 +206,6 @@ const MultichainAddressTxs = ({ addressData, isLoading }: Props) => { socketType="address_txs" top={ ACTION_BAR_HEIGHT_DESKTOP } sorting={ txsQueryLocal.sort } - setSort={ txsQueryLocal.setSort } - showTableView /> </MultichainProvider> </SocketProvider> diff --git a/src/features/multichain/pages/address/__screenshots__/MultichainAddress.pw.tsx_default_base-view-1.png b/src/features/multichain/pages/address/__screenshots__/MultichainAddress.pw.tsx_default_base-view-1.png index 36514b0134b..2514d61c497 100644 Binary files a/src/features/multichain/pages/address/__screenshots__/MultichainAddress.pw.tsx_default_base-view-1.png and b/src/features/multichain/pages/address/__screenshots__/MultichainAddress.pw.tsx_default_base-view-1.png differ diff --git a/src/features/multichain/pages/address/__screenshots__/MultichainAddressPortfolio.pw.tsx_default_nfts-base-view-1.png b/src/features/multichain/pages/address/__screenshots__/MultichainAddressPortfolio.pw.tsx_default_nfts-base-view-1.png index b4b889f47e4..83bb972fe3e 100644 Binary files a/src/features/multichain/pages/address/__screenshots__/MultichainAddressPortfolio.pw.tsx_default_nfts-base-view-1.png and b/src/features/multichain/pages/address/__screenshots__/MultichainAddressPortfolio.pw.tsx_default_nfts-base-view-1.png differ diff --git a/src/features/multichain/pages/address/__screenshots__/MultichainAddressPortfolio.pw.tsx_default_nfts-mobile-base-view-1.png b/src/features/multichain/pages/address/__screenshots__/MultichainAddressPortfolio.pw.tsx_default_nfts-mobile-base-view-1.png index 81ddaed8249..0ddf4818e01 100644 Binary files a/src/features/multichain/pages/address/__screenshots__/MultichainAddressPortfolio.pw.tsx_default_nfts-mobile-base-view-1.png and b/src/features/multichain/pages/address/__screenshots__/MultichainAddressPortfolio.pw.tsx_default_nfts-mobile-base-view-1.png differ diff --git a/src/features/multichain/pages/address/__screenshots__/MultichainAddressTokenTransfers.pw.tsx_default_local-transfers-base-view-1.png b/src/features/multichain/pages/address/__screenshots__/MultichainAddressTokenTransfers.pw.tsx_default_local-transfers-base-view-1.png index 26c80cdca6c..796a1696f13 100644 Binary files a/src/features/multichain/pages/address/__screenshots__/MultichainAddressTokenTransfers.pw.tsx_default_local-transfers-base-view-1.png and b/src/features/multichain/pages/address/__screenshots__/MultichainAddressTokenTransfers.pw.tsx_default_local-transfers-base-view-1.png differ diff --git a/src/features/multichain/pages/address/__screenshots__/MultichainAddressTokenTransfers.pw.tsx_default_local-transfers-mobile-base-view-1.png b/src/features/multichain/pages/address/__screenshots__/MultichainAddressTokenTransfers.pw.tsx_default_local-transfers-mobile-base-view-1.png index 41d29b50bf0..2950488fde5 100644 Binary files a/src/features/multichain/pages/address/__screenshots__/MultichainAddressTokenTransfers.pw.tsx_default_local-transfers-mobile-base-view-1.png and b/src/features/multichain/pages/address/__screenshots__/MultichainAddressTokenTransfers.pw.tsx_default_local-transfers-mobile-base-view-1.png differ diff --git a/src/features/multichain/pages/address/__screenshots__/MultichainAddressTxs.pw.tsx_default_local-txs-base-view-1.png b/src/features/multichain/pages/address/__screenshots__/MultichainAddressTxs.pw.tsx_default_local-txs-base-view-1.png index cc3bf84a4d7..9a9f06e5f33 100644 Binary files a/src/features/multichain/pages/address/__screenshots__/MultichainAddressTxs.pw.tsx_default_local-txs-base-view-1.png and b/src/features/multichain/pages/address/__screenshots__/MultichainAddressTxs.pw.tsx_default_local-txs-base-view-1.png differ diff --git a/src/features/multichain/pages/address/__screenshots__/MultichainAddressTxs.pw.tsx_default_local-txs-mobile-base-view-1.png b/src/features/multichain/pages/address/__screenshots__/MultichainAddressTxs.pw.tsx_default_local-txs-mobile-base-view-1.png deleted file mode 100644 index 75c5a24359c..00000000000 Binary files a/src/features/multichain/pages/address/__screenshots__/MultichainAddressTxs.pw.tsx_default_local-txs-mobile-base-view-1.png and /dev/null differ diff --git a/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioCard.tsx b/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioCard.tsx index f5510fecec8..3cf50f4be2f 100644 --- a/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioCard.tsx +++ b/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioCard.tsx @@ -12,7 +12,7 @@ import SimpleValue from 'src/shared/values/entity/SimpleValue'; import { DEFAULT_ACCURACY_USD } from 'src/shared/values/entity/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import { formatPercentage } from './utils'; @@ -63,7 +63,7 @@ const MultichainAddressPortfolioCard = ({ chain, value, share, isLoading, isSele > <ChainIcon data={ chain } boxSize="30px" flexShrink={ 0 } isLoading={ isLoading } noTooltip/> <VStack alignItems="flex-start" gap={ 1 } overflow="hidden"> - <TruncatedText text={ chain.name } loading={ isLoading } color="text.secondary" maxW="100%"/> + <Truncate value={ chain.name } type="end" loading={ isLoading } color="text.secondary" maxW="100%"/> <HStack gap={ 1 } maxW="100%"> <SimpleValue value={ value } prefix="$" loading={ isLoading } noTooltip accuracy={ DEFAULT_ACCURACY_USD }/> { share !== undefined && share > 0 && ( diff --git a/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioNetWorth.pw.tsx b/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioNetWorth.pw.tsx new file mode 100644 index 00000000000..410ad8e0d17 --- /dev/null +++ b/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioNetWorth.pw.tsx @@ -0,0 +1,61 @@ +import React from 'react'; + +import type { MultichainProviderConfig } from 'src/features/multichain-button/types/client'; + +import { test, expect } from 'playwright/lib'; +import * as pwConfig from 'playwright/utils/config'; + +import MultichainAddressPortfolioNetWorth from './MultichainAddressPortfolioNetWorth'; + +const ICON_URL = 'https://localhost:3000/my-icon.png'; +const ICON_URL_2 = 'https://localhost:3000/my-icon-2.png'; +const ADDRESS_HASH = '0x1234567890123456789012345678901234567890'; +const TOP_TOKENS = [ { symbol: 'USDT', share: 0.5 }, { symbol: 'DuckDuckToken', share: 0.3 }, { symbol: 'Others', share: 0.2 } ]; + +test.beforeEach(async({ mockEnvs, mockAssetResponse }) => { + await mockEnvs([ + [ 'NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG', JSON.stringify([ + { name: 'Duck portfolio', dapp_id: 'duck', url_template: 'https://duck.url/{address}', logo: ICON_URL }, + { name: 'duck3', dapp_id: 'duck', url_template: 'https://duck.url/{address}', logo: ICON_URL, view: 'icon' }, + { name: 'Goose tracker', url_template: 'https://duck.url/{address}', logo: ICON_URL_2, view: 'full' }, + { name: 'goose', url_template: 'https://duck.url/{address}', logo: ICON_URL_2, view: 'icon' }, + ] satisfies Array<MultichainProviderConfig>) ], + ]); + + await mockAssetResponse(ICON_URL, './playwright/mocks/duck.png'); + await mockAssetResponse(ICON_URL_2, './playwright/mocks/goose.png'); +}); + +test('base view +@mobile', async({ render, page }) => { + const component = await render( + <MultichainAddressPortfolioNetWorth + addressHash={ ADDRESS_HASH } + netWorth="449022.89544" + isLoading={ false } + topTokens={ TOP_TOKENS } + />, + ); + + await expect(component).toHaveScreenshot({ + mask: [ page.locator(pwConfig.adsBannerSelector) ], + maskColor: pwConfig.maskColor, + }); +}); + +test.describe('small desktop', () => { + test.use({ viewport: { width: 1024, height: 768 } }); + test('base view', async({ render, page }) => { + const component = await render( + <MultichainAddressPortfolioNetWorth + addressHash={ ADDRESS_HASH } + netWorth="449022.89544" + isLoading={ false } + topTokens={ TOP_TOKENS } + />, + ); + await expect(component).toHaveScreenshot({ + mask: [ page.locator(pwConfig.adsBannerSelector) ], + maskColor: pwConfig.maskColor, + }); + }); +}); diff --git a/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioNetWorth.tsx b/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioNetWorth.tsx index e089cc38992..f98061ee0c1 100644 --- a/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioNetWorth.tsx +++ b/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioNetWorth.tsx @@ -8,7 +8,7 @@ import AdBanner from 'src/features/ads/banner/components/AdBanner'; import AddressMultichainButton from 'src/features/multichain-button/pages/address/AddressMultichainButton'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import SimpleValue from 'src/shared/values/entity/SimpleValue'; import { DEFAULT_ACCURACY_USD } from 'src/shared/values/entity/utils'; @@ -43,7 +43,7 @@ const MultichainAddressPortfolioNetWorth = ({ addressHash, netWorth, isLoading, const isMobile = useIsMobile(); const handleMultichainClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.BUTTON_CLICK, { Content: 'Multichain', Source: 'address' }); + analytics.logEvent(analytics.EventTypes.BUTTON_CLICK, { Content: 'Multichain', Source: 'address' }); }, []); const topTokensContent = (() => { @@ -88,31 +88,31 @@ const MultichainAddressPortfolioNetWorth = ({ addressHash, netWorth, isLoading, })(); return ( - <HStack alignItems="center" w="full" h={{ base: 'auto', lg: '100px' }}> + <HStack alignItems="flex-start" w="full"> <VStack flexGrow={ 1 } borderRadius="base" overflow="hidden" - h="100%" + alignSelf="stretch" rowGap="1px" > <Flex - alignItems={{ base: 'flex-start', lg: 'center' }} bgColor={{ _light: 'blackAlpha.50', _dark: 'whiteAlpha.100' }} flexBasis="50%" w="full" p={ 3 } - gap={ 3 } whiteSpace="pre" - flexDirection={{ base: 'column', lg: 'row' }} textStyle="sm" + alignItems="center" > - <Flex alignItems="center"> - <SpriteIcon name="wallet" boxSize={ 5 } flexShrink={ 0 } color="icon.primary"/> - <Text ml={ 2 } fontWeight={ 500 }>Total net worth</Text> - <Text color="text.secondary"> (without NFT)</Text> - </Flex> - <Flex > + <HStack alignItems="center" flexWrap="wrap" columnGap={ 3 } rowGap={ 2 }> + <HStack w={{ base: 'full', lg: 'auto' }} minH={{ base: 'auto', lg: '32px' }}> + <SpriteIcon name="wallet" boxSize={ 5 } flexShrink={ 0 } color="icon.primary"/> + <Text fontWeight={ 500 }> + Total net worth + <chakra.span color="text.secondary" fontWeight={ 400 }> (without NFT)</chakra.span> + </Text> + </HStack> <SimpleValue value={ BigNumber(netWorth ?? 0) } prefix="$" @@ -123,8 +123,8 @@ const MultichainAddressPortfolioNetWorth = ({ addressHash, netWorth, isLoading, /> { multichainBalanceFeature.isEnabled && ( <> - <Separator mx={ 3 } height="16px" orientation="vertical"/> - <HStack gap={ 3 }> + <Separator height="16px" orientation="vertical"/> + <HStack gap={ 1 } flexWrap="wrap"> { multichainBalanceFeature.providers.map((item) => ( <AddressMultichainButton key={ item.name } @@ -136,7 +136,7 @@ const MultichainAddressPortfolioNetWorth = ({ addressHash, netWorth, isLoading, </HStack> </> ) } - </Flex> + </HStack> </Flex> <Flex alignItems={{ base: 'flex-start', lg: 'center' }} diff --git a/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioTokens.pw.tsx b/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioTokens.pw.tsx index b5e7a240752..13da7139145 100644 --- a/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioTokens.pw.tsx +++ b/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioTokens.pw.tsx @@ -31,16 +31,9 @@ test('many chains +@mobile +@dark-mode', async({ render, mockApiResponse, page } { pathParams: { hash: CURRENT_ADDRESS }, queryParams: { include_poor_reputation_tokens: false }, }); await mockApiResponse('multichainAggregator:address_tokens', { - items: [ tokensMock.tokenAA, tokensMock.tokenAB, tokensMock.tokenBA, tokensMock.tokenBB, tokensMock.tokenCA, tokensMock.tokenDA ], + items: [ tokensMock.tokenAA, tokensMock.tokenAB, tokensMock.tokenBA, tokensMock.tokenBB, tokensMock.tokenBC, tokensMock.tokenCA, tokensMock.tokenDA ], next_page_params: { page_token: '1', page_size: 10 }, - }, { pathParams: { hash: CURRENT_ADDRESS }, queryParams: { type: 'ERC-20,NATIVE,ERC-7984', include_poor_reputation_tokens: false } }); - await mockApiResponse('multichainAggregator:address_tokens', { - items: [ ], - next_page_params: undefined, - }, { - pathParams: { hash: CURRENT_ADDRESS }, - queryParams: { type: 'ERC-20,NATIVE,ERC-7984', chain_id: chainDataMock.chainE.id, include_poor_reputation_tokens: false }, - }); + }, { pathParams: { hash: CURRENT_ADDRESS }, queryParams: { type: 'ERC-20,NATIVE,ERC-7984,ERC-8056', include_poor_reputation_tokens: false } }); const component = await render( <MultichainAddressPortfolioTokens addressData={ addressMock.addressA } isLoading={ false }/>, @@ -50,9 +43,31 @@ test('many chains +@mobile +@dark-mode', async({ render, mockApiResponse, page } mask: [ page.locator(pwConfig.adsBannerSelector) ], maskColor: pwConfig.maskColor, }); +}); + +test('many chains, selected chain +@mobile +@dark-mode', async({ render, mockApiResponse, page }) => { + await mockApiResponse('multichainAggregator:address_portfolio', + portfolioMock.base, + { pathParams: { hash: CURRENT_ADDRESS }, queryParams: { include_poor_reputation_tokens: false }, + }); + await mockApiResponse('multichainAggregator:address_tokens', { + items: [ tokensMock.tokenAA, tokensMock.tokenAB, tokensMock.tokenBA, tokensMock.tokenBB, tokensMock.tokenBC, tokensMock.tokenCA, tokensMock.tokenDA ], + next_page_params: { page_token: '1', page_size: 10 }, + }, { pathParams: { hash: CURRENT_ADDRESS }, queryParams: { type: 'ERC-20,NATIVE,ERC-7984,ERC-8056', include_poor_reputation_tokens: false } }); + const selectedChainTokensUrl = await mockApiResponse('multichainAggregator:address_tokens', { + items: [ ], + next_page_params: undefined, + }, { + pathParams: { hash: CURRENT_ADDRESS }, + queryParams: { chain_id: chainDataMock.chainE.id, type: 'ERC-20,NATIVE,ERC-7984,ERC-8056', include_poor_reputation_tokens: false }, + }); - await component.getByText('show more').click(); - await component.getByLabel('White goose portfolio selector').click(); + const component = await render( + <MultichainAddressPortfolioTokens addressData={ addressMock.addressA } isLoading={ false }/>, + { hooksConfig: { router: { query: { ...hooksConfig.router.query, chain_id: chainDataMock.chainE.id } } } }, + ); + await page.waitForResponse(selectedChainTokensUrl); + await expect(component.getByText('show less')).toBeVisible(); await expect(component).toHaveScreenshot({ mask: [ page.locator(pwConfig.adsBannerSelector) ], maskColor: pwConfig.maskColor, diff --git a/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioTokens.tsx b/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioTokens.tsx index 46ea4d677a4..2dadd5667cd 100644 --- a/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioTokens.tsx +++ b/src/features/multichain/pages/address/portfolio/MultichainAddressPortfolioTokens.tsx @@ -3,7 +3,6 @@ import { Box } from '@chakra-ui/react'; import BigNumber from 'bignumber.js'; import { groupBy, mapValues } from 'es-toolkit'; -import { useRouter } from 'next/router'; import React from 'react'; import { isMobile } from 'react-device-detect'; @@ -17,12 +16,13 @@ import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ import multichainConfig from 'src/features/multichain/chains-config'; import { ADDRESS_PORTFOLIO, TOKEN } from 'src/features/multichain/stubs'; -import useDebounce from 'src/shared/hooks/useDebounce'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import * as cookies from 'src/shared/storage/cookies'; import { TableContainerScrollable } from 'src/toolkit/chakra/table'; @@ -37,19 +37,14 @@ import { calculateUsdValue } from './utils'; interface Props { addressData: multichain.GetAddressResponse | undefined; isLoading: boolean; - onChainChange?: (chainId: string | null) => void; } -const MultichainAddressPortfolioTokens = ({ addressData, isLoading, onChainChange }: Props) => { +const MultichainAddressPortfolioTokens = ({ addressData, isLoading }: Props) => { const config = multichainConfig(); const router = useRouter(); const hash = getQueryParamString(router.query.hash); const chainIdParam = getQueryParamString(router.query.chain_id); - const q = getQueryParamString(router.query.query); - - const [ searchTerm, setSearchTerm ] = React.useState(q || undefined); - const debouncedSearchTerm = useDebounce(searchTerm || '', 300); const tokenReputationFilter = React.useMemo(() => { return cookies.get(cookies.NAMES.SHOW_POOR_REPUTATION_TOKENS) === 'true' ? true : false; @@ -72,15 +67,10 @@ const MultichainAddressPortfolioTokens = ({ addressData, isLoading, onChainChang }; }, [ addressData?.chain_infos, portfolioQuery.data?.portfolio?.chain_values ]); - const [ selectedChainId, setSelectedChainId ] = React.useState<string | null>(null); - - React.useEffect(() => { - if (!portfolioQuery.isPlaceholderData && !isLoading) { - const [ chainId ] = chainIdParam ? chainIdParam.split(',').filter((chainId) => Object.keys(portfolioData).includes(chainId)) : []; - setSelectedChainId(chainId ?? null); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ portfolioQuery.isPlaceholderData, isLoading ]); + const selectedChainId = React.useMemo(() => { + const [ chainId ] = chainIdParam ? chainIdParam.split(',').filter((chainId) => Object.keys(portfolioData).includes(chainId)) : []; + return chainId ?? null; + }, [ chainIdParam, portfolioData ]); const typeFilter = React.useMemo(() => { const additionalTypes = getAdditionalTokenTypes( @@ -91,13 +81,12 @@ const MultichainAddressPortfolioTokens = ({ addressData, isLoading, onChainChang return [ 'ERC-20', 'NATIVE', ...additionalTypes.map(({ id }) => id) ].filter(Boolean).join(','); }, [ config?.chains, portfolioData ]); - const tokensQuery = useQueryWithPages({ + const tokensQuery = useApiPaginatedQuery({ resourceName: 'multichainAggregator:address_tokens', pathParams: { hash }, - filters: { + queryParams: { type: typeFilter, chain_id: selectedChainId ?? undefined, - query: debouncedSearchTerm, include_poor_reputation_tokens: tokenReputationFilter, }, options: { @@ -107,22 +96,17 @@ const MultichainAddressPortfolioTokens = ({ addressData, isLoading, onChainChang noScroll: true, }); + const searchTerm = getQueryParamString(tokensQuery.filters.query); + const { onFilterChange } = tokensQuery; + const handleSelectedChainChange = React.useCallback((chainId: string) => { - setSelectedChainId((prev) => { - const nextValue = chainId === prev ? null : chainId; - tokensQuery.onFilterChange({ - chain_id: nextValue ?? undefined, - query: debouncedSearchTerm, - }); - onChainChange?.(nextValue); - return nextValue; - }); - }, [ tokensQuery, debouncedSearchTerm, onChainChange ]); - - const handleSearchTermChange = React.useCallback((value: string) => { - setSearchTerm(value); - tokensQuery.onFilterChange({ query: value }); - }, [ tokensQuery ]); + const nextValue = chainId === selectedChainId ? undefined : chainId; + onFilterChange({ chain_id: nextValue, query: searchTerm }); + }, [ onFilterChange, selectedChainId, searchTerm ]); + + const handleSearchTermChange = useDebouncedFilterChange((value) => { + onFilterChange({ chain_id: selectedChainId ?? undefined, query: value }); + }); const allTokensQuery = useApiQuery('multichainAggregator:address_tokens', { pathParams: { hash }, @@ -200,7 +184,7 @@ const MultichainAddressPortfolioTokens = ({ addressData, isLoading, onChainChang <MultichainAddressTokensTable data={ tokensQuery.data.items } top={ ACTION_BAR_HEIGHT_DESKTOP } - isLoading={ tokensQuery.isPlaceholderData } + isLoading={ tokensQuery.isInitialLoading } resetKey={ tokensQuery.queryHash } /> </TableContainerScrollable> @@ -241,10 +225,11 @@ const MultichainAddressPortfolioTokens = ({ addressData, isLoading, onChainChang isError={ tokensQuery.isError } itemsNum={ tokensQuery.data?.items?.length } actionBar={ actionBar } - hasActiveFilters={ Boolean(debouncedSearchTerm) || Boolean(selectedChainId) } + hasActiveFilters={ Boolean(searchTerm) || Boolean(selectedChainId) } emptyStateProps={{ term: 'token', }} + isTransitioning={ tokensQuery.isTransitioning } > { tokensContent } </DataList> diff --git a/src/features/multichain/pages/address/portfolio/MultichainAddressTokensListItem.tsx b/src/features/multichain/pages/address/portfolio/MultichainAddressTokensListItem.tsx deleted file mode 100644 index e004d62483f..00000000000 --- a/src/features/multichain/pages/address/portfolio/MultichainAddressTokensListItem.tsx +++ /dev/null @@ -1,124 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Grid } from '@chakra-ui/react'; -import { BigNumber } from 'bignumber.js'; -import React from 'react'; - -import type { AddressTokenItem } from 'src/features/multichain/types/client'; -import { getTokenTypeName, isConfidentialTokenType } from 'src/slices/token/utils/token-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; -import NativeTokenTag from 'src/slices/token/components/NativeTokenTag'; - -import multichainConfig from 'src/features/multichain/chains-config'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import calculateUsdValue from 'src/shared/values/entity/calculateUsdValue'; -import ConfidentialValue from 'src/shared/values/entity/ConfidentialValue'; -import SimpleValue from 'src/shared/values/entity/SimpleValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Tag } from 'src/toolkit/chakra/tag'; - -interface Props { - data: AddressTokenItem; - isLoading: boolean; -} - -const MultichainAddressTokensListItem = ({ data, isLoading }: Props) => { - const chainInfo = React.useMemo(() => { - if (!data.chain_values) { - return; - } - - const chainId = Object.keys(data.chain_values)[0]; - const chain = multichainConfig()?.chains.find((chain) => chain.id === chainId); - return chain; - }, [ data.chain_values ]); - - const isNativeToken = chainInfo?.app_config.slices.address.nativeTokenAddress && - data.token.address_hash.toLowerCase() === chainInfo?.app_config.slices.address.nativeTokenAddress.toLowerCase(); - - const { - valueBn: tokenQuantity, - usdBn: tokenValue, - } = calculateUsdValue({ amount: data.value, exchangeRate: data.token.exchange_rate, decimals: data.token.decimals }); - - return ( - <ListItemMobile py={ 3 } rowGap={ 3 } textStyle="sm"> - { isNativeToken ? - <NativeTokenTag chainConfig={ chainInfo?.app_config }/> : - <Tag loading={ isLoading }>{ getTokenTypeName(data.token.type, chainInfo?.app_config) }</Tag> } - <TokenEntity - token={ data.token } - chain={ chainInfo } - isLoading={ isLoading } - noCopy - jointSymbol - fontWeight="600" - width="auto" - maxW="100%" - noLink={ data.token.type === 'NATIVE' } - /> - { data.token.type !== 'NATIVE' && ( - <AddressEntity - address={{ hash: data.token.address_hash }} - isLoading={ isLoading } - noIcon - link={{ variant: 'secondary' }} - w="full" - /> - ) } - <Grid - gridTemplateColumns="minmax(auto, 100px) 1fr" - rowGap={ 3 } - > - { data.token.exchange_rate ? ( - <> - <Skeleton loading={ isLoading } fontWeight="500"> - <span>Price</span> - </Skeleton> - <SimpleValue - value={ BigNumber(data.token.exchange_rate) } - prefix="$" - loading={ isLoading } - color={ isNativeToken ? 'text.secondary' : undefined } - /> - </> - ) : null } - <Skeleton loading={ isLoading } fontWeight="500"> - <span>Quantity</span> - </Skeleton> - { isConfidentialTokenType(data.token.type) ? ( - <ConfidentialValue loading={ isLoading }/> - ) : ( - <SimpleValue - value={ tokenQuantity } - loading={ isLoading } - color={ isNativeToken ? 'text.secondary' : undefined } - /> - ) } - { data.token.exchange_rate && ( - <> - <Skeleton loading={ isLoading } fontWeight="500"> - <span>Value</span> - </Skeleton> - { isConfidentialTokenType(data.token.type) ? ( - <ConfidentialValue loading={ isLoading }/> - ) : ( - <SimpleValue - value={ tokenValue } - prefix="$" - loading={ isLoading } - color={ isNativeToken ? 'text.secondary' : undefined } - /> - ) } - </> - ) } - </Grid> - </ListItemMobile> - ); -}; - -export default React.memo(MultichainAddressTokensListItem); diff --git a/src/features/multichain/pages/address/portfolio/MultichainAddressTokensTable.tsx b/src/features/multichain/pages/address/portfolio/MultichainAddressTokensTable.tsx index e823ffadd62..6b9667f0431 100644 --- a/src/features/multichain/pages/address/portfolio/MultichainAddressTokensTable.tsx +++ b/src/features/multichain/pages/address/portfolio/MultichainAddressTokensTable.tsx @@ -4,6 +4,7 @@ import React from 'react'; import type { AddressTokenItem } from 'src/features/multichain/types/client'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -17,8 +18,12 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: AddressTokenItem): string => + item.token.address_hash + (item.chain_values ? Object.keys(item.chain_values).join(',') : ''); + const MultichainAddressTokensTable = ({ data, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); return ( <TableRoot minW="900px"> @@ -33,7 +38,7 @@ const MultichainAddressTokensTable = ({ data, top, isLoading, resetKey }: Props) <TableBody> { data.slice(0, renderedItemsNum).map((item, index) => ( <MultichainAddressTokensTableItem - key={ item.token.address_hash + (isLoading ? index : '') + (item.chain_values ? Object.keys(item.chain_values).join(',') : '') } + key={ keys[index] } data={ item } isLoading={ isLoading } /> diff --git a/src/features/multichain/pages/address/portfolio/MultichainAddressTokensTableItem.tsx b/src/features/multichain/pages/address/portfolio/MultichainAddressTokensTableItem.tsx index 2eee241f346..4efcbc59b9e 100644 --- a/src/features/multichain/pages/address/portfolio/MultichainAddressTokensTableItem.tsx +++ b/src/features/multichain/pages/address/portfolio/MultichainAddressTokensTableItem.tsx @@ -10,8 +10,8 @@ import { getTokenTypeName, isConfidentialTokenType } from 'src/slices/token/util import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; import NativeTokenTag from 'src/slices/token/components/NativeTokenTag'; - -import multichainConfig from 'src/features/multichain/chains-config'; +import TokenMultiplierTag from 'src/slices/token/components/ui-multiplier/TokenMultiplierTag'; +import { getUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; import calculateUsdValue from 'src/shared/values/entity/calculateUsdValue'; import ConfidentialValue from 'src/shared/values/entity/ConfidentialValue'; @@ -21,6 +21,8 @@ import { DEFAULT_ACCURACY_USD } from 'src/shared/values/entity/utils'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; import { Tag } from 'src/toolkit/chakra/tag'; +import { getTokenChain } from './utils'; + interface Props { data: AddressTokenItem; isLoading: boolean; @@ -28,20 +30,15 @@ interface Props { const MultichainAddressTokensTableItem = ({ data, isLoading }: Props) => { + const chainInfo = React.useMemo(() => getTokenChain(data), [ data ]); + + const multiplier = getUiMultiplier(data.token, chainInfo?.app_config); + const { valueBn: tokenQuantity, + rawValueBn: tokenRawQuantity, usdBn: tokenValue, - } = calculateUsdValue({ amount: data.value, exchangeRate: data.token.exchange_rate, decimals: data.token.decimals }); - - const chainInfo = React.useMemo(() => { - if (!data.chain_values) { - return; - } - - const chainId = Object.keys(data.chain_values)[0]; - const chain = multichainConfig()?.chains.find((chain) => chain.id === chainId); - return chain; - }, [ data.chain_values ]); + } = calculateUsdValue({ amount: data.value, exchangeRate: data.token.exchange_rate, decimals: data.token.decimals, multiplier }); const isNativeToken = chainInfo?.app_config.slices.address.nativeTokenAddress && data.token.address_hash.toLowerCase() === chainInfo?.app_config.slices.address.nativeTokenAddress.toLowerCase(); @@ -89,6 +86,9 @@ const MultichainAddressTokensTableItem = ({ data, isLoading }: Props) => { ) : ( <SimpleValue value={ tokenQuantity } + rawValue={ tokenRawQuantity } + multiplier={ multiplier } + startElement={ multiplier && <TokenMultiplierTag multiplier={ multiplier } loading={ isLoading } mr={ 2 }/> } loading={ isLoading } color={ isNativeToken ? 'text.secondary' : undefined } /> diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioNetWorth.pw.tsx_default_base-view-mobile-1.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioNetWorth.pw.tsx_default_base-view-mobile-1.png new file mode 100644 index 00000000000..b32bcccb0f8 Binary files /dev/null and b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioNetWorth.pw.tsx_default_base-view-mobile-1.png differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioNetWorth.pw.tsx_default_small-desktop-base-view-1.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioNetWorth.pw.tsx_default_small-desktop-base-view-1.png new file mode 100644 index 00000000000..ad9f0d7811a Binary files /dev/null and b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioNetWorth.pw.tsx_default_small-desktop-base-view-1.png differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioNetWorth.pw.tsx_mobile_base-view-mobile-1.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioNetWorth.pw.tsx_mobile_base-view-mobile-1.png new file mode 100644 index 00000000000..6263bdc1e28 Binary files /dev/null and b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioNetWorth.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_dark-color-mode_many-chains-mobile-dark-mode-1.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_dark-color-mode_many-chains-mobile-dark-mode-1.png index 94e1bee2cf9..e5c27bbfcbf 100644 Binary files a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_dark-color-mode_many-chains-mobile-dark-mode-1.png and b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_dark-color-mode_many-chains-mobile-dark-mode-1.png differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_dark-color-mode_many-chains-mobile-dark-mode-2.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_dark-color-mode_many-chains-mobile-dark-mode-2.png deleted file mode 100644 index 7c6af7d3b8a..00000000000 Binary files a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_dark-color-mode_many-chains-mobile-dark-mode-2.png and /dev/null differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_dark-color-mode_many-chains-selected-chain-mobile-dark-mode-1.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_dark-color-mode_many-chains-selected-chain-mobile-dark-mode-1.png new file mode 100644 index 00000000000..8fa4b4f9436 Binary files /dev/null and b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_dark-color-mode_many-chains-selected-chain-mobile-dark-mode-1.png differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_many-chains-mobile-dark-mode-1.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_many-chains-mobile-dark-mode-1.png index 86e7d979998..0000108e5d2 100644 Binary files a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_many-chains-mobile-dark-mode-1.png and b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_many-chains-mobile-dark-mode-1.png differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_many-chains-mobile-dark-mode-2.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_many-chains-mobile-dark-mode-2.png deleted file mode 100644 index ba7eb1f5358..00000000000 Binary files a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_many-chains-mobile-dark-mode-2.png and /dev/null differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_many-chains-selected-chain-mobile-dark-mode-1.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_many-chains-selected-chain-mobile-dark-mode-1.png new file mode 100644 index 00000000000..90e70177eb3 Binary files /dev/null and b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_many-chains-selected-chain-mobile-dark-mode-1.png differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_zero-net-worth-1.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_zero-net-worth-1.png index 47c24d92d7e..094aca5347d 100644 Binary files a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_zero-net-worth-1.png and b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_default_zero-net-worth-1.png differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_mobile_many-chains-mobile-dark-mode-1.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_mobile_many-chains-mobile-dark-mode-1.png index 0a4e942256b..44d672fb73a 100644 Binary files a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_mobile_many-chains-mobile-dark-mode-1.png and b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_mobile_many-chains-mobile-dark-mode-1.png differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_mobile_many-chains-mobile-dark-mode-2.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_mobile_many-chains-mobile-dark-mode-2.png deleted file mode 100644 index d78e9aa2614..00000000000 Binary files a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_mobile_many-chains-mobile-dark-mode-2.png and /dev/null differ diff --git a/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_mobile_many-chains-selected-chain-mobile-dark-mode-1.png b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_mobile_many-chains-selected-chain-mobile-dark-mode-1.png new file mode 100644 index 00000000000..583c644642a Binary files /dev/null and b/src/features/multichain/pages/address/portfolio/__screenshots__/MultichainAddressPortfolioTokens.pw.tsx_mobile_many-chains-selected-chain-mobile-dark-mode-1.png differ diff --git a/src/features/multichain/pages/address/portfolio/utils.ts b/src/features/multichain/pages/address/portfolio/utils.ts index 4d7fe6db4cf..dcbbc617bdc 100644 --- a/src/features/multichain/pages/address/portfolio/utils.ts +++ b/src/features/multichain/pages/address/portfolio/utils.ts @@ -2,9 +2,13 @@ import BigNumber from 'bignumber.js'; -import type { AddressTokenItem } from 'src/features/multichain/types/client'; +import type { AddressTokenItem, ClusterChainConfig } from 'src/features/multichain/types/client'; import { isFungibleTokenType } from 'src/slices/token/utils/token-types'; +import { getUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; + +import multichainConfig from 'src/features/multichain/chains-config'; + import { hairsp } from 'src/toolkit/utils/htmlEntities'; export function formatPercentage(percentage: number) { @@ -18,6 +22,16 @@ export function formatPercentage(percentage: number) { return `${ value }%`; } +// An address-portfolio token item belongs to exactly one chain, the single key of `chain_values`. +export const getTokenChain = (data: AddressTokenItem): ClusterChainConfig | undefined => { + if (!data.chain_values) { + return; + } + + const chainId = Object.keys(data.chain_values)[0]; + return multichainConfig()?.chains.find((chain) => chain.id === chainId); +}; + export const calculateUsdValue = (data: AddressTokenItem) => { const isFungibleToken = isFungibleTokenType(data.token?.type); @@ -31,7 +45,9 @@ export const calculateUsdValue = (data: AddressTokenItem) => { } const decimals = Number(data.token?.decimals || '18'); + const multiplier = getUiMultiplier(data.token, getTokenChain(data)?.app_config); + const value = BigNumber(data.value ?? '0').div(BigNumber(10 ** decimals)); return { - usd: BigNumber(data.value ?? '0').div(BigNumber(10 ** decimals)).multipliedBy(BigNumber(exchangeRate)), + usd: (multiplier ? value.times(multiplier) : value).multipliedBy(BigNumber(exchangeRate)), }; }; diff --git a/src/features/multichain/pages/address/useChainSelectErc20.ts b/src/features/multichain/pages/address/useChainSelectErc20.ts deleted file mode 100644 index ce0ca11e669..00000000000 --- a/src/features/multichain/pages/address/useChainSelectErc20.ts +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useRouter } from 'next/router'; -import React from 'react'; - -import getQueryParamString from 'src/shared/router/get-query-param-string'; - -interface Props { - chainIds: Array<string>; -} -export default function useChainSelectErc20({ chainIds }: Props) { - const router = useRouter(); - const chainId = getQueryParamString(router.query.chain_id); - - return React.useState<Array<string> | undefined>( - chainId && chainIds.includes(chainId) ? [ chainId ] : [ 'all' ], - ); -} diff --git a/src/features/multichain/pages/addresses/MultichainAccounts.tsx b/src/features/multichain/pages/addresses/MultichainAccounts.tsx index fd77fda2975..8c8c59691fe 100644 --- a/src/features/multichain/pages/addresses/MultichainAccounts.tsx +++ b/src/features/multichain/pages/addresses/MultichainAccounts.tsx @@ -1,27 +1,29 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import { BigNumber } from 'bignumber.js'; import React from 'react'; import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; -import AddressesList from 'src/slices/address/pages/index/AddressesList'; import AddressesTable from 'src/slices/address/pages/index/AddressesTable'; import { TOP_ADDRESS } from 'src/slices/address/stubs/address'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; import { MultichainProvider } from 'src/features/multichain/context'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import DataList from 'src/shared/lists/DataList'; import getItemIndex from 'src/shared/lists/get-item-index'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + const MultichainAccounts = () => { - const { isError, isPlaceholderData, data, pagination, chainValue, onChainValueChange, queryHash } = useQueryWithPages({ + const { chainValue, chain, onChainValueChange } = useChainValue(); + const { isError, isInitialLoading, isTransitioning, data, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:addresses', options: { placeholderData: generateListStub<'core:addresses'>(TOP_ADDRESS, 50, { @@ -34,7 +36,7 @@ const MultichainAccounts = () => { exchange_rate: '1', }), }, - isMultichain: true, + chain, }); const pageStartIndex = getItemIndex(0, pagination.page); @@ -43,26 +45,17 @@ const MultichainAccounts = () => { }, [ data?.total_supply ]); const content = data?.items ? ( - <MultichainProvider chainId={ chainValue?.[0] }> - <Box hideBelow="lg"> + <MultichainProvider chainId={ chain?.id }> + <TableContainerScrollable> <AddressesTable top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } items={ data.items } totalSupply={ totalSupply } pageStartIndex={ pageStartIndex } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - <Box hideFrom="lg"> - <AddressesList - items={ data.items } - totalSupply={ totalSupply } - pageStartIndex={ pageStartIndex } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } resetKey={ queryHash } /> - </Box> + </TableContainerScrollable> </MultichainProvider> ) : null; @@ -89,6 +82,7 @@ const MultichainAccounts = () => { actionBar={ actionBar } showActionBarIfError showActionBarIfEmpty + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/multichain/pages/block/MultichainBlock.tsx b/src/features/multichain/pages/block/MultichainBlock.tsx index b1efa266f6e..0a0eae70ae1 100644 --- a/src/features/multichain/pages/block/MultichainBlock.tsx +++ b/src/features/multichain/pages/block/MultichainBlock.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import Block from 'src/slices/block/pages/details/Block'; @@ -9,6 +8,7 @@ import multichainConfig from 'src/features/multichain/chains-config'; import { MultichainProvider } from 'src/features/multichain/context'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; const MultichainBlock = () => { const router = useRouter(); diff --git a/src/features/multichain/pages/blocks/MultichainBlocks.tsx b/src/features/multichain/pages/blocks/MultichainBlocks.tsx index 7a16bef7783..17ab157efa8 100644 --- a/src/features/multichain/pages/blocks/MultichainBlocks.tsx +++ b/src/features/multichain/pages/blocks/MultichainBlocks.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -9,16 +8,18 @@ import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; import PageTitle from 'src/shell/page/title/PageTitle'; import { BLOCK_ITEM } from 'src/slices/block/stubs/list'; +import ChainUtilization from 'src/slices/chain/ChainUtilization'; -import multichainConfig from 'src/features/multichain/chains-config'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Link } from 'src/toolkit/chakra/link'; @@ -41,72 +42,78 @@ const MultichainBlocks = () => { const router = useRouter(); const tab = getQueryParamString(router.query.tab); const isMobile = useIsMobile(); + const { chainValue, chain, onChainValueChange } = useChainValue(); + const hiddenViews = chain?.app_config.slices.block.hiddenViews; - const blocksQuery = useQueryWithPages({ + const isReorgsTab = !hiddenViews?.reorgs && tab === 'reorgs'; + const isUnclesTab = !hiddenViews?.uncles && tab === 'uncles'; + + const blocksQuery = useApiPaginatedQuery({ resourceName: 'core:blocks', - filters: { type: 'block' }, + queryParams: { type: 'block' }, options: { - enabled: tab === 'blocks' || !tab, + enabled: !isReorgsTab && !isUnclesTab, placeholderData: generateListStub<'core:blocks'>(BLOCK_ITEM, 50, { next_page_params: { block_number: 8988686, items_count: 50, } }), }, - isMultichain: true, + chain, }); - const reorgsQuery = useQueryWithPages({ + const reorgsQuery = useApiPaginatedQuery({ resourceName: 'core:blocks', - filters: { type: 'reorg' }, + queryParams: { type: 'reorg' }, options: { - enabled: tab === 'reorgs', + enabled: isReorgsTab, placeholderData: generateListStub<'core:blocks'>(BLOCK_ITEM, 50, { next_page_params: { block_number: 8988686, items_count: 50, } }), }, - isMultichain: true, + chain, }); - const unclesQuery = useQueryWithPages({ + const unclesQuery = useApiPaginatedQuery({ resourceName: 'core:blocks', - filters: { type: 'uncle' }, + queryParams: { type: 'uncle' }, options: { - enabled: tab === 'uncles', + enabled: isUnclesTab, placeholderData: generateListStub<'core:blocks'>(BLOCK_ITEM, 50, { next_page_params: { block_number: 8988686, items_count: 50, } }), }, - isMultichain: true, + chain, }); const tabs: Array<TabItemRegular> = [ - { id: 'blocks', title: 'All', component: <MultichainBlocksContent type="block" query={ blocksQuery } chainId={ blocksQuery.chainValue?.[0] }/> }, - { id: 'reorgs', title: 'Forked', component: <MultichainBlocksContent type="reorg" query={ reorgsQuery } chainId={ reorgsQuery.chainValue?.[0] }/> }, - { id: 'uncles', title: 'Uncles', component: <MultichainBlocksContent type="uncle" query={ unclesQuery } chainId={ unclesQuery.chainValue?.[0] }/> }, - ]; + { id: 'blocks', title: 'All', component: <MultichainBlocksContent type="block" query={ blocksQuery } chainId={ chain?.id }/> }, + !hiddenViews?.reorgs && { id: 'reorgs', title: 'Forked', component: <MultichainBlocksContent type="reorg" query={ reorgsQuery } chainId={ chain?.id }/> }, + !hiddenViews?.uncles && { id: 'uncles', title: 'Uncles', component: <MultichainBlocksContent type="uncle" query={ unclesQuery } chainId={ chain?.id }/> }, + ].filter(Boolean); const currentQuery = (() => { - switch (tab) { - case 'reorgs': return reorgsQuery; - case 'uncles': return unclesQuery; - default: return blocksQuery; + if (isReorgsTab) { + return reorgsQuery; + } + if (isUnclesTab) { + return unclesQuery; } + return blocksQuery; })(); - const currentChainInfo = multichainConfig()?.chains.find(chain => chain.id === currentQuery.chainValue?.[0]); - const leftSlot = ( <ChainSelect - value={ currentQuery.chainValue } - onValueChange={ currentQuery.onChainValueChange } + value={ chainValue } + onValueChange={ onChainValueChange } /> ); const rightSlot = ( <HStack gap={ 8 } hideBelow="lg"> - <Link href={ route({ pathname: '/block/countdown' }, { chain: currentChainInfo }) }> + <ChainUtilization label="Utilization (last 50 blocks):" chain={ chain }/> + <Link href={ route({ pathname: '/block/countdown' }, { chain }) }> <SpriteIcon name="hourglass" boxSize={ 5 } mr={ 2 }/> <span>Block countdown</span> </Link> diff --git a/src/features/multichain/pages/contracts/MultichainVerifiedContracts.tsx b/src/features/multichain/pages/contracts/MultichainVerifiedContracts.tsx index 3d3df25f0a8..e6e51fec5f4 100644 --- a/src/features/multichain/pages/contracts/MultichainVerifiedContracts.tsx +++ b/src/features/multichain/pages/contracts/MultichainVerifiedContracts.tsx @@ -10,17 +10,18 @@ import useVerifiedContractsQuery from 'src/slices/contract/hooks/useVerifiedCont import { SORT_OPTIONS } from 'src/slices/contract/pages/index/sort'; import VerifiedContractsCounters from 'src/slices/contract/pages/index/VerifiedContractsCounters'; import VerifiedContractsFilter from 'src/slices/contract/pages/index/VerifiedContractsFilter'; -import VerifiedContractsList from 'src/slices/contract/pages/index/VerifiedContractsList'; import VerifiedContractsTable from 'src/slices/contract/pages/index/VerifiedContractsTable'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; import { MultichainProvider } from 'src/features/multichain/context'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; import Sort from 'src/shared/sort/Sort'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { FilterInput } from 'src/toolkit/components/filters/FilterInput'; const sortCollection = createListCollection({ @@ -30,8 +31,9 @@ const sortCollection = createListCollection({ const MultichainVerifiedContracts = () => { const isMobile = useIsMobile(); - const { query, type, searchTerm, sort, onSearchTermChange, onTypeChange, onSortChange } = useVerifiedContractsQuery({ isMultichain: true }); - const { isError, isPlaceholderData, data, pagination, chainValue, onChainValueChange } = query; + const { chainValue, chain, onChainValueChange } = useChainValue(); + const { query, type, searchTerm, sort, onSearchTermChange, onTypeChange, onSortChange } = useVerifiedContractsQuery({ chain }); + const { isError, isInitialLoading, data, pagination } = query; const typeFilter = ( <VerifiedContractsFilter @@ -57,7 +59,7 @@ const MultichainVerifiedContracts = () => { defaultValue={ [ sort ] } collection={ sortCollection } onValueChange={ onSortChange } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } /> ); @@ -81,14 +83,9 @@ const MultichainVerifiedContracts = () => { ); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <VerifiedContractsList data={ data.items } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> - </Box> - <Box hideBelow="lg"> - <VerifiedContractsTable data={ data.items } sort={ sort } setSorting={ onSortChange } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> - </Box> - </> + <TableContainerScrollable> + <VerifiedContractsTable data={ data.items } sort={ sort } setSorting={ onSortChange } isLoading={ isInitialLoading } resetKey={ query.queryHash }/> + </TableContainerScrollable> ) : null; return ( @@ -103,7 +100,7 @@ const MultichainVerifiedContracts = () => { mode="default" mb={ 3 } /> - <MultichainProvider chainId={ chainValue?.[0] }> + <MultichainProvider chainId={ chain?.id }> <VerifiedContractsCounters/> <DataList isError={ isError } @@ -114,6 +111,7 @@ const MultichainVerifiedContracts = () => { term: 'contract', }} actionBar={ actionBar } + isTransitioning={ query.isTransitioning } > { content } </DataList> diff --git a/src/features/multichain/pages/ecosystems/MultichainEcosystems.pw.tsx b/src/features/multichain/pages/ecosystems/MultichainEcosystems.pw.tsx index 493999239bc..3ad22d4c0b6 100644 --- a/src/features/multichain/pages/ecosystems/MultichainEcosystems.pw.tsx +++ b/src/features/multichain/pages/ecosystems/MultichainEcosystems.pw.tsx @@ -8,7 +8,7 @@ import { test, expect } from 'playwright/lib'; import MultichainEcosystems from './MultichainEcosystems'; -test('base view +@mobile', async({ render, mockTextAd, mockApiResponse, mockEnvs, mockMultichainConfig, mockAssetResponse }) => { +test('base view', async({ render, mockTextAd, mockApiResponse, mockEnvs, mockMultichainConfig, mockAssetResponse }) => { test.slow(); await mockMultichainConfig(); await mockEnvs(ENVS_MAP.multichain); diff --git a/src/features/multichain/pages/ecosystems/MultichainEcosystems.tsx b/src/features/multichain/pages/ecosystems/MultichainEcosystems.tsx index 3a673fc004e..1e4e8972fea 100644 --- a/src/features/multichain/pages/ecosystems/MultichainEcosystems.tsx +++ b/src/features/multichain/pages/ecosystems/MultichainEcosystems.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, createListCollection } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; +import { createListCollection } from '@chakra-ui/react'; import React from 'react'; import type { ChainMetricsSorting, ChainMetricsSortingField, ChainMetricsSortingValue } from 'src/features/multichain/types/client'; @@ -13,12 +12,15 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import { CHAIN_METRICS } from 'src/features/multichain/stubs'; +import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; +import { useRouter } from 'src/shared/router/useRouter'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; import getSortValueFromQuery from 'src/shared/sort/get-sort-value-from-query'; import Sort from 'src/shared/sort/Sort'; -import MultichainEcosystemsList from './MultichainEcosystemsList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import MultichainEcosystemsTable from './MultichainEcosystemsTable'; import { SORT_OPTIONS } from './utils'; @@ -28,6 +30,7 @@ const sortCollection = createListCollection({ const MultichainEcosystems = () => { const router = useRouter(); + const isMobile = useIsMobile(); const [ sort, setSort ] = React.useState<ChainMetricsSortingValue>(getSortValueFromQuery<ChainMetricsSortingValue>(router.query, SORT_OPTIONS) ?? 'default'); @@ -44,33 +47,28 @@ const MultichainEcosystems = () => { }, [ setSort ]); const content = data?.items ? ( - <> - <Box hideBelow="lg"> - <MultichainEcosystemsTable - data={ data.items } - sort={ sort } - setSorting={ handleSortChange } - isLoading={ isPlaceholderData } - resetKey={ sort } - /> - </Box> - <Box hideFrom="lg"> - <ActionBar> - <Sort - name="chain_metrics_sorting" - defaultValue={ [ sort ] } - collection={ sortCollection } - onValueChange={ handleSortChange } - isLoading={ isPlaceholderData } - /> - </ActionBar> - <MultichainEcosystemsList - data={ data.items } - isLoading={ isPlaceholderData } - resetKey={ sort } - /> - </Box> - </> + <TableContainerScrollable> + <MultichainEcosystemsTable + data={ data.items } + sort={ sort } + setSorting={ handleSortChange } + isLoading={ isPlaceholderData } + resetKey={ sort } + /> + </TableContainerScrollable> + ) : null; + + const actionBar = isMobile ? ( + <ActionBar> + <Sort + name="chain_metrics_sorting" + defaultValue={ [ sort ] } + collection={ sortCollection } + onValueChange={ handleSortChange } + isLoading={ isPlaceholderData } + hideFrom="lg" + /> + </ActionBar> ) : null; return ( @@ -83,6 +81,7 @@ const MultichainEcosystems = () => { isError={ isError } itemsNum={ data?.items.length } emptyText="There are no chains in the cluster." + actionBar={ actionBar } > { content } </DataList> diff --git a/src/features/multichain/pages/ecosystems/MultichainEcosystemsList.tsx b/src/features/multichain/pages/ecosystems/MultichainEcosystemsList.tsx deleted file mode 100644 index aadb0fcb2e9..00000000000 --- a/src/features/multichain/pages/ecosystems/MultichainEcosystemsList.tsx +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type * as multichain from '@blockscout/multichain-aggregator-types'; - -import multichainConfig from 'src/features/multichain/chains-config'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import MultichainEcosystemsListItem from './MultichainEcosystemsListItem'; - -interface Props { - data: Array<multichain.ChainMetrics>; - isLoading?: boolean; - resetKey?: string; -} - -const MultichainEcosystemsList = ({ data, isLoading, resetKey }: Props) => { - const chains = multichainConfig()?.chains; - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <MultichainEcosystemsListItem - key={ item.chain_id + (isLoading ? String(index) : '') } - data={ item } - chainInfo={ chains?.find((chain) => chain.id === item.chain_id) } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(MultichainEcosystemsList); diff --git a/src/features/multichain/pages/ecosystems/MultichainEcosystemsListItem.tsx b/src/features/multichain/pages/ecosystems/MultichainEcosystemsListItem.tsx deleted file mode 100644 index 5b26854f34a..00000000000 --- a/src/features/multichain/pages/ecosystems/MultichainEcosystemsListItem.tsx +++ /dev/null @@ -1,111 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { chakra, Grid, HStack, Stat } from '@chakra-ui/react'; -import React from 'react'; - -import type * as multichain from '@blockscout/multichain-aggregator-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; - -import ChainSnippetList from 'src/shared/external-chains/ChainSnippetList'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - data: multichain.ChainMetrics; - chainInfo: ClusterChainConfig | undefined; - isLoading?: boolean; -} - -const MultichainEcosystemsListItem = ({ data, chainInfo, isLoading }: Props) => { - const activeAddresses = { - value: data.active_accounts?.current_full_week ? Number(data.active_accounts.current_full_week) : 0, - delta: data.active_accounts?.wow_diff_percent ? Number(data.active_accounts.wow_diff_percent) : 0, - }; - - const newAddresses = { - value: data.new_addresses?.current_full_week ? Number(data.new_addresses.current_full_week) : 0, - delta: data.new_addresses?.wow_diff_percent ? Number(data.new_addresses.wow_diff_percent) : 0, - }; - - const dailyTransactions = { - value: data.daily_transactions?.current_full_week ? Number(data.daily_transactions.current_full_week) : 0, - delta: data.daily_transactions?.wow_diff_percent ? Number(data.daily_transactions.wow_diff_percent) : 0, - }; - - return ( - <ListItemMobile rowGap={ 3 } py={ 4 } fontSize="sm" alignItems="stretch"> - { chainInfo && <ChainSnippetList data={ chainInfo } isLoading={ isLoading }/> } - <Grid gridTemplateColumns="140px 1fr" columnGap={ 2 } rowGap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 }> - <span>Active addresses</span> - <chakra.span color="text.secondary"> 7D</chakra.span> - </Skeleton> - <HStack gap={ 1 }> - <Skeleton loading={ isLoading }> - <span>{ activeAddresses.value.toLocaleString() }</span> - </Skeleton> - { activeAddresses.delta ? ( - <Skeleton loading={ isLoading }> - <Stat.Root positive={ activeAddresses.delta > 0 }> - <Stat.ValueText> - { activeAddresses.delta.toFixed(2) }% - </Stat.ValueText> - { activeAddresses.delta > 0 ? <Stat.UpIndicator/> : <Stat.DownIndicator/> } - </Stat.Root> - </Skeleton> - ) : null } - </HStack> - - <Skeleton loading={ isLoading } fontWeight={ 500 }> - <span>New addresses</span> - <chakra.span color="text.secondary"> 7D</chakra.span> - </Skeleton> - <HStack gap={ 1 }> - <Skeleton loading={ isLoading }> - <span>{ newAddresses.value.toLocaleString() }</span> - </Skeleton> - { newAddresses.delta ? ( - <Skeleton loading={ isLoading }> - <Stat.Root positive={ newAddresses.delta > 0 }> - <Stat.ValueText> - { newAddresses.delta.toFixed(2) }% - </Stat.ValueText> - { newAddresses.delta > 0 ? <Stat.UpIndicator/> : <Stat.DownIndicator/> } - </Stat.Root> - </Skeleton> - ) : null } - </HStack> - - <Skeleton loading={ isLoading } fontWeight={ 500 }> - <span>Daily txs</span> - <chakra.span color="text.secondary"> 7D</chakra.span> - </Skeleton> - <HStack gap={ 1 }> - <Skeleton loading={ isLoading }> - <span>{ dailyTransactions.value.toLocaleString() }</span> - </Skeleton> - { dailyTransactions.delta ? ( - <Skeleton loading={ isLoading }> - <Stat.Root positive={ dailyTransactions.delta > 0 }> - <Stat.ValueText> - { dailyTransactions.delta.toFixed(2) }% - </Stat.ValueText> - { dailyTransactions.delta > 0 ? <Stat.UpIndicator/> : <Stat.DownIndicator/> } - </Stat.Root> - </Skeleton> - ) : null } - </HStack> - - <Skeleton loading={ isLoading } fontWeight={ 500 }> - <span>TPS</span> - </Skeleton> - <Skeleton loading={ isLoading }> - <span>{ Number(data.tps ?? 0).toLocaleString(undefined, { maximumFractionDigits: 2 }) }</span> - </Skeleton> - </Grid> - </ListItemMobile> - ); -}; - -export default React.memo(MultichainEcosystemsListItem); diff --git a/src/features/multichain/pages/ecosystems/__screenshots__/MultichainEcosystems.pw.tsx_default_base-view-1.png b/src/features/multichain/pages/ecosystems/__screenshots__/MultichainEcosystems.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..4a1f043b2d9 Binary files /dev/null and b/src/features/multichain/pages/ecosystems/__screenshots__/MultichainEcosystems.pw.tsx_default_base-view-1.png differ diff --git a/src/features/multichain/pages/ecosystems/__screenshots__/MultichainEcosystems.pw.tsx_default_base-view-mobile-1.png b/src/features/multichain/pages/ecosystems/__screenshots__/MultichainEcosystems.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index e765da59683..00000000000 Binary files a/src/features/multichain/pages/ecosystems/__screenshots__/MultichainEcosystems.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/multichain/pages/ecosystems/__screenshots__/MultichainEcosystems.pw.tsx_mobile_base-view-mobile-1.png b/src/features/multichain/pages/ecosystems/__screenshots__/MultichainEcosystems.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 0694f943ed7..00000000000 Binary files a/src/features/multichain/pages/ecosystems/__screenshots__/MultichainEcosystems.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/multichain/pages/home/LatestTxs.tsx b/src/features/multichain/pages/home/LatestTxs.tsx index 78008e6ff9c..a70a6edd96f 100644 --- a/src/features/multichain/pages/home/LatestTxs.tsx +++ b/src/features/multichain/pages/home/LatestTxs.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; @@ -9,6 +8,7 @@ import useRoutedChainSelect from 'src/features/multichain/hooks/useRoutedChainSe import config from 'src/config'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { EmptyState } from 'src/toolkit/chakra/empty-state'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; diff --git a/src/features/multichain/pages/home/LatestTxsCrossChain.tsx b/src/features/multichain/pages/home/LatestTxsCrossChain.tsx index 482691fed31..1f8ea1b3810 100644 --- a/src/features/multichain/pages/home/LatestTxsCrossChain.tsx +++ b/src/features/multichain/pages/home/LatestTxsCrossChain.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Separator } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -10,6 +9,7 @@ import TransactionsCrossChainContent from 'src/features/cross-chain-txs/componen import { INTERCHAIN_MESSAGE } from 'src/features/cross-chain-txs/stubs/messages'; import { generateListStub } from 'src/shared/pagination/utils'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/features/multichain/pages/home/LatestTxsLocal.tsx b/src/features/multichain/pages/home/LatestTxsLocal.tsx index 5a96db22a53..38b901fcb19 100644 --- a/src/features/multichain/pages/home/LatestTxsLocal.tsx +++ b/src/features/multichain/pages/home/LatestTxsLocal.tsx @@ -45,7 +45,7 @@ const LatestTxsLocal = () => { <SocketProvider url={ getSocketUrl(chain?.app_config) }> <TxsContent items={ query.data } - isPlaceholderData={ query.isPlaceholderData } + isInitialLoading={ query.isPlaceholderData } isError={ query.isError } pagination={ PAGINATION_PARAMS } sort="default" diff --git a/src/features/multichain/pages/home/MultichainHome.tsx b/src/features/multichain/pages/home/MultichainHome.tsx index 6eee8ab4134..7c40a251062 100644 --- a/src/features/multichain/pages/home/MultichainHome.tsx +++ b/src/features/multichain/pages/home/MultichainHome.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, HStack, VStack } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -11,6 +10,8 @@ import HeroBanner from 'src/slices/home/pages/index/HeroBanner'; import multichainConfig from 'src/features/multichain/chains-config'; import { MultichainProvider } from 'src/features/multichain/context'; +import { route } from 'src/shared/router/routes'; + import { Link } from 'src/toolkit/chakra/link'; import ChainWidget from './ChainWidget'; diff --git a/src/features/multichain/pages/home/Stats.tsx b/src/features/multichain/pages/home/Stats.tsx index ee4882b5ad3..18bcdde5264 100644 --- a/src/features/multichain/pages/home/Stats.tsx +++ b/src/features/multichain/pages/home/Stats.tsx @@ -5,15 +5,20 @@ import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; -import type { HomeStatsWidgetItem } from 'src/slices/home/utils/stats'; import { sortHomeStatsItems, isHomeStatsItemEnabled } from 'src/slices/home/utils/stats'; import { HOMEPAGE_STATS } from 'src/features/multichain/stubs'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; import ChainIndicators from './ChainIndicators'; +const COLUMNS_NUM = { + desktop: 1, + mobile: 2, +}; + const Stats = () => { const statsQuery = useApiQuery('multichainStats:pages_main', { queryOptions: { @@ -22,7 +27,7 @@ const Stats = () => { }, }); - const items: Array<HomeStatsWidgetItem> = React.useMemo(() => { + const items = React.useMemo(() => { return [ statsQuery.data?.total_multichain_txns && { id: 'total_txs' as const, @@ -45,9 +50,9 @@ const Stats = () => { }, [ statsQuery.data ]); return ( - <Flex mt={ 6 } gap={ 2 } flexDirection={{ base: 'column', lg: 'row' }}> + <Flex mt={ 6 } gap={{ base: 1, lg: 2 }} flexDirection={{ base: 'column', lg: 'row' }}> { items.length > 0 && ( - <Flex gap={ 2 } flexDirection={{ base: 'row', lg: 'column' }} w={{ base: '100%', lg: '270px' }}> + <StatsContainer columnsNum={ COLUMNS_NUM } w={{ base: '100%', lg: '270px' }}> { items.map((item) => ( <StatsWidget key={ item.id } @@ -56,10 +61,9 @@ const Stats = () => { icon={ item.icon } isLoading={ statsQuery.isPlaceholderData } hint={ item.hint } - w={{ base: 'calc((100% - 8px) / 2)', lg: '100%' }} /> )) } - </Flex> + </StatsContainer> ) } <ChainIndicators/> </Flex> diff --git a/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png b/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png index 5f8b143bf69..104c7ec39eb 100644 Binary files a/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png and b/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_default_base-view-mobile-dark-mode-1.png b/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_default_base-view-mobile-dark-mode-1.png index 480e1c204f7..52c5f93078b 100644 Binary files a/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_default_base-view-mobile-dark-mode-1.png and b/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_default_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_mobile_base-view-mobile-dark-mode-1.png b/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_mobile_base-view-mobile-dark-mode-1.png index 251b85cb2c0..195f3396d65 100644 Binary files a/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_mobile_base-view-mobile-dark-mode-1.png and b/src/features/multichain/pages/home/__screenshots__/MultichainHome.pw.tsx_mobile_base-view-mobile-dark-mode-1.png differ diff --git a/src/features/multichain/pages/internal-txs/MultichainInternalTxs.tsx b/src/features/multichain/pages/internal-txs/MultichainInternalTxs.tsx index a58cca36c43..80e5f72da8c 100644 --- a/src/features/multichain/pages/internal-txs/MultichainInternalTxs.tsx +++ b/src/features/multichain/pages/internal-txs/MultichainInternalTxs.tsx @@ -6,24 +6,26 @@ import React from 'react'; import ActionBar from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; -import InternalTxsList from 'src/slices/internal-tx/components/InternalTxsList'; import InternalTxsTable from 'src/slices/internal-tx/components/InternalTxsTable'; import useInternalTxsQuery from 'src/slices/internal-tx/hooks/useInternalTxsQuery'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; import { MultichainProvider } from 'src/features/multichain/context'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { FilterInput } from 'src/toolkit/components/filters/FilterInput'; const MultichainInternalTxs = () => { const isMobile = useIsMobile(); - const { query, searchTerm, onSearchTermChange } = useInternalTxsQuery({ isMultichain: true }); - const { isError, isPlaceholderData, data, pagination } = query; + const { chainValue, chain, onChainValueChange } = useChainValue(); + const { query, searchTerm, onSearchTermChange } = useInternalTxsQuery({ chain }); + const { isError, isInitialLoading, data, pagination } = query; const filterInput = ( <FilterInput @@ -38,8 +40,8 @@ const MultichainInternalTxs = () => { const chainSelect = ( <ChainSelect - value={ query.chainValue } - onValueChange={ query.onChainValueChange } + value={ chainValue } + onValueChange={ onChainValueChange } /> ); @@ -59,13 +61,10 @@ const MultichainInternalTxs = () => { ); const content = data?.items ? ( - <MultichainProvider chainId={ query.chainValue?.[0] }> - <Box hideBelow="lg"> - <InternalTxsTable data={ data.items } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> - </Box> - <Box hideFrom="lg"> - <InternalTxsList data={ data.items } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> - </Box> + <MultichainProvider chainId={ chain?.id }> + <TableContainerScrollable> + <InternalTxsTable data={ data.items } isLoading={ isInitialLoading } resetKey={ query.queryHash }/> + </TableContainerScrollable> </MultichainProvider> ) : null; @@ -86,6 +85,7 @@ const MultichainInternalTxs = () => { actionBar={ actionBar } showActionBarIfError showActionBarIfEmpty + isTransitioning={ query.isTransitioning } > { content } </DataList> diff --git a/src/features/multichain/pages/search-results/SearchResults.pw.tsx b/src/features/multichain/pages/search-results/SearchResults.pw.tsx index aa3e65b4ece..3260ff10847 100644 --- a/src/features/multichain/pages/search-results/SearchResults.pw.tsx +++ b/src/features/multichain/pages/search-results/SearchResults.pw.tsx @@ -2,6 +2,8 @@ import React from 'react'; import type { GetAddressResponse } from '@blockscout/multichain-aggregator-types'; +import * as indexingStatusMock from 'src/slices/chain/indexing-status/mocks'; + import * as chainDataMock from 'src/features/multichain/mocks/chains'; import * as searchMock from 'src/features/multichain/mocks/search'; @@ -24,6 +26,7 @@ test.beforeEach(async({ mockApiResponse, mockMultichainConfig, mockEnvs, mockAss await mockMultichainConfig(); await mockEnvs(ENVS_MAP.multichain); await mockTextAd(); + await mockApiResponse('core:homepage_indexing_status', indexingStatusMock.finished); await mockApiResponse('multichainAggregator:search_addresses', { items: [ diff --git a/src/features/multichain/pages/search-results/SearchResults.tsx b/src/features/multichain/pages/search-results/SearchResults.tsx index e1e95d3f976..120fceca43b 100644 --- a/src/features/multichain/pages/search-results/SearchResults.tsx +++ b/src/features/multichain/pages/search-results/SearchResults.tsx @@ -44,10 +44,10 @@ const SearchResults = () => { persistedParams: [ 'q', 'tab' ], }); const chainId = chainSelect.value?.[0]; - const { searchTerm, debouncedSearchTerm, handleSearchTermChange, handleSubmit, queries, checkRedirectQuery } = useSearchQuery({ + const { searchTerm, appliedSearchTerm, handleSearchTermChange, handleSubmit, queries, checkRedirectQuery } = useSearchQuery({ chainId: chainId === 'all' ? undefined : chainId, }); - const showContent = useSearchRedirect({ checkRedirectQuery, hasSearchTerm: debouncedSearchTerm.trim().length > 0 }); + const showContent = useSearchRedirect({ checkRedirectQuery, hasSearchTerm: appliedSearchTerm.trim().length > 0 }); const isLoading = Object.values(queries).some((query) => query.isPending); @@ -102,7 +102,7 @@ const SearchResults = () => { queries={ queries } queryType={ queryType } isLoading={ isLoading } - searchTerm={ debouncedSearchTerm } + searchTerm={ appliedSearchTerm } beforeContent={ isMobile ? chainSelectElement : undefined } /> ), @@ -118,7 +118,7 @@ const SearchResults = () => { queries={ queries } queryType={ undefined } isLoading={ isLoading } - searchTerm={ debouncedSearchTerm } + searchTerm={ appliedSearchTerm } beforeContent={ isMobile ? chainSelectElement : undefined } /> ), diff --git a/src/features/multichain/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_desktop-base-view-1.png b/src/features/multichain/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_desktop-base-view-1.png index 60ef3594f5e..0b83ee29e31 100644 Binary files a/src/features/multichain/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_desktop-base-view-1.png and b/src/features/multichain/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_desktop-base-view-1.png differ diff --git a/src/features/multichain/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_mobile-base-view-1.png b/src/features/multichain/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_mobile-base-view-1.png index 083394dcba7..47dbbbb2618 100644 Binary files a/src/features/multichain/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_mobile-base-view-1.png and b/src/features/multichain/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_mobile-base-view-1.png differ diff --git a/src/features/multichain/pages/search-results/items/SearchResultItemToken.tsx b/src/features/multichain/pages/search-results/items/SearchResultItemToken.tsx index 0e4c101b9ba..c9f47e87d77 100644 --- a/src/features/multichain/pages/search-results/items/SearchResultItemToken.tsx +++ b/src/features/multichain/pages/search-results/items/SearchResultItemToken.tsx @@ -6,16 +6,18 @@ import React from 'react'; import type * as multichain from '@blockscout/multichain-aggregator-types'; import type { ClusterChainConfig } from 'src/features/multichain/types/client'; +import { isFungibleTokenType } from 'src/slices/token/utils/token-types'; import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; import * as contract from 'src/features/multichain/utils/contract'; import { route } from 'src/shared/router/routes'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; -import shortenString from 'src/shared/texts/shorten-string'; import SpriteIcon from 'src/sprite/SpriteIcon'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; +import { shortenString } from 'src/toolkit/utils/texts'; + import SearchResultListItem from '../SearchResultListItem'; interface Props { @@ -25,6 +27,7 @@ interface Props { } const SearchResultItemToken = ({ data, chain, isMobile }: Props) => { + const isFungibleToken = isFungibleTokenType(data.type, chain.app_config); const isVerified = contract.isVerified({ chain_infos: mapValues(data.chain_infos, (chainInfo) => ({ ...chainInfo, is_contract: true, coin_balance: '0' })) }); @@ -59,7 +62,7 @@ const SearchResultItemToken = ({ data, chain, isMobile }: Props) => { _groupHover={{ color: 'inherit' }} > { isMobile ? shortenString(data.address_hash) : ( - <HashStringShortenDynamic hash={ data.address_hash }/> + <Truncate value={ data.address_hash }/> ) } </Box> { isVerified && <SpriteIcon name="status/success" boxSize="14px" color="green.500" ml={ 1 } flexShrink={ 0 }/> } @@ -71,8 +74,8 @@ const SearchResultItemToken = ({ data, chain, isMobile }: Props) => { ml="auto" maxW={{ base: '60%', lg: 'unset' }} > - { (data.type as string) === 'ERC-20' && data.exchange_rate && `$${ Number(data.exchange_rate).toLocaleString() }` } - { (data.type as string) !== 'ERC-20' && data.total_supply && `Items ${ Number(data.total_supply).toLocaleString() }` } + { isFungibleToken && data.exchange_rate && `$${ Number(data.exchange_rate).toLocaleString() }` } + { !isFungibleToken && data.total_supply && `Items ${ Number(data.total_supply).toLocaleString() }` } </Text> </Flex> </SearchResultListItem> diff --git a/src/features/multichain/pages/search-results/useSearchQuery.ts b/src/features/multichain/pages/search-results/useSearchQuery.ts new file mode 100644 index 00000000000..08ea5e036b8 --- /dev/null +++ b/src/features/multichain/pages/search-results/useSearchQuery.ts @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import useApiInfiniteQuery from 'src/api/hooks/useApiInfiniteQuery'; +import useApiQuery from 'src/api/hooks/useApiQuery'; + +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; + +interface Props { + chainId: string | undefined; +} + +export default function useSearchQuery({ chainId }: Props) { + const router = useRouter(); + const q = React.useRef(getQueryParamString(router.query.q)); + const initialValue = q.current; + const checkRedirect = getQueryParamString(router.query.redirect) === 'true'; + + const appliedSearchTerm = getQueryParamString(router.query.q); + const [ searchTerm, setSearchTerm ] = React.useState(appliedSearchTerm); + + const checkRedirectQuery = useApiQuery('multichainAggregator:search_check_redirect', { + // on search result page we check redirect only once on mount + queryParams: { q: initialValue }, + queryOptions: { enabled: Boolean(initialValue) && checkRedirect }, + }); + + const addressesQuery = useApiInfiniteQuery({ + resourceName: 'multichainAggregator:search_addresses', + queryParams: { q: appliedSearchTerm, chain_id: chainId }, + }); + + const tokensQuery = useApiInfiniteQuery({ + resourceName: 'multichainAggregator:search_tokens', + queryParams: { q: appliedSearchTerm, chain_id: chainId }, + }); + + const blockNumbersQuery = useApiInfiniteQuery({ + resourceName: 'multichainAggregator:search_block_numbers', + queryParams: { q: appliedSearchTerm, chain_id: chainId }, + }); + + const blocksQuery = useApiInfiniteQuery({ + resourceName: 'multichainAggregator:search_blocks', + queryParams: { q: appliedSearchTerm, chain_id: chainId }, + }); + + const nftsQuery = useApiInfiniteQuery({ + resourceName: 'multichainAggregator:search_nfts', + queryParams: { q: appliedSearchTerm, chain_id: chainId }, + }); + + const transactionsQuery = useApiInfiniteQuery({ + resourceName: 'multichainAggregator:search_transactions', + queryParams: { q: appliedSearchTerm, chain_id: chainId }, + }); + + const domainsQuery = useApiInfiniteQuery({ + resourceName: 'multichainAggregator:search_domains', + queryParams: { q: appliedSearchTerm, chain_id: chainId }, + }); + + const applySearchTerm = useDebouncedFilterChange((value) => { + router.push({ + pathname: router.pathname, + query: { ...router.query, q: value }, + }, { shallow: true }); + }); + + const handleSearchTermChange = React.useCallback((value: string) => { + setSearchTerm(value); + applySearchTerm(value); + }, [ applySearchTerm ]); + + const handleSubmit = React.useCallback((event: React.FormEvent<HTMLFormElement>) => { + event.preventDefault(); + }, [ ]); + + const queries = React.useMemo(() => ({ + addresses: addressesQuery, + tokens: tokensQuery, + blockNumbers: blockNumbersQuery, + blocks: blocksQuery, + nfts: nftsQuery, + transactions: transactionsQuery, + domains: domainsQuery, + }), [ addressesQuery, tokensQuery, blockNumbersQuery, blocksQuery, nftsQuery, transactionsQuery, domainsQuery ]); + + return React.useMemo(() => ({ + searchTerm, + appliedSearchTerm, + handleSearchTermChange, + handleSubmit, + queries, + checkRedirectQuery, + }), [ + queries, + appliedSearchTerm, + handleSearchTermChange, + handleSubmit, + searchTerm, + checkRedirectQuery, + ]); +} diff --git a/src/features/multichain/pages/search-results/useSearchQuery.tsx b/src/features/multichain/pages/search-results/useSearchQuery.tsx deleted file mode 100644 index 126a1ee9068..00000000000 --- a/src/features/multichain/pages/search-results/useSearchQuery.tsx +++ /dev/null @@ -1,104 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useRouter } from 'next/router'; -import React from 'react'; - -import useApiInfiniteQuery from 'src/api/hooks/useApiInfiniteQuery'; -import useApiQuery from 'src/api/hooks/useApiQuery'; - -import useDebounce from 'src/shared/hooks/useDebounce'; -import getQueryParamString from 'src/shared/router/get-query-param-string'; - -interface Props { - chainId: string | undefined; -} - -export default function useSearchQuery({ chainId }: Props) { - const router = useRouter(); - const q = React.useRef(getQueryParamString(router.query.q)); - const initialValue = q.current; - const checkRedirect = getQueryParamString(router.query.redirect) === 'true'; - - const [ searchTerm, setSearchTerm ] = React.useState(initialValue); - - const debouncedSearchTerm = useDebounce(searchTerm, 300); - - const checkRedirectQuery = useApiQuery('multichainAggregator:search_check_redirect', { - // on search result page we check redirect only once on mount - queryParams: { q: initialValue }, - queryOptions: { enabled: Boolean(initialValue) && checkRedirect }, - }); - - const addressesQuery = useApiInfiniteQuery({ - resourceName: 'multichainAggregator:search_addresses', - queryParams: { q: debouncedSearchTerm, chain_id: chainId }, - }); - - const tokensQuery = useApiInfiniteQuery({ - resourceName: 'multichainAggregator:search_tokens', - queryParams: { q: debouncedSearchTerm, chain_id: chainId }, - }); - - const blockNumbersQuery = useApiInfiniteQuery({ - resourceName: 'multichainAggregator:search_block_numbers', - queryParams: { q: debouncedSearchTerm, chain_id: chainId }, - }); - - const blocksQuery = useApiInfiniteQuery({ - resourceName: 'multichainAggregator:search_blocks', - queryParams: { q: debouncedSearchTerm, chain_id: chainId }, - }); - - const nftsQuery = useApiInfiniteQuery({ - resourceName: 'multichainAggregator:search_nfts', - queryParams: { q: debouncedSearchTerm, chain_id: chainId }, - }); - - const transactionsQuery = useApiInfiniteQuery({ - resourceName: 'multichainAggregator:search_transactions', - queryParams: { q: debouncedSearchTerm, chain_id: chainId }, - }); - - const domainsQuery = useApiInfiniteQuery({ - resourceName: 'multichainAggregator:search_domains', - queryParams: { q: debouncedSearchTerm, chain_id: chainId }, - }); - - const handleSearchTermChange = React.useCallback((value: string) => { - setSearchTerm(value); - router.push({ - pathname: router.pathname, - query: { ...router.query, q: value }, - }); - }, [ router ]); - - const handleSubmit = React.useCallback((event: React.FormEvent<HTMLFormElement>) => { - event.preventDefault(); - }, [ ]); - - const queries = React.useMemo(() => ({ - addresses: addressesQuery, - tokens: tokensQuery, - blockNumbers: blockNumbersQuery, - blocks: blocksQuery, - nfts: nftsQuery, - transactions: transactionsQuery, - domains: domainsQuery, - }), [ addressesQuery, tokensQuery, blockNumbersQuery, blocksQuery, nftsQuery, transactionsQuery, domainsQuery ]); - - return React.useMemo(() => ({ - searchTerm, - debouncedSearchTerm, - handleSearchTermChange, - handleSubmit, - queries, - checkRedirectQuery, - }), [ - queries, - debouncedSearchTerm, - handleSearchTermChange, - handleSubmit, - searchTerm, - checkRedirectQuery, - ]); -} diff --git a/src/features/multichain/pages/search-results/useSearchRedirect.ts b/src/features/multichain/pages/search-results/useSearchRedirect.ts new file mode 100644 index 00000000000..64bffab510c --- /dev/null +++ b/src/features/multichain/pages/search-results/useSearchRedirect.ts @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { UseQueryResult } from '@tanstack/react-query'; +import React from 'react'; + +import type * as multichain from '@blockscout/multichain-aggregator-types'; + +import type { ResourceError } from 'src/api/resources'; + +import multichainConfig from 'src/features/multichain/chains-config'; + +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import removeQueryParam from 'src/shared/router/remove-query-param'; +import { useRouter } from 'src/shared/router/useRouter'; + +interface Params { + checkRedirectQuery: UseQueryResult<multichain.CheckRedirectResponse, ResourceError<unknown>>; + hasSearchTerm: boolean; +} + +export default function useSearchRedirect({ checkRedirectQuery, hasSearchTerm }: Params) { + const router = useRouter(); + const enabled = getQueryParamString(router.query.redirect) === 'true'; + + const [ showContent, setShowContent ] = React.useState(!enabled); + + React.useEffect(() => { + if (showContent) { + return; + } + + if (!hasSearchTerm) { + setShowContent(true); + return; + } + + if (checkRedirectQuery.data?.redirect && checkRedirectQuery.data.parameter) { + switch (checkRedirectQuery.data.type) { + case 'block': { + const chainInfo = multichainConfig()?.chains.find((chain) => chain.id === checkRedirectQuery.data.chain_id); + if (chainInfo) { + router.replace({ + pathname: '/chain/[chain_slug_or_id]/block/[height_or_hash]', + query: { height_or_hash: checkRedirectQuery.data.parameter, chain_slug_or_id: chainInfo.slug }, + }); + return; + } + break; + } + case 'address': { + router.replace({ pathname: '/address/[hash]', query: { hash: checkRedirectQuery.data.parameter } }); + return; + } + case 'transaction': { + const chainInfo = multichainConfig()?.chains.find((chain) => chain.id === checkRedirectQuery.data.chain_id); + if (chainInfo) { + router.replace({ + pathname: '/chain/[chain_slug_or_id]/tx/[hash]', + query: { + hash: checkRedirectQuery.data.parameter, + chain_slug_or_id: chainInfo.slug, + }, + }); + return; + } + break; + } + } + } + + if (!checkRedirectQuery.isPending) { + setShowContent(true); + removeQueryParam(router, 'redirect'); + } + }, [ checkRedirectQuery, router, hasSearchTerm, showContent ]); + + return showContent; +} diff --git a/src/features/multichain/pages/search-results/useSearchRedirect.tsx b/src/features/multichain/pages/search-results/useSearchRedirect.tsx deleted file mode 100644 index ba8e76f8ae6..00000000000 --- a/src/features/multichain/pages/search-results/useSearchRedirect.tsx +++ /dev/null @@ -1,78 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { UseQueryResult } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; -import React from 'react'; - -import type * as multichain from '@blockscout/multichain-aggregator-types'; - -import type { ResourceError } from 'src/api/resources'; - -import multichainConfig from 'src/features/multichain/chains-config'; - -import getQueryParamString from 'src/shared/router/get-query-param-string'; -import removeQueryParam from 'src/shared/router/remove-query-param'; - -interface Params { - checkRedirectQuery: UseQueryResult<multichain.CheckRedirectResponse, ResourceError<unknown>>; - hasSearchTerm: boolean; -} - -export default function useSearchRedirect({ checkRedirectQuery, hasSearchTerm }: Params) { - const router = useRouter(); - const enabled = getQueryParamString(router.query.redirect) === 'true'; - - const [ showContent, setShowContent ] = React.useState(!enabled); - - React.useEffect(() => { - if (showContent) { - return; - } - - if (!hasSearchTerm) { - setShowContent(true); - return; - } - - if (checkRedirectQuery.data?.redirect && checkRedirectQuery.data.parameter) { - switch (checkRedirectQuery.data.type) { - case 'block': { - const chainInfo = multichainConfig()?.chains.find((chain) => chain.id === checkRedirectQuery.data.chain_id); - if (chainInfo) { - router.replace({ - pathname: '/chain/[chain_slug_or_id]/block/[height_or_hash]', - query: { height_or_hash: checkRedirectQuery.data.parameter, chain_slug_or_id: chainInfo.slug }, - }); - return; - } - break; - } - case 'address': { - router.replace({ pathname: '/address/[hash]', query: { hash: checkRedirectQuery.data.parameter } }); - return; - } - case 'transaction': { - const chainInfo = multichainConfig()?.chains.find((chain) => chain.id === checkRedirectQuery.data.chain_id); - if (chainInfo) { - router.replace({ - pathname: '/chain/[chain_slug_or_id]/tx/[hash]', - query: { - hash: checkRedirectQuery.data.parameter, - chain_slug_or_id: chainInfo.slug, - }, - }); - return; - } - break; - } - } - } - - if (!checkRedirectQuery.isPending) { - setShowContent(true); - removeQueryParam(router, 'redirect'); - } - }, [ checkRedirectQuery, router, hasSearchTerm, showContent ]); - - return showContent; -} diff --git a/src/features/multichain/pages/token-instance/MultichainTokenInstance.tsx b/src/features/multichain/pages/token-instance/MultichainTokenInstance.tsx index 54d063a66db..16d9ad19235 100644 --- a/src/features/multichain/pages/token-instance/MultichainTokenInstance.tsx +++ b/src/features/multichain/pages/token-instance/MultichainTokenInstance.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import { SocketProvider } from 'src/api/socket/context'; @@ -12,6 +11,7 @@ import multichainConfig from 'src/features/multichain/chains-config'; import { MultichainProvider } from 'src/features/multichain/context'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; const MultichainTokenInstance = () => { const router = useRouter(); diff --git a/src/features/multichain/pages/token-transfers/MultichainTokenTransfers.tsx b/src/features/multichain/pages/token-transfers/MultichainTokenTransfers.tsx index e2369430330..cbba384ecc0 100644 --- a/src/features/multichain/pages/token-transfers/MultichainTokenTransfers.tsx +++ b/src/features/multichain/pages/token-transfers/MultichainTokenTransfers.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TokenType } from 'src/slices/token/types/api'; @@ -8,6 +7,7 @@ import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; import PageTitle from 'src/shell/page/title/PageTitle'; +import { useTokenTransferColumns } from 'src/slices/token-transfer/hooks/useTokenTransferColumns'; import useTokenTransfersQuery from 'src/slices/token-transfer/hooks/useTokenTransfersQuery'; import TokenTypeFilter from 'src/slices/token/components/TokenTypeFilter'; import { getTokenFilterValue } from 'src/slices/token/utils/list-utils'; @@ -16,12 +16,15 @@ import TokenTransfersCrossChain from 'src/features/cross-chain-txs/pages/token-t import multichainConfig from 'src/features/multichain/chains-config'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; import { MultichainProvider } from 'src/features/multichain/context'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import config from 'src/config'; import PopoverFilter from 'src/shared/filters/PopoverFilter'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import ColumnsButton from 'src/shared/lists/columns/ColumnsButton'; import Pagination from 'src/shared/pagination/Pagination'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { EmptyState } from 'src/toolkit/chakra/empty-state'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -48,12 +51,13 @@ const MultichainTokenTransfers = () => { const isLocalTab = tab === 'local' || !tab; - const queryLocal = useTokenTransfersQuery({ enabled: isLocalTab, isMultichain: true }); - const chainId = queryLocal.query.chainValue?.[0]; - const chainData = multichainConfig()?.chains.find(chain => chain.id === chainId); + const { chainValue, chain, onChainValueChange } = useChainValue(); + const queryLocal = useTokenTransfersQuery({ enabled: isLocalTab, chain }); + const columnsState = useTokenTransferColumns('index', { typeFilter: queryLocal.typeFilter, chainConfig: chain?.app_config }); + const chainId = chain?.id; const handleChainValueChange = React.useCallback(({ value }: { value: Array<string> }) => { - queryLocal.query.onChainValueChange({ value }); + onChainValueChange({ value }); const chainConfig = multichainConfig()?.chains.find(chain => chain.id === value[0]); const tokenTypes = getTokenFilterValue(router.query.type, chainConfig?.app_config); if (tokenTypes) { @@ -62,7 +66,7 @@ const MultichainTokenTransfers = () => { queryLocal.onTokenTypesChange(chainTokenTypes); } } - }, [ queryLocal, router.query.type ]); + }, [ onChainValueChange, queryLocal, router.query.type ]); const tabs: Array<TabItemRegular> = React.useMemo(() => { return [ @@ -80,12 +84,13 @@ const MultichainTokenTransfers = () => { query={ queryLocal.query } typeFilter={ queryLocal.typeFilter } onTokenTypesChange={ queryLocal.onTokenTypesChange } + columnsState={ columnsState } /> </MultichainProvider> ), }, ]; - }, [ queryLocal.query, queryLocal.typeFilter, queryLocal.onTokenTypesChange, chainId ]); + }, [ queryLocal.query, queryLocal.typeFilter, queryLocal.onTokenTypesChange, columnsState, chainId ]); const filter = isLocalTab && ( <PopoverFilter contentProps={{ w: '200px' }} appliedFiltersNum={ queryLocal.typeFilter.length }> @@ -93,7 +98,7 @@ const MultichainTokenTransfers = () => { onChange={ queryLocal.onTokenTypesChange } defaultValue={ queryLocal.typeFilter } category="all" - chainConfig={ chainData?.app_config } + chainConfig={ chain?.app_config } /> </PopoverFilter> ); @@ -101,8 +106,18 @@ const MultichainTokenTransfers = () => { const rightSlot = isLocalTab && ( <> { !isMobile && filter } + { !isMobile && ( + <ColumnsButton + tableColumns={ columnsState.selectableColumns } + columns={ columnsState.checkedColumns } + onChange={ columnsState.onColumnsChange } + onOrderChange={ columnsState.onColumnsReorder } + selected={ columnsState.isCustomized } + onReset={ columnsState.onColumnsReset } + /> + ) } <ChainSelect - value={ queryLocal.query.chainValue } + value={ chainValue } onValueChange={ handleChainValueChange } ml={ isMobile ? 'auto' : undefined } /> diff --git a/src/features/multichain/pages/token-transfers/MultichainTokenTransfersLocal.tsx b/src/features/multichain/pages/token-transfers/MultichainTokenTransfersLocal.tsx index 59d4a9a3f9c..c57cb43594b 100644 --- a/src/features/multichain/pages/token-transfers/MultichainTokenTransfersLocal.tsx +++ b/src/features/multichain/pages/token-transfers/MultichainTokenTransfersLocal.tsx @@ -1,55 +1,58 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; +import { HStack } from '@chakra-ui/react'; import React from 'react'; import type { TokenType } from 'src/slices/token/types/api'; import ActionBar from 'src/shell/page/action-bar/ActionBar'; -import TokenTransfersListItem from 'src/slices/token-transfer/pages/index/TokenTransfersListItem'; -import TokenTransfersTable from 'src/slices/token-transfer/pages/index/TokenTransfersTable'; -import { getTokenTransferKey } from 'src/slices/token-transfer/utils/get-token-transfer-key'; +import TokenTransfersTable from 'src/slices/token-transfer/components/table/TokenTransfersTable'; +import type { TokenTransferColumnsState } from 'src/slices/token-transfer/hooks/useTokenTransferColumns'; import TokenTypeFilter from 'src/slices/token/components/TokenTypeFilter'; import { useMultichainContext } from 'src/features/multichain/context'; import PopoverFilter from 'src/shared/filters/PopoverFilter'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import ColumnsButton from 'src/shared/lists/columns/ColumnsButton'; import DataList from 'src/shared/lists/DataList'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import Pagination from 'src/shared/pagination/Pagination'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; - -const ACTION_BAR_HEIGHT = 24 * 2 + 40; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; interface Props { - query: QueryWithPagesResult<'core:token_transfers_all'>; + query: ApiPaginatedQueryResult<'core:token_transfers_all'>; typeFilter: Array<TokenType>; onTokenTypesChange: (value: Array<TokenType>) => void; + columnsState: TokenTransferColumnsState; } -const MultichainTokenTransfersLocal = ({ query, typeFilter, onTokenTypesChange }: Props) => { +const MultichainTokenTransfersLocal = ({ query, typeFilter, onTokenTypesChange, columnsState }: Props) => { const isMobile = useIsMobile(); const multichainContext = useMultichainContext(); const chainData = multichainContext?.chain; - const { cutRef, renderedItemsNum } = useLazyRenderedList({ - list: query.data?.items, - isEnabled: !query.isPlaceholderData, - resetKey: query.queryHash, - }); const actionBar = isMobile && ( <ActionBar mt={ -6 }> - <PopoverFilter contentProps={{ w: '200px' }} appliedFiltersNum={ typeFilter.length }> - <TokenTypeFilter<TokenType> - onChange={ onTokenTypesChange } - defaultValue={ typeFilter } - category="all" - chainConfig={ chainData?.app_config } + <HStack gap={ 3 }> + <PopoverFilter contentProps={{ w: '200px' }} appliedFiltersNum={ typeFilter.length }> + <TokenTypeFilter<TokenType> + onChange={ onTokenTypesChange } + defaultValue={ typeFilter } + category="all" + chainConfig={ chainData?.app_config } + /> + </PopoverFilter> + <ColumnsButton + tableColumns={ columnsState.selectableColumns } + columns={ columnsState.checkedColumns } + onChange={ columnsState.onColumnsChange } + onOrderChange={ columnsState.onColumnsReorder } + selected={ columnsState.isCustomized } + onReset={ columnsState.onColumnsReset } /> - </PopoverFilter> + </HStack> <Pagination { ...query.pagination }/> </ActionBar> ); @@ -60,27 +63,16 @@ const MultichainTokenTransfersLocal = ({ query, typeFilter, onTokenTypesChange } itemsNum={ query.data?.items.length } emptyText="There are no token transfers." actionBar={ actionBar } + hasActiveFilters={ Boolean(typeFilter.length) } + isTransitioning={ query.isTransitioning } > - <Box hideFrom="lg"> - { query.data?.items.slice(0, renderedItemsNum).map((item, index) => ( - <TokenTransfersListItem - key={ getTokenTransferKey(item) + (query.isPlaceholderData ? index : '') + (chainData ? chainData.id : '') } - isLoading={ query.isPlaceholderData } - item={ item } - chainData={ chainData } - /> - )) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - <Box hideBelow="lg"> - <TokenTransfersTable - items={ query.data?.items } - top={ query.pagination.isVisible ? ACTION_BAR_HEIGHT : 0 } - isLoading={ query.isPlaceholderData } - chainData={ chainData } - resetKey={ query.queryHash } - /> - </Box> + <TokenTransfersTable + columns={ columnsState.columns } + items={ query.data?.items } + isLoading={ query.isInitialLoading } + resetKey={ query.queryHash } + enableTimeIncrement + /> </DataList> ); }; diff --git a/src/features/multichain/pages/token/MultichainToken.tsx b/src/features/multichain/pages/token/MultichainToken.tsx index 82d48d6e371..812c7f3b01a 100644 --- a/src/features/multichain/pages/token/MultichainToken.tsx +++ b/src/features/multichain/pages/token/MultichainToken.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import { SocketProvider } from 'src/api/socket/context'; @@ -12,6 +11,7 @@ import multichainConfig from 'src/features/multichain/chains-config'; import { MultichainProvider } from 'src/features/multichain/context'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; const MultichainToken = () => { const router = useRouter(); diff --git a/src/features/multichain/pages/tokens/MultichainTokens.tsx b/src/features/multichain/pages/tokens/MultichainTokens.tsx index 0ca63a30bf9..23c2ec625a1 100644 --- a/src/features/multichain/pages/tokens/MultichainTokens.tsx +++ b/src/features/multichain/pages/tokens/MultichainTokens.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { TokenType } from 'src/slices/token/types/api'; @@ -15,13 +14,14 @@ import { getTokenFilterValue } from 'src/slices/token/utils/list-utils'; import multichainConfig from 'src/features/multichain/chains-config'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import { TOKEN } from 'src/features/multichain/stubs'; import PopoverFilter from 'src/shared/filters/PopoverFilter'; -import useDebounce from 'src/shared/hooks/useDebounce'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; @@ -32,31 +32,18 @@ const getChainIdFilterValue = (chainIds: Array<string>) => { }; const MultichainTokens = () => { - const router = useRouter(); const isMobile = useIsMobile(); const chainConfigs = React.useMemo(() => { return multichainConfig()?.chains.map((chain) => chain.app_config); }, []); - const q = getQueryParamString(router.query.query); - const chainIdParam = getQueryParamString(router.query.chain_id); + const { chainValue: chainIds } = useChainValue({ withAllOption: true }); + const chainIdFilter = React.useMemo(() => getChainIdFilterValue(chainIds), [ chainIds ]); - const [ chainIds, setChainIds ] = React.useState<Array<string>>(chainIdParam ? [ chainIdParam ] : [ 'all' ]); - const [ searchTerm, setSearchTerm ] = React.useState<string>(q ?? ''); - const [ tokenTypes, setTokenTypes ] = React.useState<Array<TokenType> | undefined>( - getTokenFilterValue(router.query.type, chainConfigs), - ); - - const debouncedSearchTerm = useDebounce(searchTerm, 300); - - const tokensQuery = useQueryWithPages({ + const tokensQuery = useApiPaginatedQuery({ resourceName: 'multichainAggregator:tokens', - filters: { - type: tokenTypes?.join(','), - chain_id: getChainIdFilterValue(chainIds), - query: debouncedSearchTerm, - }, + queryParams: { chain_id: chainIdFilter }, options: { placeholderData: generateListStub<'multichainAggregator:tokens'>(TOKEN['token'], 50, { next_page_params: { @@ -68,32 +55,35 @@ const MultichainTokens = () => { }, }); + const searchTerm = getQueryParamString(tokensQuery.filters.query); + const typeParam = tokensQuery.filters.type; + const tokenTypes = React.useMemo(() => getTokenFilterValue(typeParam, chainConfigs), [ typeParam, chainConfigs ]); + + const { onFilterChange } = tokensQuery; + const handleTokenTypesChange = React.useCallback((value: Array<TokenType>) => { - tokensQuery.onFilterChange({ + onFilterChange({ type: value.join(','), - chain_id: getChainIdFilterValue(chainIds), - query: debouncedSearchTerm, + chain_id: chainIdFilter, + query: searchTerm, }); - setTokenTypes(value); - }, [ tokensQuery, chainIds, debouncedSearchTerm ]); + }, [ onFilterChange, chainIdFilter, searchTerm ]); - const handleSearchTermChange = React.useCallback((value: string) => { - tokensQuery.onFilterChange({ + const handleSearchTermChange = useDebouncedFilterChange((value) => { + onFilterChange({ type: tokenTypes?.join(','), - chain_id: getChainIdFilterValue(chainIds), + chain_id: chainIdFilter, query: value, }); - setSearchTerm(value); - }, [ tokenTypes, tokensQuery, chainIds ]); + }); const handleChainIdsChange = React.useCallback(({ value }: { value: Array<string> }) => { - tokensQuery.onFilterChange({ + onFilterChange({ chain_id: getChainIdFilterValue(value), type: tokenTypes?.join(','), - query: debouncedSearchTerm, + query: searchTerm, }); - setChainIds(value); - }, [ tokensQuery, tokenTypes, debouncedSearchTerm ]); + }, [ onFilterChange, tokenTypes, searchTerm ]); const filter = ( <PopoverFilter contentProps={{ w: '200px' }} appliedFiltersNum={ tokenTypes?.length }> diff --git a/src/features/multichain/pages/tx/MultichainTx.tsx b/src/features/multichain/pages/tx/MultichainTx.tsx index 286671ec83b..d0d3bcc258f 100644 --- a/src/features/multichain/pages/tx/MultichainTx.tsx +++ b/src/features/multichain/pages/tx/MultichainTx.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import Transaction from 'src/slices/tx/pages/details/Transaction'; @@ -9,6 +8,7 @@ import multichainConfig from 'src/features/multichain/chains-config'; import { MultichainProvider } from 'src/features/multichain/context'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; const MultichainTx = () => { const router = useRouter(); diff --git a/src/features/multichain/pages/txs/MultichainTxs.tsx b/src/features/multichain/pages/txs/MultichainTxs.tsx index cd86a290a4f..ddac54fc979 100644 --- a/src/features/multichain/pages/txs/MultichainTxs.tsx +++ b/src/features/multichain/pages/txs/MultichainTxs.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -14,6 +13,7 @@ import useRoutedChainSelect from 'src/features/multichain/hooks/useRoutedChainSe import config from 'src/config'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { EmptyState } from 'src/toolkit/chakra/empty-state'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; diff --git a/src/features/multichain/pages/user-ops/MultichainUserOps.tsx b/src/features/multichain/pages/user-ops/MultichainUserOps.tsx index 4a4f67eda07..e228049ae22 100644 --- a/src/features/multichain/pages/user-ops/MultichainUserOps.tsx +++ b/src/features/multichain/pages/user-ops/MultichainUserOps.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; @@ -9,21 +8,24 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import multichainConfig from 'src/features/multichain/chains-config'; import ChainSelect from 'src/features/multichain/components/ChainSelect'; import { MultichainProvider } from 'src/features/multichain/context'; -import UserOpsList from 'src/features/user-ops/pages/index/UserOpsList'; +import { useChainValue } from 'src/features/multichain/hooks/useChainValue'; import UserOpsTable from 'src/features/user-ops/pages/index/UserOpsTable'; import { USER_OPS_ITEM } from 'src/features/user-ops/stubs'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + const MultichainUserOps = () => { const chains = React.useMemo(() => (multichainConfig()?.chains || []).filter(chain => chain.app_config.features.userOps.isEnabled), []); const chainIds = React.useMemo(() => chains.map(chain => chain.id).filter(Boolean), [ chains ]); + const { chainValue, chain, onChainValueChange } = useChainValue({ chainIds }); - const query = useQueryWithPages({ + const query = useApiPaginatedQuery({ resourceName: 'core:user_ops', options: { placeholderData: generateListStub<'core:user_ops'>(USER_OPS_ITEM, 50, { next_page_params: { @@ -31,42 +33,29 @@ const MultichainUserOps = () => { page_size: 50, } }), }, - isMultichain: true, - chainIds, + chain, }); - const chainConfig = chains.find(chain => chain.id === query.chainValue?.[0]); - const content = query.data?.items ? ( - <MultichainProvider chainId={ query.chainValue?.[0] }> - <Box hideBelow="lg"> + <MultichainProvider chainId={ chain?.id }> + <TableContainerScrollable> <UserOpsTable items={ query.data.items } top={ query.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ query.isPlaceholderData } - showTx - showSender - resetKey={ query.queryHash } - /> - </Box> - <Box hideFrom="lg"> - <UserOpsList - items={ query.data.items } - isLoading={ query.isPlaceholderData } + isLoading={ query.isInitialLoading } showTx showSender - chainData={ chainConfig } resetKey={ query.queryHash } /> - </Box> + </TableContainerScrollable> </MultichainProvider> ) : null; const actionBar = ( <ActionBar mt={ -6 }> <ChainSelect - value={ query.chainValue } - onValueChange={ query.onChainValueChange } + value={ chainValue } + onValueChange={ onChainValueChange } chainIds={ chainIds } /> <Pagination ml="auto" { ...query.pagination }/> @@ -86,6 +75,7 @@ const MultichainUserOps = () => { actionBar={ actionBar } showActionBarIfError showActionBarIfEmpty + isTransitioning={ query.isTransitioning } > { content } </DataList> diff --git a/src/features/multichain/stubs.ts b/src/features/multichain/stubs.ts index ff18f4ee7cf..b58d6410c39 100644 --- a/src/features/multichain/stubs.ts +++ b/src/features/multichain/stubs.ts @@ -45,6 +45,9 @@ export const TOKEN: AddressTokenItem = { type: 'ERC-20' as const, exchange_rate: '123.456', reputation: null, + ui_multiplier: null, + new_ui_multiplier: null, + ui_multiplier_effective_at: null, chain_infos: { '11155111': { holders_count: '141268', diff --git a/src/features/multichain/types/client.ts b/src/features/multichain/types/client.ts index 8d973eea4a5..6cce8f6a90d 100644 --- a/src/features/multichain/types/client.ts +++ b/src/features/multichain/types/client.ts @@ -30,6 +30,9 @@ export interface AggregatedTokenInfo extends Pick<multichain.AggregatedTokenInfo exchange_rate: string | null; icon_url: string | null; reputation: null; + ui_multiplier: string | null; + new_ui_multiplier: string | null; + ui_multiplier_effective_at: string | null; } export interface AddressTokenItem extends diff --git a/src/features/multichain/utils/get-chain-value-from-query.ts b/src/features/multichain/utils/get-chain-value-from-query.ts index 294219c9878..2e356e7bf0d 100644 --- a/src/features/multichain/utils/get-chain-value-from-query.ts +++ b/src/features/multichain/utils/get-chain-value-from-query.ts @@ -1,10 +1,9 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { Router } from 'next/router'; - import multichainConfig from 'src/features/multichain/chains-config'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import type { Router } from 'src/shared/router/useRouter'; export default function getChainValueFromQuery( query: Router['query'], diff --git a/src/features/name-services/clusters/components/ClustersEntity.tsx b/src/features/name-services/clusters/components/ClustersEntity.tsx index 6cd5e7c686e..dfbb986e07e 100644 --- a/src/features/name-services/clusters/components/ClustersEntity.tsx +++ b/src/features/name-services/clusters/components/ClustersEntity.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, chakra, Flex, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import config from 'src/config'; import * as EntityBase from 'src/shared/entities/components'; import { distributeEntityProps, getIconProps } from 'src/shared/entities/utils'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Image } from 'src/toolkit/chakra/image'; diff --git a/src/features/name-services/clusters/components/SearchBarSuggestCluster.tsx b/src/features/name-services/clusters/components/SearchBarSuggestCluster.tsx index 15e08d466db..25ea0e3fc11 100644 --- a/src/features/name-services/clusters/components/SearchBarSuggestCluster.tsx +++ b/src/features/name-services/clusters/components/SearchBarSuggestCluster.tsx @@ -9,9 +9,10 @@ import type { ItemsProps } from 'src/slices/search/components/search-bar/SearchB import { toBech32Address } from 'src/slices/address/utils/bech32'; import { isEvmAddress } from 'src/slices/address/utils/is-evm-address'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import highlightText from 'src/shared/texts/highlight-text'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; + import ClusterIcon from './ClusterIcon'; const SearchBarSuggestCluster = ({ data, searchTerm, addressFormat }: ItemsProps<SearchResultCluster>) => { @@ -45,7 +46,7 @@ const SearchBarSuggestCluster = ({ data, searchTerm, addressFormat }: ItemsProps whiteSpace="nowrap" color="text.secondary" > - <HashStringShortenDynamic hash={ hash } noTooltip/> + <Truncate value={ hash } tooltip={ false }/> </Text> ); diff --git a/src/features/name-services/clusters/components/__screenshots__/ClustersEntity.pw.tsx_default_customization-no-icon-1.png b/src/features/name-services/clusters/components/__screenshots__/ClustersEntity.pw.tsx_default_customization-no-icon-1.png index 76bdb675a1b..a26f678b774 100644 Binary files a/src/features/name-services/clusters/components/__screenshots__/ClustersEntity.pw.tsx_default_customization-no-icon-1.png and b/src/features/name-services/clusters/components/__screenshots__/ClustersEntity.pw.tsx_default_customization-no-icon-1.png differ diff --git a/src/features/name-services/clusters/hooks/useClusterPagination.spec.ts b/src/features/name-services/clusters/hooks/useClusterPagination.spec.ts index a3a2479bb6a..d76e164d005 100644 --- a/src/features/name-services/clusters/hooks/useClusterPagination.spec.ts +++ b/src/features/name-services/clusters/hooks/useClusterPagination.spec.ts @@ -1,23 +1,18 @@ // @vitest-environment jsdom -import { useRouter } from 'next/router'; - import getQueryParamString from 'src/shared/router/get-query-param-string'; import { useQueryParams } from 'src/shared/router/useQueryParams'; import type { Mock } from 'vitest'; -import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { renderHook, act } from 'vitest/lib'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { renderHook, act, cleanup } from 'vitest/lib'; +import { routerStandIn } from 'vitest/utils/routerStandIn'; import { useClusterPagination } from './useClusterPagination'; -vi.mock('next/router', () => ({ - useRouter: vi.fn(), -})); vi.mock('src/shared/router/useQueryParams'); vi.mock('src/shared/router/get-query-param-string'); -const mockUseRouter = useRouter as Mock<typeof useRouter>; const mockUseQueryParams = useQueryParams as Mock<typeof useQueryParams>; const mockGetQueryParamString = getQueryParamString as Mock<typeof getQueryParamString>; @@ -26,19 +21,19 @@ describe('useClusterPagination', () => { beforeEach(() => { vi.clearAllMocks(); - mockUseRouter.mockReturnValue({ - query: {}, - } as unknown as ReturnType<typeof useRouter>); + routerStandIn.reset({ pathname: '/name-domains', query: {} }); mockUseQueryParams.mockReturnValue({ updateQuery: mockUpdateQuery, }); }); + afterEach(cleanup); + describe('page calculation', () => { it('should default to page 1 when no page param', () => { mockGetQueryParamString.mockReturnValue(''); - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); expect(result.current.page).toBe(1); expect(result.current.pagination.page).toBe(1); @@ -47,7 +42,7 @@ describe('useClusterPagination', () => { it('should parse page from query param', () => { mockGetQueryParamString.mockReturnValue('3'); - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); expect(result.current.page).toBe(3); expect(result.current.pagination.page).toBe(3); @@ -56,7 +51,7 @@ describe('useClusterPagination', () => { it('should handle invalid page param gracefully', () => { mockGetQueryParamString.mockReturnValue('invalid'); - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); expect(result.current.page).toBeNaN(); }); @@ -68,7 +63,7 @@ describe('useClusterPagination', () => { }); it('should increment page on next click', () => { - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); act(() => { result.current.pagination.onNextPageClick(); @@ -78,7 +73,7 @@ describe('useClusterPagination', () => { }); it('should decrement page on prev click', () => { - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); act(() => { result.current.pagination.onPrevPageClick(); @@ -89,7 +84,7 @@ describe('useClusterPagination', () => { it('should handle prev click from page 3', () => { mockGetQueryParamString.mockReturnValue('3'); - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); act(() => { result.current.pagination.onPrevPageClick(); @@ -99,7 +94,7 @@ describe('useClusterPagination', () => { }); it('should reset page to undefined', () => { - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); act(() => { result.current.pagination.resetPage(); @@ -113,7 +108,7 @@ describe('useClusterPagination', () => { it('should set hasPages true when page > 1', () => { mockGetQueryParamString.mockReturnValue('2'); - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); expect(result.current.pagination.hasPages).toBe(true); }); @@ -121,7 +116,7 @@ describe('useClusterPagination', () => { it('should set hasPages false when page = 1', () => { mockGetQueryParamString.mockReturnValue('1'); - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); expect(result.current.pagination.hasPages).toBe(false); }); @@ -129,7 +124,7 @@ describe('useClusterPagination', () => { it('should set canGoBackwards true when page > 1', () => { mockGetQueryParamString.mockReturnValue('2'); - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); expect(result.current.pagination.canGoBackwards).toBe(true); }); @@ -137,7 +132,7 @@ describe('useClusterPagination', () => { it('should set canGoBackwards false when page = 1', () => { mockGetQueryParamString.mockReturnValue('1'); - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); expect(result.current.pagination.canGoBackwards).toBe(false); }); @@ -171,7 +166,7 @@ describe('useClusterPagination', () => { it('should be visible when hasNextPage is true', () => { mockGetQueryParamString.mockReturnValue('1'); - const { result } = renderHook(() => useClusterPagination(true, false)); + const { result } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); expect(result.current.pagination.isVisible).toBe(true); }); @@ -189,7 +184,7 @@ describe('useClusterPagination', () => { it('should not recreate functions when dependencies do not change', () => { mockGetQueryParamString.mockReturnValue('2'); - const { result, rerender } = renderHook(() => useClusterPagination(true, false)); + const { result, rerender } = renderHook(() => useClusterPagination(true, false), { wrapper: routerStandIn.wrapper }); const firstOnNext = result.current.pagination.onNextPageClick; const firstOnPrev = result.current.pagination.onPrevPageClick; diff --git a/src/features/name-services/clusters/hooks/useClusterPagination.ts b/src/features/name-services/clusters/hooks/useClusterPagination.ts index 34e88ba04de..a134492a7e2 100644 --- a/src/features/name-services/clusters/hooks/useClusterPagination.ts +++ b/src/features/name-services/clusters/hooks/useClusterPagination.ts @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import { useCallback, useMemo } from 'react'; import type { PaginationParams } from 'src/shared/pagination/types'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { useQueryParams } from 'src/shared/router/useQueryParams'; +import { useRouter } from 'src/shared/router/useRouter'; export function useClusterPagination(hasNextPage: boolean, isLoading: boolean) { const router = useRouter(); diff --git a/src/features/name-services/clusters/hooks/useClusterSearch.spec.ts b/src/features/name-services/clusters/hooks/useClusterSearch.spec.ts index e939043ce92..e9a7608aec6 100644 --- a/src/features/name-services/clusters/hooks/useClusterSearch.spec.ts +++ b/src/features/name-services/clusters/hooks/useClusterSearch.spec.ts @@ -1,50 +1,34 @@ // @vitest-environment jsdom -import { useRouter } from 'next/router'; - -import type { Mock } from 'vitest'; -import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { renderHook } from 'vitest/lib'; +import { describe, it, expect, afterEach } from 'vitest'; +import { renderHook, cleanup } from 'vitest/lib'; +import { routerStandIn } from 'vitest/utils/routerStandIn'; import { useClusterSearch } from './useClusterSearch'; -vi.mock('next/router', () => ({ - useRouter: vi.fn(), -})); - -const mockUseRouter = useRouter as Mock<typeof useRouter>; - describe('useClusterSearch', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); + afterEach(cleanup); - it('should return search term from router query', async() => { - mockUseRouter.mockReturnValue({ - query: { q: 'test-search' }, - } as unknown as ReturnType<typeof useRouter>); + it('should return search term from router query', () => { + routerStandIn.reset({ pathname: '/name-domains', query: { q: 'test-search' } }); - const { result } = await renderHook(() => useClusterSearch()); + const { result } = renderHook(() => useClusterSearch(), { wrapper: routerStandIn.wrapper }); expect(result.current.searchTerm).toBe('test-search'); }); - it('should debounce search term', async() => { - mockUseRouter.mockReturnValue({ - query: { q: 'test' }, - } as unknown as ReturnType<typeof useRouter>); + it('should debounce search term', () => { + routerStandIn.reset({ pathname: '/name-domains', query: { q: 'test' } }); - const { result } = await renderHook(() => useClusterSearch()); + const { result } = renderHook(() => useClusterSearch(), { wrapper: routerStandIn.wrapper }); expect(result.current.debouncedSearchTerm).toBe('test'); }); - it('should handle empty query', async() => { - mockUseRouter.mockReturnValue({ - query: {}, - } as unknown as ReturnType<typeof useRouter>); + it('should handle empty query', () => { + routerStandIn.reset({ pathname: '/name-domains', query: {} }); - const { result } = await renderHook(() => useClusterSearch()); + const { result } = renderHook(() => useClusterSearch(), { wrapper: routerStandIn.wrapper }); expect(result.current.searchTerm).toBe(''); expect(result.current.debouncedSearchTerm).toBe(''); diff --git a/src/features/name-services/clusters/hooks/useClusterSearch.ts b/src/features/name-services/clusters/hooks/useClusterSearch.ts index 812ab5d9075..90e34880510 100644 --- a/src/features/name-services/clusters/hooks/useClusterSearch.ts +++ b/src/features/name-services/clusters/hooks/useClusterSearch.ts @@ -1,9 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; - import useDebounce from 'src/shared/hooks/useDebounce'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; export function useClusterSearch() { const router = useRouter(); diff --git a/src/features/name-services/clusters/pages/address/AddressClusters.tsx b/src/features/name-services/clusters/pages/address/AddressClusters.tsx index 58f96e799f4..33b0c6e5904 100644 --- a/src/features/name-services/clusters/pages/address/AddressClusters.tsx +++ b/src/features/name-services/clusters/pages/address/AddressClusters.tsx @@ -2,7 +2,6 @@ import { Grid, chakra } from '@chakra-ui/react'; import type { UseQueryResult } from '@tanstack/react-query'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { ClustersByAddressResponse } from 'src/features/name-services/clusters/types/api'; @@ -19,6 +18,7 @@ import { hasMoreClusters, } from 'src/features/name-services/clusters/utils/clusters-utils'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; diff --git a/src/features/name-services/clusters/pages/details/Cluster.pw.tsx b/src/features/name-services/clusters/pages/details/Cluster.pw.tsx index 79856efb1f9..d7b29d4c91f 100644 --- a/src/features/name-services/clusters/pages/details/Cluster.pw.tsx +++ b/src/features/name-services/clusters/pages/details/Cluster.pw.tsx @@ -39,7 +39,6 @@ test.describe('Cluster Details Page', () => { hooksConfig: { router: { query: { name: 'campnetwork/lol' }, - isReady: true, }, }, }, @@ -68,7 +67,6 @@ test.describe('Cluster Details Page', () => { hooksConfig: { router: { query: { name: 'test/cluster' }, - isReady: true, }, }, }, diff --git a/src/features/name-services/clusters/pages/details/Cluster.tsx b/src/features/name-services/clusters/pages/details/Cluster.tsx index a263c74880c..4eaf1f0feba 100644 --- a/src/features/name-services/clusters/pages/details/Cluster.tsx +++ b/src/features/name-services/clusters/pages/details/Cluster.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -11,6 +10,7 @@ import TextAd from 'src/features/ads/text/components/TextAd'; import ClusterDetails from 'src/features/name-services/clusters/pages/details/ClusterDetails'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; const Cluster = () => { const router = useRouter(); diff --git a/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_default_Cluster-Details-Page-mainnet-cluster-details-mobile-1.png b/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_default_Cluster-Details-Page-mainnet-cluster-details-mobile-1.png index 6786f75c1b4..0c7b06de5b3 100644 Binary files a/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_default_Cluster-Details-Page-mainnet-cluster-details-mobile-1.png and b/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_default_Cluster-Details-Page-mainnet-cluster-details-mobile-1.png differ diff --git a/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_default_Cluster-Details-Page-testnet-cluster-details-mobile-1.png b/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_default_Cluster-Details-Page-testnet-cluster-details-mobile-1.png index e7c1d4e4cdf..098a465508c 100644 Binary files a/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_default_Cluster-Details-Page-testnet-cluster-details-mobile-1.png and b/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_default_Cluster-Details-Page-testnet-cluster-details-mobile-1.png differ diff --git a/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_mobile_Cluster-Details-Page-mainnet-cluster-details-mobile-1.png b/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_mobile_Cluster-Details-Page-mainnet-cluster-details-mobile-1.png index da9979c2ad2..f3f0d63bca8 100644 Binary files a/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_mobile_Cluster-Details-Page-mainnet-cluster-details-mobile-1.png and b/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_mobile_Cluster-Details-Page-mainnet-cluster-details-mobile-1.png differ diff --git a/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_mobile_Cluster-Details-Page-testnet-cluster-details-mobile-1.png b/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_mobile_Cluster-Details-Page-testnet-cluster-details-mobile-1.png index 76a022fce7b..acf6c20419a 100644 Binary files a/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_mobile_Cluster-Details-Page-testnet-cluster-details-mobile-1.png and b/src/features/name-services/clusters/pages/details/__screenshots__/Cluster.pw.tsx_mobile_Cluster-Details-Page-testnet-cluster-details-mobile-1.png differ diff --git a/src/features/name-services/clusters/pages/index/Clusters.tsx b/src/features/name-services/clusters/pages/index/Clusters.tsx index f7b90285ead..cee1ec2ce33 100644 --- a/src/features/name-services/clusters/pages/index/Clusters.tsx +++ b/src/features/name-services/clusters/pages/index/Clusters.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; +import { Text } from '@chakra-ui/react'; import React, { useCallback } from 'react'; import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; @@ -23,13 +22,13 @@ import type { ViewMode } from 'src/features/name-services/clusters/utils/page-ut import DataList from 'src/shared/lists/DataList'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { useQueryParams } from 'src/shared/router/useQueryParams'; +import { useRouter } from 'src/shared/router/useRouter'; import { Link } from 'src/toolkit/chakra/link'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import ClustersActionBar from './ClustersActionBar'; -import ClustersDirectoryList from './ClustersDirectoryList'; import ClustersDirectoryTable from './ClustersDirectoryTable'; -import ClustersLeaderboardList from './ClustersLeaderboardList'; import ClustersLeaderboardTable from './ClustersLeaderboardTable'; const Clusters = () => { @@ -91,42 +90,24 @@ const Clusters = () => { const resetKey = `${ viewMode }:${ debouncedSearchTerm }:${ page }`; const content = ( - <> - <Box hideFrom="lg"> - { showDirectoryView ? ( - <ClustersDirectoryList - data={ directoryData } - isLoading={ isLoading } - isClusterDetailsLoading={ isClusterDetailsLoading && inputType === 'address' } - resetKey={ resetKey } - /> - ) : ( - <ClustersLeaderboardList - data={ leaderboardData } - isLoading={ isLoading } - resetKey={ resetKey } - /> - ) } - </Box> - <Box hideBelow="lg"> - { showDirectoryView ? ( - <ClustersDirectoryTable - data={ directoryData } - isLoading={ isLoading } - isClusterDetailsLoading={ isClusterDetailsLoading && inputType === 'address' } - top={ ACTION_BAR_HEIGHT_DESKTOP } - resetKey={ resetKey } - /> - ) : ( - <ClustersLeaderboardTable - data={ leaderboardData } - isLoading={ isLoading } - top={ ACTION_BAR_HEIGHT_DESKTOP } - resetKey={ resetKey } - /> - ) } - </Box> - </> + <TableContainerScrollable> + { showDirectoryView ? ( + <ClustersDirectoryTable + data={ directoryData } + isLoading={ isLoading } + isClusterDetailsLoading={ isClusterDetailsLoading && inputType === 'address' } + top={ ACTION_BAR_HEIGHT_DESKTOP } + resetKey={ resetKey } + /> + ) : ( + <ClustersLeaderboardTable + data={ leaderboardData } + isLoading={ isLoading } + top={ ACTION_BAR_HEIGHT_DESKTOP } + resetKey={ resetKey } + /> + ) } + </TableContainerScrollable> ); const actionBar = ( diff --git a/src/features/name-services/clusters/pages/index/ClustersDirectoryList.tsx b/src/features/name-services/clusters/pages/index/ClustersDirectoryList.tsx deleted file mode 100644 index 824e685ec08..00000000000 --- a/src/features/name-services/clusters/pages/index/ClustersDirectoryList.tsx +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { ClustersDirectoryObject } from 'src/features/name-services/clusters/types/api'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ClustersDirectoryListItem from './ClustersDirectoryListItem'; - -interface Props { - data: Array<ClustersDirectoryObject>; - isLoading?: boolean; - isClusterDetailsLoading?: boolean; - resetKey?: string; -} - -const ClustersDirectoryList = ({ data, isLoading, isClusterDetailsLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <ClustersDirectoryListItem - key={ `${ item.name }-${ index }${ isLoading ? '-loading' : '' }` } - item={ item } - isLoading={ isLoading } - isClusterDetailsLoading={ isClusterDetailsLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(ClustersDirectoryList); diff --git a/src/features/name-services/clusters/pages/index/ClustersDirectoryListItem.tsx b/src/features/name-services/clusters/pages/index/ClustersDirectoryListItem.tsx deleted file mode 100644 index dbfdbecef71..00000000000 --- a/src/features/name-services/clusters/pages/index/ClustersDirectoryListItem.tsx +++ /dev/null @@ -1,71 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { ClustersDirectoryObject } from 'src/features/name-services/clusters/types/api'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import { isEvmAddress } from 'src/slices/address/utils/is-evm-address'; - -import ClustersEntity from 'src/features/name-services/clusters/components/ClustersEntity'; - -import dayjs from 'src/shared/date-and-time/dayjs'; -import Time from 'src/shared/date-and-time/Time'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - item: ClustersDirectoryObject; - isLoading?: boolean; - isClusterDetailsLoading?: boolean; -} - -const ClustersDirectoryListItem = ({ item, isLoading, isClusterDetailsLoading }: Props) => { - return ( - <ListItemMobileGrid.Container> - <ListItemMobileGrid.Label isLoading={ isLoading }> - Cluster name - </ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <ClustersEntity clusterName={ item.name } isLoading={ isLoading } fontWeight={ 500 }/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }> - Address - </ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { item.owner && ( - <AddressEntity - address={{ hash: item.owner }} - isLoading={ isLoading } - fontWeight={ 500 } - noLink={ !isEvmAddress(item.owner) } - /> - ) } - { !item.owner && <Skeleton loading={ isLoading }>—</Skeleton> } - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }> - Joined - </ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - <Time timestamp={ item.createdAt } display="block"/> - <div> { dayjs(item.createdAt).fromNow() }</div> - </Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }> - Active chains - </ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading || isClusterDetailsLoading }> - { (item.chainIds?.length || 1) } { (item.chainIds?.length || 1) === 1 ? 'chain' : 'chains' } - </Skeleton> - </ListItemMobileGrid.Value> - </ListItemMobileGrid.Container> - ); -}; - -export default React.memo(ClustersDirectoryListItem); diff --git a/src/features/name-services/clusters/pages/index/ClustersDirectoryTable.tsx b/src/features/name-services/clusters/pages/index/ClustersDirectoryTable.tsx index 5a06d3fb76a..79e29b9b486 100644 --- a/src/features/name-services/clusters/pages/index/ClustersDirectoryTable.tsx +++ b/src/features/name-services/clusters/pages/index/ClustersDirectoryTable.tsx @@ -26,7 +26,7 @@ const ClustersDirectoryTable = ({ data, isLoading, top, isClusterDetailsLoading, return ( <AddressHighlightProvider> - <TableRoot> + <TableRoot minW="900px"> <TableHeaderSticky top={ top }> <TableRow> <TableColumnHeader width="40%">Cluster name</TableColumnHeader> diff --git a/src/features/name-services/clusters/pages/index/ClustersLeaderboardList.tsx b/src/features/name-services/clusters/pages/index/ClustersLeaderboardList.tsx deleted file mode 100644 index cc8137b7ebe..00000000000 --- a/src/features/name-services/clusters/pages/index/ClustersLeaderboardList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { ClustersLeaderboardObject } from 'src/features/name-services/clusters/types/api'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ClustersLeaderboardListItem from './ClustersLeaderboardListItem'; - -interface Props { - data: Array<ClustersLeaderboardObject>; - isLoading?: boolean; - resetKey?: string; -} - -const ClustersLeaderboardList = ({ data, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <ClustersLeaderboardListItem - key={ `${ item.name }-${ index }${ isLoading ? '-loading' : '' }` } - item={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(ClustersLeaderboardList); diff --git a/src/features/name-services/clusters/pages/index/ClustersLeaderboardListItem.tsx b/src/features/name-services/clusters/pages/index/ClustersLeaderboardListItem.tsx deleted file mode 100644 index 9f471d25ec8..00000000000 --- a/src/features/name-services/clusters/pages/index/ClustersLeaderboardListItem.tsx +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { ClustersLeaderboardObject } from 'src/features/name-services/clusters/types/api'; - -import ClustersEntity from 'src/features/name-services/clusters/components/ClustersEntity'; - -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - item: ClustersLeaderboardObject; - isLoading?: boolean; -} - -const ClustersLeaderboardListItem = ({ item, isLoading }: Props) => { - return ( - <ListItemMobileGrid.Container> - <ListItemMobileGrid.Label isLoading={ isLoading }> - Rank - </ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - #{ item.rank } - </Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }> - Cluster name - </ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <ClustersEntity clusterName={ item.name } isLoading={ isLoading } fontWeight={ 500 }/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }> - Names - </ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - { item.nameCount } - </Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }> - Backing - </ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - { (parseFloat(item.totalWeiAmount) / 1e18).toFixed(2) } ETH - </Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }> - Network presence - </ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - { item.chainIds.length } { item.chainIds.length === 1 ? 'chain' : 'chains' } - </Skeleton> - </ListItemMobileGrid.Value> - </ListItemMobileGrid.Container> - ); -}; - -export default React.memo(ClustersLeaderboardListItem); diff --git a/src/features/name-services/clusters/pages/index/ClustersLeaderboardTable.tsx b/src/features/name-services/clusters/pages/index/ClustersLeaderboardTable.tsx index 8ae84cd5f24..3bea8530d37 100644 --- a/src/features/name-services/clusters/pages/index/ClustersLeaderboardTable.tsx +++ b/src/features/name-services/clusters/pages/index/ClustersLeaderboardTable.tsx @@ -21,14 +21,14 @@ const ClustersLeaderboardTable = ({ data, isLoading, top, resetKey }: Props) => const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); return ( - <TableRoot> + <TableRoot minW="800px"> <TableHeaderSticky top={ top }> <TableRow> - <TableColumnHeader width="5%">Rank</TableColumnHeader> - <TableColumnHeader width="40%">Cluster name</TableColumnHeader> - <TableColumnHeader width="10%">Names</TableColumnHeader> - <TableColumnHeader width="10%">Total backing</TableColumnHeader> - <TableColumnHeader width="10%">Active chains</TableColumnHeader> + <TableColumnHeader width="60px">Rank</TableColumnHeader> + <TableColumnHeader width="50%">Cluster name</TableColumnHeader> + <TableColumnHeader width="15%">Names</TableColumnHeader> + <TableColumnHeader width="15%">Total backing</TableColumnHeader> + <TableColumnHeader width="15%">Active chains</TableColumnHeader> </TableRow> </TableHeaderSticky> <TableBody> diff --git a/src/features/name-services/common/pages/NameServices.pw.tsx b/src/features/name-services/common/pages/NameServices.pw.tsx index b9489a44359..12d868d3f0b 100644 --- a/src/features/name-services/common/pages/NameServices.pw.tsx +++ b/src/features/name-services/common/pages/NameServices.pw.tsx @@ -5,7 +5,7 @@ import { clustersLeaderboardMock } from 'src/features/name-services/clusters/moc import * as ensDomainMock from 'src/features/name-services/domains/mocks/domain'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; -import { test, expect, devices } from 'playwright/lib'; +import { test, expect } from 'playwright/lib'; import NameServices from './NameServices'; @@ -50,15 +50,6 @@ test.describe('domains', () => { await expect(component).toHaveScreenshot({ timeout: 10_000 }); }); - test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - - test('default view', async({ render }) => { - const component = await render(<NameServices/>, { hooksConfig }); - await expect(component).toHaveScreenshot({ timeout: 10_000 }); - }); - }); - test('filters', async({ render, page }) => { const component = await render(<NameServices/>, { hooksConfig }); @@ -75,13 +66,11 @@ test.describe('directories', () => { directories: { router: { query: { tab: 'directories', view: 'directory' }, - isReady: true, }, }, leaderboard: { router: { query: { tab: 'directories', view: 'leaderboard' }, - isReady: true, }, }, }; @@ -125,18 +114,4 @@ test.describe('directories', () => { const component = await render(<NameServices/>, { hooksConfig: hooksConfig.leaderboard }); await expect(component).toHaveScreenshot(); }); - - test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - - test('directory view', async({ render }) => { - const component = await render(<NameServices/>, { hooksConfig: hooksConfig.directories }); - await expect(component).toHaveScreenshot(); - }); - - test('leaderboard view', async({ render }) => { - const component = await render(<NameServices/>, { hooksConfig: hooksConfig.leaderboard }); - await expect(component).toHaveScreenshot(); - }); - }); }); diff --git a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-directory-view-1.png b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-directory-view-1.png index b1142c53a92..19487405a29 100644 Binary files a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-directory-view-1.png and b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-directory-view-1.png differ diff --git a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-leaderboard-view-1.png b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-leaderboard-view-1.png index 87488a035f6..6b7280eb62d 100644 Binary files a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-leaderboard-view-1.png and b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-leaderboard-view-1.png differ diff --git a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-mobile-directory-view-1.png b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-mobile-directory-view-1.png deleted file mode 100644 index 5b38481c99b..00000000000 Binary files a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-mobile-directory-view-1.png and /dev/null differ diff --git a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-mobile-leaderboard-view-1.png b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-mobile-leaderboard-view-1.png deleted file mode 100644 index 160a7ebfe11..00000000000 Binary files a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_directories-mobile-leaderboard-view-1.png and /dev/null differ diff --git a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-default-view-1.png b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-default-view-1.png index 9a1b572a4ac..33243fa0e57 100644 Binary files a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-default-view-1.png and b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-default-view-1.png differ diff --git a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-filters-1.png b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-filters-1.png index dbcda4bf79a..1a987e5270d 100644 Binary files a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-filters-1.png and b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-filters-1.png differ diff --git a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-mobile-default-view-1.png b/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-mobile-default-view-1.png deleted file mode 100644 index 191ab012129..00000000000 Binary files a/src/features/name-services/common/pages/__screenshots__/NameServices.pw.tsx_default_domains-mobile-default-view-1.png and /dev/null differ diff --git a/src/features/name-services/domains/components/EnsEntity.pw.tsx b/src/features/name-services/domains/components/EnsEntity.pw.tsx index b4f6c02de2e..269205597ad 100644 --- a/src/features/name-services/domains/components/EnsEntity.pw.tsx +++ b/src/features/name-services/domains/components/EnsEntity.pw.tsx @@ -81,7 +81,16 @@ test.describe('tooltip test', () => { />, ); - await component.getByAltText(`${ domainMock.protocolA.title } protocol icon`).first().hover(); + const protocolIcon = component.getByAltText(`${ domainMock.protocolA.title } protocol icon`).first(); + await protocolIcon.hover(); + + // The first hover mounts the lazy tooltip, which remounts the icon and briefly swaps it with a skeleton. + // With a still cursor the browser may leave the hover state on the removed skeleton, so the tooltip + // never opens; re-entering the settled icon opens it through a regular pointer event. + await expect(protocolIcon).toHaveAttribute('data-part', 'trigger'); + await expect(protocolIcon).toBeVisible(); + await page.mouse.move(599, 399); + await protocolIcon.hover(); await expect(page.getByText(domainMock.protocolA.description)).toBeVisible(); await expect(page).toHaveScreenshot(); diff --git a/src/features/name-services/domains/components/EnsEntity.tsx b/src/features/name-services/domains/components/EnsEntity.tsx index bb38d0831de..1c0ef4c5011 100644 --- a/src/features/name-services/domains/components/EnsEntity.tsx +++ b/src/features/name-services/domains/components/EnsEntity.tsx @@ -1,13 +1,13 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, Flex, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type * as bens from '@blockscout/bens-types'; import * as EntityBase from 'src/shared/entities/components'; import { distributeEntityProps, getIconProps } from 'src/shared/entities/utils'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Image } from 'src/toolkit/chakra/image'; diff --git a/src/features/name-services/domains/components/SearchBarSuggestDomain.tsx b/src/features/name-services/domains/components/SearchBarSuggestDomain.tsx index 76854cd67af..0d7b4c3a6ee 100644 --- a/src/features/name-services/domains/components/SearchBarSuggestDomain.tsx +++ b/src/features/name-services/domains/components/SearchBarSuggestDomain.tsx @@ -12,10 +12,11 @@ import { toBech32Address } from 'src/slices/address/utils/bech32'; import * as EnsEntity from 'src/features/name-services/domains/components/EnsEntity'; import dayjs from 'src/shared/date-and-time/dayjs'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import highlightText from 'src/shared/texts/highlight-text'; import SpriteIcon from 'src/sprite/SpriteIcon'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; + const SearchBarSuggestDomain = ({ data, isMobile, searchTerm, addressFormat }: ItemsProps<SearchResultDomain | multichain.QuickSearchResultDomain>) => { @@ -51,7 +52,7 @@ const SearchBarSuggestDomain = whiteSpace="nowrap" color="text.secondary" > - <HashStringShortenDynamic hash={ hash } noTooltip/> + <Truncate value={ hash } tooltip={ false }/> </Text> ) : null; diff --git a/src/features/name-services/domains/components/__screenshots__/EnsEntity.pw.tsx_default_loading-1.png b/src/features/name-services/domains/components/__screenshots__/EnsEntity.pw.tsx_default_loading-1.png index 2c83d443c41..1f3bdb94f8c 100644 Binary files a/src/features/name-services/domains/components/__screenshots__/EnsEntity.pw.tsx_default_loading-1.png and b/src/features/name-services/domains/components/__screenshots__/EnsEntity.pw.tsx_default_loading-1.png differ diff --git a/src/features/name-services/domains/hooks/useCheckDomainNameParam.ts b/src/features/name-services/domains/hooks/useCheckDomainNameParam.ts index c4135244ff8..f96a0743f3f 100644 --- a/src/features/name-services/domains/hooks/useCheckDomainNameParam.ts +++ b/src/features/name-services/domains/hooks/useCheckDomainNameParam.ts @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; import config from 'src/config'; +import { useRouter } from 'src/shared/router/useRouter'; const DOMAIN_NAME_REGEXP = /.\../; @@ -15,7 +15,6 @@ export default function useCheckDomainNameParam(hashOrDomainName: string) { const router = useRouter(); const maybeDomainName = DOMAIN_NAME_REGEXP.test(hashOrDomainName); const isQueryEnabled = feature.isEnabled && feature.ens.isEnabled && maybeDomainName; - const [ isLoading, setIsLoading ] = React.useState(isQueryEnabled); const domainLookupQuery = useApiQuery('bens:domains_lookup', { queryParams: { @@ -28,24 +27,13 @@ export default function useCheckDomainNameParam(hashOrDomainName: string) { }, }); - React.useEffect(() => { - if (domainLookupQuery.isPending) { - return; - } + const firstDomainAddress = domainLookupQuery.data?.items[0]?.resolved_address?.hash; - const firstDomainAddress = domainLookupQuery.data?.items[0]?.resolved_address?.hash; + React.useEffect(() => { if (firstDomainAddress) { router.replace({ pathname: '/address/[hash]', query: { hash: firstDomainAddress } }); - } else { - setIsLoading(false); - } - }, [ domainLookupQuery.isPending, domainLookupQuery.data, router ]); - - React.useEffect(() => { - if (!maybeDomainName) { - setIsLoading(false); } - }, [ maybeDomainName ]); + }, [ firstDomainAddress, router ]); - return isLoading; + return isQueryEnabled && (domainLookupQuery.isPending || Boolean(firstDomainAddress)); } diff --git a/src/features/name-services/domains/pages/address/AddressEnsDomains.tsx b/src/features/name-services/domains/pages/address/AddressEnsDomains.tsx index da507aebdcd..47bf43b4888 100644 --- a/src/features/name-services/domains/pages/address/AddressEnsDomains.tsx +++ b/src/features/name-services/domains/pages/address/AddressEnsDomains.tsx @@ -3,7 +3,6 @@ import { Box, Flex, Grid, chakra } from '@chakra-ui/react'; import type { UseQueryResult } from '@tanstack/react-query'; import { clamp } from 'es-toolkit'; -import { route } from 'nextjs-routes'; import React from 'react'; import type * as bens from '@blockscout/bens-types'; @@ -13,6 +12,7 @@ import type { ResourceError } from 'src/api/resources'; import EnsEntity from 'src/features/name-services/domains/components/EnsEntity'; import dayjs from 'src/shared/date-and-time/dayjs'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; diff --git a/src/features/name-services/domains/pages/details/NameDomain.pw.tsx b/src/features/name-services/domains/pages/details/NameDomain.pw.tsx index 076a978edea..0098c7e45a1 100644 --- a/src/features/name-services/domains/pages/details/NameDomain.pw.tsx +++ b/src/features/name-services/domains/pages/details/NameDomain.pw.tsx @@ -20,14 +20,13 @@ test('details tab', async({ render, mockTextAd, mockApiResponse, mockAssetRespon { hooksConfig: { router: { query: { name: ensDomainMock.ensDomainA.name }, - isReady: true, }, } }, ); await expect(component).toHaveScreenshot(); }); -test('history tab +@mobile', async({ render, mockTextAd, mockApiResponse, mockAssetResponse }) => { +test('history tab', async({ render, mockTextAd, mockApiResponse, mockAssetResponse }) => { await mockTextAd(); await mockApiResponse('bens:domain_info', ensDomainMock.ensDomainA, { pathParams: { name: ensDomainMock.ensDomainA.name }, @@ -48,7 +47,6 @@ test('history tab +@mobile', async({ render, mockTextAd, mockApiResponse, mockAs { hooksConfig: { router: { query: { name: ensDomainMock.ensDomainA.name, tab: 'history' }, - isReady: true, }, } }, ); diff --git a/src/features/name-services/domains/pages/details/NameDomain.tsx b/src/features/name-services/domains/pages/details/NameDomain.tsx index d49648219a7..b20e74571d2 100644 --- a/src/features/name-services/domains/pages/details/NameDomain.tsx +++ b/src/features/name-services/domains/pages/details/NameDomain.tsx @@ -1,8 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -22,6 +20,8 @@ import { ENS_DOMAIN } from 'src/features/name-services/domains/stubs'; import config from 'src/config'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_default_details-tab-1.png b/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_default_details-tab-1.png index c0cca32a9ed..5b011366a09 100644 Binary files a/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_default_details-tab-1.png and b/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_default_details-tab-1.png differ diff --git a/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_default_history-tab-1.png b/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_default_history-tab-1.png new file mode 100644 index 00000000000..328e7b8e8a0 Binary files /dev/null and b/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_default_history-tab-1.png differ diff --git a/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_default_history-tab-mobile-1.png b/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_default_history-tab-mobile-1.png deleted file mode 100644 index e11042fdc84..00000000000 Binary files a/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_default_history-tab-mobile-1.png and /dev/null differ diff --git a/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_mobile_history-tab-mobile-1.png b/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_mobile_history-tab-mobile-1.png deleted file mode 100644 index 42cfac40fc3..00000000000 Binary files a/src/features/name-services/domains/pages/details/__screenshots__/NameDomain.pw.tsx_mobile_history-tab-mobile-1.png and /dev/null differ diff --git a/src/features/name-services/domains/pages/details/history/NameDomainHistory.tsx b/src/features/name-services/domains/pages/details/history/NameDomainHistory.tsx index 3e554088f97..ec7a33eccac 100644 --- a/src/features/name-services/domains/pages/details/history/NameDomainHistory.tsx +++ b/src/features/name-services/domains/pages/details/history/NameDomainHistory.tsx @@ -1,36 +1,46 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; +import { createListCollection } from '@chakra-ui/react'; import React from 'react'; import type * as bens from '@blockscout/bens-types'; import useApiQuery from 'src/api/hooks/useApiQuery'; +import ActionBar from 'src/shell/page/action-bar/ActionBar'; + import { ENS_DOMAIN_EVENT } from 'src/features/name-services/domains/stubs'; import config from 'src/config'; +import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; +import Sort from 'src/shared/sort/Sort'; + +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import NameDomainHistoryList from './NameDomainHistoryList'; import NameDomainHistoryTable from './NameDomainHistoryTable'; -import { getNextSortValue, type Sort, type SortField } from './utils'; +import { getNextSortValue, SORT_OPTIONS, type Sort as SortValue, type SortField } from './utils'; const feature = config.features.nameServices; const availableProtocols = feature.isEnabled && feature.ens.isEnabled ? feature.ens.protocols : []; +const sortCollection = createListCollection({ + items: SORT_OPTIONS, +}); + interface Props { domain: bens.DetailedDomain | undefined; } const NameDomainHistory = ({ domain }: Props) => { const router = useRouter(); + const isMobile = useIsMobile(); const domainName = getQueryParamString(router.query.name); const protocolId = getQueryParamString(router.query.protocol_id) || availableProtocols[0]; - const [ sort, setSort ] = React.useState<Sort>('default'); + const [ sort, setSort ] = React.useState<SortValue>('default'); const { isPlaceholderData, isError, data } = useApiQuery('bens:domain_events', { pathParams: { name: domainName }, @@ -52,25 +62,33 @@ const NameDomainHistory = ({ domain }: Props) => { } }, [ isPlaceholderData ]); + const handleSortValueChange = React.useCallback(({ value }: { value: Array<string> }) => { + setSort(value[0] as SortValue); + }, []); + const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <NameDomainHistoryList - items={ data.items } - domain={ domain } - isLoading={ isPlaceholderData } - /> - </Box> - <Box hideBelow="lg"> - <NameDomainHistoryTable - items={ data.items } - domain={ domain } - isLoading={ isPlaceholderData } - sort={ sort } - onSortToggle={ handleSortToggle } - /> - </Box> - </> + <TableContainerScrollable> + <NameDomainHistoryTable + items={ data.items } + domain={ domain } + isLoading={ isPlaceholderData } + sort={ sort } + onSortToggle={ handleSortToggle } + /> + </TableContainerScrollable> + ) : null; + + const actionBar = isMobile ? ( + <ActionBar mt={ -6 }> + <Sort + name="name_domain_history_sorting" + defaultValue={ [ sort ] } + collection={ sortCollection } + onValueChange={ handleSortValueChange } + isLoading={ isPlaceholderData } + hideFrom="lg" + /> + </ActionBar> ) : null; return ( @@ -78,6 +96,7 @@ const NameDomainHistory = ({ domain }: Props) => { isError={ isError } itemsNum={ data?.items.length } emptyText="There are no events for this domain." + actionBar={ actionBar } > { content } </DataList> diff --git a/src/features/name-services/domains/pages/details/history/NameDomainHistoryList.tsx b/src/features/name-services/domains/pages/details/history/NameDomainHistoryList.tsx deleted file mode 100644 index f10d859561d..00000000000 --- a/src/features/name-services/domains/pages/details/history/NameDomainHistoryList.tsx +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type * as bens from '@blockscout/bens-types'; - -import NameDomainHistoryListItem from './NameDomainHistoryListItem'; - -interface Props { - items: Array<bens.DomainEvent>; - domain: bens.DetailedDomain | undefined; - isLoading?: boolean; -} - -const NameDomainHistoryList = ({ items, domain, isLoading }: Props) => { - return ( - <Box> - { items.map((item, index) => ( - <NameDomainHistoryListItem - key={ index } - event={ item } - domain={ domain } - isLoading={ isLoading } - /> - )) } - </Box> - ); -}; - -export default React.memo(NameDomainHistoryList); diff --git a/src/features/name-services/domains/pages/details/history/NameDomainHistoryListItem.tsx b/src/features/name-services/domains/pages/details/history/NameDomainHistoryListItem.tsx deleted file mode 100644 index d24cdd909d1..00000000000 --- a/src/features/name-services/domains/pages/details/history/NameDomainHistoryListItem.tsx +++ /dev/null @@ -1,72 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { route } from 'nextjs-routes'; -import React from 'react'; - -import type * as bens from '@blockscout/bens-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Badge } from 'src/toolkit/chakra/badge'; -import { stripTrailingSlash } from 'src/toolkit/utils/url'; - -interface Props { - event: bens.DomainEvent; - domain: bens.DetailedDomain | undefined; - isLoading?: boolean; -} - -const NameDomainHistoryListItem = ({ isLoading, domain, event }: Props) => { - const isProtocolBaseChain = stripTrailingSlash(domain?.protocol?.deployment_blockscout_base_url ?? '') === config.app.baseUrl; - const txEntityProps = { - link: { external: !isProtocolBaseChain ? true : false }, - href: !isProtocolBaseChain ? ( - stripTrailingSlash(domain?.protocol?.deployment_blockscout_base_url ?? '') + - route({ pathname: '/tx/[hash]', query: { hash: event.transaction_hash } }) - ) : undefined, - }; - - return ( - <ListItemMobileGrid.Container> - <ListItemMobileGrid.Label isLoading={ isLoading }>Txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntity { ...txEntityProps } hash={ event.transaction_hash } isLoading={ isLoading } fontWeight={ 500 } truncation="constant_long" noCopy/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ event.timestamp } - isLoading={ isLoading } - color="text.secondary" - display="inline-block" - /> - </ListItemMobileGrid.Value> - - { event.from_address && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>From</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity address={ event.from_address } isLoading={ isLoading } truncation="constant"/> - </ListItemMobileGrid.Value> - </> - ) } - - { event.action && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Method</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Badge colorPalette="gray" loading={ isLoading }>{ event.action }</Badge> - </ListItemMobileGrid.Value> - </> - ) } - </ListItemMobileGrid.Container> - ); -}; - -export default React.memo(NameDomainHistoryListItem); diff --git a/src/features/name-services/domains/pages/details/history/NameDomainHistoryTable.tsx b/src/features/name-services/domains/pages/details/history/NameDomainHistoryTable.tsx index c05bfcbb72c..2648fba40ab 100644 --- a/src/features/name-services/domains/pages/details/history/NameDomainHistoryTable.tsx +++ b/src/features/name-services/domains/pages/details/history/NameDomainHistoryTable.tsx @@ -24,7 +24,7 @@ const NameDomainHistoryTable = ({ items, domain, isLoading, sort, onSortToggle } const sortedItems = React.useMemo(() => items.slice().sort(sortFn(sort)), [ items, sort ]); return ( - <TableRoot> + <TableRoot minW="900px"> <TableHeaderSticky top={ 0 }> <TableRow> <TableColumnHeader width="25%">Txn hash</TableColumnHeader> diff --git a/src/features/name-services/domains/pages/details/history/NameDomainHistoryTableItem.tsx b/src/features/name-services/domains/pages/details/history/NameDomainHistoryTableItem.tsx index 656ed936538..49d3df9345d 100644 --- a/src/features/name-services/domains/pages/details/history/NameDomainHistoryTableItem.tsx +++ b/src/features/name-services/domains/pages/details/history/NameDomainHistoryTableItem.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { route } from 'nextjs-routes'; import React from 'react'; import type * as bens from '@blockscout/bens-types'; @@ -10,6 +9,7 @@ import TxEntity from 'src/slices/tx/components/entity/TxEntity'; import config from 'src/config'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import { route } from 'src/shared/router/routes'; import { Badge } from 'src/toolkit/chakra/badge'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; diff --git a/src/features/name-services/domains/pages/details/history/utils.ts b/src/features/name-services/domains/pages/details/history/utils.ts index 8e2e58429c3..3c32fe8ed08 100644 --- a/src/features/name-services/domains/pages/details/history/utils.ts +++ b/src/features/name-services/domains/pages/details/history/utils.ts @@ -5,9 +5,17 @@ import type * as bens from '@blockscout/bens-types'; import getNextSortValueShared from 'src/shared/sort/get-next-sort-value'; import { collator } from 'src/shared/texts/collator'; +import type { SelectOption } from 'src/toolkit/chakra/select'; + export type SortField = 'timestamp'; export type Sort = `${ SortField }-asc` | `${ SortField }-desc` | 'default'; +export const SORT_OPTIONS: Array<SelectOption<Sort>> = [ + { label: 'Default', value: 'default' }, + { label: 'Timestamp descending', value: 'timestamp-desc' }, + { label: 'Timestamp ascending', value: 'timestamp-asc' }, +]; + const SORT_SEQUENCE: Record<SortField, Array<Sort>> = { timestamp: [ 'timestamp-desc', 'timestamp-asc', 'default' ], }; diff --git a/src/features/name-services/domains/pages/details/info/NameDomainDetails.tsx b/src/features/name-services/domains/pages/details/info/NameDomainDetails.tsx index 66adf29a5bf..6a12eaf8cee 100644 --- a/src/features/name-services/domains/pages/details/info/NameDomainDetails.tsx +++ b/src/features/name-services/domains/pages/details/info/NameDomainDetails.tsx @@ -2,7 +2,6 @@ import { Flex } from '@chakra-ui/react'; import type { UseQueryResult } from '@tanstack/react-query'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as bens from '@blockscout/bens-types'; @@ -17,6 +16,7 @@ import NameDomainExpiryStatus from 'src/features/name-services/domains/component import config from 'src/config'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import DetailedInfoTimestamp from 'src/shared/detailed-info/DetailedInfoTimestamp'; +import { route } from 'src/shared/router/routes'; import TextSeparator from 'src/shared/texts/TextSeparator'; import SpriteIcon from 'src/sprite/SpriteIcon'; diff --git a/src/features/name-services/domains/pages/index/NameDomains.tsx b/src/features/name-services/domains/pages/index/NameDomains.tsx index 8f180a90335..1b76cec6f43 100644 --- a/src/features/name-services/domains/pages/index/NameDomains.tsx +++ b/src/features/name-services/domains/pages/index/NameDomains.tsx @@ -1,28 +1,28 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { EnsDomainLookupFiltersOptions, EnsLookupSorting } from 'src/features/name-services/domains/types/api'; import useApiQuery from 'src/api/hooks/useApiQuery'; +import type { PaginationFilters } from 'src/api/resources'; import { ENS_DOMAIN } from 'src/features/name-services/domains/stubs'; import config from 'src/config'; -import useDebounce from 'src/shared/hooks/useDebounce'; import DataList from 'src/shared/lists/DataList'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; +import { usePaginationParams } from 'src/shared/pagination/usePaginationParams'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; import getSortValueFromQuery from 'src/shared/sort/get-sort-value-from-query'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { ADDRESS_REGEXP } from 'src/toolkit/utils/regexp'; import NameDomainsActionBar from './NameDomainsActionBar'; -import NameDomainsList from './NameDomainsList'; import NameDomainsTable from './NameDomainsTable'; import type { Sort, SortField } from './utils'; import { SORT_OPTIONS, getNextSortValue } from './utils'; @@ -30,69 +30,75 @@ import { SORT_OPTIONS, getNextSortValue } from './utils'; const feature = config.features.nameServices; const availableProtocols = feature.isEnabled && feature.ens.isEnabled ? feature.ens.protocols : []; -const NameDomains = () => { - const router = useRouter(); - - const q = getQueryParamString(router.query.name) || getQueryParamString(router.query.address); - const ownedBy = getQueryParamString(router.query.owned_by); - const resolvedTo = getQueryParamString(router.query.resolved_to); - const onlyActive = getQueryParamString(router.query.only_active); - - const protocols = (() => { - if (router.query.protocols) { - const valueFromQuery = getQueryParamString(router.query.protocols) - .split(',') - .filter(Boolean) - .filter((protocol) => availableProtocols.includes(protocol)); - - if (valueFromQuery.length > 0) { - return valueFromQuery; - } - } +const NO_PROTOCOLS: Array<string> = []; +const ADDRESS_SEARCH_DEFAULT_FILTERS: EnsDomainLookupFiltersOptions = [ 'owned_by', 'resolved_to' ]; + +type AddressesLookupFilters = PaginationFilters<'bens:addresses_lookup'>; + +interface LookupState { + readonly searchTerm: string; + readonly filterValue: EnsDomainLookupFiltersOptions; + readonly protocols: Array<string>; +} - return []; - })(); +// The resource types these as booleans; read from the URL they are the strings 'true' / 'false'. +function isFalseParam(value: boolean | string | Array<string> | undefined): boolean { + return String(value) === 'false'; +} - const initialFilters: EnsDomainLookupFiltersOptions = [ - ownedBy === 'true' ? 'owned_by' as const : undefined, - resolvedTo === 'true' ? 'resolved_to' as const : undefined, - onlyActive === 'false' ? 'with_inactive' as const : undefined, +function getFilterValueFromQuery(filters: AddressesLookupFilters, isAddressSearch: boolean): EnsDomainLookupFiltersOptions { + return [ + isAddressSearch && !isFalseParam(filters.owned_by) ? 'owned_by' as const : undefined, + isAddressSearch && !isFalseParam(filters.resolved_to) ? 'resolved_to' as const : undefined, + isFalseParam(filters.only_active) ? 'with_inactive' as const : undefined, ].filter(Boolean); - const initialSort = getSortValueFromQuery<Sort>(router.query, SORT_OPTIONS); +} + +function getProtocolsFromQuery(value: string | Array<string> | undefined): Array<string> { + const protocols = getQueryParamString(value) + .split(',') + .filter(Boolean) + .filter((protocol) => availableProtocols.includes(protocol)); + + return protocols.length > 0 ? protocols : NO_PROTOCOLS; +} + +const NameDomains = () => { + const { filters: addressesFilters, sorting } = usePaginationParams('bens:addresses_lookup'); + const { filters: domainsFilters } = usePaginationParams('bens:domains_lookup'); - const [ searchTerm, setSearchTerm ] = React.useState<string>(q || ''); - const [ filterValue, setFilterValue ] = React.useState<EnsDomainLookupFiltersOptions>(initialFilters); - const [ sort, setSort ] = React.useState<Sort>(initialSort ?? 'default'); - const [ protocolsFilter, setProtocolsFilter ] = React.useState<Array<string>>(protocols); + const searchTerm = getQueryParamString(domainsFilters.name) || getQueryParamString(addressesFilters.address); + const isAddressSearch = ADDRESS_REGEXP.test(searchTerm); + const filterValue = React.useMemo(() => getFilterValueFromQuery(addressesFilters, isAddressSearch), [ addressesFilters, isAddressSearch ]); + const protocolsParam = addressesFilters.protocols; + const protocolsFilter = React.useMemo(() => getProtocolsFromQuery(protocolsParam), [ protocolsParam ]); + const sort = getSortValueFromQuery<Sort>({ ...sorting }, SORT_OPTIONS) ?? 'default'; - const debouncedSearchTerm = useDebounce(searchTerm, 300); - const isAddressSearch = React.useMemo(() => ADDRESS_REGEXP.test(debouncedSearchTerm), [ debouncedSearchTerm ]); - const sortParams = getSortParamsFromValue<Sort, EnsLookupSorting['sort'], EnsLookupSorting['order']>(sort); + const onlyActive = !filterValue.includes('with_inactive'); + const requestedProtocols = protocolsFilter.length > 0 ? protocolsFilter : availableProtocols; - const addressesLookupQuery = useQueryWithPages({ + const addressesLookupQuery = useApiPaginatedQuery({ resourceName: 'bens:addresses_lookup', - filters: { - address: debouncedSearchTerm, + queryParams: { + address: searchTerm, resolved_to: filterValue.includes('resolved_to'), owned_by: filterValue.includes('owned_by'), - only_active: !filterValue.includes('with_inactive'), - protocols: protocolsFilter.length > 0 ? protocolsFilter : availableProtocols, + only_active: onlyActive, + protocols: requestedProtocols, }, - sorting: sortParams, options: { enabled: isAddressSearch, placeholderData: generateListStub<'bens:addresses_lookup'>(ENS_DOMAIN, 50, { next_page_params: undefined }), }, }); - const domainsLookupQuery = useQueryWithPages({ + const domainsLookupQuery = useApiPaginatedQuery({ resourceName: 'bens:domains_lookup', - filters: { - name: debouncedSearchTerm, - only_active: !filterValue.includes('with_inactive'), - protocols: protocolsFilter.length > 0 ? protocolsFilter : availableProtocols, + queryParams: { + name: searchTerm, + only_active: onlyActive, + protocols: requestedProtocols, }, - sorting: sortParams, options: { enabled: !isAddressSearch, placeholderData: generateListStub<'bens:domains_lookup'>(ENS_DOMAIN, 50, { next_page_params: undefined }), @@ -102,129 +108,68 @@ const NameDomains = () => { const protocolsQuery = useApiQuery('bens:protocols'); const query = isAddressSearch ? addressesLookupQuery : domainsLookupQuery; - const { data, isError, isPlaceholderData: isLoading, onFilterChange, onSortingChange, queryHash } = query; + const { data, isError, isInitialLoading, isTransitioning, onFilterChange, onSortingChange, queryHash } = query; - React.useEffect(() => { - const hasInactiveFilter = filterValue.some((value) => value === 'with_inactive'); - if (isAddressSearch) { - setFilterValue([ 'owned_by' as const, 'resolved_to' as const, hasInactiveFilter ? 'with_inactive' as const : undefined ].filter(Boolean)); + const pushLookupState = React.useCallback((next: LookupState) => { + if (ADDRESS_REGEXP.test(next.searchTerm)) { onFilterChange<'bens:addresses_lookup'>({ - address: debouncedSearchTerm, - resolved_to: true, - owned_by: true, - only_active: !hasInactiveFilter, - protocols: protocolsFilter, + address: next.searchTerm, + resolved_to: next.filterValue.includes('resolved_to'), + owned_by: next.filterValue.includes('owned_by'), + only_active: !next.filterValue.includes('with_inactive'), + protocols: next.protocols, }); - } else { - setFilterValue([ hasInactiveFilter ? 'with_inactive' as const : undefined ].filter(Boolean)); - onFilterChange<'bens:domains_lookup'>({ - name: debouncedSearchTerm, - only_active: !hasInactiveFilter, - protocols: protocolsFilter, - }); - } - // should run only the type of search changes - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ isAddressSearch ]); - - const handleSortToggle = React.useCallback((field: SortField) => { - if (isLoading) { return; } - if (field) { - setSort((prevValue) => { - const nextSortValue = getNextSortValue(field)(prevValue); - onSortingChange(getSortParamsFromValue(nextSortValue)); - return nextSortValue; - }); - } - }, [ isLoading, onSortingChange ]); - - const handleSearchTermChange = React.useCallback((value: string) => { - setSearchTerm(value); - const isAddressSearch = ADDRESS_REGEXP.test(value); - if (isAddressSearch) { - onFilterChange<'bens:addresses_lookup'>({ - address: value, - resolved_to: filterValue.includes('resolved_to'), - owned_by: filterValue.includes('owned_by'), - only_active: !filterValue.includes('with_inactive'), - protocols: protocolsFilter, - }); - } else { - onFilterChange<'bens:domains_lookup'>({ - name: value, - only_active: !filterValue.includes('with_inactive'), - protocols: protocolsFilter, - }); - } - }, [ onFilterChange, filterValue, protocolsFilter ]); + onFilterChange<'bens:domains_lookup'>({ + name: next.searchTerm, + only_active: !next.filterValue.includes('with_inactive'), + protocols: next.protocols, + }); + }, [ onFilterChange ]); + + const handleSearchTermChange = useDebouncedFilterChange((value) => { + const switchesToAddressSearch = !isAddressSearch && ADDRESS_REGEXP.test(value); + const nextFilterValue = switchesToAddressSearch ? + [ ...ADDRESS_SEARCH_DEFAULT_FILTERS, ...filterValue.filter((item) => item === 'with_inactive') ] : + filterValue; + pushLookupState({ searchTerm: value, filterValue: nextFilterValue, protocols: protocolsFilter }); + }); const handleFilterValueChange = React.useCallback((value: EnsDomainLookupFiltersOptions) => { - setFilterValue(value); - - const isAddressSearch = ADDRESS_REGEXP.test(debouncedSearchTerm); - if (isAddressSearch) { - onFilterChange<'bens:addresses_lookup'>({ - address: debouncedSearchTerm, - resolved_to: value.includes('resolved_to'), - owned_by: value.includes('owned_by'), - only_active: !value.includes('with_inactive'), - protocols: protocolsFilter, - }); - } else { - onFilterChange<'bens:domains_lookup'>({ - name: debouncedSearchTerm, - only_active: !value.includes('with_inactive'), - protocols: protocolsFilter, - }); - } - }, [ debouncedSearchTerm, onFilterChange, protocolsFilter ]); + pushLookupState({ searchTerm, filterValue: value, protocols: protocolsFilter }); + }, [ pushLookupState, searchTerm, protocolsFilter ]); const handleProtocolsFilterChange = React.useCallback((nextValue: Array<string>) => { - setProtocolsFilter(nextValue); + pushLookupState({ searchTerm, filterValue, protocols: nextValue }); + }, [ pushLookupState, searchTerm, filterValue ]); - const isAddressSearch = ADDRESS_REGEXP.test(debouncedSearchTerm); - if (isAddressSearch) { - onFilterChange<'bens:addresses_lookup'>({ - address: debouncedSearchTerm, - resolved_to: filterValue.includes('resolved_to'), - owned_by: filterValue.includes('owned_by'), - only_active: !filterValue.includes('with_inactive'), - protocols: nextValue, - }); - } else { - onFilterChange<'bens:domains_lookup'>({ - name: debouncedSearchTerm, - only_active: !filterValue.includes('with_inactive'), - protocols: nextValue, - }); + const handleSortChange = React.useCallback((nextValue: Sort) => { + onSortingChange(getSortParamsFromValue<Sort, EnsLookupSorting['sort'], EnsLookupSorting['order']>(nextValue)); + }, [ onSortingChange ]); + + const handleSortToggle = React.useCallback((field: SortField) => { + if (isInitialLoading || !field) { + return; } - }, [ debouncedSearchTerm, filterValue, onFilterChange ]); - const hasActiveFilters = Boolean(debouncedSearchTerm) || filterValue.length > 0 || + handleSortChange(getNextSortValue(field)(sort)); + }, [ isInitialLoading, handleSortChange, sort ]); + + const hasActiveFilters = Boolean(searchTerm) || filterValue.length > 0 || (protocolsQuery.data && availableProtocols.length > 1 ? protocolsFilter.length > 0 : false); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <NameDomainsList - items={ data.items } - isLoading={ isLoading } - resetKey={ queryHash } - /> - </Box> - <Box hideBelow="lg"> - <NameDomainsTable - items={ data.items } - isLoading={ isLoading } - sort={ sort } - onSortToggle={ handleSortToggle } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <NameDomainsTable + items={ data.items } + isLoading={ isInitialLoading } + sort={ sort } + onSortToggle={ handleSortToggle } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const protocolsData = React.useMemo(() => { @@ -233,7 +178,7 @@ const NameDomains = () => { const actionBar = ( <NameDomainsActionBar - isLoading={ isLoading } + isLoading={ isInitialLoading } searchTerm={ searchTerm } onSearchChange={ handleSearchTermChange } filterValue={ filterValue } @@ -242,7 +187,7 @@ const NameDomains = () => { protocolsFilterValue={ protocolsFilter } onProtocolsFilterChange={ handleProtocolsFilterChange } sort={ sort } - onSortChange={ setSort } + onSortChange={ handleSortChange } isAddressSearch={ isAddressSearch } pagination={ query.pagination } /> @@ -258,6 +203,7 @@ const NameDomains = () => { term: 'name domain', }} actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/name-services/domains/pages/index/NameDomainsList.tsx b/src/features/name-services/domains/pages/index/NameDomainsList.tsx deleted file mode 100644 index 62cbffb0a18..00000000000 --- a/src/features/name-services/domains/pages/index/NameDomainsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type * as bens from '@blockscout/bens-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import NameDomainsListItem from './NameDomainsListItem'; - -interface Props { - items: Array<bens.Domain>; - isLoading?: boolean; - resetKey?: string; -} - -const NameDomainsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <NameDomainsListItem - key={ item.id + (isLoading ? index : '') } - { ...item } - isLoading={ Boolean(isLoading) } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(NameDomainsList); diff --git a/src/features/name-services/domains/pages/index/NameDomainsListItem.tsx b/src/features/name-services/domains/pages/index/NameDomainsListItem.tsx deleted file mode 100644 index 3e3bb499fc0..00000000000 --- a/src/features/name-services/domains/pages/index/NameDomainsListItem.tsx +++ /dev/null @@ -1,83 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type * as bens from '@blockscout/bens-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import EnsEntity from 'src/features/name-services/domains/components/EnsEntity'; -import NameDomainExpiryStatus from 'src/features/name-services/domains/components/NameDomainExpiryStatus'; - -import dayjs from 'src/shared/date-and-time/dayjs'; -import Time from 'src/shared/date-and-time/Time'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props extends bens.Domain { - isLoading: boolean; -} - -const NameDomainsListItem = ({ - name, - isLoading, - resolved_address: resolvedAddress, - registration_date: registrationDate, - expiry_date: expiryDate, - protocol, - protocol_dapp_url: protocolDappUrl, - protocol_dapp_logo: protocolDappLogo, -}: Props) => { - - const protocolDapp = React.useMemo(() => { - return { - url: protocolDappUrl, - logo: protocolDappLogo, - }; - }, [ protocolDappUrl, protocolDappLogo ]); - - return ( - <ListItemMobileGrid.Container> - <ListItemMobileGrid.Label isLoading={ isLoading }>Domain</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <EnsEntity domain={ name } protocol={ protocol } protocolDapp={ protocolDapp } isLoading={ isLoading } fontWeight={ 500 }/> - </ListItemMobileGrid.Value> - - { resolvedAddress && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Address</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity address={ resolvedAddress } isLoading={ isLoading } fontWeight={ 500 }/> - </ListItemMobileGrid.Value> - </> - ) } - - { registrationDate && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Registered on</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - <Time timestamp={ registrationDate }/> - <div> { dayjs(registrationDate).fromNow() }</div> - </Skeleton> - </ListItemMobileGrid.Value> - </> - ) } - - { expiryDate && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Expiration date</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } whiteSpace="pre-wrap"> - <Time timestamp={ expiryDate } display="block"/> - <NameDomainExpiryStatus date={ expiryDate }/> - </Skeleton> - </ListItemMobileGrid.Value> - </> - ) } - </ListItemMobileGrid.Container> - ); -}; - -export default React.memo(NameDomainsListItem); diff --git a/src/features/name-services/domains/pages/index/NameDomainsTable.tsx b/src/features/name-services/domains/pages/index/NameDomainsTable.tsx index 0c0c441beb9..a056eccf136 100644 --- a/src/features/name-services/domains/pages/index/NameDomainsTable.tsx +++ b/src/features/name-services/domains/pages/index/NameDomainsTable.tsx @@ -9,6 +9,7 @@ import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableColumnHeaderSortable, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -24,12 +25,15 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: bens.Domain): string => item.id; + const NameDomainsTable = ({ items, isLoading, sort, onSortToggle, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( <AddressHighlightProvider> - <TableRoot> + <TableRoot minW="900px"> <TableHeaderSticky top={ ACTION_BAR_HEIGHT_DESKTOP }> <TableRow> <TableColumnHeader width="25%">Domain</TableColumnHeader> @@ -52,7 +56,7 @@ const NameDomainsTable = ({ items, isLoading, sort, onSortToggle, resetKey }: Pr </TableHeaderSticky> <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( - <NameDomainsTableItem key={ item.id + (isLoading ? index : '') } { ...item } isLoading={ isLoading }/> + <NameDomainsTableItem key={ keys[index] } { ...item } isLoading={ isLoading }/> )) } <TableRow ref={ cutRef }/> </TableBody> diff --git a/src/features/op-interop/components/AddressEntityInterop.tsx b/src/features/op-interop/components/AddressEntityInterop.tsx index 125dbce854d..e15ed6a2272 100644 --- a/src/features/op-interop/components/AddressEntityInterop.tsx +++ b/src/features/op-interop/components/AddressEntityInterop.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, chakra, Flex } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { ChainInfo } from 'src/features/op-interop/types/api'; @@ -9,6 +8,7 @@ import type { ChainInfo } from 'src/features/op-interop/types/api'; import * as AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import { distributeEntityProps } from 'src/shared/entities/utils'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Image } from 'src/toolkit/chakra/image'; diff --git a/src/features/op-interop/components/TxEntityInterop.tsx b/src/features/op-interop/components/TxEntityInterop.tsx index 24d1fbeb6ab..7d8b6a8816c 100644 --- a/src/features/op-interop/components/TxEntityInterop.tsx +++ b/src/features/op-interop/components/TxEntityInterop.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { ChainInfo } from 'src/features/op-interop/types/api'; @@ -9,6 +8,7 @@ import type { ChainInfo } from 'src/features/op-interop/types/api'; import * as TxEntity from 'src/slices/tx/components/entity/TxEntity'; import { distributeEntityProps } from 'src/shared/entities/utils'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Image } from 'src/toolkit/chakra/image'; diff --git a/src/features/op-interop/components/__screenshots__/AddressEntityInterop.pw.tsx_dark-color-mode_with-chain-icon-stub-dark-mode-1.png b/src/features/op-interop/components/__screenshots__/AddressEntityInterop.pw.tsx_dark-color-mode_with-chain-icon-stub-dark-mode-1.png index bab192184b7..8b22031b7c5 100644 Binary files a/src/features/op-interop/components/__screenshots__/AddressEntityInterop.pw.tsx_dark-color-mode_with-chain-icon-stub-dark-mode-1.png and b/src/features/op-interop/components/__screenshots__/AddressEntityInterop.pw.tsx_dark-color-mode_with-chain-icon-stub-dark-mode-1.png differ diff --git a/src/features/op-interop/components/__screenshots__/AddressEntityInterop.pw.tsx_default_with-chain-icon-stub-dark-mode-1.png b/src/features/op-interop/components/__screenshots__/AddressEntityInterop.pw.tsx_default_with-chain-icon-stub-dark-mode-1.png index 08b2de7b3c3..45b28005ff8 100644 Binary files a/src/features/op-interop/components/__screenshots__/AddressEntityInterop.pw.tsx_default_with-chain-icon-stub-dark-mode-1.png and b/src/features/op-interop/components/__screenshots__/AddressEntityInterop.pw.tsx_default_with-chain-icon-stub-dark-mode-1.png differ diff --git a/src/features/op-interop/pages/messages/InteropMessages.pw.tsx b/src/features/op-interop/pages/messages/InteropMessages.pw.tsx index 78beefd0bdc..0fe1b6ea2da 100644 --- a/src/features/op-interop/pages/messages/InteropMessages.pw.tsx +++ b/src/features/op-interop/pages/messages/InteropMessages.pw.tsx @@ -3,7 +3,6 @@ import React from 'react'; import * as interopMessageMock from 'src/features/op-interop/mocks/interop'; import { test, expect } from 'playwright/lib'; -import * as pwConfig from 'playwright/utils/config'; import InteropMessages from './InteropMessages'; @@ -29,15 +28,3 @@ test('default view', async({ render, mockTextAd, mockAssetResponse, mockApiRespo const component = await render(<InteropMessages/>); await expect(component).toHaveScreenshot({ maxDiffPixels: 30 }); }); - -test.describe('mobile', () => { - test.use({ viewport: pwConfig.viewport.mobile }); - test('default view', async({ render, mockTextAd, mockAssetResponse, mockApiResponse }) => { - await mockTextAd(); - await mockAssetResponse(interopMessageMock.chain.chain_logo as string, './playwright/mocks/image_s.jpg'); - await mockApiResponse('core:optimistic_l2_interop_messages', MESSAGES_RESPONSE); - await mockApiResponse('core:optimistic_l2_interop_messages_count', 4000000); - const component = await render(<InteropMessages/>); - await expect(component).toHaveScreenshot({ maxDiffPixels: 30 }); - }); -}); diff --git a/src/features/op-interop/pages/messages/InteropMessages.tsx b/src/features/op-interop/pages/messages/InteropMessages.tsx index ab1dd467fb8..95f7ae68dca 100644 --- a/src/features/op-interop/pages/messages/InteropMessages.tsx +++ b/src/features/op-interop/pages/messages/InteropMessages.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -12,16 +11,16 @@ import { INTEROP_MESSAGE } from 'src/features/op-interop/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import InteropMessagesListItem from './InteropMessagesListItem'; import InteropMessagesTable from './InteropMessagesTable'; const InteropMessages = () => { - const interopMessagesQuery = useQueryWithPages({ + const interopMessagesQuery = useApiPaginatedQuery({ resourceName: 'core:optimistic_l2_interop_messages', options: { placeholderData: generateListStub<'core:optimistic_l2_interop_messages'>(INTEROP_MESSAGE, 50, { next_page_params: { @@ -44,7 +43,7 @@ const InteropMessages = () => { } return ( - <Skeleton loading={ countQuery.isPlaceholderData }> + <Skeleton loading={ countQuery.isInitialLoading }> A total of { countQuery.data?.toLocaleString() } messages found </Skeleton> ); @@ -53,24 +52,13 @@ const InteropMessages = () => { const actionBar = <StickyPaginationWithText text={ text } pagination={ interopMessagesQuery.pagination }/>; const content = ( - <> - <Box hideFrom="lg"> - { interopMessagesQuery.data?.items.map((item, index) => ( - <InteropMessagesListItem - key={ item.init_transaction_hash + (interopMessagesQuery.isPlaceholderData ? index : '') } - item={ item } - isLoading={ interopMessagesQuery.isPlaceholderData } - /> - )) } - </Box> - <Box hideBelow="lg"> - <InteropMessagesTable - items={ interopMessagesQuery.data?.items } - top={ interopMessagesQuery.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ interopMessagesQuery.isPlaceholderData } - /> - </Box> - </> + <TableContainerScrollable> + <InteropMessagesTable + items={ interopMessagesQuery.data?.items } + top={ interopMessagesQuery.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ interopMessagesQuery.isInitialLoading } + /> + </TableContainerScrollable> ); return ( @@ -84,6 +72,7 @@ const InteropMessages = () => { itemsNum={ interopMessagesQuery.data?.items.length } emptyText="There are no interop messages." actionBar={ actionBar } + isTransitioning={ interopMessagesQuery.isTransitioning } > { content } </DataList> diff --git a/src/features/op-interop/pages/messages/InteropMessagesListItem.tsx b/src/features/op-interop/pages/messages/InteropMessagesListItem.tsx deleted file mode 100644 index acf5b18d83f..00000000000 --- a/src/features/op-interop/pages/messages/InteropMessagesListItem.tsx +++ /dev/null @@ -1,75 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, HStack, Text, Grid } from '@chakra-ui/react'; -import React from 'react'; - -import type { InteropMessage } from 'src/features/op-interop/types/api'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import AddressFromToIcon from 'src/slices/address/components/from-to/AddressFromToIcon'; - -import AddressEntityInterop from 'src/features/op-interop/components/AddressEntityInterop'; -import InteropMessageDestinationTx from 'src/features/op-interop/components/InteropMessageDestinationTx'; -import InteropMessageSourceTx from 'src/features/op-interop/components/InteropMessageSourceTx'; -import InteropMessageStatus from 'src/features/op-interop/components/InteropMessageStatus'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import InteropMessageAdditionalInfo from './InteropMessageAdditionalInfo'; - -interface Props { - item: InteropMessage; - isLoading?: boolean; -} - -const InteropMessagesListItem = ({ item, isLoading }: Props) => { - return ( - <ListItemMobile rowGap={ 2 }> - <Flex alignItems="center" justifyContent="space-between" w="100%"> - <InteropMessageStatus status={ item.status } isLoading={ isLoading }/> - <InteropMessageAdditionalInfo payload={ item.payload } isLoading={ isLoading }/> - </Flex> - <Flex alignItems="flex-start" flexDirection="column" gap={ 2 } w="100%"> - <HStack w="100%"> - <Text fontWeight={ 500 } flexGrow={ 1 }>#{ item.nonce }</Text> - <TimeWithTooltip timestamp={ item.timestamp } isLoading={ isLoading } color="text.secondary"/> - </HStack> - <Grid templateColumns="120px 1fr" rowGap={ 2 }> - <Text as="span" color="text.secondary">Source tx</Text> - <InteropMessageSourceTx { ...item } isLoading={ isLoading }/> - <Text as="span" color="text.secondary">Destination tx</Text> - <InteropMessageDestinationTx { ...item } isLoading={ isLoading }/> - </Grid> - <Flex gap={ 2 } justifyContent="space-between" mt={ 2 }> - { item.init_chain !== undefined ? ( - <AddressEntityInterop - chain={ item.init_chain } - address={{ hash: item.sender_address_hash }} - isLoading={ isLoading } - truncation="constant" - /> - ) : ( - <AddressEntity address={{ hash: item.sender_address_hash }} isLoading={ isLoading } truncation="constant"/> - ) } - <AddressFromToIcon - isLoading={ isLoading } - type={ item.init_chain !== undefined ? 'in' : 'out' } - /> - { item.relay_chain !== undefined ? ( - <AddressEntityInterop - chain={ item.relay_chain } - address={{ hash: item.target_address_hash }} - isLoading={ isLoading } - truncation="constant" - /> - ) : ( - <AddressEntity address={{ hash: item.target_address_hash }} isLoading={ isLoading } truncation="constant"/> - ) } - </Flex> - </Flex> - </ListItemMobile> - ); -}; - -export default React.memo(InteropMessagesListItem); diff --git a/src/features/op-interop/pages/messages/InteropMessagesTable.tsx b/src/features/op-interop/pages/messages/InteropMessagesTable.tsx index 01c4d1a5fac..6d0a17db3c9 100644 --- a/src/features/op-interop/pages/messages/InteropMessagesTable.tsx +++ b/src/features/op-interop/pages/messages/InteropMessagesTable.tsx @@ -5,6 +5,7 @@ import React from 'react'; import type { InteropMessage } from 'src/features/op-interop/types/api'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -16,9 +17,13 @@ interface Props { isLoading?: boolean; } +const getBaseKey = (item: InteropMessage): string => item.init_transaction_hash + '_' + item.nonce; + const InteropMessagesTable = ({ items, top, isLoading }: Props) => { + const keys = useUniqueKeys(items, getBaseKey); + return ( - <TableRoot tableLayout="auto"> + <TableRoot tableLayout="auto" minW="1200px"> <TableHeaderSticky top={ top }> <TableRow> <TableColumnHeader/> @@ -38,7 +43,7 @@ const InteropMessagesTable = ({ items, top, isLoading }: Props) => { <TableBody> { items?.map((item, index) => ( <InteropMessagesTableItem - key={ item.init_transaction_hash + '_' + index } + key={ keys[index] } item={ item } isLoading={ isLoading } /> diff --git a/src/features/op-interop/pages/messages/__screenshots__/InteropMessages.pw.tsx_default_default-view-1.png b/src/features/op-interop/pages/messages/__screenshots__/InteropMessages.pw.tsx_default_default-view-1.png index 2905cad77c2..1415b43db9b 100644 Binary files a/src/features/op-interop/pages/messages/__screenshots__/InteropMessages.pw.tsx_default_default-view-1.png and b/src/features/op-interop/pages/messages/__screenshots__/InteropMessages.pw.tsx_default_default-view-1.png differ diff --git a/src/features/op-interop/pages/messages/__screenshots__/InteropMessages.pw.tsx_default_mobile-default-view-1.png b/src/features/op-interop/pages/messages/__screenshots__/InteropMessages.pw.tsx_default_mobile-default-view-1.png deleted file mode 100644 index 029cce8a045..00000000000 Binary files a/src/features/op-interop/pages/messages/__screenshots__/InteropMessages.pw.tsx_default_mobile-default-view-1.png and /dev/null differ diff --git a/src/features/rewards/components/NavLinkRewards.tsx b/src/features/rewards/components/NavLinkRewards.tsx index b8a888a8f2f..5dbf8c58295 100644 --- a/src/features/rewards/components/NavLinkRewards.tsx +++ b/src/features/rewards/components/NavLinkRewards.tsx @@ -1,7 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; -import type { Route } from 'nextjs-routes'; import React, { useCallback } from 'react'; import NavLink from 'src/shell/navigation/vertical/NavLink'; @@ -9,6 +7,8 @@ import NavLink from 'src/shell/navigation/vertical/NavLink'; import { useRewardsContext } from 'src/features/rewards/context'; import config from 'src/config'; +import type { Route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; type Props = { isCollapsed?: boolean; diff --git a/src/features/rewards/components/RewardsActivityTracker.ts b/src/features/rewards/components/RewardsActivityTracker.ts new file mode 100644 index 00000000000..eeb3ee87272 --- /dev/null +++ b/src/features/rewards/components/RewardsActivityTracker.ts @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { useEffect } from 'react'; + +import useRewardsActivity from 'src/features/rewards/hooks/useRewardsActivity'; + +import { useRouter } from 'src/shared/router/useRouter'; + +const RewardsActivityTracker = () => { + const router = useRouter(); + const { trackUsage } = useRewardsActivity(); + + useEffect(() => { + trackUsage('explore'); + }, [ router.pathname, router.query, trackUsage ]); + + return null; +}; + +export default RewardsActivityTracker; diff --git a/src/features/rewards/components/RewardsActivityTracker.tsx b/src/features/rewards/components/RewardsActivityTracker.tsx deleted file mode 100644 index a7dc5d12a5d..00000000000 --- a/src/features/rewards/components/RewardsActivityTracker.tsx +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useRouter } from 'next/router'; -import { useEffect } from 'react'; - -import useRewardsActivity from 'src/features/rewards/hooks/useRewardsActivity'; - -const RewardsActivityTracker = () => { - const router = useRouter(); - const { trackUsage } = useRewardsActivity(); - - useEffect(() => { - trackUsage('explore'); - }, [ router.pathname, router.query, trackUsage ]); - - return null; -}; - -export default RewardsActivityTracker; diff --git a/src/features/rewards/components/RewardsButton.tsx b/src/features/rewards/components/RewardsButton.tsx index dd637243a7d..9e70774ed14 100644 --- a/src/features/rewards/components/RewardsButton.tsx +++ b/src/features/rewards/components/RewardsButton.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React, { useCallback } from 'react'; import { useRewardsContext } from 'src/features/rewards/context'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import type { ButtonProps } from 'src/toolkit/chakra/button'; diff --git a/src/features/rewards/components/login/RewardsLoginModal.tsx b/src/features/rewards/components/login/RewardsLoginModal.tsx index 7cd8c40405b..a720b2af621 100644 --- a/src/features/rewards/components/login/RewardsLoginModal.tsx +++ b/src/features/rewards/components/login/RewardsLoginModal.tsx @@ -14,7 +14,7 @@ import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; import CongratsStepContent from './steps/CongratsStepContent'; import LoginStepContent from './steps/LoginStepContent'; -const MIXPANEL_CONFIG = { +const ANALYTICS_CONFIG = { account_link_info: { source: 'Merits' as const, }, @@ -91,7 +91,7 @@ const RewardsLoginModal = () => { <AuthModal onClose={ handleAuthModalClose } initialScreen={ authModalInitialScreen } - mixpanelConfig={ MIXPANEL_CONFIG } + analyticsConfig={ ANALYTICS_CONFIG } closeOnError /> ) } diff --git a/src/features/rewards/components/login/steps/CongratsStepContent.tsx b/src/features/rewards/components/login/steps/CongratsStepContent.tsx index 68f3dde357c..8775bdb67c0 100644 --- a/src/features/rewards/components/login/steps/CongratsStepContent.tsx +++ b/src/features/rewards/components/login/steps/CongratsStepContent.tsx @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Text, Box, Flex, Center } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import { useRewardsContext } from 'src/features/rewards/context'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; diff --git a/src/features/rewards/components/login/steps/LoginStepContent.tsx b/src/features/rewards/components/login/steps/LoginStepContent.tsx index 56468dfa3a1..4594b0e7e9d 100644 --- a/src/features/rewards/components/login/steps/LoginStepContent.tsx +++ b/src/features/rewards/components/login/steps/LoginStepContent.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Text, Box, Flex, Separator } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import type { ChangeEvent } from 'react'; import React from 'react'; @@ -9,6 +8,7 @@ import useProfileQuery from 'src/features/account/hooks/useProfileQuery'; import useWallet from 'src/features/connect-wallet/hooks/useWallet'; import { useRewardsContext } from 'src/features/rewards/context'; +import { useRouter } from 'src/shared/router/useRouter'; import * as cookies from 'src/shared/storage/cookies'; import { Alert } from 'src/toolkit/chakra/alert'; @@ -70,7 +70,7 @@ const LoginStepContent = ({ goNext, closeModal, openAuthModal }: Props) => { goNext(isRefCodeUsed, reward); } else { closeModal(); - router.push({ pathname: '/account/merits' }, undefined, { shallow: true }); + router.push({ pathname: '/account/merits' }, { shallow: true }); } } } catch (error) {} diff --git a/src/features/rewards/context.tsx b/src/features/rewards/context.tsx index 6a283e08251..c0d227ecac0 100644 --- a/src/features/rewards/context.tsx +++ b/src/features/rewards/context.tsx @@ -2,7 +2,6 @@ import { useQueryClient, type UseQueryResult } from '@tanstack/react-query'; import { useToggle } from '@uidotdev/usehooks'; -import { useRouter } from 'next/router'; import React, { createContext, useContext, useEffect, useMemo, useCallback, useState } from 'react'; import type * as rewards from '@blockscout/points-types'; @@ -21,6 +20,7 @@ import getErrorMessage from 'src/shared/errors/get-error-message'; import getErrorObjPayload from 'src/shared/errors/get-error-obj-payload'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import removeQueryParam from 'src/shared/router/remove-query-param'; +import { useRouter } from 'src/shared/router/useRouter'; import * as cookies from 'src/shared/storage/cookies'; import { toaster } from 'src/toolkit/chakra/toaster'; diff --git a/src/features/rewards/mocks/activity-pass.ts b/src/features/rewards/mocks/activity-pass.ts new file mode 100644 index 00000000000..62105e5327c --- /dev/null +++ b/src/features/rewards/mocks/activity-pass.ts @@ -0,0 +1,11 @@ +import type { CheckActivityPassResponse } from '@blockscout/points-types'; + +export const valid: CheckActivityPassResponse = { + is_valid: true, + activity_pass: { + offer_id: '1', + details: undefined, + valid_since: '2022-11-01T00:00:00.000Z', + valid_until: '2023-11-01T00:00:00.000Z', + }, +}; diff --git a/src/features/rewards/mocks/instances.ts b/src/features/rewards/mocks/instances.ts new file mode 100644 index 00000000000..ff3edd50389 --- /dev/null +++ b/src/features/rewards/mocks/instances.ts @@ -0,0 +1,18 @@ +import type { GetInstancesResponse } from '@blockscout/points-types'; + +export const base: GetInstancesResponse = { + items: [ + { + chain_id: '1', + name: 'Ethereum', + domain: 'eth.blockscout.com', + details: undefined, + }, + { + chain_id: '100', + name: 'Gnosis', + domain: 'gnosis.blockscout.com', + details: undefined, + }, + ], +}; diff --git a/src/features/rewards/pages/dashboard/RewardsDashboard.pw.tsx b/src/features/rewards/pages/dashboard/RewardsDashboard.pw.tsx index 3e6efc9119b..9beea5f2ccc 100644 --- a/src/features/rewards/pages/dashboard/RewardsDashboard.pw.tsx +++ b/src/features/rewards/pages/dashboard/RewardsDashboard.pw.tsx @@ -3,10 +3,13 @@ import React from 'react'; import * as profileMock from 'src/features/account/mocks/user-profile'; import * as activityMock from 'src/features/rewards/mocks/activity'; +import * as activityPassMock from 'src/features/rewards/mocks/activity-pass'; import * as rewardsBalanceMock from 'src/features/rewards/mocks/balance'; import * as dailyRewardMock from 'src/features/rewards/mocks/daily-reward'; +import * as instancesMock from 'src/features/rewards/mocks/instances'; import * as referralsMock from 'src/features/rewards/mocks/referrals'; import * as rewardsConfigMock from 'src/features/rewards/mocks/rewards-config'; +import * as streakBadgesMock from 'src/features/rewards/mocks/streak-badges'; import { contextWithAuth } from 'playwright/fixtures/auth'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; @@ -34,6 +37,11 @@ const testTab = (tab: 'activity' | 'referrals' | 'resources') => await mockApiResponse('rewards:user_referrals', referralsMock.base); await mockApiResponse('rewards:config', rewardsConfigMock.base); await mockApiResponse('rewards:user_activity', activityMock.base); + await mockApiResponse('rewards:user_badges', streakBadgesMock.base); + await mockApiResponse('rewards:instances', instancesMock.base); + await mockApiResponse('rewards:user_check_activity_pass', activityPassMock.valid, { + queryParams: { address: profileMock.withEmailAndWallet.address_hash }, + }); const component = await render(<RewardsDashboard/>, { hooksConfig: { router: { query: { tab } } } }); @@ -49,7 +57,20 @@ testTab('activity'); testTab('referrals'); testTab('resources'); -testWithAuth('with error', async({ page, render }) => { +testWithAuth('with error', async({ page, render, mockApiResponse }) => { + const failed = { status: 500 }; + await mockApiResponse('rewards:user_balances', null as never, failed); + await mockApiResponse('rewards:user_daily_check', null as never, failed); + await mockApiResponse('rewards:user_referrals', null as never, failed); + await mockApiResponse('rewards:config', null as never, failed); + await mockApiResponse('rewards:user_activity', null as never, failed); + await mockApiResponse('rewards:user_badges', null as never, failed); + await mockApiResponse('rewards:instances', null as never, failed); + await mockApiResponse('rewards:user_check_activity_pass', null as never, { + ...failed, + queryParams: { address: profileMock.withEmailAndWallet.address_hash }, + }); + const component = await render(<RewardsDashboard/>); await expect(component).toHaveScreenshot({ diff --git a/src/features/rewards/pages/dashboard/RewardsDashboardCard.tsx b/src/features/rewards/pages/dashboard/RewardsDashboardCard.tsx index 55d8e78405b..061039131a6 100644 --- a/src/features/rewards/pages/dashboard/RewardsDashboardCard.tsx +++ b/src/features/rewards/pages/dashboard/RewardsDashboardCard.tsx @@ -52,7 +52,7 @@ const RewardsDashboardCard = ({ { title && ( <Flex alignItems="center" gap={ 2 }> <Heading level="3">{ title }</Heading> - { hint && <Hint label={ hint } tooltipProps={{ interactive: true }}/> } + { Boolean(hint) && <Hint label={ hint } tooltipProps={{ interactive: true }}/> } { availableSoon && <Badge colorPalette="blue">Available soon</Badge> } </Flex> ) } diff --git a/src/features/rewards/pages/dashboard/RewardsDashboardCardValue.tsx b/src/features/rewards/pages/dashboard/RewardsDashboardCardValue.tsx index b2b44abf850..be7349bb056 100644 --- a/src/features/rewards/pages/dashboard/RewardsDashboardCardValue.tsx +++ b/src/features/rewards/pages/dashboard/RewardsDashboardCardValue.tsx @@ -23,7 +23,7 @@ const RewardsDashboardCardValue = ({ label, value, withIcon, hint, isLoading, bo <Flex key={ label } flexDirection="column" alignItems="center" gap={{ base: 1, md: 2 }}> { label && ( <Flex alignItems="center" gap={ 1 }> - { hint && <Hint label={ hint }/> } + { Boolean(hint) && <Hint label={ hint }/> } <Text textStyle="xs" fontWeight="500" color="text.secondary"> { label } </Text> diff --git a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_activity-tab-dark-mode-mobile-1.png b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_activity-tab-dark-mode-mobile-1.png index 18e6ddd16c0..b6c173d4d3f 100644 Binary files a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_activity-tab-dark-mode-mobile-1.png and b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_activity-tab-dark-mode-mobile-1.png differ diff --git a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_referrals-tab-dark-mode-mobile-1.png b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_referrals-tab-dark-mode-mobile-1.png index 62c06bcb365..8773a66e32a 100644 Binary files a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_referrals-tab-dark-mode-mobile-1.png and b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_referrals-tab-dark-mode-mobile-1.png differ diff --git a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_resources-tab-dark-mode-mobile-1.png b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_resources-tab-dark-mode-mobile-1.png index 8d273a72e72..8f33a4d3592 100644 Binary files a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_resources-tab-dark-mode-mobile-1.png and b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_dark-color-mode_resources-tab-dark-mode-mobile-1.png differ diff --git a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_activity-tab-dark-mode-mobile-1.png b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_activity-tab-dark-mode-mobile-1.png index 1f904776e5d..ee153335438 100644 Binary files a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_activity-tab-dark-mode-mobile-1.png and b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_activity-tab-dark-mode-mobile-1.png differ diff --git a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_referrals-tab-dark-mode-mobile-1.png b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_referrals-tab-dark-mode-mobile-1.png index 5cd89cb7ec8..2b770463ad5 100644 Binary files a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_referrals-tab-dark-mode-mobile-1.png and b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_referrals-tab-dark-mode-mobile-1.png differ diff --git a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_resources-tab-dark-mode-mobile-1.png b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_resources-tab-dark-mode-mobile-1.png index 25919f67854..f78f78e4a25 100644 Binary files a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_resources-tab-dark-mode-mobile-1.png and b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_resources-tab-dark-mode-mobile-1.png differ diff --git a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_with-error-1.png b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_with-error-1.png index 8a2e1efc74a..4e24eca239d 100644 Binary files a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_with-error-1.png and b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_default_with-error-1.png differ diff --git a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_activity-tab-dark-mode-mobile-1.png b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_activity-tab-dark-mode-mobile-1.png index 5940304976a..6a8525bfd8e 100644 Binary files a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_activity-tab-dark-mode-mobile-1.png and b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_activity-tab-dark-mode-mobile-1.png differ diff --git a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_referrals-tab-dark-mode-mobile-1.png b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_referrals-tab-dark-mode-mobile-1.png index 7c4d7924a20..b8ee24a2258 100644 Binary files a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_referrals-tab-dark-mode-mobile-1.png and b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_referrals-tab-dark-mode-mobile-1.png differ diff --git a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_resources-tab-dark-mode-mobile-1.png b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_resources-tab-dark-mode-mobile-1.png index 1271bfa9c0e..efa74c23da5 100644 Binary files a/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_resources-tab-dark-mode-mobile-1.png and b/src/features/rewards/pages/dashboard/__screenshots__/RewardsDashboard.pw.tsx_mobile_resources-tab-dark-mode-mobile-1.png differ diff --git a/src/features/rewards/pages/dashboard/tabs/ActivityTab.tsx b/src/features/rewards/pages/dashboard/tabs/ActivityTab.tsx index ce9f8da2275..1666757cb9a 100644 --- a/src/features/rewards/pages/dashboard/tabs/ActivityTab.tsx +++ b/src/features/rewards/pages/dashboard/tabs/ActivityTab.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex, Text, chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import { useCallback, useMemo, useState } from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -14,6 +13,7 @@ import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; import dayjs from 'src/shared/date-and-time/dayjs'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; @@ -360,7 +360,7 @@ export default function ActivityTab() { <Text textStyle="xs" color="text.secondary" fontWeight="500"> Metrics are not updated in real time. Please allow up to one hour for your Performance Rank and earned Merits to reflect recent activity. If you experience any issues, feel free to reach out on{ ' ' } - <Link external href="https://discord.gg/blockscout"> + <Link external href="https://discord.gg/3yAWj8TXV2"> Discord </Link> </Text> diff --git a/src/features/rollup/arbitrum/components/ArbitrumL2Messages.tsx b/src/features/rollup/arbitrum/components/ArbitrumL2Messages.tsx index c6459b9d79e..f4c81ecc235 100644 --- a/src/features/rollup/arbitrum/components/ArbitrumL2Messages.tsx +++ b/src/features/rollup/arbitrum/components/ArbitrumL2Messages.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -12,14 +11,14 @@ import { layerLabels } from 'src/features/rollup/common/utils/layer'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { rightLineArrow, nbsp } from 'src/toolkit/utils/htmlEntities'; import { ARBITRUM_MESSAGES_ITEM } from '../stubs'; -import ArbitrumL2MessagesList from './ArbitrumL2MessagesList'; import ArbitrumL2MessagesTable from './ArbitrumL2MessagesTable'; export type MessagesDirection = 'from-rollup' | 'to-rollup'; @@ -30,7 +29,7 @@ interface Props { const ArbitrumL2Messages = ({ direction }: Props) => { const type = direction === 'from-rollup' ? 'withdrawals' : 'deposits'; - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:arbitrum_l2_messages', pathParams: { direction }, options: { @@ -50,25 +49,15 @@ const ArbitrumL2Messages = ({ direction }: Props) => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <ArbitrumL2MessagesList - items={ data.items } - direction={ direction } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - <Box hideBelow="lg"> - <ArbitrumL2MessagesTable - items={ data.items } - direction={ direction } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <ArbitrumL2MessagesTable + items={ data.items } + direction={ direction } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -101,6 +90,7 @@ const ArbitrumL2Messages = ({ direction }: Props) => { itemsNum={ data?.items.length } emptyText={ `There are no ${ type }.` } actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/arbitrum/components/ArbitrumL2MessagesList.tsx b/src/features/rollup/arbitrum/components/ArbitrumL2MessagesList.tsx deleted file mode 100644 index b16825a2b72..00000000000 --- a/src/features/rollup/arbitrum/components/ArbitrumL2MessagesList.tsx +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import type { MessagesDirection } from './ArbitrumL2Messages'; -import ArbitrumL2MessagesListItem from './ArbitrumL2MessagesListItem'; - -type Props = { - items: Array<schemas['ArbitrumMessage']>; - direction: MessagesDirection; - isLoading?: boolean; - resetKey?: string; -}; - -const ArbitrumL2MessagesList = ({ items, direction, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <ArbitrumL2MessagesListItem - key={ String(item.id) + (isLoading ? index : '') } - isLoading={ isLoading } - item={ item } - direction={ direction } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default ArbitrumL2MessagesList; diff --git a/src/features/rollup/arbitrum/components/ArbitrumL2MessagesListItem.tsx b/src/features/rollup/arbitrum/components/ArbitrumL2MessagesListItem.tsx deleted file mode 100644 index 8658a5b7ef1..00000000000 --- a/src/features/rollup/arbitrum/components/ArbitrumL2MessagesListItem.tsx +++ /dev/null @@ -1,132 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import BlockEntityL1 from 'src/features/rollup/common/components/BlockEntityL1'; -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -import type { MessagesDirection } from './ArbitrumL2Messages'; -import ArbitrumL2MessageStatus from './ArbitrumL2MessageStatus'; - -const rollupFeature = config.features.rollup; - -type Props = { item: schemas['ArbitrumMessage']; isLoading?: boolean; direction: MessagesDirection }; - -const ArbitrumL2MessagesListItem = ({ item, isLoading, direction }: Props) => { - if (!rollupFeature.isEnabled || rollupFeature.type !== 'arbitrum') { - return null; - } - - const l1TxHash = direction === 'from-rollup' ? item.completion_transaction_hash : item.origination_transaction_hash; - const l2TxHash = direction === 'from-rollup' ? item.origination_transaction_hash : item.completion_transaction_hash; - - return ( - <ListItemMobileGrid.Container gridTemplateColumns="110px auto"> - - { direction === 'to-rollup' && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } block</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { item.origination_transaction_block_number ? ( - <BlockEntityL1 - number={ item.origination_transaction_block_number } - isLoading={ isLoading } - fontWeight={ 600 } - /> - ) : <chakra.span>N/A</chakra.span> } - </ListItemMobileGrid.Value> - </> - ) } - - { direction === 'from-rollup' && item.origination_address_hash && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>From</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity - address={{ hash: item.origination_address_hash }} - truncation="constant" - isLoading={ isLoading } - fontWeight={ 600 } - /> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Message #</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block"> - { item.id } - </Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } transaction</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { l2TxHash ? ( - <TxEntity - isLoading={ isLoading } - hash={ l2TxHash } - truncation="constant_long" - /> - ) : ( - <chakra.span> - N/A - </chakra.span> - ) } - </ListItemMobileGrid.Value> - - { item.origination_timestamp && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.origination_timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { item.status === 'confirmed' && direction === 'from-rollup' && item.origination_transaction_hash ? - <Link href={ route({ pathname: '/txn-withdrawals', query: { q: item.origination_transaction_hash } }) }>Ready for relay</Link> : - <ArbitrumL2MessageStatus status={ item.status } isLoading={ isLoading }/> } - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } transaction</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { l1TxHash ? ( - <TxEntityL1 - isLoading={ isLoading } - hash={ l1TxHash } - truncation="constant_long" - noCopy - /> - ) : ( - <chakra.span> - N/A - </chakra.span> - ) } - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default ArbitrumL2MessagesListItem; diff --git a/src/features/rollup/arbitrum/components/ArbitrumL2MessagesTable.tsx b/src/features/rollup/arbitrum/components/ArbitrumL2MessagesTable.tsx index cd29c73cdd7..0b1678fd00b 100644 --- a/src/features/rollup/arbitrum/components/ArbitrumL2MessagesTable.tsx +++ b/src/features/rollup/arbitrum/components/ArbitrumL2MessagesTable.tsx @@ -7,6 +7,7 @@ import type { schemas } from '@blockscout/api-types'; import { layerLabels } from 'src/features/rollup/common/utils/layer'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -22,8 +23,11 @@ type Props = { resetKey?: string; }; +const getBaseKey = (item: schemas['ArbitrumMessage']): string => String(item.id); + const ArbitrumL2MessagesTable = ({ items, direction, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( <TableRoot tableLayout="auto" minW="950px"> @@ -44,7 +48,7 @@ const ArbitrumL2MessagesTable = ({ items, direction, top, isLoading, resetKey }: <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( <ArbitrumL2MessagesTableItem - key={ String(item.id) + (isLoading ? index : '') } + key={ keys[index] } item={ item } direction={ direction } isLoading={ isLoading } diff --git a/src/features/rollup/arbitrum/components/ArbitrumL2MessagesTableItem.tsx b/src/features/rollup/arbitrum/components/ArbitrumL2MessagesTableItem.tsx index eb915ac0b48..c9cc38a0901 100644 --- a/src/features/rollup/arbitrum/components/ArbitrumL2MessagesTableItem.tsx +++ b/src/features/rollup/arbitrum/components/ArbitrumL2MessagesTableItem.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -14,6 +13,7 @@ import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; import config from 'src/config'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; diff --git a/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatch.tsx b/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatch.tsx index f3e393f5fb9..d2c065c626b 100644 --- a/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatch.tsx +++ b/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatch.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -18,9 +17,10 @@ import throwOnAbsentParamError from 'src/shared/errors/throw-on-absent-param-err import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -45,7 +45,7 @@ const ArbitrumL2TxnBatch = () => { const batchQuery = useBatchQuery(); - const batchTxsQuery = useQueryWithPages({ + const batchTxsQuery = useApiPaginatedQuery({ resourceName: 'core:arbitrum_l2_txn_batch_txs', pathParams: { number: String(batchQuery.data?.number) }, options: { @@ -59,7 +59,7 @@ const ArbitrumL2TxnBatch = () => { }, }); - const batchBlocksQuery = useQueryWithPages({ + const batchBlocksQuery = useApiPaginatedQuery({ resourceName: 'core:arbitrum_l2_txn_batch_blocks', pathParams: { number: String(batchQuery.data?.number) }, options: { diff --git a/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetails.tsx b/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetails.tsx index 90ae0e28326..7ea8bbb781a 100644 --- a/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetails.tsx +++ b/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetails.tsx @@ -2,8 +2,6 @@ import { GridItem } from '@chakra-ui/react'; import type { UseQueryResult } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -20,12 +18,14 @@ import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import DetailedInfoTimestamp from 'src/shared/detailed-info/DetailedInfoTimestamp'; import isCustomAppError from 'src/shared/errors/is-custom-app-error'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; +import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import { CollapsibleDetails } from 'src/toolkit/chakra/collapsible'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import ArbitrumL2TxnBatchDA from '../../components/ArbitrumL2TxnBatchDA'; import ArbitrumL2TxnBatchDetailsAnyTrustDA from './ArbitrumL2TxnBatchDetailsAnyTrustDA'; @@ -48,7 +48,7 @@ const ArbitrumL2TxnBatchDetails = ({ query }: Props) => { const increment = direction === 'next' ? +1 : -1; const nextId = String(data.number + increment); - router.push({ pathname: '/batches/[number]', query: { number: nextId } }, undefined); + router.push({ pathname: '/batches/[number]', query: { number: nextId } }); }, [ data, router ]); if (isError) { @@ -145,7 +145,7 @@ const ArbitrumL2TxnBatchDetails = ({ query }: Props) => { </> ) } - { data.commitment_transaction.block_number && ( + { data.commitment_transaction.block_number !== null && ( <> <DetailedInfo.ItemLabel isLoading={ isPlaceholderData } @@ -183,7 +183,7 @@ const ArbitrumL2TxnBatchDetails = ({ query }: Props) => { </DetailedInfo.ItemLabel> <DetailedInfo.ItemValue flexWrap="nowrap" > <Skeleton loading={ isPlaceholderData } overflow="hidden"> - <HashStringShortenDynamic hash={ data.before_acc_hash }/> + <Truncate value={ data.before_acc_hash }/> </Skeleton> <CopyToClipboard text={ data.before_acc_hash } isLoading={ isPlaceholderData }/> </DetailedInfo.ItemValue> @@ -196,7 +196,7 @@ const ArbitrumL2TxnBatchDetails = ({ query }: Props) => { </DetailedInfo.ItemLabel> <DetailedInfo.ItemValue flexWrap="nowrap"> <Skeleton loading={ isPlaceholderData } overflow="hidden"> - <HashStringShortenDynamic hash={ data.after_acc_hash }/> + <Truncate value={ data.after_acc_hash }/> </Skeleton> <CopyToClipboard text={ data.after_acc_hash } isLoading={ isPlaceholderData }/> </DetailedInfo.ItemValue> diff --git a/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetailsAnyTrustDA.tsx b/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetailsAnyTrustDA.tsx index b8dac2f1caf..c44c2c8a1ca 100644 --- a/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetailsAnyTrustDA.tsx +++ b/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetailsAnyTrustDA.tsx @@ -9,10 +9,11 @@ import dayjs from 'src/shared/date-and-time/dayjs'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import DetailsTimestamp from 'src/shared/detailed-info/DetailedInfoTimestamp'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShorten from 'src/shared/texts/HashStringShorten'; import TextSeparator from 'src/shared/texts/TextSeparator'; import SpriteIcon from 'src/sprite/SpriteIcon'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; + type Props = { data: schemas['ArbitrumDataAvailabilityAnytrust']; }; @@ -90,7 +91,7 @@ const ArbitrumL2TxnBatchDetailsAnyTrustDA = ({ data }: Props) => { </Box> { signer.proof ? ( <Flex> - <HashStringShorten hash={ signer.proof }/> + <Truncate value={ signer.proof } type="middle-static"/> <CopyToClipboard text={ signer.proof } ml={ 2 }/> </Flex> ) : '-' } @@ -115,7 +116,7 @@ const ArbitrumL2TxnBatchDetailsAnyTrustDA = ({ data }: Props) => { <Text fontWeight={ 600 } mr={ 2 }>Proof</Text> { signer.proof ? ( <Flex> - <HashStringShorten hash={ signer.proof }/> + <Truncate value={ signer.proof } type="middle-static"/> <CopyToClipboard text={ signer.proof } ml={ 2 }/> </Flex> ) : '-' } diff --git a/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetailsCelestiaDA.tsx b/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetailsCelestiaDA.tsx index 45c6278263f..78265a07ee1 100644 --- a/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetailsCelestiaDA.tsx +++ b/src/features/rollup/arbitrum/pages/batch-details/ArbitrumL2TxnBatchDetailsCelestiaDA.tsx @@ -10,7 +10,8 @@ import CeleniumLink from 'src/features/rollup/common/components/CeleniumLink'; import config from 'src/config'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; + +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const feature = config.features.rollup; @@ -39,10 +40,10 @@ const ArbitrumL2TxnBatchDetailsCelestiaDA = ({ data }: Props) => { </DetailedInfo.ItemLabel> <DetailedInfo.ItemValue flexWrap="nowrap"> <Flex overflow="hidden" minW="0"> - <HashStringShortenDynamic hash={ data.transaction_commitment }/> + <Truncate value={ data.transaction_commitment }/> </Flex> <CopyToClipboard text={ data.transaction_commitment } mr={ 3 }/> - { feature.isEnabled && feature.DA.celestia.namespace && data.height && ( + { feature.isEnabled && feature.DA.celestia.namespace && data.height !== null && ( <CeleniumLink commitment={ data.transaction_commitment } namespace={ feature.DA.celestia.namespace } diff --git a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_base-view-1.png b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_base-view-1.png index 6f38043cdbf..abe57c3a333 100644 Binary files a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_base-view-1.png and b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-base-view-1.png b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-base-view-1.png index 778aa94d109..0d3e6d5b07a 100644 Binary files a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-base-view-1.png and b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-base-view-1.png differ diff --git a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-with-anytrust-DA-1.png b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-with-anytrust-DA-1.png index edda176bddb..4b02ebdc473 100644 Binary files a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-with-anytrust-DA-1.png and b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-with-anytrust-DA-1.png differ diff --git a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-with-celestia-DA-1.png b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-with-celestia-DA-1.png index a5b9c7ab3c6..0f51ddf1b87 100644 Binary files a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-with-celestia-DA-1.png and b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_mobile-with-celestia-DA-1.png differ diff --git a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_with-anytrust-DA-1.png b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_with-anytrust-DA-1.png index e505c8f56ee..69a9d1b3d2e 100644 Binary files a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_with-anytrust-DA-1.png and b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_with-anytrust-DA-1.png differ diff --git a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_with-celestia-DA-1.png b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_with-celestia-DA-1.png index 39a60c6221c..d1314d36941 100644 Binary files a/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_with-celestia-DA-1.png and b/src/features/rollup/arbitrum/pages/batch-details/__screenshots__/ArbitrumL2TxnBatch.pw.tsx_default_with-celestia-DA-1.png differ diff --git a/src/features/rollup/arbitrum/pages/batch-details/useBatchQuery.ts b/src/features/rollup/arbitrum/pages/batch-details/useBatchQuery.ts new file mode 100644 index 00000000000..8f805905b13 --- /dev/null +++ b/src/features/rollup/arbitrum/pages/batch-details/useBatchQuery.ts @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import useApiQuery from 'src/api/hooks/useApiQuery'; + +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; + +import { ARBITRUM_L2_TXN_BATCH, ARBITRUM_L2_TXN_BATCH_CELESTIA } from '../../stubs'; + +export default function useBatchQuery() { + const router = useRouter(); + const number = getQueryParamString(router.query.number); + const height = getQueryParamString(router.query.height); + const commitment = getQueryParamString(router.query.commitment); + + const batchByNumberQuery = useApiQuery('core:arbitrum_l2_txn_batch', { + pathParams: { number }, + queryOptions: { + enabled: Boolean(number), + placeholderData: ARBITRUM_L2_TXN_BATCH, + }, + }); + + const batchByHeightQuery = useApiQuery('core:arbitrum_l2_txn_batch_celestia', { + pathParams: { height, commitment }, + queryOptions: { + enabled: Boolean(height && commitment), + placeholderData: ARBITRUM_L2_TXN_BATCH_CELESTIA, + }, + }); + + return number ? batchByNumberQuery : batchByHeightQuery; +} diff --git a/src/features/rollup/arbitrum/pages/batch-details/useBatchQuery.tsx b/src/features/rollup/arbitrum/pages/batch-details/useBatchQuery.tsx deleted file mode 100644 index 8c7fcec7864..00000000000 --- a/src/features/rollup/arbitrum/pages/batch-details/useBatchQuery.tsx +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useRouter } from 'next/router'; - -import useApiQuery from 'src/api/hooks/useApiQuery'; - -import getQueryParamString from 'src/shared/router/get-query-param-string'; - -import { ARBITRUM_L2_TXN_BATCH, ARBITRUM_L2_TXN_BATCH_CELESTIA } from '../../stubs'; - -export default function useBatchQuery() { - const router = useRouter(); - const number = getQueryParamString(router.query.number); - const height = getQueryParamString(router.query.height); - const commitment = getQueryParamString(router.query.commitment); - - const batchByNumberQuery = useApiQuery('core:arbitrum_l2_txn_batch', { - pathParams: { number }, - queryOptions: { - enabled: Boolean(number), - placeholderData: ARBITRUM_L2_TXN_BATCH, - }, - }); - - const batchByHeightQuery = useApiQuery('core:arbitrum_l2_txn_batch_celestia', { - pathParams: { height, commitment }, - queryOptions: { - enabled: Boolean(height && commitment), - placeholderData: ARBITRUM_L2_TXN_BATCH_CELESTIA, - }, - }); - - return number ? batchByNumberQuery : batchByHeightQuery; -} diff --git a/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatches.pw.tsx b/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatches.pw.tsx index 03b9268b114..037d740f115 100644 --- a/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatches.pw.tsx +++ b/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatches.pw.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; -import { test, expect, devices } from 'playwright/lib'; +import { test, expect } from 'playwright/lib'; import * as arbitrumTxnBatchesMock from '../../mocks/txn-batches'; import ArbitrumL2TxnBatches from './ArbitrumL2TxnBatches'; @@ -16,17 +16,3 @@ test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { const component = await render(<ArbitrumL2TxnBatches/>); await expect(component).toHaveScreenshot(); }); - -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { - test.slow(); - await mockEnvs(ENVS_MAP.arbitrumRollup); - await mockTextAd(); - await mockApiResponse('core:arbitrum_l2_txn_batches', arbitrumTxnBatchesMock.baseResponse); - await mockApiResponse('core:arbitrum_l2_txn_batches_count', 9927); - - const component = await render(<ArbitrumL2TxnBatches/>); - await expect(component).toHaveScreenshot(); - }); -}); diff --git a/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatches.tsx b/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatches.tsx index 3d5670b6545..7cc4e475e91 100644 --- a/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatches.tsx +++ b/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatches.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Text } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -10,17 +10,17 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { ARBITRUM_L2_TXN_BATCHES_ITEM } from '../../stubs'; -import ArbitrumL2TxnBatchesList from './ArbitrumL2TxnBatchesList'; import ArbitrumL2TxnBatchesTable from './ArbitrumL2TxnBatchesTable'; const ArbitrumL2TxnBatches = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:arbitrum_l2_txn_batches', options: { placeholderData: generateListStub<'core:arbitrum_l2_txn_batches'>( @@ -43,19 +43,14 @@ const ArbitrumL2TxnBatches = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <ArbitrumL2TxnBatchesList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <ArbitrumL2TxnBatchesTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <ArbitrumL2TxnBatchesTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -64,7 +59,7 @@ const ArbitrumL2TxnBatches = () => { } return ( - <Skeleton loading={ countersQuery.isPlaceholderData || isPlaceholderData } display="flex" flexWrap="wrap"> + <Skeleton loading={ countersQuery.isPlaceholderData || isInitialLoading } display="flex" flexWrap="wrap"> Txn batch <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[0].number } </Text>to <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[data.items.length - 1].number } </Text> @@ -83,6 +78,7 @@ const ArbitrumL2TxnBatches = () => { itemsNum={ data?.items.length } emptyText="There are no txn batches." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatchesList.tsx b/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatchesList.tsx deleted file mode 100644 index beadbd33fdc..00000000000 --- a/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatchesList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ArbitrumL2TxnBatchesListItem from './ArbitrumL2TxnBatchesListItem'; - -type Props = { - items: Array<schemas['ArbitrumBatchForList']>; - isLoading?: boolean; - resetKey?: string; -}; - -const ArbitrumL2TxnBatchesList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <ArbitrumL2TxnBatchesListItem - key={ item.number + (isLoading ? String(index) : '') } - item={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default ArbitrumL2TxnBatchesList; diff --git a/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatchesListItem.tsx b/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatchesListItem.tsx deleted file mode 100644 index f35eec32d50..00000000000 --- a/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatchesListItem.tsx +++ /dev/null @@ -1,115 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { route } from 'nextjs-routes'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import BatchEntityL2 from 'src/features/rollup/common/components/BatchEntityL2'; -import BlockEntityL1 from 'src/features/rollup/common/components/BlockEntityL1'; -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -import ArbitrumL2TxnBatchDA from '../../components/ArbitrumL2TxnBatchDA'; -import ArbitrumL2TxnBatchStatus from '../../components/ArbitrumL2TxnBatchStatus'; - -const rollupFeature = config.features.rollup; - -type Props = { item: schemas['ArbitrumBatchForList']; isLoading?: boolean }; - -const ArbitrumL2TxnBatchesListItem = ({ item, isLoading }: Props) => { - if (!rollupFeature.isEnabled || rollupFeature.type !== 'arbitrum') { - return null; - } - - return ( - <ListItemMobileGrid.Container gridTemplateColumns="110px auto"> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Batch #</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BatchEntityL2 - isLoading={ isLoading } - number={ item.number } - fontWeight={ 600 } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <ArbitrumL2TxnBatchStatus status={ item.commitment_transaction.status } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - { item.commitment_transaction.block_number && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } block</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntityL1 - number={ item.commitment_transaction.block_number } - isLoading={ isLoading } - /> - </ListItemMobileGrid.Value> - </> - ) } - - { item.blocks_count && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Block count</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block">{ item.blocks_count.toLocaleString() }</Skeleton> - </ListItemMobileGrid.Value> - </> - ) } - - { item.commitment_transaction.hash && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } transaction</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntityL1 - hash={ item.commitment_transaction.hash } - isLoading={ isLoading } - truncation="constant_long" - noCopy - /> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.commitment_transaction.timestamp } - fallbackText="Undefined" - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Txn count</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Link - href={ route({ pathname: '/batches/[number]', query: { number: item.number.toString(), tab: 'txs' } }) } - loading={ isLoading } - fontWeight={ 600 } - minW="40px" - > - { item.transactions_count.toLocaleString() } - </Link> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Data container</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <ArbitrumL2TxnBatchDA dataContainer={ item.batch_data_container } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default ArbitrumL2TxnBatchesListItem; diff --git a/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatchesTableItem.tsx b/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatchesTableItem.tsx index beeeb9969e2..0b38a1c7878 100644 --- a/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatchesTableItem.tsx +++ b/src/features/rollup/arbitrum/pages/batches/ArbitrumL2TxnBatchesTableItem.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { HStack } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -12,6 +11,7 @@ import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; import config from 'src/config'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; diff --git a/src/features/rollup/arbitrum/pages/batches/__screenshots__/ArbitrumL2TxnBatches.pw.tsx_default_base-view-1.png b/src/features/rollup/arbitrum/pages/batches/__screenshots__/ArbitrumL2TxnBatches.pw.tsx_default_base-view-1.png index 9c43990b2f3..e083b1ac636 100644 Binary files a/src/features/rollup/arbitrum/pages/batches/__screenshots__/ArbitrumL2TxnBatches.pw.tsx_default_base-view-1.png and b/src/features/rollup/arbitrum/pages/batches/__screenshots__/ArbitrumL2TxnBatches.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/arbitrum/pages/batches/__screenshots__/ArbitrumL2TxnBatches.pw.tsx_default_mobile-base-view-1.png b/src/features/rollup/arbitrum/pages/batches/__screenshots__/ArbitrumL2TxnBatches.pw.tsx_default_mobile-base-view-1.png deleted file mode 100644 index 27e0ade3f45..00000000000 Binary files a/src/features/rollup/arbitrum/pages/batches/__screenshots__/ArbitrumL2TxnBatches.pw.tsx_default_mobile-base-view-1.png and /dev/null differ diff --git a/src/features/rollup/arbitrum/pages/deposits/ArbitrumL2Deposits.pw.tsx b/src/features/rollup/arbitrum/pages/deposits/ArbitrumL2Deposits.pw.tsx index debafc1697a..5c1e932b653 100644 --- a/src/features/rollup/arbitrum/pages/deposits/ArbitrumL2Deposits.pw.tsx +++ b/src/features/rollup/arbitrum/pages/deposits/ArbitrumL2Deposits.pw.tsx @@ -6,7 +6,7 @@ import { test, expect } from 'playwright/lib'; import * as depositsMock from '../../mocks/deposits'; import ArbitrumL2Deposits from './ArbitrumL2Deposits'; -test('base view +@mobile', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { +test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { test.slow(); await mockTextAd(); await mockEnvs(ENVS_MAP.arbitrumRollup); diff --git a/src/features/rollup/arbitrum/pages/deposits/__screenshots__/ArbitrumL2Deposits.pw.tsx_default_base-view-1.png b/src/features/rollup/arbitrum/pages/deposits/__screenshots__/ArbitrumL2Deposits.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..afa0d023a5b Binary files /dev/null and b/src/features/rollup/arbitrum/pages/deposits/__screenshots__/ArbitrumL2Deposits.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/arbitrum/pages/deposits/__screenshots__/ArbitrumL2Deposits.pw.tsx_default_base-view-mobile-1.png b/src/features/rollup/arbitrum/pages/deposits/__screenshots__/ArbitrumL2Deposits.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index a2b26af7599..00000000000 Binary files a/src/features/rollup/arbitrum/pages/deposits/__screenshots__/ArbitrumL2Deposits.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/arbitrum/pages/deposits/__screenshots__/ArbitrumL2Deposits.pw.tsx_mobile_base-view-mobile-1.png b/src/features/rollup/arbitrum/pages/deposits/__screenshots__/ArbitrumL2Deposits.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index d85dc9807c1..00000000000 Binary files a/src/features/rollup/arbitrum/pages/deposits/__screenshots__/ArbitrumL2Deposits.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/arbitrum/pages/home/LatestArbitrumDeposits.pw.tsx b/src/features/rollup/arbitrum/pages/home/LatestArbitrumDeposits.pw.tsx index 09e3258797a..e9a5f310b86 100644 --- a/src/features/rollup/arbitrum/pages/home/LatestArbitrumDeposits.pw.tsx +++ b/src/features/rollup/arbitrum/pages/home/LatestArbitrumDeposits.pw.tsx @@ -6,7 +6,7 @@ import { test, expect } from 'playwright/lib'; import * as depositMock from '../../mocks/deposits'; import LatestArbitrumDeposits from './LatestArbitrumDeposits'; -test('default view +@mobile', async({ render, mockApiResponse, mockEnvs }) => { +test('default view', async({ render, mockApiResponse, mockEnvs }) => { await mockEnvs(ENVS_MAP.arbitrumRollup); mockApiResponse('core:homepage_arbitrum_deposits', depositMock.latestDepositsResponse); const component = await render(<LatestArbitrumDeposits/>); diff --git a/src/features/rollup/arbitrum/pages/home/LatestArbitrumDeposits.tsx b/src/features/rollup/arbitrum/pages/home/LatestArbitrumDeposits.tsx index b238411393a..b75490b5f91 100644 --- a/src/features/rollup/arbitrum/pages/home/LatestArbitrumDeposits.tsx +++ b/src/features/rollup/arbitrum/pages/home/LatestArbitrumDeposits.tsx @@ -13,14 +13,12 @@ import LatestTxsFallback from 'src/slices/home/pages/index/txs/LatestTxsFallback import LatestDeposits from 'src/features/rollup/common/pages/home/LatestDeposits'; -import useIsMobile from 'src/shared/hooks/useIsMobile'; import useGradualIncrement from 'src/shared/numbers/useGradualIncrement'; import { ARBITRUM_MESSAGES_ITEM } from '../../stubs'; const LatestArbitrumDeposits = () => { - const isMobile = useIsMobile(); - const itemsCount = isMobile ? 2 : 5; + const itemsCount = 5; const { data, isPlaceholderData, isError } = useApiQuery('core:homepage_arbitrum_deposits', { queryOptions: { placeholderData: { items: Array(itemsCount).fill(ARBITRUM_MESSAGES_ITEM) }, diff --git a/src/features/rollup/arbitrum/pages/home/LatestArbitrumL2Batches.tsx b/src/features/rollup/arbitrum/pages/home/LatestArbitrumL2Batches.tsx index 9d967f62309..61475ba2697 100644 --- a/src/features/rollup/arbitrum/pages/home/LatestArbitrumL2Batches.tsx +++ b/src/features/rollup/arbitrum/pages/home/LatestArbitrumL2Batches.tsx @@ -3,7 +3,6 @@ import { Box, Flex, VStack } from '@chakra-ui/react'; import { useQueryClient } from '@tanstack/react-query'; // import { AnimatePresence } from 'framer-motion'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { operations } from '@blockscout/api-types'; @@ -17,6 +16,7 @@ import LatestBlocksFallback from 'src/slices/home/pages/index/blocks/LatestBlock import useIsMobile from 'src/shared/hooks/useIsMobile'; import useInitialList from 'src/shared/lists/useInitialList'; +import { route } from 'src/shared/router/routes'; import { Heading } from 'src/toolkit/chakra/heading'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/features/rollup/arbitrum/pages/home/LatestBatchItem.tsx b/src/features/rollup/arbitrum/pages/home/LatestBatchItem.tsx index e2f163a329f..1b13813bc9a 100644 --- a/src/features/rollup/arbitrum/pages/home/LatestBatchItem.tsx +++ b/src/features/rollup/arbitrum/pages/home/LatestBatchItem.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import BatchEntityL2 from 'src/features/rollup/common/components/BatchEntityL2'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; diff --git a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumDeposits.pw.tsx_default_default-view-1.png b/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumDeposits.pw.tsx_default_default-view-1.png new file mode 100644 index 00000000000..e6e75a35c44 Binary files /dev/null and b/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumDeposits.pw.tsx_default_default-view-1.png differ diff --git a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumDeposits.pw.tsx_default_default-view-mobile-1.png b/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumDeposits.pw.tsx_default_default-view-mobile-1.png deleted file mode 100644 index 9ee4962174f..00000000000 Binary files a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumDeposits.pw.tsx_default_default-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumDeposits.pw.tsx_mobile_default-view-mobile-1.png b/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumDeposits.pw.tsx_mobile_default-view-mobile-1.png deleted file mode 100644 index 291a1526e92..00000000000 Binary files a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumDeposits.pw.tsx_mobile_default-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png b/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png index 3a69b80e703..6e8de471063 100644 Binary files a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png and b/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png differ diff --git a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_default_default-view-mobile-dark-mode-1.png b/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_default_default-view-mobile-dark-mode-1.png index a877937de79..39d4890503e 100644 Binary files a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_default_default-view-mobile-dark-mode-1.png and b/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_default_default-view-mobile-dark-mode-1.png differ diff --git a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_mobile_default-view-mobile-dark-mode-1.png b/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_mobile_default-view-mobile-dark-mode-1.png index 4c459a5c7c5..690ff1615b9 100644 Binary files a/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_mobile_default-view-mobile-dark-mode-1.png and b/src/features/rollup/arbitrum/pages/home/__screenshots__/LatestArbitrumL2Batches.pw.tsx_mobile_default-view-mobile-dark-mode-1.png differ diff --git a/src/features/rollup/arbitrum/pages/tx/TxDetailsWithdrawalStatusArbitrum.tsx b/src/features/rollup/arbitrum/pages/tx/TxDetailsWithdrawalStatusArbitrum.tsx index 9e9bd0204bb..c46ddac8249 100644 --- a/src/features/rollup/arbitrum/pages/tx/TxDetailsWithdrawalStatusArbitrum.tsx +++ b/src/features/rollup/arbitrum/pages/tx/TxDetailsWithdrawalStatusArbitrum.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -12,6 +11,7 @@ import { layerLabels } from 'src/features/rollup/common/utils/layer'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import VerificationSteps from 'src/shared/lifecycle/steps/VerificationSteps'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawals.pw.tsx b/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawals.pw.tsx index 062b7b6714c..5e668d641e6 100644 --- a/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawals.pw.tsx +++ b/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawals.pw.tsx @@ -14,7 +14,7 @@ const hooksConfig = { }, }; -test('base view +@mobile', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { +test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { await mockTextAd(); await mockEnvs(ENVS_MAP.arbitrumRollup); await mockApiResponse( diff --git a/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawals.tsx b/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawals.tsx index 7a56030a7c5..09ecc4f40e7 100644 --- a/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawals.tsx +++ b/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawals.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, chakra, Text } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; +import { chakra, Text } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -12,13 +11,14 @@ import { layerLabels } from 'src/features/rollup/common/utils/layer'; import DataList from 'src/shared/lists/DataList'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { FilterInput } from 'src/toolkit/components/filters/FilterInput'; import { FormFieldError } from 'src/toolkit/components/forms/components/FormFieldError'; import { TRANSACTION_HASH_REGEXP } from 'src/toolkit/components/forms/validators/transaction'; import { ARBITRUM_L2_TXN_WITHDRAWALS_ITEM } from '../../stubs'; -import ArbitrumL2TxnWithdrawalsList from './ArbitrumL2TxnWithdrawalsList'; import ArbitrumL2TxnWithdrawalsTable from './ArbitrumL2TxnWithdrawalsTable'; const ArbitrumL2TxnWithdrawals = () => { @@ -51,11 +51,7 @@ const ArbitrumL2TxnWithdrawals = () => { if (!value || TRANSACTION_HASH_REGEXP.test(value)) { setSearchTerm(value); setError(null); - router.push( - { pathname: router.pathname, query: value ? { q: value } : undefined }, - undefined, - { shallow: true }, - ); + router.push({ pathname: router.pathname, query: value ? { q: value } : undefined }, { shallow: true }); } else { setError('Invalid transaction hash'); setSearchTerm(undefined); @@ -70,14 +66,9 @@ const ArbitrumL2TxnWithdrawals = () => { }, [ handleSearchInputBlur ]); const content = data?.items ? ( - <> - <Box display={{ base: 'block', lg: 'none' }} mt={ 6 }> - <ArbitrumL2TxnWithdrawalsList data={ data.items } txHash={ searchTerm } isLoading={ isPlaceholderData }/> - </Box> - <Box display={{ base: 'none', lg: 'block' }} mt={ 6 }> - <ArbitrumL2TxnWithdrawalsTable data={ data.items } txHash={ searchTerm } isLoading={ isPlaceholderData }/> - </Box> - </> + <TableContainerScrollable> + <ArbitrumL2TxnWithdrawalsTable data={ data.items } txHash={ searchTerm } isLoading={ isPlaceholderData }/> + </TableContainerScrollable> ) : null; return ( diff --git a/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawalsList.tsx b/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawalsList.tsx deleted file mode 100644 index e890fb60b04..00000000000 --- a/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawalsList.tsx +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import ArbitrumL2TxnWithdrawalsListItem from './ArbitrumL2TxnWithdrawalsListItem'; - -interface Props { - data: Array<schemas['ArbitrumWithdrawal']>; - isLoading: boolean; - txHash: string | undefined; -} - -const ArbitrumL2TxnWithdrawalsList = ({ data, isLoading, txHash }: Props) => { - return ( - <Box> - { data.map((item, index) => ( - <ArbitrumL2TxnWithdrawalsListItem - key={ String(item.id) + (isLoading ? index : '') } - data={ item } - isLoading={ isLoading } - txHash={ txHash } - /> - )) } - </Box> - ); -}; - -export default React.memo(ArbitrumL2TxnWithdrawalsList); diff --git a/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawalsListItem.tsx b/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawalsListItem.tsx deleted file mode 100644 index 5f7392b6e5a..00000000000 --- a/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawalsListItem.tsx +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntityL1 from 'src/features/rollup/common/components/AddressEntityL1'; - -import config from 'src/config'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -import ArbitrumL2MessageStatus from '../../components/ArbitrumL2MessageStatus'; -import ArbitrumL2TxnWithdrawalsClaimButton from './ArbitrumL2TxnWithdrawalsClaimButton'; -import ArbitrumL2TxnWithdrawalsValue from './ArbitrumL2TxnWithdrawalsValue'; - -const rollupFeature = config.features.rollup; - -interface Props { - data: schemas['ArbitrumWithdrawal']; - isLoading: boolean; - txHash: string | undefined; -} - -const ArbitrumL2TxnWithdrawalsListItem = ({ data, isLoading, txHash }: Props) => { - if (!rollupFeature.isEnabled || rollupFeature.type !== 'arbitrum') { - return null; - } - - return ( - <ListItemMobileGrid.Container gridTemplateColumns="110px auto"> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Message #</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }>{ data.id }</Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Receiver</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntityL1 address={{ hash: data.token?.destination_address_hash || data.destination_address_hash }} isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Value</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading }> - <ArbitrumL2TxnWithdrawalsValue data={ data }/> - </Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value - display="flex" - alignItems="center" - justifyContent="space-between" - flexWrap="wrap" - rowGap={ 2 } - columnGap={ 3 } - py={ 0 } - > - <ArbitrumL2MessageStatus status={ data.status } isLoading={ isLoading }/> - { (data.status === 'confirmed' || data.status === 'relayed') && ( - <ArbitrumL2TxnWithdrawalsClaimButton - messageId={ data.id } - txHash={ txHash } - completionTxHash={ data.completion_transaction_hash || undefined } - isLoading={ isLoading } - /> - ) } - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default ArbitrumL2TxnWithdrawalsListItem; diff --git a/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawalsTable.tsx b/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawalsTable.tsx index a07aacc914a..70bedcffca7 100644 --- a/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawalsTable.tsx +++ b/src/features/rollup/arbitrum/pages/txn-withdrawals/ArbitrumL2TxnWithdrawalsTable.tsx @@ -4,6 +4,8 @@ import React from 'react'; import type { schemas } from '@blockscout/api-types'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; + import { TableBody, TableColumnHeader, TableHeader, TableRoot, TableRow } from 'src/toolkit/chakra/table'; import ArbitrumL2TxnWithdrawalsTableItem from './ArbitrumL2TxnWithdrawalsTableItem'; @@ -14,9 +16,13 @@ interface Props { isLoading: boolean; } +const getBaseKey = (item: schemas['ArbitrumWithdrawal']): string => String(item.id); + const ArbitrumL2TxnWithdrawalsTable = ({ data, txHash, isLoading }: Props) => { + const keys = useUniqueKeys(data, getBaseKey); + return ( - <TableRoot minW="900px"> + <TableRoot minW="900px" mt={ 6 }> <TableHeader> <TableRow> <TableColumnHeader width="150px">Message #</TableColumnHeader> @@ -28,7 +34,7 @@ const ArbitrumL2TxnWithdrawalsTable = ({ data, txHash, isLoading }: Props) => { <TableBody> { data.map((item, index) => ( <ArbitrumL2TxnWithdrawalsTableItem - key={ String(item.id) + (isLoading ? index : '') } + key={ keys[index] } data={ item } isLoading={ isLoading } txHash={ txHash }/> diff --git a/src/features/rollup/arbitrum/pages/txn-withdrawals/__screenshots__/ArbitrumL2TxnWithdrawals.pw.tsx_default_base-view-1.png b/src/features/rollup/arbitrum/pages/txn-withdrawals/__screenshots__/ArbitrumL2TxnWithdrawals.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..51b463c275f Binary files /dev/null and b/src/features/rollup/arbitrum/pages/txn-withdrawals/__screenshots__/ArbitrumL2TxnWithdrawals.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/arbitrum/pages/txn-withdrawals/__screenshots__/ArbitrumL2TxnWithdrawals.pw.tsx_default_base-view-mobile-1.png b/src/features/rollup/arbitrum/pages/txn-withdrawals/__screenshots__/ArbitrumL2TxnWithdrawals.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 78967d022ed..00000000000 Binary files a/src/features/rollup/arbitrum/pages/txn-withdrawals/__screenshots__/ArbitrumL2TxnWithdrawals.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/arbitrum/pages/txn-withdrawals/__screenshots__/ArbitrumL2TxnWithdrawals.pw.tsx_mobile_base-view-mobile-1.png b/src/features/rollup/arbitrum/pages/txn-withdrawals/__screenshots__/ArbitrumL2TxnWithdrawals.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 56f4c764714..00000000000 Binary files a/src/features/rollup/arbitrum/pages/txn-withdrawals/__screenshots__/ArbitrumL2TxnWithdrawals.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/arbitrum/pages/withdrawals/ArbitrumL2Withdrawals.pw.tsx b/src/features/rollup/arbitrum/pages/withdrawals/ArbitrumL2Withdrawals.pw.tsx index 04458b19cf1..9708541b2b0 100644 --- a/src/features/rollup/arbitrum/pages/withdrawals/ArbitrumL2Withdrawals.pw.tsx +++ b/src/features/rollup/arbitrum/pages/withdrawals/ArbitrumL2Withdrawals.pw.tsx @@ -6,7 +6,7 @@ import { test, expect } from 'playwright/lib'; import * as depositsMock from '../../mocks/withdrawals'; import ArbitrumL2Withdrawals from './ArbitrumL2Withdrawals'; -test('base view +@mobile', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { +test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { test.slow(); await mockTextAd(); await mockEnvs(ENVS_MAP.arbitrumRollup); diff --git a/src/features/rollup/arbitrum/pages/withdrawals/__screenshots__/ArbitrumL2Withdrawals.pw.tsx_default_base-view-1.png b/src/features/rollup/arbitrum/pages/withdrawals/__screenshots__/ArbitrumL2Withdrawals.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..421d12d4d6d Binary files /dev/null and b/src/features/rollup/arbitrum/pages/withdrawals/__screenshots__/ArbitrumL2Withdrawals.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/arbitrum/pages/withdrawals/__screenshots__/ArbitrumL2Withdrawals.pw.tsx_default_base-view-mobile-1.png b/src/features/rollup/arbitrum/pages/withdrawals/__screenshots__/ArbitrumL2Withdrawals.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 780b452012d..00000000000 Binary files a/src/features/rollup/arbitrum/pages/withdrawals/__screenshots__/ArbitrumL2Withdrawals.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/arbitrum/pages/withdrawals/__screenshots__/ArbitrumL2Withdrawals.pw.tsx_mobile_base-view-mobile-1.png b/src/features/rollup/arbitrum/pages/withdrawals/__screenshots__/ArbitrumL2Withdrawals.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 753776dc422..00000000000 Binary files a/src/features/rollup/arbitrum/pages/withdrawals/__screenshots__/ArbitrumL2Withdrawals.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/common/components/AddressEntityL1.tsx b/src/features/rollup/common/components/AddressEntityL1.tsx index 724b0d27f9a..fdf1f57fe07 100644 --- a/src/features/rollup/common/components/AddressEntityL1.tsx +++ b/src/features/rollup/common/components/AddressEntityL1.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; const rollupFeature = config.features.rollup; diff --git a/src/features/rollup/common/components/BatchEntityL2.tsx b/src/features/rollup/common/components/BatchEntityL2.tsx index 06770fc9dca..0966b579357 100644 --- a/src/features/rollup/common/components/BatchEntityL2.tsx +++ b/src/features/rollup/common/components/BatchEntityL2.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as BlockEntity from 'src/slices/block/components/entity/BlockEntity'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; const rollupFeature = config.features.rollup; diff --git a/src/features/rollup/common/components/BlockEntityL1.tsx b/src/features/rollup/common/components/BlockEntityL1.tsx index 7b5549c2914..e9749bee290 100644 --- a/src/features/rollup/common/components/BlockEntityL1.tsx +++ b/src/features/rollup/common/components/BlockEntityL1.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as BlockEntity from 'src/slices/block/components/entity/BlockEntity'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; const rollupFeature = config.features.rollup; diff --git a/src/features/rollup/common/components/TokenEntityL1.tsx b/src/features/rollup/common/components/TokenEntityL1.tsx index 12e6cfbb5eb..089bdf47b3f 100644 --- a/src/features/rollup/common/components/TokenEntityL1.tsx +++ b/src/features/rollup/common/components/TokenEntityL1.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as TokenEntity from 'src/slices/token/components/entity/TokenEntity'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; const rollupFeature = config.features.rollup; diff --git a/src/features/rollup/common/components/TxEntityL1.tsx b/src/features/rollup/common/components/TxEntityL1.tsx index 250448db15c..750ce2fd432 100644 --- a/src/features/rollup/common/components/TxEntityL1.tsx +++ b/src/features/rollup/common/components/TxEntityL1.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as TxEntity from 'src/slices/tx/components/entity/TxEntity'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; const rollupFeature = config.features.rollup; diff --git a/src/features/rollup/common/pages/home/LatestDeposits.tsx b/src/features/rollup/common/pages/home/LatestDeposits.tsx index aa041bd3535..9b790ec56d7 100644 --- a/src/features/rollup/common/pages/home/LatestDeposits.tsx +++ b/src/features/rollup/common/pages/home/LatestDeposits.tsx @@ -1,12 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { - Box, - Flex, - Grid, - GridItem, -} from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; +import { Box, Flex, VStack } from '@chakra-ui/react'; import React from 'react'; import SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; @@ -18,10 +12,14 @@ import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; import { layerLabels } from 'src/features/rollup/common/utils/layer'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableBody, TableCell, TableContainerScrollable, TableRoot, TableRow } from 'src/toolkit/chakra/table'; + +const LATEST_DEPOSITS_TABLE_MIN_WIDTH = '750px'; interface DepositsItem { l1BlockNumber: number | null; @@ -43,8 +41,6 @@ interface ItemProps { }; const LatestDepositsItem = ({ item, isLoading }: ItemProps) => { - const isMobile = useIsMobile(); - const l1BlockLink = item.l1BlockNumber ? ( <BlockEntityL1 number={ item.l1BlockNumber } @@ -64,7 +60,7 @@ const LatestDepositsItem = ({ item, isLoading }: ItemProps) => { <TxEntityL1 isLoading={ isLoading } hash={ item.l1TxHash } - truncation={ isMobile ? 'constant_long' : 'dynamic' } + truncation="dynamic" noCopy /> ) : ( @@ -81,7 +77,7 @@ const LatestDepositsItem = ({ item, isLoading }: ItemProps) => { <TxEntity isLoading={ isLoading } hash={ item.l2TxHash } - truncation={ isMobile ? 'constant_long' : 'dynamic' } + truncation="dynamic" /> ) : ( <TxEntity @@ -93,95 +89,74 @@ const LatestDepositsItem = ({ item, isLoading }: ItemProps) => { /> ); - const content = (() => { - if (isMobile) { - return ( - <> - <Flex justifyContent="space-between" alignItems="center" mb={ 1 }> - { l1BlockLink } - { item.timestamp ? ( - <TimeWithTooltip - timestamp={ item.timestamp } - timeFormat="relative" - isLoading={ isLoading } - color="text.secondary" - /> - ) : <GridItem/> } - </Flex> - <Grid gridTemplateColumns="56px auto"> - <Skeleton loading={ isLoading } my="5px" w="fit-content"> - { layerLabels.parent } txn - </Skeleton> - { l1TxLink } - <Skeleton loading={ isLoading } my="3px" w="fit-content"> - { layerLabels.current } txn - </Skeleton> - { l2TxLink } - </Grid> - </> - ); - } - - return ( - <Grid width="100%" columnGap={ 4 } rowGap={ 2 } templateColumns="max-content max-content auto" w="100%"> - { l1BlockLink } - <Skeleton loading={ isLoading } w="fit-content" h="fit-content" my="5px"> - { layerLabels.parent } txn - </Skeleton> - { l1TxLink } - { item.timestamp ? ( - <TimeWithTooltip - timestamp={ item.timestamp } - timeFormat="relative" - isLoading={ isLoading } - color="text.secondary" - w="fit-content" - h="fit-content" - my="2px" - /> - ) : <GridItem/> } - <Skeleton loading={ isLoading } w="fit-content" h="fit-content" my="2px"> - { layerLabels.current } txn - </Skeleton> - { l2TxLink } - </Grid> - ); - })(); - return ( - <Box - width="100%" - borderBottom="1px solid" - borderColor="border.divider" - py={ 4 } - px={{ base: 0, lg: 4 }} - textStyle="sm" - > - { content } - </Box> + <TableRow> + <TableCell w="130px"> + <VStack alignItems="start" gap={ 2 }> + { l1BlockLink } + { item.timestamp && ( + <TimeWithTooltip + timestamp={ item.timestamp } + timeFormat="relative" + isLoading={ isLoading } + color="text.secondary" + w="fit-content" + h="fit-content" + /> + ) } + </VStack> + </TableCell> + <TableCell w="80px"> + <VStack alignItems="start" gap={ 2 }> + <Skeleton loading={ isLoading } w="fit-content" h="fit-content"> + { layerLabels.parent } txn + </Skeleton> + <Skeleton loading={ isLoading } w="fit-content" h="fit-content"> + { layerLabels.current } txn + </Skeleton> + </VStack> + </TableCell> + <TableCell> + <VStack alignItems="stretch" gap={ 2 } overflow="hidden"> + { l1TxLink } + { l2TxLink } + </VStack> + </TableCell> + </TableRow> ); }; +const getBaseKey = (item: DepositsItem): string => (item.l1TxHash ?? '') + (item.l2TxHash ?? ''); + const LatestDeposits = ({ isLoading, items, showSocketErrorAlert, socketItemsNum }: Props) => { const depositsUrl = route({ pathname: '/deposits' }); + const keys = useUniqueKeys(items, getBaseKey); + return ( <> - <SocketNewItemsNotice - borderBottomRadius={ 0 } - url={ depositsUrl } - num={ socketItemsNum } - showErrorAlert={ showSocketErrorAlert } - type="deposit" - isLoading={ isLoading } - /> - <Box mb={{ base: 3, lg: 4 }}> - { items.map(((item, index) => ( - <LatestDepositsItem - key={ (item.l1TxHash ?? '') + (item.l2TxHash ?? '') + (isLoading ? index : '') } - item={ item } + <Box mb={{ base: 3, lg: 4 }} textStyle="sm"> + <TableContainerScrollable> + <SocketNewItemsNotice + borderBottomRadius={ 0 } + minW={ LATEST_DEPOSITS_TABLE_MIN_WIDTH } + url={ depositsUrl } + num={ socketItemsNum } + showErrorAlert={ showSocketErrorAlert } + type="deposit" isLoading={ isLoading } /> - ))) } + <TableRoot minW={ LATEST_DEPOSITS_TABLE_MIN_WIDTH }> + <TableBody> + { items.map(((item, index) => ( + <LatestDepositsItem + key={ keys[index] } + item={ item } + isLoading={ isLoading } + /> + ))) } + </TableBody> + </TableRoot> + </TableContainerScrollable> </Box> <Flex justifyContent="center"> <Link textStyle="sm" href={ depositsUrl }>View all deposits</Link> diff --git a/src/features/rollup/common/pages/home/LatestDepositsItem.tsx b/src/features/rollup/common/pages/home/LatestDepositsItem.tsx deleted file mode 100644 index fd81f9f3f7b..00000000000 --- a/src/features/rollup/common/pages/home/LatestDepositsItem.tsx +++ /dev/null @@ -1,129 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { - Box, - Flex, - Grid, -} from '@chakra-ui/react'; -import React from 'react'; - -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import BlockEntityL1 from 'src/features/rollup/common/components/BlockEntityL1'; -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import useIsMobile from 'src/shared/hooks/useIsMobile'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -type Props = { - l1BlockNumber: number; - l1TxHash: string; - l2TxHash: string | null; - timestamp: string | null; - isLoading?: boolean; -}; - -const LatestDepositsItem = ({ l1BlockNumber, l1TxHash, l2TxHash, timestamp, isLoading }: Props) => { - const isMobile = useIsMobile(); - - const l1BlockLink = ( - <BlockEntityL1 - number={ l1BlockNumber } - isLoading={ isLoading } - fontSize="sm" - lineHeight={ 5 } - fontWeight={ 700 } - /> - ); - - const l1TxLink = ( - <TxEntityL1 - isLoading={ isLoading } - hash={ l1TxHash } - fontSize="sm" - lineHeight={ 5 } - truncation={ isMobile ? 'constant_long' : 'dynamic' } - /> - ); - - const l2TxLink = l2TxHash ? ( - <TxEntity - isLoading={ isLoading } - hash={ l2TxHash } - fontSize="sm" - lineHeight={ 5 } - truncation={ isMobile ? 'constant_long' : 'dynamic' } - /> - ) : null; - - const content = (() => { - if (isMobile) { - return ( - <> - <Flex justifyContent="space-between" alignItems="center" mb={ 1 }> - { l1BlockLink } - <TimeWithTooltip - timestamp={ timestamp } - timeFormat="relative" - isLoading={ isLoading } - color="text.secondary" - /> - </Flex> - <Grid gridTemplateColumns="56px auto"> - <Skeleton loading={ isLoading } my="5px" w="fit-content"> - { layerLabels.parent } txn - </Skeleton> - { l1TxLink } - <Skeleton loading={ isLoading } my="3px" w="fit-content"> - { layerLabels.current } txn - </Skeleton> - { l2TxLink } - </Grid> - </> - ); - } - - return ( - <Grid width="100%" columnGap={ 4 } rowGap={ 2 } templateColumns="max-content max-content auto" w="100%"> - { l1BlockLink } - <Skeleton loading={ isLoading } w="fit-content" h="fit-content" my="5px"> - { layerLabels.parent } txn - </Skeleton> - { l1TxLink } - <TimeWithTooltip - timestamp={ timestamp } - timeFormat="relative" - isLoading={ isLoading } - color="text.secondary" - w="fit-content" - h="fit-content" - my="2px" - /> - <Skeleton loading={ isLoading } w="fit-content" h="fit-content" my="2px"> - { layerLabels.current } txn - </Skeleton> - { l2TxLink } - </Grid> - ); - })(); - - return ( - <Box - width="100%" - borderTop="1px solid" - borderColor="border.divider" - py={ 4 } - px={{ base: 0, lg: 4 }} - _last={{ borderBottom: '1px solid', borderColor: 'border.divider' }} - fontSize="sm" - lineHeight={ 5 } - > - { content } - </Box> - ); -}; - -export default React.memo(LatestDepositsItem); diff --git a/src/features/rollup/optimism/mocks/dispute-games.ts b/src/features/rollup/optimism/mocks/dispute-games.ts index adb336ceabc..8de71840dc7 100644 --- a/src/features/rollup/optimism/mocks/dispute-games.ts +++ b/src/features/rollup/optimism/mocks/dispute-games.ts @@ -8,7 +8,11 @@ export const data: operations['OptimismController.games']['json'] = { game_type: 0, index: 6662, l2_block_number: 12542890, +<<<<<<< HEAD l2_timestamp: null, +======= + l2_timestamp: '2022-05-27T01:13:00.000000Z', +>>>>>>> v2.13.0 resolved_at: null, status: 'In progress', }, @@ -18,7 +22,11 @@ export const data: operations['OptimismController.games']['json'] = { game_type: 0, index: 6662, l2_block_number: 12542890, +<<<<<<< HEAD l2_timestamp: null, +======= + l2_timestamp: '2022-05-27T01:13:00.000000Z', +>>>>>>> v2.13.0 resolved_at: '2022-05-27T01:13:48.000000Z', status: 'Defender wins', }, diff --git a/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatch.tsx b/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatch.tsx index 1da3d87f0e6..69d0245095e 100644 --- a/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatch.tsx +++ b/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatch.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -18,9 +17,10 @@ import throwOnAbsentParamError from 'src/shared/errors/throw-on-absent-param-err import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -45,7 +45,7 @@ const OptimisticL2TxnBatch = () => { const batchQuery = useBatchQuery(); - const batchTxsQuery = useQueryWithPages({ + const batchTxsQuery = useApiPaginatedQuery({ resourceName: 'core:optimistic_l2_txn_batch_txs', pathParams: { number: String(batchQuery.data?.number) }, options: { @@ -58,7 +58,7 @@ const OptimisticL2TxnBatch = () => { }, }); - const batchBlocksQuery = useQueryWithPages({ + const batchBlocksQuery = useApiPaginatedQuery({ resourceName: 'core:optimistic_l2_txn_batch_blocks', pathParams: { number: String(batchQuery.data?.number) }, options: { diff --git a/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchBlobCelestia.tsx b/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchBlobCelestia.tsx index 4b4aeef71ab..1426c3eb005 100644 --- a/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchBlobCelestia.tsx +++ b/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchBlobCelestia.tsx @@ -11,7 +11,8 @@ import { layerLabels } from 'src/features/rollup/common/utils/layer'; import DetailedInfoTimestamp from 'src/shared/detailed-info/DetailedInfoTimestamp'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; + +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import OptimisticL2TxnBatchBlobWrapper from './OptimisticL2TxnBatchBlobWrapper'; @@ -29,7 +30,7 @@ const OptimisticL2TxnBatchBlobCelestia = ({ blobs, isLoading }: Props) => { <GridItem fontWeight={ 600 }>Commitment</GridItem> <GridItem overflow="hidden"> <Flex minW="0" w="calc(100% - 20px)"> - <HashStringShortenDynamic hash={ blob.commitment }/> + <Truncate value={ blob.commitment }/> <CopyToClipboard text={ blob.commitment }/> </Flex> </GridItem> diff --git a/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchBlobEigenda.tsx b/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchBlobEigenda.tsx index 686e11867a9..f0ecca2f1a1 100644 --- a/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchBlobEigenda.tsx +++ b/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchBlobEigenda.tsx @@ -10,7 +10,8 @@ import { layerLabels } from 'src/features/rollup/common/utils/layer'; import DetailedInfoTimestamp from 'src/shared/detailed-info/DetailedInfoTimestamp'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; + +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import OptimisticL2TxnBatchBlobWrapper from './OptimisticL2TxnBatchBlobWrapper'; @@ -28,7 +29,7 @@ const OptimisticL2TxnBatchBlobEigenda = ({ blobs, isLoading }: Props) => { <GridItem fontWeight={ 600 }>Cert</GridItem> <GridItem overflow="hidden"> <Flex minW="0" w="calc(100% - 20px)"> - <HashStringShortenDynamic hash={ blob.cert }/> + <Truncate value={ blob.cert }/> <CopyToClipboard text={ blob.cert }/> </Flex> </GridItem> diff --git a/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchDetails.tsx b/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchDetails.tsx index 78d0b557626..e1919c80ed2 100644 --- a/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchDetails.tsx +++ b/src/features/rollup/optimism/pages/batch-details/OptimisticL2TxnBatchDetails.tsx @@ -1,8 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { UseQueryResult } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -18,6 +16,8 @@ import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import DetailedInfoTimestamp from 'src/shared/detailed-info/DetailedInfoTimestamp'; import isCustomAppError from 'src/shared/errors/is-custom-app-error'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; +import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; @@ -44,7 +44,7 @@ const OptimisticL2TxnBatchDetails = ({ query }: Props) => { const increment = direction === 'next' ? +1 : -1; const nextId = String(data.number + increment); - router.push({ pathname: '/batches/[number]', query: { number: nextId } }, undefined); + router.push({ pathname: '/batches/[number]', query: { number: nextId } }); }, [ data, router ]); if (isError) { diff --git a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_EIP-4844-blob-container-mobile-1.png b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_EIP-4844-blob-container-mobile-1.png index f8b71aa4046..762f581b786 100644 Binary files a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_EIP-4844-blob-container-mobile-1.png and b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_EIP-4844-blob-container-mobile-1.png differ diff --git a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_Eigenda-blob-container-mobile-1.png b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_Eigenda-blob-container-mobile-1.png index 63f790da5d8..36fdf820edd 100644 Binary files a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_Eigenda-blob-container-mobile-1.png and b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_Eigenda-blob-container-mobile-1.png differ diff --git a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_call-data-blob-container-mobile-1.png b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_call-data-blob-container-mobile-1.png index 5a33e1b8e7f..d7463d8df27 100644 Binary files a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_call-data-blob-container-mobile-1.png and b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_call-data-blob-container-mobile-1.png differ diff --git a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_celestia-blob-container-mobile-1.png b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_celestia-blob-container-mobile-1.png index f7cbe767c2f..454e2c2b041 100644 Binary files a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_celestia-blob-container-mobile-1.png and b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_default_celestia-blob-container-mobile-1.png differ diff --git a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_EIP-4844-blob-container-mobile-1.png b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_EIP-4844-blob-container-mobile-1.png index 17c0a931063..7ed2409ce70 100644 Binary files a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_EIP-4844-blob-container-mobile-1.png and b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_EIP-4844-blob-container-mobile-1.png differ diff --git a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_Eigenda-blob-container-mobile-1.png b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_Eigenda-blob-container-mobile-1.png index 0e45d43f8ad..35931dde4c1 100644 Binary files a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_Eigenda-blob-container-mobile-1.png and b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_Eigenda-blob-container-mobile-1.png differ diff --git a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_call-data-blob-container-mobile-1.png b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_call-data-blob-container-mobile-1.png index e97ef3bf48b..e83c511e5ba 100644 Binary files a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_call-data-blob-container-mobile-1.png and b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_call-data-blob-container-mobile-1.png differ diff --git a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_celestia-blob-container-mobile-1.png b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_celestia-blob-container-mobile-1.png index 8ab97caee23..2dbe5e9df7c 100644 Binary files a/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_celestia-blob-container-mobile-1.png and b/src/features/rollup/optimism/pages/batch-details/__screenshots__/OptimisticL2TxnBatchDetails.pw.tsx_mobile_celestia-blob-container-mobile-1.png differ diff --git a/src/features/rollup/optimism/pages/batch-details/useBatchQuery.ts b/src/features/rollup/optimism/pages/batch-details/useBatchQuery.ts new file mode 100644 index 00000000000..02cba36802b --- /dev/null +++ b/src/features/rollup/optimism/pages/batch-details/useBatchQuery.ts @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import useApiQuery from 'src/api/hooks/useApiQuery'; + +import { L2_TXN_BATCH } from 'src/features/rollup/optimism/stubs'; + +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; + +export default function useBatchQuery() { + const router = useRouter(); + const number = getQueryParamString(router.query.number); + const height = getQueryParamString(router.query.height); + const commitment = getQueryParamString(router.query.commitment); + + const batchByNumberQuery = useApiQuery('core:optimistic_l2_txn_batch', { + pathParams: { number }, + queryOptions: { + enabled: Boolean(number), + placeholderData: L2_TXN_BATCH, + }, + }); + + const batchByHeightQuery = useApiQuery('core:optimistic_l2_txn_batch_celestia', { + pathParams: { height, commitment }, + queryOptions: { + enabled: Boolean(height && commitment), + placeholderData: L2_TXN_BATCH, + }, + }); + + return number ? batchByNumberQuery : batchByHeightQuery; +} diff --git a/src/features/rollup/optimism/pages/batch-details/useBatchQuery.tsx b/src/features/rollup/optimism/pages/batch-details/useBatchQuery.tsx deleted file mode 100644 index d404c85f5c2..00000000000 --- a/src/features/rollup/optimism/pages/batch-details/useBatchQuery.tsx +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useRouter } from 'next/router'; - -import useApiQuery from 'src/api/hooks/useApiQuery'; - -import { L2_TXN_BATCH } from 'src/features/rollup/optimism/stubs'; - -import getQueryParamString from 'src/shared/router/get-query-param-string'; - -export default function useBatchQuery() { - const router = useRouter(); - const number = getQueryParamString(router.query.number); - const height = getQueryParamString(router.query.height); - const commitment = getQueryParamString(router.query.commitment); - - const batchByNumberQuery = useApiQuery('core:optimistic_l2_txn_batch', { - pathParams: { number }, - queryOptions: { - enabled: Boolean(number), - placeholderData: L2_TXN_BATCH, - }, - }); - - const batchByHeightQuery = useApiQuery('core:optimistic_l2_txn_batch_celestia', { - pathParams: { height, commitment }, - queryOptions: { - enabled: Boolean(height && commitment), - placeholderData: L2_TXN_BATCH, - }, - }); - - return number ? batchByNumberQuery : batchByHeightQuery; -} diff --git a/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatches.pw.tsx b/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatches.pw.tsx index 3b3c9479391..0f33c877e4e 100644 --- a/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatches.pw.tsx +++ b/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatches.pw.tsx @@ -7,10 +7,7 @@ import { test, expect } from 'playwright/lib'; import OptimisticL2TxnBatches from './OptimisticL2TxnBatches'; -test('base view +@mobile', async({ render, mockTextAd, mockEnvs, mockApiResponse }) => { - // test on mobile is flaky - // my assumption is there is not enough time to calculate hashes truncation so component is unstable - // so I raised the test timeout to check if it helps +test('base view', async({ render, mockTextAd, mockEnvs, mockApiResponse }) => { test.slow(); await mockTextAd(); await mockEnvs(ENVS_MAP.optimisticRollup); diff --git a/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatches.tsx b/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatches.tsx index 7f57e717e5b..3ed74c91621 100644 --- a/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatches.tsx +++ b/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatches.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Text } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -8,19 +8,19 @@ import useApiQuery from 'src/api/hooks/useApiQuery'; import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; -import OptimisticL2TxnBatchesList from 'src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesList'; import OptimisticL2TxnBatchesTable from 'src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesTable'; import { L2_TXN_BATCHES_ITEM } from 'src/features/rollup/optimism/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; const OptimisticL2TxnBatches = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:optimistic_l2_txn_batches', options: { placeholderData: generateListStub<'core:optimistic_l2_txn_batches'>( @@ -43,19 +43,14 @@ const OptimisticL2TxnBatches = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <OptimisticL2TxnBatchesList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <OptimisticL2TxnBatchesTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <OptimisticL2TxnBatchesTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -64,7 +59,7 @@ const OptimisticL2TxnBatches = () => { } return ( - <Skeleton loading={ countersQuery.isPlaceholderData || isPlaceholderData } display="flex" flexWrap="wrap"> + <Skeleton loading={ countersQuery.isPlaceholderData || isInitialLoading } display="flex" flexWrap="wrap"> Txn batch <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[0].number } </Text>to <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[data.items.length - 1].number } </Text> @@ -83,6 +78,7 @@ const OptimisticL2TxnBatches = () => { itemsNum={ data?.items?.length } emptyText="There are no txn batches." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesList.tsx b/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesList.tsx deleted file mode 100644 index a81b9ca24d6..00000000000 --- a/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import OptimisticL2TxnBatchesListItem from './OptimisticL2TxnBatchesListItem'; - -type Props = { - items: Array<schemas['OptimismBatch']>; - isLoading?: boolean; - resetKey?: string; -}; - -const OptimisticL2TxnBatchesList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <OptimisticL2TxnBatchesListItem - key={ item.number + (isLoading ? String(index) : '') } - item={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default OptimisticL2TxnBatchesList; diff --git a/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesListItem.tsx b/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesListItem.tsx deleted file mode 100644 index ce35be4eaef..00000000000 --- a/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesListItem.tsx +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { route } from 'nextjs-routes'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import BatchEntityL2 from 'src/features/rollup/common/components/BatchEntityL2'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; -import OptimisticL2TxnBatchDA from 'src/features/rollup/optimism/components/TxnBatchDA'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -const rollupFeature = config.features.rollup; - -type Props = { item: schemas['OptimismBatch']; isLoading?: boolean }; - -const OptimisticL2TxnBatchesListItem = ({ item, isLoading }: Props) => { - if (!rollupFeature.isEnabled || rollupFeature.type !== 'optimistic') { - return null; - } - - return ( - <ListItemMobileGrid.Container gridTemplateColumns="100px auto"> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Batch ID</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BatchEntityL2 number={ item.number } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - { item.batch_data_container && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }> - Storage - </ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <OptimisticL2TxnBatchDA container={ item.batch_data_container } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.l1_timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } txn count</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } minW="40px"> - { item.l1_transaction_hashes.length } - </Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } blocks</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Link - href={ route({ pathname: '/batches/[number]', query: { number: item.number.toString(), tab: 'blocks' } }) } - loading={ isLoading } - minW="40px" - > - { item.l2_end_block_number - item.l2_start_block_number + 1 } - </Link> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Txn</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Link - href={ route({ pathname: '/batches/[number]', query: { number: item.number.toString(), tab: 'txs' } }) } - loading={ isLoading } - minW="40px" - > - { item.transactions_count } - </Link> - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default OptimisticL2TxnBatchesListItem; diff --git a/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesTableItem.tsx b/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesTableItem.tsx index ae8f7867ca3..f26743b940f 100644 --- a/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesTableItem.tsx +++ b/src/features/rollup/optimism/pages/batches/OptimisticL2TxnBatchesTableItem.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -10,6 +9,7 @@ import OptimisticL2TxnBatchDA from 'src/features/rollup/optimism/components/TxnB import config from 'src/config'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; diff --git a/src/features/rollup/optimism/pages/batches/__screenshots__/OptimisticL2TxnBatches.pw.tsx_default_base-view-1.png b/src/features/rollup/optimism/pages/batches/__screenshots__/OptimisticL2TxnBatches.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..c66e695d3ce Binary files /dev/null and b/src/features/rollup/optimism/pages/batches/__screenshots__/OptimisticL2TxnBatches.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/optimism/pages/batches/__screenshots__/OptimisticL2TxnBatches.pw.tsx_default_base-view-mobile-1.png b/src/features/rollup/optimism/pages/batches/__screenshots__/OptimisticL2TxnBatches.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index de1d2599ffc..00000000000 Binary files a/src/features/rollup/optimism/pages/batches/__screenshots__/OptimisticL2TxnBatches.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/optimism/pages/batches/__screenshots__/OptimisticL2TxnBatches.pw.tsx_mobile_base-view-mobile-1.png b/src/features/rollup/optimism/pages/batches/__screenshots__/OptimisticL2TxnBatches.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 734370e5222..00000000000 Binary files a/src/features/rollup/optimism/pages/batches/__screenshots__/OptimisticL2TxnBatches.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/optimism/pages/deposits/OptimisticDepositsList.tsx b/src/features/rollup/optimism/pages/deposits/OptimisticDepositsList.tsx deleted file mode 100644 index 811cc3bf7c5..00000000000 --- a/src/features/rollup/optimism/pages/deposits/OptimisticDepositsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import OptimisticDepositsListItem from './OptimisticDepositsListItem'; - -type Props = { - items: Array<schemas['OptimismDeposit']>; - isLoading?: boolean; - resetKey?: string; -}; - -const OptimisticDepositsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <OptimisticDepositsListItem - key={ `${ (item.l2_transaction_hash ?? '') + (isLoading ? index : '') }` } - isLoading={ isLoading } - item={ item } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default OptimisticDepositsList; diff --git a/src/features/rollup/optimism/pages/deposits/OptimisticDepositsListItem.tsx b/src/features/rollup/optimism/pages/deposits/OptimisticDepositsListItem.tsx deleted file mode 100644 index b6f10d769d8..00000000000 --- a/src/features/rollup/optimism/pages/deposits/OptimisticDepositsListItem.tsx +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import BigNumber from 'bignumber.js'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import AddressEntityL1 from 'src/features/rollup/common/components/AddressEntityL1'; -import BlockEntityL1 from 'src/features/rollup/common/components/BlockEntityL1'; -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -const rollupFeature = config.features.rollup; - -type Props = { item: schemas['OptimismDeposit']; isLoading?: boolean }; - -const OptimisticDepositsListItem = ({ item, isLoading }: Props) => { - if (!rollupFeature.isEnabled || rollupFeature.type !== 'optimistic') { - return null; - } - - return ( - <ListItemMobileGrid.Container> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } block No</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntityL1 - number={ item.l1_block_number } - isLoading={ isLoading } - fontWeight={ 600 } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntity - isLoading={ isLoading } - hash={ item.l2_transaction_hash } - truncation="constant_long" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.l1_block_timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntityL1 - isLoading={ isLoading } - hash={ item.l1_transaction_hash } - truncation="constant_long" - noCopy - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } txn origin</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntityL1 - address={{ hash: item.l1_transaction_origin, name: '', is_contract: false, is_verified: false, ens_domain_name: null, implementations: [] }} - isLoading={ isLoading } - noCopy - truncation="constant" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Gas limit</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block">{ BigNumber(item.l2_transaction_gas_limit).toFormat() }</Skeleton> - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default OptimisticDepositsListItem; diff --git a/src/features/rollup/optimism/pages/deposits/OptimisticDepositsTable.tsx b/src/features/rollup/optimism/pages/deposits/OptimisticDepositsTable.tsx index 1f3703b2b37..47d03b5f7d6 100644 --- a/src/features/rollup/optimism/pages/deposits/OptimisticDepositsTable.tsx +++ b/src/features/rollup/optimism/pages/deposits/OptimisticDepositsTable.tsx @@ -9,6 +9,7 @@ import { AddressHighlightProvider } from 'src/slices/address/contexts/address-hi import { layerLabels } from 'src/features/rollup/common/utils/layer'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -22,8 +23,11 @@ type Props = { resetKey?: string; }; +const getBaseKey = (item: schemas['OptimismDeposit']): string => item.l2_transaction_hash; + const OptimisticDepositsTable = ({ items, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( <AddressHighlightProvider> @@ -43,7 +47,7 @@ const OptimisticDepositsTable = ({ items, top, isLoading, resetKey }: Props) => </TableHeaderSticky> <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( - <OptimisticDepositsTableItem key={ item.l2_transaction_hash + (isLoading ? index : '') } item={ item } isLoading={ isLoading }/> + <OptimisticDepositsTableItem key={ keys[index] } item={ item } isLoading={ isLoading }/> )) } <TableRow ref={ cutRef }/> </TableBody> diff --git a/src/features/rollup/optimism/pages/deposits/OptimisticL2Deposits.pw.tsx b/src/features/rollup/optimism/pages/deposits/OptimisticL2Deposits.pw.tsx index d3d2917292c..c21ca12179d 100644 --- a/src/features/rollup/optimism/pages/deposits/OptimisticL2Deposits.pw.tsx +++ b/src/features/rollup/optimism/pages/deposits/OptimisticL2Deposits.pw.tsx @@ -7,10 +7,7 @@ import { test, expect } from 'playwright/lib'; import OptimisticL2Deposits from './OptimisticL2Deposits'; -test('base view +@mobile', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { - // test on mobile is flaky - // my assumption is there is not enough time to calculate hashes truncation so component is unstable - // so I raised the test timeout to check if it helps +test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { test.slow(); await mockEnvs(ENVS_MAP.optimisticRollup); await mockTextAd(); diff --git a/src/features/rollup/optimism/pages/deposits/OptimisticL2Deposits.tsx b/src/features/rollup/optimism/pages/deposits/OptimisticL2Deposits.tsx index 3c83a9a0a8a..46c271ebaa6 100644 --- a/src/features/rollup/optimism/pages/deposits/OptimisticL2Deposits.tsx +++ b/src/features/rollup/optimism/pages/deposits/OptimisticL2Deposits.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -9,20 +8,20 @@ import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; import { layerLabels } from 'src/features/rollup/common/utils/layer'; -import OptimisticDepositsList from 'src/features/rollup/optimism/pages/deposits/OptimisticDepositsList'; import OptimisticDepositsTable from 'src/features/rollup/optimism/pages/deposits/OptimisticDepositsTable'; import { L2_DEPOSIT_ITEM } from 'src/features/rollup/optimism/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { rightLineArrow, nbsp } from 'src/toolkit/utils/htmlEntities'; const OptimisticL2Deposits = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:optimistic_l2_deposits', options: { placeholderData: generateListStub<'core:optimistic_l2_deposits'>( @@ -46,19 +45,14 @@ const OptimisticL2Deposits = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <OptimisticDepositsList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <OptimisticDepositsTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <OptimisticDepositsTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -83,6 +77,7 @@ const OptimisticL2Deposits = () => { itemsNum={ data?.items?.length } emptyText="There are no deposits." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/optimism/pages/deposits/__screenshots__/OptimisticL2Deposits.pw.tsx_default_base-view-1.png b/src/features/rollup/optimism/pages/deposits/__screenshots__/OptimisticL2Deposits.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..098667ea3cf Binary files /dev/null and b/src/features/rollup/optimism/pages/deposits/__screenshots__/OptimisticL2Deposits.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/optimism/pages/deposits/__screenshots__/OptimisticL2Deposits.pw.tsx_default_base-view-mobile-1.png b/src/features/rollup/optimism/pages/deposits/__screenshots__/OptimisticL2Deposits.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 0638b8fe3ba..00000000000 Binary files a/src/features/rollup/optimism/pages/deposits/__screenshots__/OptimisticL2Deposits.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/optimism/pages/deposits/__screenshots__/OptimisticL2Deposits.pw.tsx_mobile_base-view-mobile-1.png b/src/features/rollup/optimism/pages/deposits/__screenshots__/OptimisticL2Deposits.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 30a0fc058a6..00000000000 Binary files a/src/features/rollup/optimism/pages/deposits/__screenshots__/OptimisticL2Deposits.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGames.pw.tsx b/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGames.pw.tsx index 8c229ca5c81..07b3b324900 100644 --- a/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGames.pw.tsx +++ b/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGames.pw.tsx @@ -7,7 +7,7 @@ import { test, expect } from 'playwright/lib'; import OptimisticL2DisputeGames from './OptimisticL2DisputeGames'; -test('base view +@mobile', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { +test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { test.slow(); await mockEnvs(ENVS_MAP.optimisticRollup); await mockTextAd(); diff --git a/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGames.tsx b/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGames.tsx index ef07f004723..43988dde042 100644 --- a/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGames.tsx +++ b/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGames.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Text } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -12,16 +12,16 @@ import { L2_DISPUTE_GAMES_ITEM } from 'src/features/rollup/optimism/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import OptimisticL2DisputeGamesList from './OptimisticL2DisputeGamesList'; import OptimisticL2DisputeGamesTable from './OptimisticL2DisputeGamesTable'; const OptimisticL2DisputeGames = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:optimistic_l2_dispute_games', options: { placeholderData: generateListStub<'core:optimistic_l2_dispute_games'>( @@ -44,19 +44,14 @@ const OptimisticL2DisputeGames = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <OptimisticL2DisputeGamesList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <OptimisticL2DisputeGamesTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <OptimisticL2DisputeGamesTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -65,7 +60,7 @@ const OptimisticL2DisputeGames = () => { } return ( - <Skeleton loading={ countersQuery.isPlaceholderData || isPlaceholderData } display="flex" flexWrap="wrap"> + <Skeleton loading={ countersQuery.isPlaceholderData || isInitialLoading } display="flex" flexWrap="wrap"> Dispute game index <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[0].index } </Text>to <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[data.items.length - 1].index } </Text> @@ -84,6 +79,7 @@ const OptimisticL2DisputeGames = () => { itemsNum={ data?.items.length } emptyText="There are no dispute games." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesList.tsx b/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesList.tsx deleted file mode 100644 index ef6b07bb4b6..00000000000 --- a/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import OptimisticL2DisputeGamesListItem from './OptimisticL2DisputeGamesListItem'; - -type Props = { - items: Array<schemas['OptimismGame']>; - isLoading?: boolean; - resetKey?: string; -}; - -const OptimisticL2DisputeGamesList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <OptimisticL2DisputeGamesListItem - key={ item.index + (isLoading ? String(index) : '') } - item={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default OptimisticL2DisputeGamesList; diff --git a/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesTable.tsx b/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesTable.tsx index 96be0a60ed9..8de52cdacd6 100644 --- a/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesTable.tsx +++ b/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesTable.tsx @@ -7,6 +7,7 @@ import type { schemas } from '@blockscout/api-types'; import { layerLabels } from 'src/features/rollup/common/utils/layer'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -21,8 +22,11 @@ type Props = { resetKey?: string; }; +const getBaseKey = (item: schemas['OptimismGame']): string => String(item.index); + const OptimisticL2DisputeGamesTable = ({ items, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( <TableRoot tableLayout="auto" minW="950px"> @@ -54,7 +58,7 @@ const OptimisticL2DisputeGamesTable = ({ items, top, isLoading, resetKey }: Prop <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( <OptimisticL2DisputeGamesTableItem - key={ String(item.index) + (isLoading ? index : '') } + key={ keys[index] } item={ item } isLoading={ isLoading } /> diff --git a/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesTableItem.tsx b/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesTableItem.tsx index 4a64fcef501..fa8c14ecdb6 100644 --- a/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesTableItem.tsx +++ b/src/features/rollup/optimism/pages/dispute-games/OptimisticL2DisputeGamesTableItem.tsx @@ -9,10 +9,12 @@ import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShorten from 'src/shared/texts/HashStringShorten'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; + +import OptimisticL2DisputeGameL2Position from './OptimisticL2DisputeGameL2Position'; import OptimisticL2DisputeGameL2Position from './OptimisticL2DisputeGameL2Position'; @@ -34,7 +36,7 @@ const OptimisticL2DisputeGamesTableItem = ({ item, isLoading }: Props) => { <TableCell verticalAlign="middle"> <Flex overflow="hidden" w="100%" alignItems="center"> <Skeleton loading={ isLoading }> - <HashStringShorten hash={ item.contract_address_hash } type="long"/> + <Truncate value={ item.contract_address_hash } type="middle-static" maxSymbols={ 16 }/> </Skeleton> <CopyToClipboard text={ item.contract_address_hash } ml={ 2 } isLoading={ isLoading }/> </Flex> diff --git a/src/features/rollup/optimism/pages/dispute-games/__screenshots__/OptimisticL2DisputeGames.pw.tsx_default_base-view-1.png b/src/features/rollup/optimism/pages/dispute-games/__screenshots__/OptimisticL2DisputeGames.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..dd07ac7d937 Binary files /dev/null and b/src/features/rollup/optimism/pages/dispute-games/__screenshots__/OptimisticL2DisputeGames.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/optimism/pages/home/LatestOptimisticDeposits.pw.tsx b/src/features/rollup/optimism/pages/home/LatestOptimisticDeposits.pw.tsx index 00ddda31171..34a3ac7f93e 100644 --- a/src/features/rollup/optimism/pages/home/LatestOptimisticDeposits.pw.tsx +++ b/src/features/rollup/optimism/pages/home/LatestOptimisticDeposits.pw.tsx @@ -7,7 +7,7 @@ import { test, expect } from 'playwright/lib'; import LatestOptimisticDeposits from './LatestOptimisticDeposits'; -test('default view +@mobile +@dark-mode', async({ render, mockApiResponse, mockEnvs }) => { +test('default view +@dark-mode', async({ render, mockApiResponse, mockEnvs }) => { await mockEnvs(ENVS_MAP.optimisticRollup); mockApiResponse('core:homepage_optimistic_deposits', depositMock.data.items); const component = await render(<LatestOptimisticDeposits/>); diff --git a/src/features/rollup/optimism/pages/home/LatestOptimisticDeposits.tsx b/src/features/rollup/optimism/pages/home/LatestOptimisticDeposits.tsx index 4b4c0a0b00d..a93f264ee55 100644 --- a/src/features/rollup/optimism/pages/home/LatestOptimisticDeposits.tsx +++ b/src/features/rollup/optimism/pages/home/LatestOptimisticDeposits.tsx @@ -14,12 +14,10 @@ import LatestTxsFallback from 'src/slices/home/pages/index/txs/LatestTxsFallback import LatestDeposits from 'src/features/rollup/common/pages/home/LatestDeposits'; import { L2_DEPOSIT_ITEM } from 'src/features/rollup/optimism/stubs'; -import useIsMobile from 'src/shared/hooks/useIsMobile'; import useGradualIncrement from 'src/shared/numbers/useGradualIncrement'; const LatestOptimisticDeposits = () => { - const isMobile = useIsMobile(); - const itemsCount = isMobile ? 2 : 5; + const itemsCount = 5; const { data, isPlaceholderData, isError } = useApiQuery('core:homepage_optimistic_deposits', { queryOptions: { placeholderData: Array(itemsCount).fill(L2_DEPOSIT_ITEM), diff --git a/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_dark-color-mode_default-view-dark-mode-1.png b/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_dark-color-mode_default-view-dark-mode-1.png new file mode 100644 index 00000000000..34434f075c7 Binary files /dev/null and b/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_dark-color-mode_default-view-dark-mode-1.png differ diff --git a/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png b/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png deleted file mode 100644 index 83f2acce8cc..00000000000 Binary files a/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_default_default-view-dark-mode-1.png b/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_default_default-view-dark-mode-1.png new file mode 100644 index 00000000000..e3a4ab3a46d Binary files /dev/null and b/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_default_default-view-dark-mode-1.png differ diff --git a/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_default_default-view-mobile-dark-mode-1.png b/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_default_default-view-mobile-dark-mode-1.png deleted file mode 100644 index afca6fb4d8d..00000000000 Binary files a/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_default_default-view-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_mobile_default-view-mobile-dark-mode-1.png b/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_mobile_default-view-mobile-dark-mode-1.png deleted file mode 100644 index f904a66ad65..00000000000 Binary files a/src/features/rollup/optimism/pages/home/__screenshots__/LatestOptimisticDeposits.pw.tsx_mobile_default-view-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRoots.pw.tsx b/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRoots.pw.tsx index 53ced8135e2..c0c5788876c 100644 --- a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRoots.pw.tsx +++ b/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRoots.pw.tsx @@ -7,7 +7,7 @@ import { test, expect } from 'playwright/lib'; import OptimisticL2OutputRoots from './OptimisticL2OutputRoots'; -test('base view +@mobile', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { +test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { test.slow(); await mockEnvs(ENVS_MAP.optimisticRollup); await mockTextAd(); diff --git a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRoots.tsx b/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRoots.tsx index fa61b0782eb..05fb8d94cda 100644 --- a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRoots.tsx +++ b/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRoots.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Text } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -13,16 +13,16 @@ import { L2_OUTPUT_ROOTS_ITEM } from 'src/features/rollup/optimism/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import OptimisticL2OutputRootsList from './OptimisticL2OutputRootsList'; import OptimisticL2OutputRootsTable from './OptimisticL2OutputRootsTable'; const OptimisticL2OutputRoots = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:optimistic_l2_output_roots', options: { placeholderData: generateListStub<'core:optimistic_l2_output_roots'>( @@ -45,19 +45,14 @@ const OptimisticL2OutputRoots = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <OptimisticL2OutputRootsList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <OptimisticL2OutputRootsTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <OptimisticL2OutputRootsTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -66,7 +61,7 @@ const OptimisticL2OutputRoots = () => { } return ( - <Skeleton loading={ countersQuery.isPlaceholderData || isPlaceholderData } display="flex" flexWrap="wrap"> + <Skeleton loading={ countersQuery.isPlaceholderData || isInitialLoading } display="flex" flexWrap="wrap"> { layerLabels.current } output index <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[0].l2_output_index } </Text>to <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[data.items.length - 1].l2_output_index } </Text> @@ -85,6 +80,7 @@ const OptimisticL2OutputRoots = () => { itemsNum={ data?.items.length } emptyText="There are no output roots." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsList.tsx b/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsList.tsx deleted file mode 100644 index fd0de54bfa7..00000000000 --- a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import OptimisticL2OutputRootsListItem from './OptimisticL2OutputRootsListItem'; - -type Props = { - items: Array<schemas['OptimismOutputRoot']>; - isLoading?: boolean; - resetKey?: string; -}; - -const OptimisticL2OutputRootsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <OptimisticL2OutputRootsListItem - key={ item.l2_output_index + (isLoading ? String(index) : '') } - item={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default OptimisticL2OutputRootsList; diff --git a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsListItem.tsx b/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsListItem.tsx deleted file mode 100644 index d76f123cc92..00000000000 --- a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsListItem.tsx +++ /dev/null @@ -1,79 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import BlockEntityL2 from 'src/features/rollup/common/components/BlockEntityL2'; -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShorten from 'src/shared/texts/HashStringShorten'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -const rollupFeature = config.features.rollup; - -type Props = { item: schemas['OptimismOutputRoot']; isLoading?: boolean }; - -const OptimisticL2OutputRootsListItem = ({ item, isLoading }: Props) => { - if (!rollupFeature.isEnabled || rollupFeature.type !== 'optimistic') { - return null; - } - - return ( - <ListItemMobileGrid.Container> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } output index</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value fontWeight={ 600 } color="text.primary"> - <Skeleton loading={ isLoading } display="inline-block">{ item.l2_output_index }</Skeleton> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.l1_timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } block #</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntityL2 - isLoading={ isLoading } - number={ item.l2_block_number } - noIcon - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value py="3px"> - <TxEntityL1 - isLoading={ isLoading } - hash={ item.l1_transaction_hash } - truncation="constant_long" - noCopy - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Output root</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Flex overflow="hidden" whiteSpace="nowrap" alignItems="center" w="100%" justifyContent="start"> - <Skeleton loading={ isLoading } color="text.secondary"> - <HashStringShorten hash={ item.output_root } type="long"/> - </Skeleton> - <CopyToClipboard text={ item.output_root } isLoading={ isLoading }/> - </Flex> - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default OptimisticL2OutputRootsListItem; diff --git a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsTable.tsx b/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsTable.tsx index 226d5851990..491d55057a2 100644 --- a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsTable.tsx +++ b/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsTable.tsx @@ -40,7 +40,7 @@ const OptimisticL2OutputRootsTable = ({ items, top, isLoading, resetKey }: Props <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( <OptimisticL2OutputRootsTableItem - key={ item.l2_output_index + (Number(isLoading ? index : '') ? String(index) : '') } + key={ item.l2_output_index + (isLoading ? String(index) : '') } item={ item } isLoading={ isLoading } /> diff --git a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsTableItem.tsx b/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsTableItem.tsx index fe25002298e..3ee04f67eb0 100644 --- a/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsTableItem.tsx +++ b/src/features/rollup/optimism/pages/output-roots/OptimisticL2OutputRootsTableItem.tsx @@ -11,10 +11,10 @@ import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; import config from 'src/config'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShorten from 'src/shared/texts/HashStringShorten'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const rollupFeature = config.features.rollup; @@ -58,7 +58,7 @@ const OptimisticL2OutputRootsTableItem = ({ item, isLoading }: Props) => { <TableCell verticalAlign="middle"> <Flex overflow="hidden" w="100%" alignItems="center"> <Skeleton loading={ isLoading }> - <HashStringShorten hash={ item.output_root } type="long"/> + <Truncate value={ item.output_root } type="middle-static" maxSymbols={ 16 }/> </Skeleton> <CopyToClipboard text={ item.output_root } ml={ 2 } isLoading={ isLoading }/> </Flex> diff --git a/src/features/rollup/optimism/pages/output-roots/__screenshots__/OptimisticL2OutputRoots.pw.tsx_default_base-view-1.png b/src/features/rollup/optimism/pages/output-roots/__screenshots__/OptimisticL2OutputRoots.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..0bc129dc30f Binary files /dev/null and b/src/features/rollup/optimism/pages/output-roots/__screenshots__/OptimisticL2OutputRoots.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/optimism/pages/output-roots/__screenshots__/OptimisticL2OutputRoots.pw.tsx_default_base-view-mobile-1.png b/src/features/rollup/optimism/pages/output-roots/__screenshots__/OptimisticL2OutputRoots.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 45eca3685f3..00000000000 Binary files a/src/features/rollup/optimism/pages/output-roots/__screenshots__/OptimisticL2OutputRoots.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/optimism/pages/output-roots/__screenshots__/OptimisticL2OutputRoots.pw.tsx_mobile_base-view-mobile-1.png b/src/features/rollup/optimism/pages/output-roots/__screenshots__/OptimisticL2OutputRoots.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 2c5260181ea..00000000000 Binary files a/src/features/rollup/optimism/pages/output-roots/__screenshots__/OptimisticL2OutputRoots.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/optimism/pages/withdrawals/OptimisticL2Withdrawals.pw.tsx b/src/features/rollup/optimism/pages/withdrawals/OptimisticL2Withdrawals.pw.tsx index d5827e29bdf..b5b99950c7a 100644 --- a/src/features/rollup/optimism/pages/withdrawals/OptimisticL2Withdrawals.pw.tsx +++ b/src/features/rollup/optimism/pages/withdrawals/OptimisticL2Withdrawals.pw.tsx @@ -7,10 +7,7 @@ import { test, expect } from 'playwright/lib'; import OptimisticL2Withdrawals from './OptimisticL2Withdrawals'; -test('base view +@mobile', async({ render, mockTextAd, mockEnvs, mockApiResponse }) => { - // test on mobile is flaky - // my assumption is there is not enough time to calculate hashes truncation so component is unstable - // so I raised the test timeout to check if it helps +test('base view', async({ render, mockTextAd, mockEnvs, mockApiResponse }) => { test.slow(); await mockTextAd(); await mockEnvs(ENVS_MAP.optimisticRollup); diff --git a/src/features/rollup/optimism/pages/withdrawals/OptimisticL2Withdrawals.tsx b/src/features/rollup/optimism/pages/withdrawals/OptimisticL2Withdrawals.tsx index 2fdcc2c850a..867e849215f 100644 --- a/src/features/rollup/optimism/pages/withdrawals/OptimisticL2Withdrawals.tsx +++ b/src/features/rollup/optimism/pages/withdrawals/OptimisticL2Withdrawals.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -9,20 +8,20 @@ import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; import { layerLabels } from 'src/features/rollup/common/utils/layer'; -import OptimisticL2WithdrawalsList from 'src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsList'; import OptimisticL2WithdrawalsTable from 'src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsTable'; import { L2_WITHDRAWAL_ITEM } from 'src/features/rollup/optimism/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { rightLineArrow, nbsp } from 'src/toolkit/utils/htmlEntities'; const OptimisticL2Withdrawals = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:optimistic_l2_withdrawals', options: { placeholderData: generateListStub<'core:optimistic_l2_withdrawals'>( @@ -45,19 +44,14 @@ const OptimisticL2Withdrawals = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <OptimisticL2WithdrawalsList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <OptimisticL2WithdrawalsTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <OptimisticL2WithdrawalsTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -85,6 +79,7 @@ const OptimisticL2Withdrawals = () => { itemsNum={ data?.items?.length } emptyText="There are no withdrawals." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsList.tsx b/src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsList.tsx deleted file mode 100644 index c3748b132f2..00000000000 --- a/src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import OptimisticL2WithdrawalsListItem from './OptimisticL2WithdrawalsListItem'; - -type Props = { - items: Array<schemas['OptimismWithdrawal']>; - isLoading?: boolean; - resetKey?: string; -}; - -const OptimisticL2WithdrawalsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <OptimisticL2WithdrawalsListItem - key={ String(item.msg_nonce_version) + item.msg_nonce + (isLoading ? index : '') } - item={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default OptimisticL2WithdrawalsList; diff --git a/src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsListItem.tsx b/src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsListItem.tsx deleted file mode 100644 index c9460826e52..00000000000 --- a/src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsListItem.tsx +++ /dev/null @@ -1,108 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import dayjs from 'src/shared/date-and-time/dayjs'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -import OptimisticL2WithdrawalsItemStatus from './OptimisticL2WithdrawalsItemStatus'; - -const rollupFeature = config.features.rollup; - -type Props = { item: schemas['OptimismWithdrawal']; isLoading?: boolean }; - -const OptimisticL2WithdrawalsListItem = ({ item, isLoading }: Props) => { - const timeToEnd = item.challenge_period_end ? dayjs(item.challenge_period_end).fromNow(true) + ' left' : null; - - if (!rollupFeature.isEnabled || rollupFeature.type !== 'optimistic') { - return null; - } - - return ( - <ListItemMobileGrid.Container> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Msg nonce</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block"> - { item.msg_nonce_version + '-' + item.msg_nonce } - </Skeleton> - </ListItemMobileGrid.Value> - - { item.from && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>From</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity - address={ item.from } - isLoading={ isLoading } - truncation="constant" - /> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntity - isLoading={ isLoading } - hash={ item.l2_transaction_hash } - truncation="constant_long" - /> - </ListItemMobileGrid.Value> - - { item.l2_timestamp && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.l2_timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <OptimisticL2WithdrawalsItemStatus data={ item } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - { item.l1_transaction_hash && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntityL1 - isLoading={ isLoading } - hash={ item.l1_transaction_hash } - truncation="constant_long" - noCopy - /> - </ListItemMobileGrid.Value> - </> - ) } - - { timeToEnd && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Time left</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value>{ timeToEnd }</ListItemMobileGrid.Value> - </> - ) } - - </ListItemMobileGrid.Container> - ); -}; - -export default OptimisticL2WithdrawalsListItem; diff --git a/src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsTable.tsx b/src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsTable.tsx index 7afac79aebe..41f620bfb46 100644 --- a/src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsTable.tsx +++ b/src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsTable.tsx @@ -9,6 +9,7 @@ import { AddressHighlightProvider } from 'src/slices/address/contexts/address-hi import { layerLabels } from 'src/features/rollup/common/utils/layer'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -22,8 +23,11 @@ type Props = { resetKey?: string; }; +const getBaseKey = (item: schemas['OptimismWithdrawal']): string => String(item.msg_nonce_version) + item.msg_nonce; + const OptimisticL2WithdrawalsTable = ({ items, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( <AddressHighlightProvider> @@ -45,7 +49,7 @@ const OptimisticL2WithdrawalsTable = ({ items, top, isLoading, resetKey }: Props <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( <OptimisticL2WithdrawalsTableItem - key={ String(item.msg_nonce_version) + item.msg_nonce + (isLoading ? index : '') } + key={ keys[index] } item={ item } isLoading={ isLoading } /> diff --git a/src/features/rollup/optimism/pages/withdrawals/__screenshots__/OptimisticL2Withdrawals.pw.tsx_default_base-view-1.png b/src/features/rollup/optimism/pages/withdrawals/__screenshots__/OptimisticL2Withdrawals.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..be4f2aee476 Binary files /dev/null and b/src/features/rollup/optimism/pages/withdrawals/__screenshots__/OptimisticL2Withdrawals.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/optimism/pages/withdrawals/__screenshots__/OptimisticL2Withdrawals.pw.tsx_default_base-view-mobile-1.png b/src/features/rollup/optimism/pages/withdrawals/__screenshots__/OptimisticL2Withdrawals.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index d1759e4435e..00000000000 Binary files a/src/features/rollup/optimism/pages/withdrawals/__screenshots__/OptimisticL2Withdrawals.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/optimism/pages/withdrawals/__screenshots__/OptimisticL2Withdrawals.pw.tsx_mobile_base-view-mobile-1.png b/src/features/rollup/optimism/pages/withdrawals/__screenshots__/OptimisticL2Withdrawals.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index a0f51211c0a..00000000000 Binary files a/src/features/rollup/optimism/pages/withdrawals/__screenshots__/OptimisticL2Withdrawals.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/scroll/pages/batch-details/ScrollL2TxnBatch.tsx b/src/features/rollup/scroll/pages/batch-details/ScrollL2TxnBatch.tsx index 8770efeec74..35278855604 100644 --- a/src/features/rollup/scroll/pages/batch-details/ScrollL2TxnBatch.tsx +++ b/src/features/rollup/scroll/pages/batch-details/ScrollL2TxnBatch.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -21,9 +20,10 @@ import throwOnAbsentParamError from 'src/shared/errors/throw-on-absent-param-err import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -51,7 +51,7 @@ const ScrollL2TxnBatch = () => { }, }); - const batchTxsQuery = useQueryWithPages({ + const batchTxsQuery = useApiPaginatedQuery({ resourceName: 'core:scroll_l2_txn_batch_txs', pathParams: { number }, options: { @@ -65,7 +65,7 @@ const ScrollL2TxnBatch = () => { }, }); - const batchBlocksQuery = useQueryWithPages({ + const batchBlocksQuery = useApiPaginatedQuery({ resourceName: 'core:scroll_l2_txn_batch_blocks', pathParams: { number }, options: { diff --git a/src/features/rollup/scroll/pages/batch-details/ScrollL2TxnBatchDetails.tsx b/src/features/rollup/scroll/pages/batch-details/ScrollL2TxnBatchDetails.tsx index 22d79ebe2d9..c15f3be1ea6 100644 --- a/src/features/rollup/scroll/pages/batch-details/ScrollL2TxnBatchDetails.tsx +++ b/src/features/rollup/scroll/pages/batch-details/ScrollL2TxnBatchDetails.tsx @@ -1,8 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { UseQueryResult } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -21,6 +19,8 @@ import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import DetailedInfoTimestamp from 'src/shared/detailed-info/DetailedInfoTimestamp'; import isCustomAppError from 'src/shared/errors/is-custom-app-error'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; +import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; @@ -41,7 +41,7 @@ const ScrollL2TxnBatchDetails = ({ query }: Props) => { const increment = direction === 'next' ? +1 : -1; const nextId = String(data.number + increment); - router.push({ pathname: '/batches/[number]', query: { number: nextId } }, undefined); + router.push({ pathname: '/batches/[number]', query: { number: nextId } }); }, [ data, router ]); if (isError) { diff --git a/src/features/rollup/scroll/pages/batch-details/__screenshots__/ScrollL2TxnBatch.pw.tsx_default_base-view-1.png b/src/features/rollup/scroll/pages/batch-details/__screenshots__/ScrollL2TxnBatch.pw.tsx_default_base-view-1.png index f160d2874f0..9a87389bd3d 100644 Binary files a/src/features/rollup/scroll/pages/batch-details/__screenshots__/ScrollL2TxnBatch.pw.tsx_default_base-view-1.png and b/src/features/rollup/scroll/pages/batch-details/__screenshots__/ScrollL2TxnBatch.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/scroll/pages/batch-details/__screenshots__/ScrollL2TxnBatch.pw.tsx_default_mobile-base-view-1.png b/src/features/rollup/scroll/pages/batch-details/__screenshots__/ScrollL2TxnBatch.pw.tsx_default_mobile-base-view-1.png index 0695c2f30f1..8382bb0e65d 100644 Binary files a/src/features/rollup/scroll/pages/batch-details/__screenshots__/ScrollL2TxnBatch.pw.tsx_default_mobile-base-view-1.png and b/src/features/rollup/scroll/pages/batch-details/__screenshots__/ScrollL2TxnBatch.pw.tsx_default_mobile-base-view-1.png differ diff --git a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatches.pw.tsx b/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatches.pw.tsx index e52d24b89c5..659d6246e41 100644 --- a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatches.pw.tsx +++ b/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatches.pw.tsx @@ -3,7 +3,7 @@ import React from 'react'; import * as scrollTxnBatchesMock from 'src/features/rollup/scroll/mocks/txn-batches'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; -import { test, expect, devices } from 'playwright/lib'; +import { test, expect } from 'playwright/lib'; import ScrollL2TxnBatches from './ScrollL2TxnBatches'; @@ -17,18 +17,3 @@ test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { const component = await render(<ScrollL2TxnBatches/>); await expect(component).toHaveScreenshot(); }); - -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - - test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { - test.slow(); - await mockEnvs(ENVS_MAP.scrollRollup); - await mockTextAd(); - await mockApiResponse('core:scroll_l2_txn_batches', scrollTxnBatchesMock.baseResponse); - await mockApiResponse('core:scroll_l2_txn_batches_count', 9927); - - const component = await render(<ScrollL2TxnBatches/>); - await expect(component).toHaveScreenshot(); - }); -}); diff --git a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatches.tsx b/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatches.tsx index fd4994c65a4..82c42dac8f3 100644 --- a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatches.tsx +++ b/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatches.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Text } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -12,16 +12,16 @@ import { SCROLL_L2_TXN_BATCH } from 'src/features/rollup/scroll/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import ScrollL2TxnBatchesList from './ScrollL2TxnBatchesList'; import ScrollL2TxnBatchesTable from './ScrollL2TxnBatchesTable'; const ScrollL2TxnBatches = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:scroll_l2_txn_batches', options: { placeholderData: generateListStub<'core:scroll_l2_txn_batches'>( @@ -44,19 +44,14 @@ const ScrollL2TxnBatches = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <ScrollL2TxnBatchesList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <ScrollL2TxnBatchesTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <ScrollL2TxnBatchesTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -65,7 +60,7 @@ const ScrollL2TxnBatches = () => { } return ( - <Skeleton loading={ countersQuery.isPlaceholderData || isPlaceholderData } display="flex" flexWrap="wrap"> + <Skeleton loading={ countersQuery.isPlaceholderData || isInitialLoading } display="flex" flexWrap="wrap"> Txn batch <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[0].number } </Text>to <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[data.items.length - 1].number } </Text> @@ -84,6 +79,7 @@ const ScrollL2TxnBatches = () => { itemsNum={ data?.items?.length } emptyText="There are no txn batches." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesList.tsx b/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesList.tsx deleted file mode 100644 index 84f85a3d00e..00000000000 --- a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ScrollL2TxnBatchesListItem from './ScrollL2TxnBatchesListItem'; - -type Props = { - items: Array<schemas['ScrollBatch']>; - isLoading?: boolean; - resetKey?: string; -}; - -const ScrollL2TxnBatchesList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <ScrollL2TxnBatchesListItem - key={ item.number + (isLoading ? String(index) : '') } - item={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default ScrollL2TxnBatchesList; diff --git a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesListItem.tsx b/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesListItem.tsx deleted file mode 100644 index 0632993092a..00000000000 --- a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesListItem.tsx +++ /dev/null @@ -1,132 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { route } from 'nextjs-routes'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import BatchEntityL2 from 'src/features/rollup/common/components/BatchEntityL2'; -import BlockEntityL1 from 'src/features/rollup/common/components/BlockEntityL1'; -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import ScrollL2TxnBatchDA from 'src/features/rollup/scroll/components/ScrollL2TxnBatchDA'; -import ScrollL2TxnBatchStatus from 'src/features/rollup/scroll/components/ScrollL2TxnBatchStatus'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -const rollupFeature = config.features.rollup; - -type Props = { item: schemas['ScrollBatch']; isLoading?: boolean }; - -const ScrollL2TxnBatchesListItem = ({ item, isLoading }: Props) => { - if (!rollupFeature.isEnabled || rollupFeature.type !== 'scroll') { - return null; - } - - return ( - <ListItemMobileGrid.Container gridTemplateColumns="110px auto"> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Batch #</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BatchEntityL2 - isLoading={ isLoading } - number={ item.number } - fontWeight={ 600 } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Data availability</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <ScrollL2TxnBatchDA container={ item.data_availability.batch_data_container } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <ScrollL2TxnBatchStatus status={ item.confirmation_transaction.hash ? 'Finalized' : 'Committed' } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Committed block</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntityL1 - number={ item.commitment_transaction.block_number } - isLoading={ isLoading } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Committed txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntityL1 - hash={ item.commitment_transaction.hash } - isLoading={ isLoading } - noCopy - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.commitment_transaction.timestamp } - fallbackText="Undefined" - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Finalized block</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { item.confirmation_transaction.block_number ? ( - <BlockEntityL1 - number={ item.confirmation_transaction.block_number } - isLoading={ isLoading } - /> - ) : <Skeleton loading={ isLoading } display="inline-block">Pending</Skeleton> } - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Finalized txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { item.confirmation_transaction.hash ? ( - <TxEntityL1 - hash={ item.confirmation_transaction.hash } - isLoading={ isLoading } - noCopy - /> - ) : <Skeleton loading={ isLoading } display="inline-block">Pending</Skeleton> } - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Blocks count</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Link - href={ route({ pathname: '/batches/[number]', query: { number: item.number.toString(), tab: 'blocks' } }) } - loading={ isLoading } - fontWeight={ 600 } - minW="40px" - > - { (item.end_block_number && item.start_block_number ? item.end_block_number - item.start_block_number + 1 : 0).toLocaleString() } - </Link> - </ListItemMobileGrid.Value> - - { typeof item.transactions_count === 'number' ? ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Txn count</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Link - href={ route({ pathname: '/batches/[number]', query: { number: item.number.toString(), tab: 'txs' } }) } - loading={ isLoading } - fontWeight={ 600 } - minW="40px" - > - { item.transactions_count.toLocaleString() } - </Link> - </ListItemMobileGrid.Value> - </> - ) : null } - - </ListItemMobileGrid.Container> - ); -}; - -export default ScrollL2TxnBatchesListItem; diff --git a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesTable.tsx b/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesTable.tsx index 163c1e26ee5..5e338174ed6 100644 --- a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesTable.tsx +++ b/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesTable.tsx @@ -22,7 +22,7 @@ const ScrollL2TxnBatchesTable = ({ items, top, isLoading, resetKey }: Props) => const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); return ( - <TableRoot tableLayout="auto" minW="1000px"> + <TableRoot tableLayout="auto" minW="1100px"> <TableHeaderSticky top={ top }> <TableRow> <TableColumnHeader>Batch #</TableColumnHeader> diff --git a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesTableItem.tsx b/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesTableItem.tsx index 0d50880d6b5..19269a88067 100644 --- a/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesTableItem.tsx +++ b/src/features/rollup/scroll/pages/batches/ScrollL2TxnBatchesTableItem.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -13,6 +12,7 @@ import ScrollL2TxnBatchStatus from 'src/features/rollup/scroll/components/Scroll import config from 'src/config'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; @@ -47,6 +47,7 @@ const ScrollL2TxnBatchesTableItem = ({ item, isLoading }: Props) => { <BlockEntityL1 number={ item.commitment_transaction.block_number } isLoading={ isLoading } + noIcon /> </TableCell> <TableCell verticalAlign="middle"> @@ -55,6 +56,7 @@ const ScrollL2TxnBatchesTableItem = ({ item, isLoading }: Props) => { isLoading={ isLoading } truncation="constant_long" noCopy + noIcon /> </TableCell> <TableCell verticalAlign="middle"> @@ -70,6 +72,7 @@ const ScrollL2TxnBatchesTableItem = ({ item, isLoading }: Props) => { <BlockEntityL1 number={ item.confirmation_transaction.block_number } isLoading={ isLoading } + noIcon /> ) : <Skeleton loading={ isLoading } display="inline-block">Pending</Skeleton> } </TableCell> @@ -80,6 +83,7 @@ const ScrollL2TxnBatchesTableItem = ({ item, isLoading }: Props) => { isLoading={ isLoading } truncation="constant_long" noCopy + noIcon /> ) : <Skeleton loading={ isLoading } display="inline-block">Pending</Skeleton> } </TableCell> diff --git a/src/features/rollup/scroll/pages/batches/__screenshots__/ScrollL2TxnBatches.pw.tsx_default_base-view-1.png b/src/features/rollup/scroll/pages/batches/__screenshots__/ScrollL2TxnBatches.pw.tsx_default_base-view-1.png index b5a0f1f2fc3..d06125f0e94 100644 Binary files a/src/features/rollup/scroll/pages/batches/__screenshots__/ScrollL2TxnBatches.pw.tsx_default_base-view-1.png and b/src/features/rollup/scroll/pages/batches/__screenshots__/ScrollL2TxnBatches.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/scroll/pages/batches/__screenshots__/ScrollL2TxnBatches.pw.tsx_default_mobile-base-view-1.png b/src/features/rollup/scroll/pages/batches/__screenshots__/ScrollL2TxnBatches.pw.tsx_default_mobile-base-view-1.png deleted file mode 100644 index 64c55f7dd9c..00000000000 Binary files a/src/features/rollup/scroll/pages/batches/__screenshots__/ScrollL2TxnBatches.pw.tsx_default_mobile-base-view-1.png and /dev/null differ diff --git a/src/features/rollup/scroll/pages/deposits/ScrollL2Deposits.pw.tsx b/src/features/rollup/scroll/pages/deposits/ScrollL2Deposits.pw.tsx index 450ac0cdc7b..7ab44849f7c 100644 --- a/src/features/rollup/scroll/pages/deposits/ScrollL2Deposits.pw.tsx +++ b/src/features/rollup/scroll/pages/deposits/ScrollL2Deposits.pw.tsx @@ -3,7 +3,7 @@ import React from 'react'; import * as messagesMock from 'src/features/rollup/scroll/mocks/messages'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; -import { test, expect, devices } from 'playwright/lib'; +import { test, expect } from 'playwright/lib'; import ScrollL2Deposits from './ScrollL2Deposits'; @@ -17,18 +17,3 @@ test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { await expect(component).toHaveScreenshot(); }); - -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - - test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { - await mockTextAd(); - await mockEnvs(ENVS_MAP.scrollRollup); - await mockApiResponse('core:scroll_l2_deposits', messagesMock.baseResponse); - await mockApiResponse('core:scroll_l2_deposits_count', 3971111); - - const component = await render(<ScrollL2Deposits/>); - - await expect(component).toHaveScreenshot(); - }); -}); diff --git a/src/features/rollup/scroll/pages/deposits/ScrollL2Deposits.tsx b/src/features/rollup/scroll/pages/deposits/ScrollL2Deposits.tsx index 46c8b682951..70a671caeda 100644 --- a/src/features/rollup/scroll/pages/deposits/ScrollL2Deposits.tsx +++ b/src/features/rollup/scroll/pages/deposits/ScrollL2Deposits.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -13,17 +12,17 @@ import { SCROLL_L2_MESSAGE_ITEM } from 'src/features/rollup/scroll/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { rightLineArrow, nbsp } from 'src/toolkit/utils/htmlEntities'; -import ScrollL2DepositsList from './ScrollL2DepositsList'; import ScrollL2DepositsTable from './ScrollL2DepositsTable'; const ScrollL2Deposits = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:scroll_l2_deposits', options: { placeholderData: generateListStub<'core:scroll_l2_deposits'>( @@ -41,19 +40,14 @@ const ScrollL2Deposits = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <ScrollL2DepositsList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <ScrollL2DepositsTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <ScrollL2DepositsTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -81,6 +75,7 @@ const ScrollL2Deposits = () => { itemsNum={ data?.items?.length } emptyText="There are no deposits." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/scroll/pages/deposits/ScrollL2DepositsList.tsx b/src/features/rollup/scroll/pages/deposits/ScrollL2DepositsList.tsx deleted file mode 100644 index 26214a6e95d..00000000000 --- a/src/features/rollup/scroll/pages/deposits/ScrollL2DepositsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ScrollL2DepositsListItem from './ScrollL2DepositsListItem'; - -type Props = { - items: Array<schemas['ScrollBridge']>; - isLoading?: boolean; - resetKey?: string; -}; - -const ScrollL2DepositsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <ScrollL2DepositsListItem - key={ String(item.id) + (isLoading ? index : '') } - isLoading={ isLoading } - item={ item } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default ScrollL2DepositsList; diff --git a/src/features/rollup/scroll/pages/deposits/ScrollL2DepositsListItem.tsx b/src/features/rollup/scroll/pages/deposits/ScrollL2DepositsListItem.tsx deleted file mode 100644 index 1775c5bfee4..00000000000 --- a/src/features/rollup/scroll/pages/deposits/ScrollL2DepositsListItem.tsx +++ /dev/null @@ -1,102 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { chakra } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import BlockEntityL1 from 'src/features/rollup/common/components/BlockEntityL1'; -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -const rollupFeature = config.features.rollup; - -type Props = { item: schemas['ScrollBridge']; isLoading?: boolean }; - -const ScrollL2DepositsListItem = ({ item, isLoading }: Props) => { - if (!rollupFeature.isEnabled || rollupFeature.type !== 'scroll') { - return null; - } - - return ( - <ListItemMobileGrid.Container> - - { item.origination_transaction_block_number && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } block</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntityL1 - number={ item.origination_transaction_block_number } - isLoading={ isLoading } - fontWeight={ 600 } - /> - </ListItemMobileGrid.Value></> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Index</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block"> - { item.id } - </Skeleton> - </ListItemMobileGrid.Value> - - { item.origination_transaction_hash && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntityL1 - isLoading={ isLoading } - hash={ item.origination_transaction_hash } - truncation="constant_long" - noCopy - /> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.origination_timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { item.completion_transaction_hash ? ( - <TxEntity - isLoading={ isLoading } - hash={ item.completion_transaction_hash } - truncation="constant_long" - /> - ) : ( - <chakra.span> - Pending Claim - </chakra.span> - ) } - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Value</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <NativeCoinValue - amount={ item.value } - loading={ isLoading } - /> - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default ScrollL2DepositsListItem; diff --git a/src/features/rollup/scroll/pages/deposits/ScrollL2DepositsTable.tsx b/src/features/rollup/scroll/pages/deposits/ScrollL2DepositsTable.tsx index 5ae53a38e3e..55b4d685a2e 100644 --- a/src/features/rollup/scroll/pages/deposits/ScrollL2DepositsTable.tsx +++ b/src/features/rollup/scroll/pages/deposits/ScrollL2DepositsTable.tsx @@ -10,6 +10,7 @@ import { layerLabels } from 'src/features/rollup/common/utils/layer'; import config from 'src/config'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -23,8 +24,11 @@ type Props = { resetKey?: string; }; +const getBaseKey = (item: schemas['ScrollBridge']): string => String(item.id); + const ScrollL2DepositsTable = ({ items, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( <AddressHighlightProvider> @@ -44,7 +48,7 @@ const ScrollL2DepositsTable = ({ items, top, isLoading, resetKey }: Props) => { </TableHeaderSticky> <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( - <ScrollL2DepositsTableItem key={ String(item.id) + (isLoading ? index : '') } item={ item } isLoading={ isLoading }/> + <ScrollL2DepositsTableItem key={ keys[index] } item={ item } isLoading={ isLoading }/> )) } <TableRow ref={ cutRef }/> </TableBody> diff --git a/src/features/rollup/scroll/pages/deposits/__screenshots__/ScrollL2Deposits.pw.tsx_default_base-view-1.png b/src/features/rollup/scroll/pages/deposits/__screenshots__/ScrollL2Deposits.pw.tsx_default_base-view-1.png index bf842b28670..e901b6db9f5 100644 Binary files a/src/features/rollup/scroll/pages/deposits/__screenshots__/ScrollL2Deposits.pw.tsx_default_base-view-1.png and b/src/features/rollup/scroll/pages/deposits/__screenshots__/ScrollL2Deposits.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/scroll/pages/deposits/__screenshots__/ScrollL2Deposits.pw.tsx_default_mobile-base-view-1.png b/src/features/rollup/scroll/pages/deposits/__screenshots__/ScrollL2Deposits.pw.tsx_default_mobile-base-view-1.png deleted file mode 100644 index 7b08c6cb782..00000000000 Binary files a/src/features/rollup/scroll/pages/deposits/__screenshots__/ScrollL2Deposits.pw.tsx_default_mobile-base-view-1.png and /dev/null differ diff --git a/src/features/rollup/scroll/pages/withdrawals/ScrollL2Withdrawals.pw.tsx b/src/features/rollup/scroll/pages/withdrawals/ScrollL2Withdrawals.pw.tsx index 8a2a76e86b2..3c0ec570be5 100644 --- a/src/features/rollup/scroll/pages/withdrawals/ScrollL2Withdrawals.pw.tsx +++ b/src/features/rollup/scroll/pages/withdrawals/ScrollL2Withdrawals.pw.tsx @@ -3,7 +3,7 @@ import React from 'react'; import * as messagesMock from 'src/features/rollup/scroll/mocks/messages'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; -import { test, expect, devices } from 'playwright/lib'; +import { test, expect } from 'playwright/lib'; import ScrollL2Withdrawals from './ScrollL2Withdrawals'; @@ -17,18 +17,3 @@ test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { await expect(component).toHaveScreenshot(); }); - -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - - test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { - await mockTextAd(); - await mockEnvs(ENVS_MAP.scrollRollup); - await mockApiResponse('core:scroll_l2_withdrawals', messagesMock.baseResponse); - await mockApiResponse('core:scroll_l2_withdrawals_count', 3971111); - - const component = await render(<ScrollL2Withdrawals/>); - - await expect(component).toHaveScreenshot(); - }); -}); diff --git a/src/features/rollup/scroll/pages/withdrawals/ScrollL2Withdrawals.tsx b/src/features/rollup/scroll/pages/withdrawals/ScrollL2Withdrawals.tsx index 3b698bc6414..cd450d70b3b 100644 --- a/src/features/rollup/scroll/pages/withdrawals/ScrollL2Withdrawals.tsx +++ b/src/features/rollup/scroll/pages/withdrawals/ScrollL2Withdrawals.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -13,17 +12,17 @@ import { SCROLL_L2_MESSAGE_ITEM } from 'src/features/rollup/scroll/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { rightLineArrow, nbsp } from 'src/toolkit/utils/htmlEntities'; -import ScrollL2WithdrawalsList from './ScrollL2WithdrawalsList'; import ScrollL2WithdrawalsTable from './ScrollL2WithdrawalsTable'; const ScrollL2Withdrawals = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:scroll_l2_withdrawals', options: { placeholderData: generateListStub<'core:scroll_l2_withdrawals'>( @@ -41,19 +40,14 @@ const ScrollL2Withdrawals = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <ScrollL2WithdrawalsList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <ScrollL2WithdrawalsTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <ScrollL2WithdrawalsTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -81,6 +75,7 @@ const ScrollL2Withdrawals = () => { itemsNum={ data?.items?.length } emptyText="There are no withdrawals." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/scroll/pages/withdrawals/ScrollL2WithdrawalsList.tsx b/src/features/rollup/scroll/pages/withdrawals/ScrollL2WithdrawalsList.tsx deleted file mode 100644 index 7b9537bae1b..00000000000 --- a/src/features/rollup/scroll/pages/withdrawals/ScrollL2WithdrawalsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ScrollL2WithdrawalsListItem from './ScrollL2WithdrawalsListItem'; - -type Props = { - items: Array<schemas['ScrollBridge']>; - isLoading?: boolean; - resetKey?: string; -}; - -const ScrollL2WithdrawalsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <ScrollL2WithdrawalsListItem - key={ String(item.id) + (isLoading ? index : '') } - isLoading={ isLoading } - item={ item } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default ScrollL2WithdrawalsList; diff --git a/src/features/rollup/scroll/pages/withdrawals/ScrollL2WithdrawalsListItem.tsx b/src/features/rollup/scroll/pages/withdrawals/ScrollL2WithdrawalsListItem.tsx deleted file mode 100644 index 8c1e8d4d155..00000000000 --- a/src/features/rollup/scroll/pages/withdrawals/ScrollL2WithdrawalsListItem.tsx +++ /dev/null @@ -1,104 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { chakra } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -const rollupFeature = config.features.rollup; - -type Props = { item: schemas['ScrollBridge']; isLoading?: boolean }; - -const ScrollL2WithdrawalsListItem = ({ item, isLoading }: Props) => { - if (!rollupFeature.isEnabled || rollupFeature.type !== 'scroll') { - return null; - } - - return ( - <ListItemMobileGrid.Container> - - { item.origination_transaction_block_number && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } block</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntity - number={ item.origination_transaction_block_number } - isLoading={ isLoading } - fontWeight={ 600 } - /> - </ListItemMobileGrid.Value> - </> - ) - } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Index</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Skeleton loading={ isLoading } display="inline-block"> - { item.id } - </Skeleton> - </ListItemMobileGrid.Value> - - { item.origination_transaction_hash && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntity - isLoading={ isLoading } - hash={ item.origination_transaction_hash } - truncation="constant_long" - /> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.origination_timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { item.completion_transaction_hash ? ( - <TxEntityL1 - isLoading={ isLoading } - hash={ item.completion_transaction_hash } - truncation="constant_long" - noCopy - /> - ) : ( - <chakra.span> - Pending Claim - </chakra.span> - ) } - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Value</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <NativeCoinValue - amount={ item.value } - loading={ isLoading } - /> - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default ScrollL2WithdrawalsListItem; diff --git a/src/features/rollup/scroll/pages/withdrawals/ScrollL2WithdrawalsTable.tsx b/src/features/rollup/scroll/pages/withdrawals/ScrollL2WithdrawalsTable.tsx index c571e1b36ae..62a672b9f36 100644 --- a/src/features/rollup/scroll/pages/withdrawals/ScrollL2WithdrawalsTable.tsx +++ b/src/features/rollup/scroll/pages/withdrawals/ScrollL2WithdrawalsTable.tsx @@ -10,6 +10,7 @@ import { layerLabels } from 'src/features/rollup/common/utils/layer'; import config from 'src/config'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -23,8 +24,11 @@ type Props = { resetKey?: string; }; +const getBaseKey = (item: schemas['ScrollBridge']): string => String(item.id); + const ScrollL2WithdrawalsTable = ({ items, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( <AddressHighlightProvider> @@ -44,7 +48,7 @@ const ScrollL2WithdrawalsTable = ({ items, top, isLoading, resetKey }: Props) => </TableHeaderSticky> <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( - <ScrollL2WithdrawalsTableItem key={ String(item.id) + (isLoading ? index : '') } item={ item } isLoading={ isLoading }/> + <ScrollL2WithdrawalsTableItem key={ keys[index] } item={ item } isLoading={ isLoading }/> )) } <TableRow ref={ cutRef }/> </TableBody> diff --git a/src/features/rollup/scroll/pages/withdrawals/__screenshots__/ScrollL2Withdrawals.pw.tsx_default_base-view-1.png b/src/features/rollup/scroll/pages/withdrawals/__screenshots__/ScrollL2Withdrawals.pw.tsx_default_base-view-1.png index 3f06b264dfa..ed17a801f71 100644 Binary files a/src/features/rollup/scroll/pages/withdrawals/__screenshots__/ScrollL2Withdrawals.pw.tsx_default_base-view-1.png and b/src/features/rollup/scroll/pages/withdrawals/__screenshots__/ScrollL2Withdrawals.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/scroll/pages/withdrawals/__screenshots__/ScrollL2Withdrawals.pw.tsx_default_mobile-base-view-1.png b/src/features/rollup/scroll/pages/withdrawals/__screenshots__/ScrollL2Withdrawals.pw.tsx_default_mobile-base-view-1.png deleted file mode 100644 index 16a5658fe27..00000000000 Binary files a/src/features/rollup/scroll/pages/withdrawals/__screenshots__/ScrollL2Withdrawals.pw.tsx_default_mobile-base-view-1.png and /dev/null differ diff --git a/src/features/rollup/shibarium/pages/deposits/DepositsList.tsx b/src/features/rollup/shibarium/pages/deposits/DepositsList.tsx deleted file mode 100644 index c8ca27956f6..00000000000 --- a/src/features/rollup/shibarium/pages/deposits/DepositsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { ShibariumDepositsItem } from 'src/features/rollup/shibarium/types/api'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import DepositsListItem from './DepositsListItem'; - -type Props = { - items: Array<ShibariumDepositsItem>; - isLoading?: boolean; - resetKey?: string; -}; - -const DepositsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <DepositsListItem - key={ `${ item.l2_transaction_hash }-${ index }` } - isLoading={ isLoading } - item={ item } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default DepositsList; diff --git a/src/features/rollup/shibarium/pages/deposits/DepositsListItem.tsx b/src/features/rollup/shibarium/pages/deposits/DepositsListItem.tsx deleted file mode 100644 index 03cfc0e14b8..00000000000 --- a/src/features/rollup/shibarium/pages/deposits/DepositsListItem.tsx +++ /dev/null @@ -1,84 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { ShibariumDepositsItem } from 'src/features/rollup/shibarium/types/api'; - -import AddressStringOrParam from 'src/slices/address/components/entity/AddressStringOrParam'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import BlockEntityL1 from 'src/features/rollup/common/components/BlockEntityL1'; -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -const feature = config.features.rollup; - -type Props = { item: ShibariumDepositsItem; isLoading?: boolean }; - -const DepositsListItem = ({ item, isLoading }: Props) => { - if (!(feature.isEnabled && feature.type === 'shibarium')) { - return null; - } - - return ( - <ListItemMobileGrid.Container> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } block No</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntityL1 - number={ item.l1_block_number } - isLoading={ isLoading } - textStyle="sm" - fontWeight={ 600 } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntityL1 - isLoading={ isLoading } - hash={ item.l1_transaction_hash } - textStyle="sm" - truncation="constant_long" - noCopy - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntity - isLoading={ isLoading } - hash={ item.l2_transaction_hash } - textStyle="sm" - truncation="constant_long" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>User</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressStringOrParam - address={ item.user } - isLoading={ isLoading } - noCopy - truncation="constant" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default DepositsListItem; diff --git a/src/features/rollup/shibarium/pages/deposits/DepositsTable.tsx b/src/features/rollup/shibarium/pages/deposits/DepositsTable.tsx index 3310dcbf401..f087e982286 100644 --- a/src/features/rollup/shibarium/pages/deposits/DepositsTable.tsx +++ b/src/features/rollup/shibarium/pages/deposits/DepositsTable.tsx @@ -9,6 +9,7 @@ import { AddressHighlightProvider } from 'src/slices/address/contexts/address-hi import { layerLabels } from 'src/features/rollup/common/utils/layer'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -22,8 +23,11 @@ type Props = { resetKey?: string; }; +const getBaseKey = (item: ShibariumDepositsItem): string => item.l2_transaction_hash; + const DepositsTable = ({ items, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( <AddressHighlightProvider> @@ -42,7 +46,7 @@ const DepositsTable = ({ items, top, isLoading, resetKey }: Props) => { </TableHeaderSticky> <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( - <DepositsTableItem key={ `${ item.l2_transaction_hash }-${ index }` } item={ item } isLoading={ isLoading }/> + <DepositsTableItem key={ keys[index] } item={ item } isLoading={ isLoading }/> )) } <TableRow ref={ cutRef }/> </TableBody> diff --git a/src/features/rollup/shibarium/pages/deposits/ShibariumDeposits.pw.tsx b/src/features/rollup/shibarium/pages/deposits/ShibariumDeposits.pw.tsx index 558cae3bc68..758083dfe4a 100644 --- a/src/features/rollup/shibarium/pages/deposits/ShibariumDeposits.pw.tsx +++ b/src/features/rollup/shibarium/pages/deposits/ShibariumDeposits.pw.tsx @@ -7,7 +7,7 @@ import { test, expect } from 'playwright/lib'; import ShibariumDeposits from './ShibariumDeposits'; -test('base view +@mobile', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { +test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { test.slow(); await mockTextAd(); await mockEnvs(ENVS_MAP.shibariumRollup); diff --git a/src/features/rollup/shibarium/pages/deposits/ShibariumDeposits.tsx b/src/features/rollup/shibarium/pages/deposits/ShibariumDeposits.tsx index 56435a0c9bb..3936d7ccad4 100644 --- a/src/features/rollup/shibarium/pages/deposits/ShibariumDeposits.tsx +++ b/src/features/rollup/shibarium/pages/deposits/ShibariumDeposits.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -13,17 +12,17 @@ import { SHIBARIUM_DEPOSIT_ITEM } from 'src/features/rollup/shibarium/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { rightLineArrow, nbsp } from 'src/toolkit/utils/htmlEntities'; -import DepositsList from './DepositsList'; import DepositsTable from './DepositsTable'; const ShibariumDeposits = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:shibarium_deposits', options: { placeholderData: generateListStub<'core:shibarium_deposits'>( @@ -46,19 +45,14 @@ const ShibariumDeposits = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <DepositsList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <DepositsTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <DepositsTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -86,6 +80,7 @@ const ShibariumDeposits = () => { itemsNum={ data?.items.length } emptyText="There are no deposits." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/shibarium/pages/deposits/__screenshots__/ShibariumDeposits.pw.tsx_default_base-view-1.png b/src/features/rollup/shibarium/pages/deposits/__screenshots__/ShibariumDeposits.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..2b612a8b88e Binary files /dev/null and b/src/features/rollup/shibarium/pages/deposits/__screenshots__/ShibariumDeposits.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/shibarium/pages/deposits/__screenshots__/ShibariumDeposits.pw.tsx_default_base-view-mobile-1.png b/src/features/rollup/shibarium/pages/deposits/__screenshots__/ShibariumDeposits.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 0d0874f83bd..00000000000 Binary files a/src/features/rollup/shibarium/pages/deposits/__screenshots__/ShibariumDeposits.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/shibarium/pages/deposits/__screenshots__/ShibariumDeposits.pw.tsx_mobile_base-view-mobile-1.png b/src/features/rollup/shibarium/pages/deposits/__screenshots__/ShibariumDeposits.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 25322dda97f..00000000000 Binary files a/src/features/rollup/shibarium/pages/deposits/__screenshots__/ShibariumDeposits.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/shibarium/pages/withdrawals/ShibariumWithdrawals.pw.tsx b/src/features/rollup/shibarium/pages/withdrawals/ShibariumWithdrawals.pw.tsx index 289830a62b0..9c174c567d8 100644 --- a/src/features/rollup/shibarium/pages/withdrawals/ShibariumWithdrawals.pw.tsx +++ b/src/features/rollup/shibarium/pages/withdrawals/ShibariumWithdrawals.pw.tsx @@ -7,10 +7,7 @@ import { test, expect } from 'playwright/lib'; import ShibariumWithdrawals from './ShibariumWithdrawals'; -test('base view +@mobile', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { - // test on mobile is flaky - // my assumption is there is not enough time to calculate hashes truncation so component is unstable - // so I raised the test timeout to check if it helps +test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { test.slow(); await mockTextAd(); diff --git a/src/features/rollup/shibarium/pages/withdrawals/ShibariumWithdrawals.tsx b/src/features/rollup/shibarium/pages/withdrawals/ShibariumWithdrawals.tsx index 79f94d6ba6e..ea1b3a948c2 100644 --- a/src/features/rollup/shibarium/pages/withdrawals/ShibariumWithdrawals.tsx +++ b/src/features/rollup/shibarium/pages/withdrawals/ShibariumWithdrawals.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -13,17 +12,17 @@ import { SHIBARIUM_WITHDRAWAL_ITEM } from 'src/features/rollup/shibarium/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { rightLineArrow, nbsp } from 'src/toolkit/utils/htmlEntities'; -import WithdrawalsList from './WithdrawalsList'; import WithdrawalsTable from './WithdrawalsTable'; const ShibariumWithdrawals = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:shibarium_withdrawals', options: { placeholderData: generateListStub<'core:shibarium_withdrawals'>( @@ -46,19 +45,14 @@ const ShibariumWithdrawals = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <WithdrawalsList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <WithdrawalsTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <WithdrawalsTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -83,6 +77,7 @@ const ShibariumWithdrawals = () => { itemsNum={ data?.items.length } emptyText="There are no withdrawals." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/shibarium/pages/withdrawals/WithdrawalsList.tsx b/src/features/rollup/shibarium/pages/withdrawals/WithdrawalsList.tsx deleted file mode 100644 index 0921cde61bd..00000000000 --- a/src/features/rollup/shibarium/pages/withdrawals/WithdrawalsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { ShibariumWithdrawalsItem } from 'src/features/rollup/shibarium/types/api'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import WithdrawalsListItem from './WithdrawalsListItem'; - -type Props = { - items: Array<ShibariumWithdrawalsItem>; - isLoading?: boolean; - resetKey?: string; -}; - -const WithdrawalsList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <WithdrawalsListItem - key={ `${ item.l2_transaction_hash }-${ index }` } - item={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default WithdrawalsList; diff --git a/src/features/rollup/shibarium/pages/withdrawals/WithdrawalsListItem.tsx b/src/features/rollup/shibarium/pages/withdrawals/WithdrawalsListItem.tsx deleted file mode 100644 index a13c530c2a2..00000000000 --- a/src/features/rollup/shibarium/pages/withdrawals/WithdrawalsListItem.tsx +++ /dev/null @@ -1,83 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { ShibariumWithdrawalsItem } from 'src/features/rollup/shibarium/types/api'; - -import AddressStringOrParam from 'src/slices/address/components/entity/AddressStringOrParam'; -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -const feature = config.features.rollup; - -type Props = { item: ShibariumWithdrawalsItem; isLoading?: boolean }; - -const WithdrawalsListItem = ({ item, isLoading }: Props) => { - if (!(feature.isEnabled && feature.type === 'shibarium')) { - return null; - } - - return ( - <ListItemMobileGrid.Container> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } block No</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntity - number={ item.l2_block_number } - isLoading={ isLoading } - textStyle="sm" - fontWeight={ 600 } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.current } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntity - isLoading={ isLoading } - hash={ item.l2_transaction_hash } - textStyle="sm" - truncation="constant_long" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>{ layerLabels.parent } txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntityL1 - isLoading={ isLoading } - hash={ item.l1_transaction_hash } - textStyle="sm" - truncation="constant_long" - noCopy - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>User</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressStringOrParam - address={ item.user } - isLoading={ isLoading } - noCopy - truncation="constant" - /> - </ListItemMobileGrid.Value> - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.timestamp } - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default WithdrawalsListItem; diff --git a/src/features/rollup/shibarium/pages/withdrawals/WithdrawalsTable.tsx b/src/features/rollup/shibarium/pages/withdrawals/WithdrawalsTable.tsx index b1d52fe58b2..d48646218f0 100644 --- a/src/features/rollup/shibarium/pages/withdrawals/WithdrawalsTable.tsx +++ b/src/features/rollup/shibarium/pages/withdrawals/WithdrawalsTable.tsx @@ -9,6 +9,7 @@ import { AddressHighlightProvider } from 'src/slices/address/contexts/address-hi import { layerLabels } from 'src/features/rollup/common/utils/layer'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -22,8 +23,11 @@ type Props = { resetKey?: string; }; +const getBaseKey = (item: ShibariumWithdrawalsItem): string => item.l2_transaction_hash; + const WithdrawalsTable = ({ items, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); return ( <AddressHighlightProvider> @@ -42,7 +46,7 @@ const WithdrawalsTable = ({ items, top, isLoading, resetKey }: Props) => { </TableHeaderSticky> <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( - <WithdrawalsTableItem key={ `${ item.l2_transaction_hash }-${ index }` } item={ item } isLoading={ isLoading }/> + <WithdrawalsTableItem key={ keys[index] } item={ item } isLoading={ isLoading }/> )) } <TableRow ref={ cutRef }/> </TableBody> diff --git a/src/features/rollup/shibarium/pages/withdrawals/__screenshots__/ShibariumWithdrawals.pw.tsx_default_base-view-1.png b/src/features/rollup/shibarium/pages/withdrawals/__screenshots__/ShibariumWithdrawals.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..fc8e974f60a Binary files /dev/null and b/src/features/rollup/shibarium/pages/withdrawals/__screenshots__/ShibariumWithdrawals.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/shibarium/pages/withdrawals/__screenshots__/ShibariumWithdrawals.pw.tsx_default_base-view-mobile-1.png b/src/features/rollup/shibarium/pages/withdrawals/__screenshots__/ShibariumWithdrawals.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 0fac76aacf8..00000000000 Binary files a/src/features/rollup/shibarium/pages/withdrawals/__screenshots__/ShibariumWithdrawals.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/shibarium/pages/withdrawals/__screenshots__/ShibariumWithdrawals.pw.tsx_mobile_base-view-mobile-1.png b/src/features/rollup/shibarium/pages/withdrawals/__screenshots__/ShibariumWithdrawals.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 508ff7f4d3a..00000000000 Binary files a/src/features/rollup/shibarium/pages/withdrawals/__screenshots__/ShibariumWithdrawals.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/zk-sync/pages/batch-details/ZkSyncL2TxnBatch.tsx b/src/features/rollup/zk-sync/pages/batch-details/ZkSyncL2TxnBatch.tsx index c4751db40c2..b279811b8c9 100644 --- a/src/features/rollup/zk-sync/pages/batch-details/ZkSyncL2TxnBatch.tsx +++ b/src/features/rollup/zk-sync/pages/batch-details/ZkSyncL2TxnBatch.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -19,9 +18,10 @@ import throwOnAbsentParamError from 'src/shared/errors/throw-on-absent-param-err import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -49,7 +49,7 @@ const ZkSyncL2TxnBatch = () => { }, }); - const batchTxsQuery = useQueryWithPages({ + const batchTxsQuery = useApiPaginatedQuery({ resourceName: 'core:zksync_l2_txn_batch_txs', pathParams: { number }, options: { diff --git a/src/features/rollup/zk-sync/pages/batch-details/ZkSyncL2TxnBatchDetails.tsx b/src/features/rollup/zk-sync/pages/batch-details/ZkSyncL2TxnBatchDetails.tsx index c3262969496..be1e1012b61 100644 --- a/src/features/rollup/zk-sync/pages/batch-details/ZkSyncL2TxnBatchDetails.tsx +++ b/src/features/rollup/zk-sync/pages/batch-details/ZkSyncL2TxnBatchDetails.tsx @@ -2,7 +2,6 @@ import { GridItem } from '@chakra-ui/react'; import type { UseQueryResult } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React from 'react'; import { ZKSYNC_L2_TX_BATCH_STATUSES, type ZkSyncBatch } from 'src/features/rollup/zk-sync/types/api'; @@ -23,13 +22,14 @@ import isCustomAppError from 'src/shared/errors/is-custom-app-error'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import VerificationSteps from 'src/shared/lifecycle/steps/VerificationSteps'; import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import GasPriceValue from 'src/shared/values/entity/GasPriceValue'; import { CollapsibleDetails } from 'src/toolkit/chakra/collapsible'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import ZkSyncL2TxnBatchHashesInfo from './ZkSyncL2TxnBatchHashesInfo'; @@ -52,7 +52,7 @@ const ZkSyncL2TxnBatchDetails = ({ query }: Props) => { const increment = direction === 'next' ? +1 : -1; const nextId = String(data.number + increment); - router.push({ pathname: '/batches/[number]', query: { number: nextId } }, undefined); + router.push({ pathname: '/batches/[number]', query: { number: nextId } }); }, [ data, router ]); if (isError) { @@ -148,7 +148,7 @@ const ZkSyncL2TxnBatchDetails = ({ query }: Props) => { flexWrap="nowrap" alignSelf="flex-start" > - <TruncatedText text={ data.root_hash }/> + <Truncate value={ data.root_hash } type="end"/> <CopyToClipboard text={ data.root_hash }/> </DetailedInfo.ItemValue> diff --git a/src/features/rollup/zk-sync/pages/batch-details/__screenshots__/ZkSyncL2TxnBatch.pw.tsx_default_base-view-1.png b/src/features/rollup/zk-sync/pages/batch-details/__screenshots__/ZkSyncL2TxnBatch.pw.tsx_default_base-view-1.png index 82c32aa1af7..316c9cda3a1 100644 Binary files a/src/features/rollup/zk-sync/pages/batch-details/__screenshots__/ZkSyncL2TxnBatch.pw.tsx_default_base-view-1.png and b/src/features/rollup/zk-sync/pages/batch-details/__screenshots__/ZkSyncL2TxnBatch.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/zk-sync/pages/batch-details/__screenshots__/ZkSyncL2TxnBatch.pw.tsx_default_mobile-base-view-1.png b/src/features/rollup/zk-sync/pages/batch-details/__screenshots__/ZkSyncL2TxnBatch.pw.tsx_default_mobile-base-view-1.png index 3cbbc41d135..646097066be 100644 Binary files a/src/features/rollup/zk-sync/pages/batch-details/__screenshots__/ZkSyncL2TxnBatch.pw.tsx_default_mobile-base-view-1.png and b/src/features/rollup/zk-sync/pages/batch-details/__screenshots__/ZkSyncL2TxnBatch.pw.tsx_default_mobile-base-view-1.png differ diff --git a/src/features/rollup/zk-sync/pages/batches/ZkSyncL2TxnBatches.pw.tsx b/src/features/rollup/zk-sync/pages/batches/ZkSyncL2TxnBatches.pw.tsx index 0d57fce99bf..4dd6ed118f9 100644 --- a/src/features/rollup/zk-sync/pages/batches/ZkSyncL2TxnBatches.pw.tsx +++ b/src/features/rollup/zk-sync/pages/batches/ZkSyncL2TxnBatches.pw.tsx @@ -7,7 +7,7 @@ import { test, expect } from 'playwright/lib'; import ZkSyncL2TxnBatches from './ZkSyncL2TxnBatches'; -test('base view +@mobile', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { +test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { test.slow(); await mockEnvs(ENVS_MAP.zkSyncRollup); await mockTextAd(); diff --git a/src/features/rollup/zk-sync/pages/batches/ZkSyncL2TxnBatches.tsx b/src/features/rollup/zk-sync/pages/batches/ZkSyncL2TxnBatches.tsx index 0c32185a5dd..ed109186d88 100644 --- a/src/features/rollup/zk-sync/pages/batches/ZkSyncL2TxnBatches.tsx +++ b/src/features/rollup/zk-sync/pages/batches/ZkSyncL2TxnBatches.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Text } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -12,16 +12,16 @@ import { ZKSYNC_L2_TXN_BATCHES_ITEM } from 'src/features/rollup/zk-sync/stubs'; import DataList from 'src/shared/lists/DataList'; import StickyPaginationWithText from 'src/shared/pagination/StickyPaginationWithText'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import ZkSyncTxnBatchesList from './ZkSyncTxnBatchesList'; import ZkSyncTxnBatchesTable from './ZkSyncTxnBatchesTable'; const ZkSyncL2TxnBatches = () => { - const { data, isError, isPlaceholderData, pagination, queryHash } = useQueryWithPages({ + const { data, isError, isInitialLoading, isTransitioning, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:zksync_l2_txn_batches', options: { placeholderData: generateListStub<'core:zksync_l2_txn_batches'>( @@ -44,19 +44,14 @@ const ZkSyncL2TxnBatches = () => { }); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <ZkSyncTxnBatchesList items={ data.items } isLoading={ isPlaceholderData } resetKey={ queryHash }/> - </Box> - <Box hideBelow="lg"> - <ZkSyncTxnBatchesTable - items={ data.items } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <ZkSyncTxnBatchesTable + items={ data.items } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; const text = (() => { @@ -65,7 +60,7 @@ const ZkSyncL2TxnBatches = () => { } return ( - <Skeleton loading={ countersQuery.isPlaceholderData || isPlaceholderData } display="flex" flexWrap="wrap"> + <Skeleton loading={ countersQuery.isPlaceholderData || isInitialLoading } display="flex" flexWrap="wrap"> Txn batch <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[0].number } </Text>to <Text fontWeight={ 600 } whiteSpace="pre"> #{ data.items[data.items.length - 1].number } </Text> @@ -84,6 +79,7 @@ const ZkSyncL2TxnBatches = () => { itemsNum={ data?.items.length } emptyText="There are no txn batches." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/rollup/zk-sync/pages/batches/ZkSyncTxnBatchesList.tsx b/src/features/rollup/zk-sync/pages/batches/ZkSyncTxnBatchesList.tsx deleted file mode 100644 index f8c9f99d43b..00000000000 --- a/src/features/rollup/zk-sync/pages/batches/ZkSyncTxnBatchesList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { ZkSyncBatchesItem } from 'src/features/rollup/zk-sync/types/api'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import ZkSyncTxnBatchesListItem from './ZkSyncTxnBatchesListItem'; - -type Props = { - items: Array<ZkSyncBatchesItem>; - isLoading?: boolean; - resetKey?: string; -}; - -const ZkSyncTxnBatchesList = ({ items, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <ZkSyncTxnBatchesListItem - key={ item.number + (isLoading ? String(index) : '') } - item={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default ZkSyncTxnBatchesList; diff --git a/src/features/rollup/zk-sync/pages/batches/ZkSyncTxnBatchesListItem.tsx b/src/features/rollup/zk-sync/pages/batches/ZkSyncTxnBatchesListItem.tsx deleted file mode 100644 index 27e324432d6..00000000000 --- a/src/features/rollup/zk-sync/pages/batches/ZkSyncTxnBatchesListItem.tsx +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; -import React from 'react'; - -import type { ZkSyncBatchesItem } from 'src/features/rollup/zk-sync/types/api'; - -import BatchEntityL2 from 'src/features/rollup/common/components/BatchEntityL2'; -import TxEntityL1 from 'src/features/rollup/common/components/TxEntityL1'; -import ZkSyncL2TxnBatchStatus from 'src/features/rollup/zk-sync/components/ZkSyncL2TxnBatchStatus'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { Link } from 'src/toolkit/chakra/link'; - -const rollupFeature = config.features.rollup; - -type Props = { item: ZkSyncBatchesItem; isLoading?: boolean }; - -const ZkSyncTxnBatchesListItem = ({ item, isLoading }: Props) => { - if (!rollupFeature.isEnabled || rollupFeature.type !== 'zkSync') { - return null; - } - - return ( - <ListItemMobileGrid.Container gridTemplateColumns="110px auto"> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Batch #</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BatchEntityL2 - isLoading={ isLoading } - number={ item.number } - textStyle="sm" - fontWeight={ 600 } - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <ZkSyncL2TxnBatchStatus status={ item.status } isLoading={ isLoading }/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.timestamp } - fallbackText="Undefined" - isLoading={ isLoading } - display="inline-block" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Txn count</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Link - href={ route({ pathname: '/batches/[number]', query: { number: item.number.toString(), tab: 'txs' } }) } - loading={ isLoading } - fontWeight={ 600 } - minW="40px" - > - { item.transactions_count } - </Link> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Commit tx</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { item.commit_transaction_hash ? ( - <TxEntityL1 - isLoading={ isLoading } - hash={ item.commit_transaction_hash } - textStyle="sm" - truncation="constant_long" - noCopy - /> - ) : <Text>Pending</Text> } - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Prove tx</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { item.prove_transaction_hash ? ( - <TxEntityL1 - isLoading={ isLoading } - hash={ item.prove_transaction_hash } - textStyle="sm" - truncation="constant_long" - noCopy - /> - ) : <Text>Pending</Text> } - </ListItemMobileGrid.Value> - - </ListItemMobileGrid.Container> - ); -}; - -export default ZkSyncTxnBatchesListItem; diff --git a/src/features/rollup/zk-sync/pages/batches/ZkSyncTxnBatchesTableItem.tsx b/src/features/rollup/zk-sync/pages/batches/ZkSyncTxnBatchesTableItem.tsx index bcb4974044c..37210239a2c 100644 --- a/src/features/rollup/zk-sync/pages/batches/ZkSyncTxnBatchesTableItem.tsx +++ b/src/features/rollup/zk-sync/pages/batches/ZkSyncTxnBatchesTableItem.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { ZkSyncBatchesItem } from 'src/features/rollup/zk-sync/types/api'; @@ -12,6 +11,7 @@ import ZkSyncL2TxnBatchStatus from 'src/features/rollup/zk-sync/components/ZkSyn import config from 'src/config'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; diff --git a/src/features/rollup/zk-sync/pages/batches/__screenshots__/ZkSyncL2TxnBatches.pw.tsx_default_base-view-1.png b/src/features/rollup/zk-sync/pages/batches/__screenshots__/ZkSyncL2TxnBatches.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..a749d005902 Binary files /dev/null and b/src/features/rollup/zk-sync/pages/batches/__screenshots__/ZkSyncL2TxnBatches.pw.tsx_default_base-view-1.png differ diff --git a/src/features/rollup/zk-sync/pages/batches/__screenshots__/ZkSyncL2TxnBatches.pw.tsx_default_base-view-mobile-1.png b/src/features/rollup/zk-sync/pages/batches/__screenshots__/ZkSyncL2TxnBatches.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index e017ed8dfc4..00000000000 Binary files a/src/features/rollup/zk-sync/pages/batches/__screenshots__/ZkSyncL2TxnBatches.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/rollup/zk-sync/pages/batches/__screenshots__/ZkSyncL2TxnBatches.pw.tsx_mobile_base-view-mobile-1.png b/src/features/rollup/zk-sync/pages/batches/__screenshots__/ZkSyncL2TxnBatches.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index f507f75f084..00000000000 Binary files a/src/features/rollup/zk-sync/pages/batches/__screenshots__/ZkSyncL2TxnBatches.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/safe/hooks/useIsSafeAddress.tsx b/src/features/safe/hooks/useIsSafeAddress.ts similarity index 100% rename from src/features/safe/hooks/useIsSafeAddress.tsx rename to src/features/safe/hooks/useIsSafeAddress.ts diff --git a/src/features/sol2uml/pages/index/Sol2Uml.tsx b/src/features/sol2uml/pages/index/Sol2Uml.tsx index 957e1968ea9..10264382f3e 100644 --- a/src/features/sol2uml/pages/index/Sol2Uml.tsx +++ b/src/features/sol2uml/pages/index/Sol2Uml.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import PageTitle from 'src/shell/page/title/PageTitle'; @@ -12,6 +11,7 @@ import { useMultichainContext } from 'src/features/multichain/context'; import Sol2UmlDiagram from 'src/features/sol2uml/components/Sol2UmlDiagram'; import ChainIcon from 'src/shared/external-chains/ChainIcon'; +import { useRouter } from 'src/shared/router/useRouter'; const Sol2Uml = () => { const router = useRouter(); diff --git a/src/features/solidity-scan/components/__screenshots__/SolidityscanReport.pw.tsx_mobile_average-report-dark-mode-mobile-1.png b/src/features/solidity-scan/components/__screenshots__/SolidityscanReport.pw.tsx_mobile_average-report-dark-mode-mobile-1.png index 72cf441ddec..a1b3184155b 100644 Binary files a/src/features/solidity-scan/components/__screenshots__/SolidityscanReport.pw.tsx_mobile_average-report-dark-mode-mobile-1.png and b/src/features/solidity-scan/components/__screenshots__/SolidityscanReport.pw.tsx_mobile_average-report-dark-mode-mobile-1.png differ diff --git a/src/features/solidity-scan/components/__screenshots__/SolidityscanReport.pw.tsx_mobile_average-report-dark-mode-mobile-2.png b/src/features/solidity-scan/components/__screenshots__/SolidityscanReport.pw.tsx_mobile_average-report-dark-mode-mobile-2.png index bea3d07e961..f77bbc5a4c4 100644 Binary files a/src/features/solidity-scan/components/__screenshots__/SolidityscanReport.pw.tsx_mobile_average-report-dark-mode-mobile-2.png and b/src/features/solidity-scan/components/__screenshots__/SolidityscanReport.pw.tsx_mobile_average-report-dark-mode-mobile-2.png differ diff --git a/src/features/token-action-button/components/TokenActionButton.spec.tsx b/src/features/token-action-button/components/TokenActionButton.spec.tsx index 21948175051..bbcc4938dc4 100644 --- a/src/features/token-action-button/components/TokenActionButton.spec.tsx +++ b/src/features/token-action-button/components/TokenActionButton.spec.tsx @@ -3,7 +3,11 @@ import React from 'react'; +<<<<<<< HEAD import { EventTypes } from 'src/services/mixpanel'; +======= +import { EventTypes } from 'src/shared/analytics'; +>>>>>>> v2.13.0 import { afterEach, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen } from 'vitest/lib'; @@ -11,7 +15,11 @@ import withEnvs from 'vitest/utils/mockEnvs'; const logEventMock = vi.hoisted(() => vi.fn()); +<<<<<<< HEAD vi.mock('src/services/mixpanel', async(importOriginal) => ({ +======= +vi.mock('src/shared/analytics', async(importOriginal) => ({ +>>>>>>> v2.13.0 ...await importOriginal<object>(), logEvent: logEventMock, })); @@ -41,7 +49,11 @@ const envsWithMalformedUrl: Array<[ string, string ]> = [ it('renders nothing when the button is not configured', async() => { const { 'default': TokenActionButton } = await import('./TokenActionButton'); +<<<<<<< HEAD render(<TokenActionButton tokenHash={ TOKEN_HASH } tokenType="ERC-20"/>); +======= + render(<TokenActionButton tokenHash={ TOKEN_HASH }/>); +>>>>>>> v2.13.0 expect(screen.queryByText(BUTTON_TEXT)).toBeNull(); }); @@ -50,12 +62,17 @@ it('renders nothing when the configured url is malformed', async() => { await withEnvs(envsWithMalformedUrl, async() => { const { 'default': TokenActionButton } = await import('./TokenActionButton'); +<<<<<<< HEAD render(<TokenActionButton tokenHash={ TOKEN_HASH } tokenType="ERC-20"/>); +======= + render(<TokenActionButton tokenHash={ TOKEN_HASH }/>); +>>>>>>> v2.13.0 expect(screen.queryByText(BUTTON_TEXT)).toBeNull(); }); }); +<<<<<<< HEAD it('renders nothing for a token that is not ERC-20', async() => { await withEnvs(envs, async() => { const { 'default': TokenActionButton } = await import('./TokenActionButton'); @@ -76,11 +93,17 @@ it('renders while the token type is still unknown', async() => { }); }); +======= +>>>>>>> v2.13.0 it('opens the configured url in a new tab, with utm params appended', async() => { await withEnvs(envs, async() => { const { 'default': TokenActionButton } = await import('./TokenActionButton'); +<<<<<<< HEAD render(<TokenActionButton tokenHash={ TOKEN_HASH } tokenType="ERC-20"/>); +======= + render(<TokenActionButton tokenHash={ TOKEN_HASH }/>); +>>>>>>> v2.13.0 const link = screen.getByRole('link', { name: BUTTON_TEXT }); expect(link.getAttribute('href')).toBe(`${ CONFIGURED_URL }?utm_source=blockscout&utm_medium=token`); @@ -92,7 +115,11 @@ it('substitutes every {hash} placeholder with the lowercased token hash', async( await withEnvs(envsWithPlaceholder, async() => { const { 'default': TokenActionButton } = await import('./TokenActionButton'); +<<<<<<< HEAD render(<TokenActionButton tokenHash={ TOKEN_HASH } tokenType="ERC-20"/>); +======= + render(<TokenActionButton tokenHash={ TOKEN_HASH }/>); +>>>>>>> v2.13.0 const link = screen.getByRole('link', { name: BUTTON_TEXT }); expect(link.getAttribute('href')) @@ -100,6 +127,7 @@ it('substitutes every {hash} placeholder with the lowercased token hash', async( }); }); +<<<<<<< HEAD it('logs a button click event with the configured text', async() => { await withEnvs(envs, async() => { const { 'default': TokenActionButton } = await import('./TokenActionButton'); @@ -109,5 +137,20 @@ it('logs a button click event with the configured text', async() => { fireEvent.click(screen.getByRole('button', { name: BUTTON_TEXT })); expect(logEventMock).toHaveBeenCalledWith(EventTypes.BUTTON_CLICK, { Content: BUTTON_TEXT, Source: 'token' }); +======= +it('logs an action button event with the destination url', async() => { + await withEnvs(envs, async() => { + const { 'default': TokenActionButton } = await import('./TokenActionButton'); + + render(<TokenActionButton tokenHash={ TOKEN_HASH }/>); + + fireEvent.click(screen.getByRole('button', { name: BUTTON_TEXT })); + + expect(logEventMock).toHaveBeenCalledWith(EventTypes.PAGE_WIDGET, { + Type: 'Action button', + Info: `${ CONFIGURED_URL }?utm_source=blockscout&utm_medium=token`, + Source: 'Token', + }); +>>>>>>> v2.13.0 }); }); diff --git a/src/features/token-action-button/components/TokenActionButton.tsx b/src/features/token-action-button/components/TokenActionButton.tsx index b57b154d262..39d85c624a0 100644 --- a/src/features/token-action-button/components/TokenActionButton.tsx +++ b/src/features/token-action-button/components/TokenActionButton.tsx @@ -2,17 +2,26 @@ import React from 'react'; +<<<<<<< HEAD import { buildUrl } from 'src/features/token-action-button/utils/build-url'; import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; import * as mixpanel from 'src/services/mixpanel'; +======= +import { buildTokenActionUrl } from 'src/features/token-action-button/utils/build-url'; + +import config from 'src/config'; +import { getFeaturePayload } from 'src/config/utils/features'; +import * as analytics from 'src/shared/analytics'; +>>>>>>> v2.13.0 import { Button } from 'src/toolkit/chakra/button'; import { useColorModeValue } from 'src/toolkit/chakra/color-mode'; import { Image } from 'src/toolkit/chakra/image'; import { Link, LinkExternalIcon } from 'src/toolkit/chakra/link'; +<<<<<<< HEAD const feature = config.features.tokenActionButton; const button = getFeaturePayload(feature)?.button; @@ -29,12 +38,31 @@ const TokenActionButton = ({ tokenHash, tokenType, isLoading }: Props) => { mixpanel.logEvent(mixpanel.EventTypes.BUTTON_CLICK, { Content: feature.button.text, Source: 'token' }); } }, []); +======= +const button = getFeaturePayload(config.features.tokenActionButton)?.button; + +interface Props { + tokenHash: string; + isLoading?: boolean; +} + +const TokenActionButton = ({ tokenHash, isLoading }: Props) => { + const href = button ? buildTokenActionUrl(button.url, tokenHash) : undefined; + + const handleClick = React.useCallback(() => { + // Stryker disable next-line ConditionalExpression: always true here (no href, no button); it narrows href for analytics + if (href) { + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Action button', Info: href, Source: 'Token' }); + } + }, [ href ]); +>>>>>>> v2.13.0 const logoSrc = useColorModeValue( button?.logo?.[0], button?.logo?.[1] || button?.logo?.[0], ); +<<<<<<< HEAD if (!button) { return null; } @@ -46,6 +74,9 @@ const TokenActionButton = ({ tokenHash, tokenType, isLoading }: Props) => { const href = buildUrl(button.url, tokenHash); if (!href) { +======= + if (!button || !href) { +>>>>>>> v2.13.0 return null; } diff --git a/src/features/token-action-button/utils/build-url.ts b/src/features/token-action-button/utils/build-url.ts index 2cf5a3b8b10..b6e4702ec3e 100644 --- a/src/features/token-action-button/utils/build-url.ts +++ b/src/features/token-action-button/utils/build-url.ts @@ -2,7 +2,11 @@ const HASH_PLACEHOLDER = '{hash}'; +<<<<<<< HEAD export const buildUrl = (template: string, tokenHash: string): string | undefined => { +======= +export const buildTokenActionUrl = (template: string, tokenHash: string): string | undefined => { +>>>>>>> v2.13.0 try { // substituted before parsing: the URL parser percent-encodes braces in the path, which would break a later replace const urlObj = new URL(template.replaceAll(HASH_PLACEHOLDER, tokenHash.toLowerCase())); diff --git a/src/features/token-action-button/utils/is-token-action-button-hidden.spec.ts b/src/features/token-action-button/utils/is-token-action-button-hidden.spec.ts new file mode 100644 index 00000000000..5635408a118 --- /dev/null +++ b/src/features/token-action-button/utils/is-token-action-button-hidden.spec.ts @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { isTokenActionButtonHidden, TOKEN_ACTION_BUTTON_HIDDEN_TAG_SLUG } from './is-token-action-button-hidden'; + +describe('isTokenActionButtonHidden', () => { + it('is true when the address carries the service tag with the blacklist slug', () => { + expect(isTokenActionButtonHidden([ + { slug: 'uniswap', tagType: 'protocol' }, + { slug: TOKEN_ACTION_BUTTON_HIDDEN_TAG_SLUG, tagType: 'service' }, + ])).toBe(true); + }); + + it('is false for the blacklist slug under another tag type', () => { + expect(isTokenActionButtonHidden([ { slug: TOKEN_ACTION_BUTTON_HIDDEN_TAG_SLUG, tagType: 'generic' } ])).toBe(false); + }); + + it('is false for another service tag', () => { + expect(isTokenActionButtonHidden([ { slug: 'some_future_flag', tagType: 'service' } ])).toBe(false); + }); + + it('is false without tags', () => { + expect(isTokenActionButtonHidden(undefined)).toBe(false); + expect(isTokenActionButtonHidden([])).toBe(false); + }); +}); diff --git a/src/features/token-action-button/utils/is-token-action-button-hidden.ts b/src/features/token-action-button/utils/is-token-action-button-hidden.ts new file mode 100644 index 00000000000..9a143148a1a --- /dev/null +++ b/src/features/token-action-button/utils/is-token-action-button-hidden.ts @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { AddressMetadataTagType } from 'src/features/address-metadata/types/api'; + +import { SERVICE_TAG_TYPE } from 'src/features/address-metadata/utils/is-hidden-tag'; + +export const TOKEN_ACTION_BUTTON_HIDDEN_TAG_SLUG = 'token-action-button-hidden'; + +interface TagCandidate { + readonly slug: string; + readonly tagType: AddressMetadataTagType; +} + +export function isTokenActionButtonHidden(tags: ReadonlyArray<TagCandidate> | undefined): boolean { + return tags?.some((tag) => tag.tagType === SERVICE_TAG_TYPE && tag.slug === TOKEN_ACTION_BUTTON_HIDDEN_TAG_SLUG) ?? false; +} diff --git a/src/features/tx-authorization/pages/tx/TxAuthorizations.tsx b/src/features/tx-authorization/pages/tx/TxAuthorizations.tsx index 8a5763f0ca8..fa0c9143d94 100644 --- a/src/features/tx-authorization/pages/tx/TxAuthorizations.tsx +++ b/src/features/tx-authorization/pages/tx/TxAuthorizations.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import TxPendingAlert from 'src/slices/tx/components/TxPendingAlert'; @@ -9,7 +8,8 @@ import type { TxQuery } from 'src/slices/tx/hooks/useTxQuery'; import DataList from 'src/shared/lists/DataList'; -import TxAuthorizationsList from './TxAuthorizationsList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import TxAuthorizationsTable from './TxAuthorizationsTable'; interface Props { @@ -23,22 +23,13 @@ const TxAuthorizations = ({ txQuery }: Props) => { } const content = txQuery.data?.authorization_list ? ( - <> - <Box hideFrom="lg"> - <TxAuthorizationsList - data={ txQuery.data.authorization_list } - isLoading={ txQuery.isPlaceholderData } - resetKey={ txQuery.data.hash } - /> - </Box> - <Box hideBelow="lg"> - <TxAuthorizationsTable - data={ txQuery.data.authorization_list } - isLoading={ txQuery.isPlaceholderData } - resetKey={ txQuery.data.hash } - /> - </Box> - </> + <TableContainerScrollable> + <TxAuthorizationsTable + data={ txQuery.data.authorization_list } + isLoading={ txQuery.isPlaceholderData } + resetKey={ txQuery.data.hash } + /> + </TableContainerScrollable> ) : null; return ( diff --git a/src/features/tx-authorization/pages/tx/TxAuthorizationsList.tsx b/src/features/tx-authorization/pages/tx/TxAuthorizationsList.tsx deleted file mode 100644 index 55a87032128..00000000000 --- a/src/features/tx-authorization/pages/tx/TxAuthorizationsList.tsx +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import TxAuthorizationsListItem from './TxAuthorizationsListItem'; - -interface Props { - data: Array<schemas['SignedAuthorization']>; - isLoading?: boolean; - resetKey?: string; -} - -const TxAuthorizationsList = ({ data, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <TxAuthorizationsListItem - key={ item.nonce.toString() + (isLoading ? index : '') } - data={ item } - isLoading={ isLoading } - /> - )) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - ); -}; - -export default TxAuthorizationsList; diff --git a/src/features/tx-authorization/pages/tx/TxAuthorizationsListItem.tsx b/src/features/tx-authorization/pages/tx/TxAuthorizationsListItem.tsx deleted file mode 100644 index a5806a3c970..00000000000 --- a/src/features/tx-authorization/pages/tx/TxAuthorizationsListItem.tsx +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { HStack } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import TxAuthorizationStatus from 'src/features/tx-authorization/components/TxAuthorizationStatus'; - -import config from 'src/config'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - data: schemas['SignedAuthorization']; - isLoading?: boolean; -} - -const TxAuthorizationsListItem = ({ data, isLoading }: Props) => { - return ( - <ListItemMobile rowGap={ 3 } fontSize="sm"> - <HStack gap={ 3 } w="100%"> - <Skeleton loading={ isLoading } fontWeight={ 500 }>Authority</Skeleton> - <AddressEntity address={{ hash: data.authority }} isLoading={ isLoading } noIcon/> - </HStack> - <HStack gap={ 3 } w="100%"> - <Skeleton loading={ isLoading } fontWeight={ 500 } flexShrink={ 0 }>Delegated address</Skeleton> - <AddressEntity address={{ hash: data.address_hash }} isLoading={ isLoading } noIcon/> - </HStack> - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 }>Chain</Skeleton> - <Skeleton loading={ isLoading } color="text.secondary">{ data.chain_id === Number(config.chain.id) ? 'this' : 'any' }</Skeleton> - </HStack> - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 }>Nonce</Skeleton> - <Skeleton loading={ isLoading } color="text.secondary">{ data.nonce }</Skeleton> - </HStack> - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 }>Status</Skeleton> - <TxAuthorizationStatus status={ data.status } loading={ isLoading }/> - </HStack> - </ListItemMobile> - ); -}; - -export default TxAuthorizationsListItem; diff --git a/src/features/tx-authorization/pages/tx/TxAuthorizationsTable.tsx b/src/features/tx-authorization/pages/tx/TxAuthorizationsTable.tsx index 53b677aa92a..85eef7bfb0c 100644 --- a/src/features/tx-authorization/pages/tx/TxAuthorizationsTable.tsx +++ b/src/features/tx-authorization/pages/tx/TxAuthorizationsTable.tsx @@ -6,6 +6,7 @@ import type { schemas } from '@blockscout/api-types'; import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -18,12 +19,15 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: schemas['SignedAuthorization']): string => item.nonce.toString(); + const TxAuthorizationsTable = ({ data, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); return ( <AddressHighlightProvider> - <TableRoot> + <TableRoot minW="900px"> <TableHeaderSticky> <TableRow> <TableColumnHeader width="50%">Authority</TableColumnHeader> @@ -36,7 +40,7 @@ const TxAuthorizationsTable = ({ data, isLoading, resetKey }: Props) => { <TableBody> { data.slice(0, renderedItemsNum).map((item, index) => ( <TxAuthorizationsTableItem - key={ item.nonce.toString() + (isLoading ? index : '') } + key={ keys[index] } data={ item } isLoading={ isLoading } /> diff --git a/src/features/tx-interpretation/common/components/TxInterpretation.tsx b/src/features/tx-interpretation/common/components/TxInterpretation.tsx index 1104f344bae..bce604ebd18 100644 --- a/src/features/tx-interpretation/common/components/TxInterpretation.tsx +++ b/src/features/tx-interpretation/common/components/TxInterpretation.tsx @@ -2,7 +2,6 @@ import type { BoxProps } from '@chakra-ui/react'; import { Box, chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -20,10 +19,11 @@ import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; import EnsEntity from 'src/features/name-services/domains/components/EnsEntity'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import dayjs from 'src/shared/date-and-time/dayjs'; import ChainIcon from 'src/shared/external-chains/ChainIcon'; import getChainTooltipText from 'src/shared/external-chains/get-chain-tooltip-text'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Badge } from 'src/toolkit/chakra/badge'; @@ -61,15 +61,15 @@ const TxInterpretationElementByType = ( { variable, addressDataMap }: { variable?: NonStringTxInterpretationVariable; addressDataMap?: Record<string, schemas['Address']> }, ) => { const onAddressClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.TX_INTERPRETATION_INTERACTION, { Type: 'Address click' }); + analytics.logEvent(analytics.EventTypes.TX_INTERPRETATION_INTERACTION, { Type: 'Address click' }); }, []); const onTokenClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.TX_INTERPRETATION_INTERACTION, { Type: 'Token click' }); + analytics.logEvent(analytics.EventTypes.TX_INTERPRETATION_INTERACTION, { Type: 'Token click' }); }, []); const onDomainClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.TX_INTERPRETATION_INTERACTION, { Type: 'Domain click' }); + analytics.logEvent(analytics.EventTypes.TX_INTERPRETATION_INTERACTION, { Type: 'Domain click' }); }, []); if (!variable) { diff --git a/src/features/tx-interpretation/common/utils/address-to-plain-text.ts b/src/features/tx-interpretation/common/utils/address-to-plain-text.ts index be5ff2758a8..884d2f2051c 100644 --- a/src/features/tx-interpretation/common/utils/address-to-plain-text.ts +++ b/src/features/tx-interpretation/common/utils/address-to-plain-text.ts @@ -3,7 +3,7 @@ import type { AddressNameSource } from 'src/slices/address/utils/get-address-name'; import getAddressName from 'src/slices/address/utils/get-address-name'; -import shortenString from 'src/shared/texts/shorten-string'; +import { shortenString } from 'src/toolkit/utils/texts'; // What `truncation="constant"` resolves to in `AddressEntity`. const HASH_CHAR_NUMBER = 8; diff --git a/src/features/tx-interpretation/noves/components/NovesTokenTooltipContent.tsx b/src/features/tx-interpretation/noves/components/NovesTokenTooltipContent.tsx index 4ac602157d9..5bc0c2745ea 100644 --- a/src/features/tx-interpretation/noves/components/NovesTokenTooltipContent.tsx +++ b/src/features/tx-interpretation/noves/components/NovesTokenTooltipContent.tsx @@ -7,9 +7,9 @@ import React from 'react'; import type { NovesNft, NovesToken } from 'src/features/tx-interpretation/noves/types/api'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import shortenString from 'src/shared/texts/shorten-string'; import { HEX_REGEXP } from 'src/toolkit/utils/regexp'; +import { shortenString } from 'src/toolkit/utils/texts'; interface Props { amount?: string; diff --git a/src/features/tx-interpretation/noves/pages/address/AddressAccountHistory.tsx b/src/features/tx-interpretation/noves/pages/address/AddressAccountHistory.tsx index 5f5fc389e14..5ad96e834ca 100644 --- a/src/features/tx-interpretation/noves/pages/address/AddressAccountHistory.tsx +++ b/src/features/tx-interpretation/noves/pages/address/AddressAccountHistory.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; +import { omit } from 'es-toolkit'; import React from 'react'; import type { NovesHistoryFilterValue } from 'src/features/tx-interpretation/noves/types/api'; @@ -14,10 +14,11 @@ import { getFromToValue } from 'src/features/tx-interpretation/noves/utils/from- import useIsMounted from 'src/shared/hooks/useIsMounted'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getFilterValueFromQuery from 'src/shared/router/get-filter-value-from-query'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { TableContainerScrollable } from 'src/toolkit/chakra/table'; @@ -26,6 +27,8 @@ import AddressAccountHistoryTable from './AddressAccountHistoryTable'; const getFilterValue = (getFilterValueFromQuery<NovesHistoryFilterValue>).bind(null, NovesHistoryFilterValues); +const FILTER_FIELDS = [ 'filter' ]; + type Props = { shouldRender?: boolean; isQueryEnabled?: boolean; @@ -36,10 +39,9 @@ const AddressAccountHistory = ({ shouldRender = true, isQueryEnabled = true }: P const isMounted = useIsMounted(); const currentAddress = getQueryParamString(router.query.hash).toLowerCase(); + const filterValue = getFilterValue(router.query.filter); - const [ filterValue, setFilterValue ] = React.useState<NovesHistoryFilterValue>(getFilterValue(router.query.filter)); - - const { data, isError, pagination, isPlaceholderData, queryHash } = useQueryWithPages({ + const { data, isError, pagination, isInitialLoading, isTransitioning, queryHash } = useApiPaginatedQuery({ resourceName: 'core:noves_address_history', pathParams: { address: currentAddress }, options: { @@ -49,10 +51,12 @@ const AddressAccountHistory = ({ shouldRender = true, isQueryEnabled = true }: P }); const handleFilterChange = React.useCallback((val: string | Array<string>) => { - - const newVal = getFilterValue(val); - setFilterValue(newVal); - }, [ ]); + const nextValue = getFilterValue(val); + router.push({ + pathname: router.pathname, + query: nextValue ? { ...router.query, filter: nextValue } : omit(router.query, FILTER_FIELDS), + }, { shallow: true }); + }, [ router ]); if (!isMounted || !shouldRender) { return null; @@ -71,14 +75,14 @@ const AddressAccountHistory = ({ shouldRender = true, isQueryEnabled = true }: P </ActionBar> ); - const filteredData = isPlaceholderData ? data?.items : data?.items.filter(i => filterValue ? getFromToValue(i, currentAddress) === filterValue : i); + const filteredData = isInitialLoading ? data?.items : data?.items.filter(i => filterValue ? getFromToValue(i, currentAddress) === filterValue : i); const content = filteredData ? ( <TableContainerScrollable> <AddressAccountHistoryTable items={ filteredData } currentAddress={ currentAddress } - isPlaceholderData={ isPlaceholderData } + isLoading={ isInitialLoading } resetKey={ `${ queryHash }:${ filterValue ?? '' }` } /> </TableContainerScrollable> @@ -94,6 +98,7 @@ const AddressAccountHistory = ({ shouldRender = true, isQueryEnabled = true }: P emptyStateProps={{ description: 'No match found for current filter', }} + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryListItem.tsx b/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryListItem.tsx deleted file mode 100644 index 7e5a69df3d1..00000000000 --- a/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryListItem.tsx +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box, Flex, Text } from '@chakra-ui/react'; -import React, { useMemo } from 'react'; - -import type { NovesResponseData } from 'src/features/tx-interpretation/noves/types/api'; - -import NovesFromTo from 'src/features/tx-interpretation/noves/components/NovesFromTo'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { SECOND } from 'src/toolkit/utils/consts'; - -type Props = { - isPlaceholderData: boolean; - tx: NovesResponseData; - currentAddress: string; -}; - -const AddressAccountHistoryListItem = (props: Props) => { - - const parsedDescription = useMemo(() => { - const description = props.tx.classificationData.description; - - return description.endsWith('.') ? description.substring(0, description.length - 1) : description; - }, [ props.tx.classificationData.description ]); - - return ( - <ListItemMobile rowGap={ 4 } w="full"> - <Skeleton borderRadius="sm" loading={ props.isPlaceholderData } w="full"> - <Flex justifyContent="space-between" w="full"> - <Flex columnGap={ 2 }> - <SpriteIcon - name="lightning" - height="5" - width="5" - color="icon.primary" - /> - - <Text fontSize="sm" fontWeight={ 500 }> - Action - </Text> - </Flex> - <TimeWithTooltip - timestamp={ props.tx.rawTransactionData.timestamp * SECOND } - color="text.secondary" - borderRadius="sm" - fontWeight={ 500 } - /> - </Flex> - </Skeleton> - <Skeleton borderRadius="sm" loading={ props.isPlaceholderData }> - <Link - href={ `/tx/${ props.tx.rawTransactionData.transactionHash }` } - fontWeight="bold" - whiteSpace="break-spaces" - wordBreak="break-word" - > - { parsedDescription } - </Link> - </Skeleton> - - <Box maxW="full"> - <NovesFromTo txData={ props.tx } currentAddress={ props.currentAddress } isLoaded={ !props.isPlaceholderData }/> - </Box> - </ListItemMobile> - ); -}; - -export default React.memo(AddressAccountHistoryListItem); diff --git a/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryTable.tsx b/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryTable.tsx index f595dc762ee..091ae0214cf 100644 --- a/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryTable.tsx +++ b/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryTable.tsx @@ -13,12 +13,12 @@ import AddressAccountHistoryTableItem from './AddressAccountHistoryTableItem'; interface Props { items: Array<NovesResponseData>; currentAddress: string; - isPlaceholderData?: boolean; + isLoading?: boolean; resetKey?: string; } -const AddressAccountHistoryTable = ({ items, currentAddress, isPlaceholderData, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isPlaceholderData, resetKey }); +const AddressAccountHistoryTable = ({ items, currentAddress, isLoading, resetKey }: Props) => { + const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); return ( <TableRoot minW="900px"> @@ -38,10 +38,10 @@ const AddressAccountHistoryTable = ({ items, currentAddress, isPlaceholderData, <TableBody maxWidth="full"> { items.slice(0, renderedItemsNum).map((item, i) => ( <AddressAccountHistoryTableItem - key={ `${ i }-${ item.rawTransactionData.transactionHash }` } + key={ item.rawTransactionData.transactionHash + (isLoading ? i : '') } tx={ item } currentAddress={ currentAddress } - isPlaceholderData={ Boolean(isPlaceholderData) } + isLoading={ Boolean(isLoading) } /> )) } <TableRow ref={ cutRef }/> diff --git a/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryTableItem.tsx b/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryTableItem.tsx index 5de2ebfdc6b..5a85e8487b2 100644 --- a/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryTableItem.tsx +++ b/src/features/tx-interpretation/noves/pages/address/AddressAccountHistoryTableItem.tsx @@ -16,7 +16,7 @@ import { TableCell, TableRow } from 'src/toolkit/chakra/table'; import { SECOND } from 'src/toolkit/utils/consts'; type Props = { - isPlaceholderData: boolean; + isLoading: boolean; tx: NovesResponseData; currentAddress: string; }; @@ -34,14 +34,14 @@ const AddressAccountHistoryTableItem = (props: Props) => { <TableCell px={ 3 } py="18px" fontSize="sm" > <TimeWithTooltip timestamp={ props.tx.rawTransactionData.timestamp * SECOND } - isLoading={ props.isPlaceholderData } + isLoading={ props.isLoading } color="text.secondary" borderRadius="sm" flexShrink={ 0 } /> </TableCell> <TableCell px={ 3 } py="18px" fontSize="sm" > - <Skeleton borderRadius="sm" loading={ props.isPlaceholderData }> + <Skeleton borderRadius="sm" loading={ props.isLoading }> <Box display="flex"> <SpriteIcon name="lightning" @@ -64,7 +64,7 @@ const AddressAccountHistoryTableItem = (props: Props) => { </TableCell> <TableCell px={ 3 } py="18px" fontSize="sm"> <Box flexShrink={ 0 } > - <NovesFromTo txData={ props.tx } currentAddress={ props.currentAddress } isLoaded={ !props.isPlaceholderData }/> + <NovesFromTo txData={ props.tx } currentAddress={ props.currentAddress } isLoaded={ !props.isLoading }/> </Box> </TableCell> </TableRow> diff --git a/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlows.tsx b/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlows.tsx index 2b7d9218219..05251f5ed48 100644 --- a/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlows.tsx +++ b/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlows.tsx @@ -18,9 +18,9 @@ import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { generateFlowViewData } from '../../utils/generateFlowViewData'; -import TxAssetFlowsList from './TxAssetFlowsList'; import TxAssetFlowsTable from './TxAssetFlowsTable'; interface FlowViewProps { @@ -78,23 +78,13 @@ export default function TxAssetFlows(props: FlowViewProps) { ); const content = data ? ( - <> - <Box hideFrom="lg"> - <TxAssetFlowsList - items={ data } - isPlaceholderData={ isPlaceholderData } - resetKey={ resetKey } - /> - </Box> - - <Box hideBelow="lg"> - <TxAssetFlowsTable - items={ data } - isPlaceholderData={ isPlaceholderData } - resetKey={ resetKey } - /> - </Box> - </> + <TableContainerScrollable> + <TxAssetFlowsTable + items={ data } + isPlaceholderData={ isPlaceholderData } + resetKey={ resetKey } + /> + </TableContainerScrollable> ) : null; return ( diff --git a/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlowsList.tsx b/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlowsList.tsx deleted file mode 100644 index 2222813d84e..00000000000 --- a/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlowsList.tsx +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import type { NovesFlowViewItem } from '../../utils/generateFlowViewData'; -import TxAssetFlowsListItem from './TxAssetFlowsListItem'; - -interface Props { - items: Array<NovesFlowViewItem>; - isPlaceholderData?: boolean; - resetKey?: string; -} - -const TxAssetFlowsList = ({ items, isPlaceholderData, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isPlaceholderData, resetKey }); - - return ( - <Box> - { items.slice(0, renderedItemsNum).map((item, i) => ( - <TxAssetFlowsListItem - key={ `${ i }-${ item.accountAddress }` } - item={ item } - isPlaceholderData={ Boolean(isPlaceholderData) } - /> - )) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - ); -}; - -export default React.memo(TxAssetFlowsList); diff --git a/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlowsListItem.tsx b/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlowsListItem.tsx deleted file mode 100644 index f406fd846ef..00000000000 --- a/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlowsListItem.tsx +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box, Text } from '@chakra-ui/react'; -import React from 'react'; - -import NovesFromTo from 'src/features/tx-interpretation/noves/components/NovesFromTo'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -import NovesActionSnippet from '../../components/NovesActionSnippet'; -import type { NovesFlowViewItem } from '../../utils/generateFlowViewData'; - -type Props = { - isPlaceholderData: boolean; - item: NovesFlowViewItem; -}; - -const TxAssetFlowsListItem = (props: Props) => { - - return ( - <ListItemMobile rowGap={ 4 } w="full" > - <Skeleton borderRadius="sm" loading={ props.isPlaceholderData } w="full"> - - <Box display="flex" > - <SpriteIcon - name="lightning" - height="5" - width="5" - color="icon.primary" - /> - - <Text textStyle="sm" fontWeight="medium"> - Action - </Text> - </Box> - - </Skeleton> - - <NovesActionSnippet item={ props.item } isLoaded={ !props.isPlaceholderData }/> - - <Box maxW="full"> - <NovesFromTo item={ props.item } isLoaded={ !props.isPlaceholderData }/> - </Box> - </ListItemMobile> - ); -}; - -export default React.memo(TxAssetFlowsListItem); diff --git a/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlowsTable.tsx b/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlowsTable.tsx index 45c3c398cc0..6f97336f021 100644 --- a/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlowsTable.tsx +++ b/src/features/tx-interpretation/noves/pages/tx-asset-flows/TxAssetFlowsTable.tsx @@ -19,7 +19,7 @@ const TxAssetFlowsTable = ({ items, isPlaceholderData, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isPlaceholderData, resetKey }); return ( - <TableRoot> + <TableRoot minW="900px"> <TableHeaderSticky top={ 75 }> <TableRow> <TableColumnHeader> diff --git a/src/features/user-ops/components/SearchBarSuggestUserOp.tsx b/src/features/user-ops/components/SearchBarSuggestUserOp.tsx index a0de7bda759..032cfe956f5 100644 --- a/src/features/user-ops/components/SearchBarSuggestUserOp.tsx +++ b/src/features/user-ops/components/SearchBarSuggestUserOp.tsx @@ -9,13 +9,14 @@ import type { ItemsProps } from 'src/slices/search/components/search-bar/SearchB import * as UserOpEntity from 'src/features/user-ops/components/entity/UserOpEntity'; import Time from 'src/shared/date-and-time/Time'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; + +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const SearchBarSuggestUserOp = ({ data, isMobile }: ItemsProps<schemas['SearchResultUserOperation']>) => { const icon = <UserOpEntity.Icon/>; const hash = ( <chakra.mark overflow="hidden" whiteSpace="nowrap" fontWeight={ 700 }> - <HashStringShortenDynamic hash={ data.user_operation_hash } noTooltip/> + <Truncate value={ data.user_operation_hash } tooltip={ false }/> </chakra.mark> ); diff --git a/src/features/user-ops/components/entity/__screenshots__/UserOpEntity.pw.tsx_default_loading-1.png b/src/features/user-ops/components/entity/__screenshots__/UserOpEntity.pw.tsx_default_loading-1.png index fc48d621cea..f06fa010cc3 100644 Binary files a/src/features/user-ops/components/entity/__screenshots__/UserOpEntity.pw.tsx_default_loading-1.png and b/src/features/user-ops/components/entity/__screenshots__/UserOpEntity.pw.tsx_default_loading-1.png differ diff --git a/src/features/user-ops/pages/address/AddressUserOps.tsx b/src/features/user-ops/pages/address/AddressUserOps.tsx index 9d260ff44bb..12e2916cc5f 100644 --- a/src/features/user-ops/pages/address/AddressUserOps.tsx +++ b/src/features/user-ops/pages/address/AddressUserOps.tsx @@ -1,15 +1,15 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import UserOpsContent from 'src/features/user-ops/pages/index/UserOpsContent'; import { USER_OPS_ITEM } from 'src/features/user-ops/stubs'; import useIsMounted from 'src/shared/hooks/useIsMounted'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; type Props = { scrollRef?: React.RefObject<HTMLDivElement>; @@ -23,7 +23,7 @@ const AddressUserOps = ({ scrollRef, shouldRender = true, isQueryEnabled = true const hash = getQueryParamString(router.query.hash); - const userOpsQuery = useQueryWithPages({ + const userOpsQuery = useApiPaginatedQuery({ resourceName: 'core:user_ops', scrollRef, options: { @@ -33,7 +33,7 @@ const AddressUserOps = ({ scrollRef, shouldRender = true, isQueryEnabled = true page_size: 50, } }), }, - filters: { sender: hash }, + queryParams: { sender: hash }, }); if (!isMounted || !shouldRender) { diff --git a/src/features/user-ops/pages/details/UserOp.pw.tsx b/src/features/user-ops/pages/details/UserOp.pw.tsx index 46228a5a724..f2b98128c34 100644 --- a/src/features/user-ops/pages/details/UserOp.pw.tsx +++ b/src/features/user-ops/pages/details/UserOp.pw.tsx @@ -1,6 +1,7 @@ import React from 'react'; import * as statsMock from 'src/slices/chain/stats/mocks'; +import * as txMock from 'src/slices/tx/mocks/details'; import { userOpData } from 'src/features/user-ops/mocks/user-op'; @@ -12,12 +13,12 @@ import UserOp from './UserOp'; const hooksConfig = { router: { query: { hash: userOpData.hash }, - isReady: true, }, }; -test.beforeEach(async({ mockEnvs }) => { +test.beforeEach(async({ mockEnvs, mockApiResponse }) => { await mockEnvs(ENVS_MAP.userOps); + await mockApiResponse('core:tx', txMock.base, { pathParams: { hash: userOpData.transaction_hash } }); }); test('base view', async({ render, mockTextAd, mockApiResponse }) => { diff --git a/src/features/user-ops/pages/details/UserOp.tsx b/src/features/user-ops/pages/details/UserOp.tsx index 36ce0befd81..76e0aaec1bd 100644 --- a/src/features/user-ops/pages/details/UserOp.tsx +++ b/src/features/user-ops/pages/details/UserOp.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { inRange } from 'es-toolkit'; -import { useRouter } from 'next/router'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -18,9 +17,11 @@ import TxLogs from 'src/slices/tx/pages/details/logs/TxLogs'; import TextAd from 'src/features/ads/text/components/TextAd'; import { USER_OP } from 'src/features/user-ops/stubs'; +import ApiDegradationAlert from 'src/shared/api-degradation/ApiDegradationAlert'; import throwOnAbsentParamError from 'src/shared/errors/throw-on-absent-param-error'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -74,16 +75,23 @@ const UserOp = () => { } }, [ userOpQuery.data ]); - const tabs: Array<TabItemRegular> = React.useMemo(() => ([ - { id: 'index', title: 'Details', component: <UserOpDetails query={ userOpQuery }/> }, - { - id: 'token_transfers', - title: 'Token transfers', - component: <TxTokenTransfer txQuery={ txQuery } tokenTransferFilter={ filterTokenTransfersByLogIndex }/>, - }, - { id: 'logs', title: 'Logs', component: <TxLogs txQuery={ txQuery } logsFilter={ filterLogsByLogIndex }/> }, - { id: 'raw', title: 'Raw', component: <UserOpRaw rawData={ userOpQuery.data?.raw } isLoading={ userOpQuery.isPlaceholderData }/> }, - ]), [ userOpQuery, txQuery, filterTokenTransfersByLogIndex, filterLogsByLogIndex ]); + const tabs: Array<TabItemRegular> = React.useMemo(() => { + // the transaction is served by the RPC node while the API catches up — nothing to list until then + const txDependentTab = (component: React.ReactNode) => txQuery.isDegradedData ? + <ApiDegradationAlert isLoading={ txQuery.isPlaceholderData }/> : + component; + + return [ + { id: 'index', title: 'Details', component: <UserOpDetails query={ userOpQuery }/> }, + { + id: 'token_transfers', + title: 'Token transfers', + component: txDependentTab(<TxTokenTransfer txQuery={ txQuery } tokenTransferFilter={ filterTokenTransfersByLogIndex }/>), + }, + { id: 'logs', title: 'Logs', component: txDependentTab(<TxLogs txQuery={ txQuery } logsFilter={ filterLogsByLogIndex }/>) }, + { id: 'raw', title: 'Raw', component: <UserOpRaw rawData={ userOpQuery.data?.raw } isLoading={ userOpQuery.isPlaceholderData }/> }, + ]; + }, [ userOpQuery, txQuery, filterTokenTransfersByLogIndex, filterLogsByLogIndex ]); throwOnAbsentParamError(hash); throwOnResourceLoadError(userOpQuery); diff --git a/src/features/user-ops/pages/details/UserOpCallDataSwitch.tsx b/src/features/user-ops/pages/details/UserOpCallDataSwitch.tsx index 30aa39fe273..21bbbdfd849 100644 --- a/src/features/user-ops/pages/details/UserOpCallDataSwitch.tsx +++ b/src/features/user-ops/pages/details/UserOpCallDataSwitch.tsx @@ -18,12 +18,10 @@ const UserOpCallDataSwitch = ({ className, initialValue, isDisabled, onChange, i const [ isChecked, setIsChecked ] = React.useState(initialValue ?? false); const handleChange = React.useCallback(() => { - setIsChecked((prevValue) => { - const nextValue = !prevValue; - onChange(nextValue); - return nextValue; - }); - }, [ onChange ]); + const nextValue = !isChecked; + setIsChecked(nextValue); + onChange(nextValue); + }, [ isChecked, onChange ]); return ( <Flex ml="auto" alignItems="center" gap={ 2 }> diff --git a/src/features/user-ops/pages/details/__screenshots__/UserOp.pw.tsx_default_base-view-1.png b/src/features/user-ops/pages/details/__screenshots__/UserOp.pw.tsx_default_base-view-1.png index 14675f48b8e..7ac2561affa 100644 Binary files a/src/features/user-ops/pages/details/__screenshots__/UserOp.pw.tsx_default_base-view-1.png and b/src/features/user-ops/pages/details/__screenshots__/UserOp.pw.tsx_default_base-view-1.png differ diff --git a/src/features/user-ops/pages/details/__screenshots__/UserOp.pw.tsx_default_mobile-base-view-1.png b/src/features/user-ops/pages/details/__screenshots__/UserOp.pw.tsx_default_mobile-base-view-1.png index cde88d78c96..48dad637102 100644 Binary files a/src/features/user-ops/pages/details/__screenshots__/UserOp.pw.tsx_default_mobile-base-view-1.png and b/src/features/user-ops/pages/details/__screenshots__/UserOp.pw.tsx_default_mobile-base-view-1.png differ diff --git a/src/features/user-ops/pages/index/UserOps.pw.tsx b/src/features/user-ops/pages/index/UserOps.pw.tsx index 302e332ef11..23575c21d65 100644 --- a/src/features/user-ops/pages/index/UserOps.pw.tsx +++ b/src/features/user-ops/pages/index/UserOps.pw.tsx @@ -9,7 +9,7 @@ import { test, expect } from 'playwright/lib'; import UserOps from './UserOps'; -test('base view +@mobile', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { +test('base view', async({ render, mockEnvs, mockTextAd, mockApiResponse }) => { test.slow(); await mockEnvs(ENVS_MAP.userOps); await mockTextAd(); diff --git a/src/features/user-ops/pages/index/UserOps.tsx b/src/features/user-ops/pages/index/UserOps.tsx index 23aafc00cbb..32239e47ef8 100644 --- a/src/features/user-ops/pages/index/UserOps.tsx +++ b/src/features/user-ops/pages/index/UserOps.tsx @@ -6,13 +6,13 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import { USER_OPS_ITEM } from 'src/features/user-ops/stubs'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import UserOpsContent from './UserOpsContent'; const UserOps = () => { - const query = useQueryWithPages({ + const query = useApiPaginatedQuery({ resourceName: 'core:user_ops', options: { placeholderData: generateListStub<'core:user_ops'>(USER_OPS_ITEM, 50, { next_page_params: { diff --git a/src/features/user-ops/pages/index/UserOpsContent.tsx b/src/features/user-ops/pages/index/UserOpsContent.tsx index 45ce1f66b84..b13a3e42b87 100644 --- a/src/features/user-ops/pages/index/UserOpsContent.tsx +++ b/src/features/user-ops/pages/index/UserOpsContent.tsx @@ -7,14 +7,14 @@ import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import UserOpsTable from './UserOpsTable'; type Props = { - query: QueryWithPagesResult<'core:user_ops'>; + query: ApiPaginatedQueryResult<'core:user_ops'>; showTx?: boolean; showSender?: boolean; }; @@ -30,7 +30,7 @@ const UserOpsContent = ({ query, showTx = true, showSender = true }: Props) => { <UserOpsTable items={ query.data.items } top={ query.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ query.isPlaceholderData } + isLoading={ query.isInitialLoading } showTx={ showTx } showSender={ showSender } resetKey={ query.queryHash } @@ -50,6 +50,7 @@ const UserOpsContent = ({ query, showTx = true, showSender = true }: Props) => { itemsNum={ query.data?.items?.length } emptyText="There are no user operations." actionBar={ actionBar } + isTransitioning={ query.isTransitioning } > { content } </DataList> diff --git a/src/features/user-ops/pages/index/UserOpsList.tsx b/src/features/user-ops/pages/index/UserOpsList.tsx deleted file mode 100644 index a626e3d6e79..00000000000 --- a/src/features/user-ops/pages/index/UserOpsList.tsx +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import UserOpsListItem from './UserOpsListItem'; - -type Props = { - items: Array<schemas['UserOperationInList']>; - isLoading?: boolean; - showTx: boolean; - showSender: boolean; - chainData?: ClusterChainConfig; - resetKey?: string; -}; - -const UserOpsList = ({ items, isLoading, showTx, showSender, chainData, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <UserOpsListItem - key={ item.hash + (isLoading ? String(index) : '') } - item={ item } - isLoading={ isLoading } - showTx={ showTx } - showSender={ showSender } - chainData={ chainData } - /> - )) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - ); -}; - -export default React.memo(UserOpsList); diff --git a/src/features/user-ops/pages/index/UserOpsListItem.tsx b/src/features/user-ops/pages/index/UserOpsListItem.tsx deleted file mode 100644 index 9890ec164b6..00000000000 --- a/src/features/user-ops/pages/index/UserOpsListItem.tsx +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; - -import AddressStringOrParam from 'src/slices/address/components/entity/AddressStringOrParam'; -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import { useMultichainContext } from 'src/features/multichain/context'; -import UserOpEntity from 'src/features/user-ops/components/entity/UserOpEntity'; -import UserOpStatus from 'src/features/user-ops/components/UserOpStatus'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -type Props = { - item: schemas['UserOperationInList']; - isLoading?: boolean; - showTx: boolean; - showSender: boolean; - chainData?: ClusterChainConfig; -}; - -const UserOpsListItem = ({ item, isLoading, showTx, showSender, chainData }: Props) => { - const multichainContext = useMultichainContext(); - const chainConfig = (multichainContext?.chain.app_config || config); - - return ( - <ListItemMobileGrid.Container gridTemplateColumns="100px auto"> - - <ListItemMobileGrid.Label isLoading={ isLoading }>User op hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <UserOpEntity hash={ item.hash } isLoading={ isLoading } fontWeight="700" noIcon={ !chainData } truncation="constant_long" chain={ chainData } noCopy/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.timestamp } - isLoading={ isLoading } - color="text.secondary" - display="inline-block" - /> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Status</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <UserOpStatus status={ item.status } loading={ isLoading }/> - </ListItemMobileGrid.Value> - - { showSender && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Sender</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressStringOrParam - address={ item.address } - isLoading={ isLoading } - truncation="constant" - /> - </ListItemMobileGrid.Value> - </> - ) } - - { showTx && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Tx hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntity - hash={ item.transaction_hash } - isLoading={ isLoading } - noIcon - truncation="constant_long" - /> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Block</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntity - number={ Number(item.block_number) } - isLoading={ isLoading } - textStyle="sm" - noIcon - /> - </ListItemMobileGrid.Value> - - { !chainConfig.slices.tx.hiddenFields?.tx_fee && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Fee</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <NativeCoinValue - amount={ item.fee } - loading={ isLoading } - /> - </ListItemMobileGrid.Value> - </> - ) } - - </ListItemMobileGrid.Container> - ); -}; - -export default UserOpsListItem; diff --git a/src/features/user-ops/pages/index/__screenshots__/UserOps.pw.tsx_default_base-view-1.png b/src/features/user-ops/pages/index/__screenshots__/UserOps.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..f167076152a Binary files /dev/null and b/src/features/user-ops/pages/index/__screenshots__/UserOps.pw.tsx_default_base-view-1.png differ diff --git a/src/features/user-ops/pages/index/__screenshots__/UserOps.pw.tsx_default_base-view-mobile-1.png b/src/features/user-ops/pages/index/__screenshots__/UserOps.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 3078ef18bf2..00000000000 Binary files a/src/features/user-ops/pages/index/__screenshots__/UserOps.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/user-ops/pages/index/__screenshots__/UserOps.pw.tsx_mobile_base-view-mobile-1.png b/src/features/user-ops/pages/index/__screenshots__/UserOps.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 016b348a195..00000000000 Binary files a/src/features/user-ops/pages/index/__screenshots__/UserOps.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/features/user-ops/pages/tx/TxUserOps.tsx b/src/features/user-ops/pages/tx/TxUserOps.tsx index c34da96d0f8..9ebd1fe9a2b 100644 --- a/src/features/user-ops/pages/tx/TxUserOps.tsx +++ b/src/features/user-ops/pages/tx/TxUserOps.tsx @@ -10,7 +10,7 @@ import UserOpsContent from 'src/features/user-ops/pages/index/UserOpsContent'; import { USER_OPS_ITEM } from 'src/features/user-ops/stubs'; import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; interface Props { @@ -18,14 +18,14 @@ interface Props { } const TxUserOps = ({ txQuery }: Props) => { - const userOpsQuery = useQueryWithPages({ + const userOpsQuery = useApiPaginatedQuery({ resourceName: 'core:user_ops', options: { enabled: !txQuery.isPlaceholderData && Boolean(txQuery.data?.status && txQuery.data?.hash), // most often there is only one user op in one tx placeholderData: generateListStub<'core:user_ops'>(USER_OPS_ITEM, 1, { next_page_params: null }), }, - filters: { transaction_hash: txQuery.data?.hash }, + queryParams: { transaction_hash: txQuery.data?.hash }, }); if (!txQuery.isPending && !txQuery.isPlaceholderData && !txQuery.isError && !txQuery.data.status) { diff --git a/src/features/web3-wallet/components/TokenAddToWallet.tsx b/src/features/web3-wallet/components/TokenAddToWallet.tsx index 7d28da2ed4f..d5b8330c456 100644 --- a/src/features/web3-wallet/components/TokenAddToWallet.tsx +++ b/src/features/web3-wallet/components/TokenAddToWallet.tsx @@ -13,7 +13,7 @@ import useProvider from 'src/features/web3-wallet/hooks/useProvider'; import useSwitchOrAddChain from 'src/features/web3-wallet/hooks/useSwitchOrAddChain'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import SpriteIcon from 'src/sprite/SpriteIcon'; @@ -99,7 +99,7 @@ const TokenAddToWallet = ({ className, token, tokenId, isLoading, variant = 'ico await trackUsage('add_token'); - mixpanel.logEvent(mixpanel.EventTypes.ADD_TO_WALLET, { + analytics.logEvent(analytics.EventTypes.ADD_TO_WALLET, { Target: 'token', Wallet: wallet, Token: token.symbol || '', diff --git a/src/features/web3-wallet/hooks/useAddChainClick.ts b/src/features/web3-wallet/hooks/useAddChainClick.ts index 2e1825b8681..3916b36fe6a 100644 --- a/src/features/web3-wallet/hooks/useAddChainClick.ts +++ b/src/features/web3-wallet/hooks/useAddChainClick.ts @@ -2,7 +2,7 @@ import React from 'react'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { toaster } from 'src/toolkit/chakra/toaster'; @@ -34,7 +34,7 @@ export default function useAddChainClick({ source, onSuccess }: Props) { description: 'Successfully added network to your wallet', }); - mixpanel.logEvent(mixpanel.EventTypes.ADD_TO_WALLET, { + analytics.logEvent(analytics.EventTypes.ADD_TO_WALLET, { Target: 'network', Wallet: wallet, Source: source, diff --git a/src/pages/_app.tsx b/src/pages/_app.tsx index 12fd35e754e..ab77b3efbd7 100644 --- a/src/pages/_app.tsx +++ b/src/pages/_app.tsx @@ -6,7 +6,6 @@ import { QueryClientProvider } from '@tanstack/react-query'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; import type { AppProps } from 'next/app'; import dynamic from 'next/dynamic'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import type { NextPageWithLayout } from 'src/server/types'; @@ -21,6 +20,7 @@ import getSocketUrl from 'src/api/socket/get-socket-url'; import { AppContextProvider } from 'src/shell/app/context'; import Layout from 'src/shell/layout/Layout'; import { SettingsContextProvider } from 'src/shell/top-bar/settings/context'; +import { SettingsModalContextProvider } from 'src/shell/top-bar/settings/modal/context'; import { Web3Provider } from 'src/features/connect-wallet/context'; import { CsvExportContextProvider } from 'src/features/csv-export/utils/context'; @@ -33,6 +33,8 @@ import { Provider as RollbarProvider } from 'src/services/rollbar'; import AppErrorBoundary from 'src/shared/errors/AppErrorBoundary'; import AppErrorGlobalContainer from 'src/shared/errors/AppErrorGlobalContainer'; import useIsMounted from 'src/shared/hooks/useIsMounted'; +import NextRouterProvider from 'src/shared/router/NextRouterProvider'; +import type { Route } from 'src/shared/router/routes'; import { FallbackProvider } from 'src/shared/utils/fallback-provider'; import SpriteInjector from 'src/sprite/SpriteInjector'; @@ -124,9 +126,11 @@ function MyApp({ Component, pageProps, router }: AppPropsWithLayout) { <RewardsProvider> <MarketplaceContextProvider> <SettingsContextProvider> - <CsvExportContextProvider> - { content } - </CsvExportContextProvider> + <SettingsModalContextProvider> + <CsvExportContextProvider> + { content } + </CsvExportContextProvider> + </SettingsModalContextProvider> </SettingsContextProvider> </MarketplaceContextProvider> </RewardsProvider> @@ -138,13 +142,8 @@ function MyApp({ Component, pageProps, router }: AppPropsWithLayout) { ); const walletBoundary = walletConnectorType === 'dynamic' ? ( - // The dynamic wallet hooks resolve their heavy connector through a dynamic import and suspend on first - // render; the pages-router dynamic() wrapper provides no Suspense boundary of its own, so one is needed - // here. A null fallback keeps the pre-connector window blank instead of remounting once it resolves. <DynamicProvider> - <React.Suspense fallback={ null }> - { appTree } - </React.Suspense> + { appTree } </DynamicProvider> ) : ( // reown / fallback: `<Web3Provider>` renders children provider-less at first paint (no wallet chunk on @@ -157,7 +156,7 @@ function MyApp({ Component, pageProps, router }: AppPropsWithLayout) { ); return ( - <> + <NextRouterProvider> <PageMetadata pathname={ router.pathname as Route['pathname'] } query={ pageProps.query } apiData={ pageProps.apiData }/> <SpriteInjector/> <ChakraProvider> @@ -172,7 +171,7 @@ function MyApp({ Component, pageProps, router }: AppPropsWithLayout) { </AppErrorBoundary> </RollbarProvider> </ChakraProvider> - </> + </NextRouterProvider> ); } diff --git a/src/pages/_document.tsx b/src/pages/_document.tsx index 9baf9230508..538338e3110 100644 --- a/src/pages/_document.tsx +++ b/src/pages/_document.tsx @@ -12,6 +12,8 @@ import * as serverTiming from 'src/server/utils/serverTiming'; import config from 'src/config'; import { SPRITE_URL } from 'src/sprite/SpriteInjector'; +import { ColorModeProvider } from 'src/toolkit/chakra/color-mode'; + const marketplaceFeature = config.features.marketplace; const usercentrics = config.services.usercentrics; @@ -41,6 +43,11 @@ class MyDocument extends Document { return ( <Html lang="en"> <Head> + { /* Color mode script: without children the provider renders only its inline script, which sets the theme */ } + { /* class on <html> before the first paint. The copy rendered by the app provider sits after the global styles */ } + { /* in <body>, and Firefox paints the page white before reaching it. */ } + <ColorModeProvider/> + { /* Early-fetch primer: fire the page's first-render API requests before the JS bundle boots */ } { primerScript && <script dangerouslySetInnerHTML={{ __html: primerScript }}/> } diff --git a/src/pages/address/[hash]/index.tsx b/src/pages/address/[hash]/index.tsx index d14885aa2c1..e7d65b00014 100644 --- a/src/pages/address/[hash]/index.tsx +++ b/src/pages/address/[hash]/index.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { GetServerSideProps, NextPage } from 'next'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import type { Props } from 'src/server/getServerSideProps/handlers'; @@ -16,6 +15,7 @@ import MultichainAddress from 'src/features/multichain/pages/address/MultichainA import config from 'src/config'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import type { Route } from 'src/shared/router/routes'; const pathname: Route['pathname'] = '/address/[hash]'; diff --git a/src/pages/api/healthz.tsx b/src/pages/api/healthz.ts similarity index 100% rename from src/pages/api/healthz.tsx rename to src/pages/api/healthz.ts diff --git a/src/pages/apps/[id]/index.tsx b/src/pages/apps/[id]/index.tsx index 4c7ca25a46f..3b4e8638f5d 100644 --- a/src/pages/apps/[id]/index.tsx +++ b/src/pages/apps/[id]/index.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import dynamic from 'next/dynamic'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import type { NextPageWithLayout } from 'src/server/types'; @@ -11,6 +10,8 @@ import PageNextJs from 'src/server/PageNextJs'; import LayoutApp from 'src/shell/layout/LayoutApp'; +import type { Route } from 'src/shared/router/routes'; + const MarketplaceAppPage = dynamic(() => import('src/features/marketplace/pages/dapp/MarketplaceApp'), { ssr: false }); const pathname: Route['pathname'] = '/apps/[id]'; diff --git a/src/pages/cross-chain-tx/[id].tsx b/src/pages/bridge/[bridgeId]/cross-chain-tx/[id].tsx similarity index 87% rename from src/pages/cross-chain-tx/[id].tsx rename to src/pages/bridge/[bridgeId]/cross-chain-tx/[id].tsx index 8e41d09ef61..a3fed06ff27 100644 --- a/src/pages/cross-chain-tx/[id].tsx +++ b/src/pages/bridge/[bridgeId]/cross-chain-tx/[id].tsx @@ -11,7 +11,7 @@ const TxCrossChain = dynamic(() => import('src/features/cross-chain-txs/pages/tx const Page: NextPage<Props> = (props: Props) => { return ( - <PageNextJs pathname="/cross-chain-tx/[id]" query={ props.query }> + <PageNextJs pathname="/bridge/[bridgeId]/cross-chain-tx/[id]" query={ props.query }> <TxCrossChain/> </PageNextJs> ); diff --git a/src/pages/chain/[chain_slug_or_id]/token/[hash]/index.tsx b/src/pages/chain/[chain_slug_or_id]/token/[hash]/index.tsx index 921321179d3..fb911084c11 100644 --- a/src/pages/chain/[chain_slug_or_id]/token/[hash]/index.tsx +++ b/src/pages/chain/[chain_slug_or_id]/token/[hash]/index.tsx @@ -2,12 +2,13 @@ import type { NextPage } from 'next'; import dynamic from 'next/dynamic'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import type { Props } from 'src/server/getServerSideProps/handlers'; import PageNextJs from 'src/server/PageNextJs'; +import type { Route } from 'src/shared/router/routes'; + const MultichainToken = dynamic(() => import('src/features/multichain/pages/token/MultichainToken'), { ssr: false }); const pathname: Route['pathname'] = '/token/[hash]'; diff --git a/src/pages/chain/[chain_slug_or_id]/token/[hash]/instance/[id].tsx b/src/pages/chain/[chain_slug_or_id]/token/[hash]/instance/[id].tsx index cc9d78949ce..dfe3d42ec53 100644 --- a/src/pages/chain/[chain_slug_or_id]/token/[hash]/instance/[id].tsx +++ b/src/pages/chain/[chain_slug_or_id]/token/[hash]/instance/[id].tsx @@ -2,12 +2,13 @@ import type { NextPage } from 'next'; import dynamic from 'next/dynamic'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import type { Props } from 'src/server/getServerSideProps/handlers'; import PageNextJs from 'src/server/PageNextJs'; +import type { Route } from 'src/shared/router/routes'; + const MultichainTokenInstance = dynamic(() => import('src/features/multichain/pages/token-instance/MultichainTokenInstance'), { ssr: false }); const pathname: Route['pathname'] = '/token/[hash]/instance/[id]'; diff --git a/src/pages/stats/[id].tsx b/src/pages/stats/[id].tsx index f597855bfa7..fa16ef2ed66 100644 --- a/src/pages/stats/[id].tsx +++ b/src/pages/stats/[id].tsx @@ -2,7 +2,6 @@ import type { GetServerSideProps, NextPage } from 'next'; import dynamic from 'next/dynamic'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import type { Props } from 'src/server/getServerSideProps/handlers'; @@ -16,6 +15,7 @@ import { MultichainProvider } from 'src/features/multichain/context'; import config from 'src/config'; import dayjs from 'src/shared/date-and-time/dayjs'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import type { Route } from 'src/shared/router/routes'; const ChainStatsDetails = dynamic(() => import('src/features/chain-stats/pages/details/ChainStatsDetails'), { ssr: false }); diff --git a/src/pages/token/[hash]/index.tsx b/src/pages/token/[hash]/index.tsx index 8b1126ad894..d58dea049a2 100644 --- a/src/pages/token/[hash]/index.tsx +++ b/src/pages/token/[hash]/index.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { GetServerSideProps, NextPage } from 'next'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import type { Props } from 'src/server/getServerSideProps/handlers'; @@ -14,6 +13,7 @@ import Token from 'src/slices/token/pages/details/Token'; import config from 'src/config'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import type { Route } from 'src/shared/router/routes'; const pathname: Route['pathname'] = '/token/[hash]'; diff --git a/src/pages/token/[hash]/instance/[id].tsx b/src/pages/token/[hash]/instance/[id].tsx index 8b088229e96..b2c3a10e0b0 100644 --- a/src/pages/token/[hash]/instance/[id].tsx +++ b/src/pages/token/[hash]/instance/[id].tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { GetServerSideProps, NextPage } from 'next'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import type { Props } from 'src/server/getServerSideProps/handlers'; @@ -14,6 +13,7 @@ import TokenInstance from 'src/slices/token/pages/instance/TokenInstance'; import config from 'src/config'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import type { Route } from 'src/shared/router/routes'; const pathname: Route['pathname'] = '/token/[hash]/instance/[id]'; diff --git a/src/pages/tx/[hash].tsx b/src/pages/tx/[hash].tsx index c07c9dd5650..a248c381135 100644 --- a/src/pages/tx/[hash].tsx +++ b/src/pages/tx/[hash].tsx @@ -2,7 +2,6 @@ import type { GetServerSideProps, NextPage } from 'next'; import dynamic from 'next/dynamic'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import type { Props } from 'src/server/getServerSideProps/handlers'; @@ -16,6 +15,7 @@ import getOgDescriptionParams from 'src/slices/tx/utils/get-og-description-param import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import type { Route } from 'src/shared/router/routes'; import { SECOND } from 'src/toolkit/utils/consts'; diff --git a/src/server/PageMetadata.tsx b/src/server/PageMetadata.tsx index 1e6687cf787..b1578c2ce13 100644 --- a/src/server/PageMetadata.tsx +++ b/src/server/PageMetadata.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import Head from 'next/head'; -import type { Route } from 'nextjs-routes'; import React from 'react'; import type { Props as PageProps } from 'src/server/getServerSideProps/handlers'; @@ -9,6 +8,7 @@ import type { Props as PageProps } from 'src/server/getServerSideProps/handlers' import * as metadata from 'src/shell/metadata'; import config from 'src/config'; +import type { Route } from 'src/shared/router/routes'; interface Props<Pathname extends Route['pathname']> { pathname: Pathname; diff --git a/src/server/PageNextJs.ts b/src/server/PageNextJs.ts new file mode 100644 index 00000000000..1b55050ec85 --- /dev/null +++ b/src/server/PageNextJs.ts @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { Props as PageProps } from 'src/server/getServerSideProps/handlers'; + +import useGetCsrfToken from 'src/features/account/hooks/useGetCsrfToken'; +import useAdblockDetect from 'src/features/ads/common/hooks/useAdblockDetect'; +import useNotifyOnNavigation from 'src/features/metasuites/hooks/useNotifyOnNavigation'; + +import useUpdateUsercentricsConsent from 'src/services/usercentrics/useUpdateUsercentricsConsent'; +import * as analytics from 'src/shared/analytics'; +import useIsMounted from 'src/shared/hooks/useIsMounted'; +import type { Route } from 'src/shared/router/routes'; + +interface Props<Pathname extends Route['pathname']> { + pathname: Pathname; + children: React.ReactNode; + query?: PageProps<Pathname>['query']; + apiData?: PageProps<Pathname>['apiData']; +} + +const PageNextJs = <Pathname extends Route['pathname']>(props: Props<Pathname>) => { + const isMounted = useIsMounted(); + + useGetCsrfToken(); + useAdblockDetect(); + useNotifyOnNavigation(); + useUpdateUsercentricsConsent(); + + const isAnalyticsInitialized = analytics.useInit(); + analytics.useLogPageView(isAnalyticsInitialized); + + return isMounted ? props.children : null; +}; + +export default React.memo(PageNextJs); diff --git a/src/server/PageNextJs.tsx b/src/server/PageNextJs.tsx deleted file mode 100644 index 23fabd796d8..00000000000 --- a/src/server/PageNextJs.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { Route } from 'nextjs-routes'; -import React from 'react'; - -import type { Props as PageProps } from 'src/server/getServerSideProps/handlers'; - -import useGetCsrfToken from 'src/features/account/hooks/useGetCsrfToken'; -import useAdblockDetect from 'src/features/ads/common/hooks/useAdblockDetect'; -import useNotifyOnNavigation from 'src/features/metasuites/hooks/useNotifyOnNavigation'; - -import * as mixpanel from 'src/services/mixpanel'; -import useUpdateUsercentricsConsent from 'src/services/usercentrics/useUpdateUsercentricsConsent'; -import useIsMounted from 'src/shared/hooks/useIsMounted'; - -interface Props<Pathname extends Route['pathname']> { - pathname: Pathname; - children: React.ReactNode; - query?: PageProps<Pathname>['query']; - apiData?: PageProps<Pathname>['apiData']; -} - -const PageNextJs = <Pathname extends Route['pathname']>(props: Props<Pathname>) => { - const isMounted = useIsMounted(); - - useGetCsrfToken(); - useAdblockDetect(); - useNotifyOnNavigation(); - useUpdateUsercentricsConsent(); - - const isMixPanelInitialized = mixpanel.useInit(); - mixpanel.useLogPageView(isMixPanelInitialized); - - return isMounted ? props.children : null; -}; - -export default React.memo(PageNextJs); diff --git a/src/server/csp/colorModeScript.spec.tsx b/src/server/csp/colorModeScript.spec.tsx new file mode 100644 index 00000000000..2917ce3b9a6 --- /dev/null +++ b/src/server/csp/colorModeScript.spec.tsx @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +// @vitest-environment jsdom + +import { createHash } from 'node:crypto'; +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; + +import { ColorModeProvider } from 'src/toolkit/chakra/color-mode'; + +import { describe, expect, it } from 'vitest'; + +import generateCspPolicy from './generateCspPolicy'; + +function getColorModeScriptHash(defaultTheme: string | undefined): string | undefined { + const html = renderToStaticMarkup(<ColorModeProvider defaultTheme={ defaultTheme }/>); + const script = new DOMParser().parseFromString(html, 'text/html').querySelector('script')?.textContent; + + return script ? `'sha256-${ createHash('sha256').update(script).digest('base64') }'` : undefined; +} + +describe('color mode inline script', () => { + it('guards against a vacuous suite — the provider must render an inline script', () => { + expect(getColorModeScriptHash('dark')).toBeDefined(); + }); + + it.each([ undefined, 'dark', 'light' ])('is allowed by the policy when the default color mode is %s', (defaultTheme) => { + expect(generateCspPolicy()).toContain(getColorModeScriptHash(defaultTheme)); + }); +}); diff --git a/src/server/csp/generateCspPolicy.ts b/src/server/csp/generateCspPolicy.ts index e33c5b1e673..e8e183b42d6 100644 --- a/src/server/csp/generateCspPolicy.ts +++ b/src/server/csp/generateCspPolicy.ts @@ -18,6 +18,7 @@ function generateCspPolicy(isPrivateMode = false, nonce?: string, primerScriptHa descriptors.mixpanel(isPrivateMode), descriptors.monaco(), descriptors.multichain(), + descriptors.posthog(isPrivateMode), descriptors.rollbar(isPrivateMode), descriptors.usercentrics(isPrivateMode), descriptors.rollup(), diff --git a/src/server/csp/index.spec.ts b/src/server/csp/index.spec.ts index 0c7adb19abf..3e42a42c1df 100644 --- a/src/server/csp/index.spec.ts +++ b/src/server/csp/index.spec.ts @@ -14,14 +14,27 @@ const csp = await import('./index'); const generateCspPolicy = (await import('./generateCspPolicy')).default; const primerScriptHashes = await (await import('src/server/primedRequests')).getPrimerScriptCspHashes(); -function makeRequest({ pathname = '/', appProfile }: { pathname?: string; appProfile?: string } = {}) { +interface RequestOptions { + pathname?: string; + appProfile?: string; + cookies?: Record<string, string>; +} + +function makeRequest({ pathname = '/', appProfile, cookies = {} }: RequestOptions = {}) { return { headers: new Headers(appProfile ? { 'x-app-profile': appProfile } : undefined), nextUrl: { pathname, searchParams: new URLSearchParams() }, - cookies: { get: () => undefined }, + cookies: { get: (name: string) => (name in cookies ? { name, value: cookies[name] } : undefined) }, } as unknown as NextRequest; } +const CUSTOM_RPC_URL = 'https://rpc.custom.example:8545/v1/key'; +const CUSTOM_RPC_ORIGIN = 'https://rpc.custom.example:8545'; + +function getConnectSrc(policy: string) { + return policy.split(';').find((directive) => directive.startsWith('connect-src ')); +} + describe('nonce policies', () => { it('guards against a vacuous suite — the nonce must be part of the policy', async() => { expect(await csp.get(makeRequest(), NONCE)).toContain(`'nonce-${ NONCE }'`); @@ -57,3 +70,41 @@ describe('nonceless policies', () => { expect(await csp.get(makeRequest({ appProfile: 'private' }))).toBe(generateCspPolicy(true, undefined, primerScriptHashes)); }); }); + +describe('custom RPC node', () => { + const inUse = { custom_rpc_url: CUSTOM_RPC_URL, custom_rpc_in_use: 'true' }; + + it('allows the origin of the custom RPC node in connect-src while it is in use', async() => { + const connectSrc = getConnectSrc(await csp.get(makeRequest({ cookies: inUse }))); + + expect(connectSrc).toContain(` ${ CUSTOM_RPC_ORIGIN } `); + expect(connectSrc).not.toContain(CUSTOM_RPC_URL); + }); + + it('allows the origin in the nonce policy too', async() => { + const policy = await csp.get(makeRequest({ cookies: inUse }), NONCE); + + expect(getConnectSrc(policy)).toContain(` ${ CUSTOM_RPC_ORIGIN } `); + expect(policy).toContain(`'nonce-${ NONCE }'`); + }); + + it('keeps the cached policy untouched for the next request without the cookie', async() => { + await csp.get(makeRequest({ cookies: inUse })); + + expect(await csp.get(makeRequest())).toBe(generateCspPolicy(false, undefined, primerScriptHashes)); + }); + + it('ignores the cookie while the node is stored but not in use', async() => { + const policy = await csp.get(makeRequest({ cookies: { custom_rpc_url: CUSTOM_RPC_URL } })); + + expect(policy).not.toContain(CUSTOM_RPC_ORIGIN); + }); + + it('ignores an invalid or non-https URL', async() => { + const http = { custom_rpc_url: 'http://rpc.custom.example', custom_rpc_in_use: 'true' }; + const garbage = { custom_rpc_url: 'not a url', custom_rpc_in_use: 'true' }; + + expect(await csp.get(makeRequest({ cookies: http }))).not.toContain('rpc.custom.example'); + expect(await csp.get(makeRequest({ cookies: garbage }))).toBe(generateCspPolicy(false, undefined, primerScriptHashes)); + }); +}); diff --git a/src/server/csp/index.ts b/src/server/csp/index.ts index 9123f0a4426..7ac13106ef5 100644 --- a/src/server/csp/index.ts +++ b/src/server/csp/index.ts @@ -4,6 +4,10 @@ import type { NextRequest } from 'next/server'; import { getPrimerScriptCspHashes } from 'src/server/primedRequests'; +import { resolveCustomRpcUrl } from 'src/features/connect-wallet/utils/rpc-urls'; + +import * as cookies from 'src/shared/storage/cookies'; + import generateCspPolicy from './generateCspPolicy'; import generateNftHtmlEmbedCspPolicy from './generateNftHtmlEmbedCspPolicy'; @@ -38,9 +42,25 @@ async function initializeCspPolicies() { } } +function getCustomRpcOrigin(req: NextRequest | undefined): string | undefined { + const url = resolveCustomRpcUrl( + req?.cookies.get(cookies.NAMES.CUSTOM_RPC_URL)?.value, + req?.cookies.get(cookies.NAMES.CUSTOM_RPC_IN_USE)?.value, + ); + + return url ? new URL(url).origin : undefined; +} + +// the cached policies are shared by every request; the user's own RPC node is spliced in per request +function withCustomRpcOrigin(policy: string, origin: string | undefined): string { + return origin ? policy.replace('connect-src ', `connect-src ${ origin } `) : policy; +} + export async function get(req?: NextRequest, nonce?: string): Promise<string> { await initializeCspPolicies(); + const customRpcOrigin = getCustomRpcOrigin(req); + // Get appProfile from request (header, query param, or cookie) const appProfile = req ? ( req.headers.get('x-app-profile') || @@ -60,8 +80,8 @@ export async function get(req?: NextRequest, nonce?: string): Promise<string> { if (nonce) { const template = isPrivateMode ? cspPolicyTemplates?.private : cspPolicyTemplates?.default; - return template?.replaceAll(CSP_NONCE_PLACEHOLDER, nonce) || ''; + return withCustomRpcOrigin(template?.replaceAll(CSP_NONCE_PLACEHOLDER, nonce) || '', customRpcOrigin); } - return isPrivateMode ? cspPolicies?.private || '' : cspPolicies?.default || ''; + return withCustomRpcOrigin(isPrivateMode ? cspPolicies?.private || '' : cspPolicies?.default || '', customRpcOrigin); } diff --git a/src/server/csp/policies/ads.spec.ts b/src/server/csp/policies/ads.spec.ts new file mode 100644 index 00000000000..decf35511b0 --- /dev/null +++ b/src/server/csp/policies/ads.spec.ts @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const GOOGLE_AD_MANAGER_HOSTS = [ + 'https://*.googlesyndication.com', + 'https://securepubads.g.doubleclick.net', + 'https://ep2.adtrafficquality.google', +]; + +async function getPolicy(provider: string, isSpecifyEnabled = false) { + return withEnvs( + [ + [ 'NEXT_PUBLIC_AD_BANNER_PROVIDER', provider ], + [ 'NEXT_PUBLIC_AD_TEXT_PROVIDER', 'none' ], + [ 'NEXT_PUBLIC_AD_BANNER_ENABLE_SPECIFY', String(isSpecifyEnabled) ], + ], + async() => (await import('./ads')).ads(false), + ); +} + +describe('ads policy', () => { + it('lets the Specify SDK request ads and load their images', async() => { + const policy = await getPolicy('slise', true); + + expect(policy['connect-src']).toContain('spfsrv.com'); + expect(policy['img-src']).toContain('content.specify.sh'); + }); + + it('does not open the Specify hosts when Specify is disabled', async() => { + const policy = await getPolicy('slise'); + + expect(policy['connect-src']).not.toContain('spfsrv.com'); + expect(policy['img-src'] ?? []).not.toContain('content.specify.sh'); + }); + + it('lets Sevio fill a zone through Google Ad Manager', async() => { + const policy = await getPolicy('sevio'); + + for (const directive of [ 'connect-src', 'script-src', 'img-src', 'frame-src' ] as const) { + expect(policy[directive]).toEqual(expect.arrayContaining(GOOGLE_AD_MANAGER_HOSTS)); + } + }); + + it('does not open the Google hosts for other providers', async() => { + const policy = await getPolicy('adbutler'); + + expect(policy['connect-src']).not.toEqual(expect.arrayContaining(GOOGLE_AD_MANAGER_HOSTS)); + }); +}); diff --git a/src/server/csp/policies/ads.ts b/src/server/csp/policies/ads.ts index 292e27f81ae..caa96d1ef8d 100644 --- a/src/server/csp/policies/ads.ts +++ b/src/server/csp/policies/ads.ts @@ -16,6 +16,17 @@ import { mergeDescriptors } from '../utils'; type AdsProviders = AdBannerProviders | AdTextProviders | AdBannerAdditionalProviders | 'specify'; +// Sevio backfills some zones through Google Ad Manager; this is the list they asked us to allow for it. +// Their other demand partners stay blocked on purpose, since allowing them all would amount to no script-src at all. +const SEVIO_GOOGLE_ADS_HOSTS = [ + 'https://www.google.com', + 'https://*.googlesyndication.com', + 'https://securepubads.g.doubleclick.net', + 'https://googleads.g.doubleclick.net', + 'https://ep1.adtrafficquality.google', + 'https://ep2.adtrafficquality.google', +]; + const getProviderDescriptor = (provider: AdsProviders, nonce?: string): CspDev.DirectiveDescriptor => { switch (provider) { case 'sevio': @@ -25,13 +36,19 @@ const getProviderDescriptor = (provider: AdsProviders, nonce?: string): CspDev.D 'https://request.adx.ws', 'https://id5-sync.com', 'https://lb.eu-1-id5-sync.com/lb/v1', + ...SEVIO_GOOGLE_ADS_HOSTS, ], 'script-src': [ 'cdn.adx.ws', ...(nonce ? [ `'nonce-${ nonce }'` ] : []), + ...SEVIO_GOOGLE_ADS_HOSTS, ], 'img-src': [ '*.adx.ws', + ...SEVIO_GOOGLE_ADS_HOSTS, + ], + 'frame-src': [ + ...SEVIO_GOOGLE_ADS_HOSTS, ], }; case 'adbutler': @@ -61,7 +78,10 @@ const getProviderDescriptor = (provider: AdsProviders, nonce?: string): CspDev.D case 'specify': return { 'connect-src': [ - 'app.specify.sh', + 'spfsrv.com', + ], + 'img-src': [ + 'content.specify.sh', ], }; default: diff --git a/src/server/csp/policies/app.spec.ts b/src/server/csp/policies/app.spec.ts new file mode 100644 index 00000000000..b76a1be11bf --- /dev/null +++ b/src/server/csp/policies/app.spec.ts @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +// the app config is frozen on first import, so the font has to be set before anything pulls it in +process.env.NEXT_PUBLIC_FONT_FAMILY_HEADING = '{\'name\':\'Custom\',\'url\':\'https://fonts.example.com/css/custom.css\'}'; + +const { app } = await import('./app'); + +describe('custom font', () => { + it('can load its stylesheet and its font files from the configured host', () => { + const policy = app(); + + expect(policy['style-src']).toContain('fonts.example.com'); + expect(policy['font-src']).toContain('fonts.example.com'); + }); +}); diff --git a/src/server/csp/policies/app.ts b/src/server/csp/policies/app.ts index a55f5c6fc52..451048d0423 100644 --- a/src/server/csp/policies/app.ts +++ b/src/server/csp/policies/app.ts @@ -11,6 +11,15 @@ const MAIN_DOMAINS = [ config.app.host, ].filter(Boolean); +const COLOR_MODE_SCRIPT_HASHES = [ + // defaultTheme: system + '\'sha256-yYJq8IP5/WhJj6zxyTmujEqBFs/MufRufp2QKJFU76M=\'', + // defaultTheme: dark + '\'sha256-Os32ny+s3zEaX+XxoAVngBThnQv/IOycQlrqgxXOgRI=\'', + // defaultTheme: light + '\'sha256-/ZmmXHg9XaKeWp0VJihBDn4cJ7lLM1jUtpgqdgVFvmA=\'', +]; + const externalFontsDomains = (() => { try { return [ @@ -36,7 +45,7 @@ export function app(isPrivateMode = false, primerScriptHashes: Array<string> = [ KEY_WORDS.SELF, ...MAIN_DOMAINS, - // webpack hmr in safari doesn't recognize localhost as 'self' for some reason + // Next.js WebSocket HMR config.app.isDev ? 'ws://localhost:3000/_next/webpack-hmr' : '', // APIs @@ -65,8 +74,9 @@ export function app(isPrivateMode = false, primerScriptHashes: Array<string> = [ // https://github.com/vercel/next.js/issues/14221#issuecomment-657258278 config.app.isDev ? KEY_WORDS.UNSAFE_EVAL : '', - // hash of ColorModeScript: system + dark - '\'sha256-yYJq8IP5/WhJj6zxyTmujEqBFs/MufRufp2QKJFU76M=\'', + // next-themes bakes defaultTheme into its inline script, so every default has its own hash; + // a blocked script leaves <html> without the color mode class until hydration (white flash on dark themes) + ...COLOR_MODE_SCRIPT_HASHES, // CapybaraRunner '\'sha256-5+YTmTcBwCYdJ8Jetbr6kyjGp0Ry/H7ptpoun6CrSwQ=\'', @@ -88,6 +98,9 @@ export function app(isPrivateMode = false, primerScriptHashes: Array<string> = [ // google fonts 'fonts.googleapis.com', + + // custom fonts are loaded as external stylesheets + ...(externalFontsDomains || []), ], 'img-src': [ @@ -136,6 +149,12 @@ export function app(isPrivateMode = false, primerScriptHashes: Array<string> = [ KEY_WORDS.NONE, ], + // All app forms submit through JS (react-hook-form), never via a native action URL. + // Keeps operator-supplied HTML (maintenance alert, banners) from posting a phishing form to a third party. + 'form-action': [ + KEY_WORDS.SELF, + ], + // Restrict frame-src in private mode to prevent iframe tracking // In normal mode, frame-src is also set by marketplace.ts when marketplace is enabled ...(isPrivateMode ? {} as CspDev.DirectiveDescriptor : { diff --git a/src/server/csp/policies/index.ts b/src/server/csp/policies/index.ts index 91f3f59f692..427bb7590eb 100644 --- a/src/server/csp/policies/index.ts +++ b/src/server/csp/policies/index.ts @@ -13,6 +13,7 @@ export { megaEth } from './mega-eth'; export { mixpanel } from './mixpanel'; export { monaco } from './monaco'; export { multichain } from './multichain'; +export { posthog } from './posthog'; export { reCaptcha } from './re-captcha'; export { rollbar } from './rollbar'; export { rollup } from './rollup'; diff --git a/src/server/csp/policies/marketplace.ts b/src/server/csp/policies/marketplace.ts index 960df58a045..61b1853751a 100644 --- a/src/server/csp/policies/marketplace.ts +++ b/src/server/csp/policies/marketplace.ts @@ -17,7 +17,6 @@ export function marketplace(isPrivateMode: boolean): CspDev.DirectiveDescriptor const externalApiEndpoints = chainsConfig?.chains.map((chain) => chain.app_config?.apis?.core?.endpoint).filter(Boolean); const defaultRpcUrls = chainsConfig?.chains.map((chain) => chain.app_config?.chain?.rpcUrls).flat().filter(Boolean); - const liFiHost = feature.essentialDapps?.swap ? 'li.quest' : ''; const multisenderHost = feature.essentialDapps?.multisend ? '*.multisender.app' : ''; const posthogHost = feature.essentialDapps?.multisend?.posthogHost ? '*.posthog.com' : ''; @@ -25,7 +24,6 @@ export function marketplace(isPrivateMode: boolean): CspDev.DirectiveDescriptor 'connect-src': [ 'api' in feature ? feature.api.endpoint : '', ...(feature.essentialDapps ? [ - liFiHost, multisenderHost, posthogHost, ...(externalApiEndpoints ?? []), diff --git a/src/server/csp/policies/posthog.spec.ts b/src/server/csp/policies/posthog.spec.ts new file mode 100644 index 00000000000..6bfd8cabf77 --- /dev/null +++ b/src/server/csp/policies/posthog.spec.ts @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const API_KEY: Array<[ string, string ]> = [ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', 'phc_test' ] ]; +const NO_API_KEY: Array<[ string, string ]> = [ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', '' ] ]; + +async function getPolicy(envs: Array<[ string, string ]>, isPrivateMode = false) { + return withEnvs(envs, async() => (await import('./posthog')).posthog(isPrivateMode)); +} + +describe('posthog policy', () => { + it('allows the PostHog hosts when the API key is configured', async() => { + expect(await getPolicy(API_KEY)).toEqual({ + 'script-src': [ '*.posthog.com' ], + 'connect-src': [ '*.posthog.com' ], + 'img-src': [ '*.posthog.com' ], + }); + }); + + it('is empty when no API key is configured', async() => { + expect(await getPolicy(NO_API_KEY)).toEqual({}); + }); + + it('stays empty in private mode', async() => { + expect(await getPolicy(API_KEY, true)).toEqual({}); + }); +}); diff --git a/src/server/csp/policies/posthog.ts b/src/server/csp/policies/posthog.ts new file mode 100644 index 00000000000..8420a87c00b --- /dev/null +++ b/src/server/csp/policies/posthog.ts @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type CspDev from 'csp-dev'; + +import config from 'src/config'; + +export function posthog(isPrivateMode: boolean): CspDev.DirectiveDescriptor { + if (!config.services.posthog.apiKey || isPrivateMode) { + return {}; + } + + // a wildcard per PostHog's CSP guidance: lazy-loaded bundles come from a separate assets subdomain + return { + 'script-src': [ '*.posthog.com' ], + 'connect-src': [ '*.posthog.com' ], + 'img-src': [ '*.posthog.com' ], + }; +} diff --git a/src/server/csp/policies/re-captcha.spec.ts b/src/server/csp/policies/re-captcha.spec.ts new file mode 100644 index 00000000000..30509602a9a --- /dev/null +++ b/src/server/csp/policies/re-captcha.spec.ts @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it, vi } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const multichainConfig = vi.hoisted(() => vi.fn()); + +vi.mock('src/features/multichain/chains-config', () => ({ + 'default': multichainConfig, +})); + +const APP_SITE_KEY: Array<[ string, string ]> = [ [ 'NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY', 'app-site-key' ] ]; +const NO_APP_SITE_KEY: Array<[ string, string ]> = [ [ 'NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY', '' ] ]; + +async function getPolicy(envs: Array<[ string, string ]>, isPrivateMode = false) { + return withEnvs(envs, async() => (await import('./re-captcha')).reCaptcha(isPrivateMode)); +} + +describe('reCaptcha policy', () => { + it('is empty when no site key is configured anywhere', async() => { + multichainConfig.mockReturnValue(undefined); + + expect(await getPolicy(NO_APP_SITE_KEY)).toEqual({}); + }); + + it('allows the widget when the app has a site key', async() => { + multichainConfig.mockReturnValue(undefined); + + const policy = await getPolicy(APP_SITE_KEY); + + expect(policy['script-src']).toContain('https://www.google.com/recaptcha/api.js'); + }); + + it('allows the widget when only a chain of the multichain config has a site key', async() => { + multichainConfig.mockReturnValue({ + chains: [ + { app_config: { services: { reCaptcha: { siteKey: undefined } } } }, + { app_config: { services: { reCaptcha: { siteKey: 'chain-site-key' } } } }, + ], + }); + + const policy = await getPolicy(NO_APP_SITE_KEY); + + expect(policy['script-src']).toContain('https://www.google.com/recaptcha/api.js'); + }); + + it('stays empty in private mode', async() => { + multichainConfig.mockReturnValue({ + chains: [ { app_config: { services: { reCaptcha: { siteKey: 'chain-site-key' } } } } ], + }); + + expect(await getPolicy(APP_SITE_KEY, true)).toEqual({}); + }); +}); diff --git a/src/server/csp/policies/re-captcha.ts b/src/server/csp/policies/re-captcha.ts index 2f2e07d8399..db570c3a2f3 100644 --- a/src/server/csp/policies/re-captcha.ts +++ b/src/server/csp/policies/re-captcha.ts @@ -2,10 +2,21 @@ import type CspDev from 'csp-dev'; +import multichainConfig from 'src/features/multichain/chains-config'; + import config from 'src/config'; +function hasSiteKey(): boolean { + if (config.services.reCaptcha.siteKey) { + return true; + } + + // in multichain mode the widget is rendered with the key of the chain the page belongs to + return Boolean(multichainConfig()?.chains.some((chain) => chain.app_config?.services?.reCaptcha?.siteKey)); +} + export function reCaptcha(isPrivateMode: boolean): CspDev.DirectiveDescriptor { - if (!config.services.reCaptcha.siteKey || isPrivateMode) { + if (!hasSiteKey() || isPrivateMode) { return {}; } diff --git a/src/server/csp/policies/verified-fetch.ts b/src/server/csp/policies/verified-fetch.ts index 117aa3187ff..e2133af9132 100644 --- a/src/server/csp/policies/verified-fetch.ts +++ b/src/server/csp/policies/verified-fetch.ts @@ -2,6 +2,8 @@ import type CspDev from 'csp-dev'; +import { VERIFIED_FETCH_GATEWAYS } from 'src/slices/token/utils/verified-fetch'; + import config from 'src/config'; import { KEY_WORDS } from '../utils'; @@ -12,10 +14,7 @@ export function verifiedFetch(): CspDev.DirectiveDescriptor { } return { - 'connect-src': [ - 'https://delegated-ipfs.dev', - 'https://trustless-gateway.link', - ], + 'connect-src': VERIFIED_FETCH_GATEWAYS, 'img-src': [ KEY_WORDS.BLOB, ], diff --git a/src/server/getServerSideProps/guards.spec.ts b/src/server/getServerSideProps/guards.spec.ts index b5eaa5cc7b3..d1624798255 100644 --- a/src/server/getServerSideProps/guards.spec.ts +++ b/src/server/getServerSideProps/guards.spec.ts @@ -2,12 +2,21 @@ import type { GetServerSidePropsContext } from 'next'; +<<<<<<< HEAD +======= +import { TOKEN_ACTION_BUTTON_HIDDEN_TAG_SLUG } from 'src/features/token-action-button/utils/is-token-action-button-hidden'; + +>>>>>>> v2.13.0 import { ENVS_MAP } from 'src/config/test-utils/env-presets'; import { describe, expect, it } from 'vitest'; import withEnvs from 'vitest/utils/mockEnvs'; +<<<<<<< HEAD import type { blocks } from './guards'; +======= +import type { accountsLabelSearch, blocks } from './guards'; +>>>>>>> v2.13.0 function makeContext(query: Record<string, string | Array<string>>): GetServerSidePropsContext { // the guard reads only `query`, so the rest of the context can stay absent @@ -56,3 +65,28 @@ describe('blocks guard', () => { }); }); }); +<<<<<<< HEAD +======= + +async function runAccountsLabelSearchGuard(context: GetServerSidePropsContext): ReturnType<ReturnType<typeof accountsLabelSearch>> { + return withEnvs([ [ 'NEXT_PUBLIC_METADATA_SERVICE_API_HOST', 'https://example.com' ] ], async() => { + const guards = await import('./guards'); + const config = (await import('src/config')).default; + return guards.accountsLabelSearch(config)(context); + }); +} + +describe('accountsLabelSearch guard', () => { + it('lets a public tag type through', async() => { + expect(await runAccountsLabelSearchGuard(makeContext({ slug: 'uniswap', tagType: 'protocol' }))).toBeUndefined(); + }); + + it('returns 404 for the service tag type', async() => { + expect(await runAccountsLabelSearchGuard(makeContext({ slug: TOKEN_ACTION_BUTTON_HIDDEN_TAG_SLUG, tagType: 'service' }))).toEqual({ notFound: true }); + }); + + it('returns 404 without a tag type', async() => { + expect(await runAccountsLabelSearchGuard(makeContext({ slug: 'uniswap' }))).toEqual({ notFound: true }); + }); +}); +>>>>>>> v2.13.0 diff --git a/src/server/getServerSideProps/guards.ts b/src/server/getServerSideProps/guards.ts index ed2e8de91fe..a49c8242409 100644 --- a/src/server/getServerSideProps/guards.ts +++ b/src/server/getServerSideProps/guards.ts @@ -1,15 +1,22 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { GetServerSidePropsContext, GetServerSidePropsResult } from 'next'; +<<<<<<< HEAD import type { Route } from 'nextjs-routes'; import { route } from 'nextjs-routes'; +======= +>>>>>>> v2.13.0 import type { RollupType } from 'src/features/rollup/common/types/config'; import type { Props } from 'src/server/getServerSideProps/handlers'; +import { SERVICE_TAG_TYPE } from 'src/features/address-metadata/utils/is-hidden-tag'; + import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; +import { route } from 'src/shared/router/routes'; +import type { Route } from 'src/shared/router/routes'; export type Guard = (chainConfig: typeof config) => <Pathname extends Route['pathname'] = never>(context: GetServerSidePropsContext) => Promise<GetServerSidePropsResult<Props<Pathname>> | undefined>; @@ -124,7 +131,7 @@ export const accounts: Guard = (chainConfig: typeof config) => async() => { }; export const accountsLabelSearch: Guard = (chainConfig: typeof config) => async(context) => { - if (!chainConfig.features.addressMetadata.isEnabled || !context.query.tagType) { + if (!chainConfig.features.addressMetadata.isEnabled || !context.query.tagType || context.query.tagType === SERVICE_TAG_TYPE) { return { notFound: true, }; diff --git a/src/server/getServerSideProps/handlers.spec.ts b/src/server/getServerSideProps/handlers.spec.ts new file mode 100644 index 00000000000..57f40a0dc2e --- /dev/null +++ b/src/server/getServerSideProps/handlers.spec.ts @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { GetServerSidePropsContext } from 'next'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const realBrowser = vi.hoisted(() => ({ + isLikelyHumanBrowser: vi.fn(() => true), + isKnownBotRequest: vi.fn(() => false), +})); +vi.mock('../utils/checkRealBrowser', () => realBrowser); + +const UUID_PATTERN = /^[0-9a-f-]{36}$/; + +interface ContextOptions { + readonly cookie?: string; + readonly headers?: Record<string, string>; +} + +function makeContext({ cookie, headers = {} }: ContextOptions = {}) { + const setHeader = vi.fn(); + const context = { + req: { headers: { ...(cookie ? { cookie } : {}), ...headers } }, + res: { getHeader: () => undefined, setHeader }, + query: { tab: 'txs' }, + } as unknown as GetServerSidePropsContext; + return { context, setHeader }; +} + +async function runBase(envs: Array<[ string, string ]>, context: GetServerSidePropsContext) { + return withEnvs(envs, async() => { + const handlers = await import('./handlers'); + return handlers.base(context); + }); +} + +describe('base handler', () => { + const fetchMock = vi.fn(() => Promise.resolve(new Response())); + + beforeEach(() => { + vi.stubGlobal('fetch', fetchMock); + vi.stubEnv('DISABLE_TRACKING', 'false'); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + vi.clearAllMocks(); + }); + + it('issues a long-lived uuid cookie to a first-time visitor', async() => { + const { context, setHeader } = makeContext(); + + const result = await runBase([ [ 'NEXT_PUBLIC_APP_PROTOCOL', 'https' ] ], context); + + const [ header, value ] = setHeader.mock.calls[0]; + expect(header).toBe('Set-Cookie'); + expect(value).toMatch(/^uuid=[0-9a-f-]{36}; Path=\/; Max-Age=31536000; Secure$/); + expect(result).toMatchObject({ props: { uuid: expect.stringMatching(UUID_PATTERN) } }); + }); + + it('omits the Secure flag when the app is served over http', async() => { + const { context, setHeader } = makeContext(); + + await runBase([ [ 'NEXT_PUBLIC_APP_PROTOCOL', 'http' ] ], context); + + expect(setHeader.mock.calls[0][1]).toMatch(/^uuid=[0-9a-f-]{36}; Path=\/; Max-Age=31536000$/); + }); + + it('keeps the uuid of a returning visitor and sets no cookie', async() => { + const { context, setHeader } = makeContext({ cookie: 'uuid=existing-uuid; foo=bar' }); + + const result = await runBase([], context); + + expect(setHeader).not.toHaveBeenCalled(); + expect(result).toMatchObject({ props: { uuid: 'existing-uuid', cookies: 'uuid=existing-uuid; foo=bar' } }); + }); + + it('neither identifies nor pings the pageview monitor in private mode', async() => { + const { context, setHeader } = makeContext({ headers: { 'x-app-profile': 'private' } }); + + const result = await runBase([], context); + + expect(setHeader).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(result).toMatchObject({ props: { uuid: undefined } }); + }); + + it('pings the pageview monitor with the visitor uuid for a real browser', async() => { + const { context } = makeContext({ cookie: 'uuid=existing-uuid', headers: { host: 'eth.blockscout.com' } }); + + await runBase([], context); + + expect(fetchMock).toHaveBeenCalledTimes(1); + const [ url, init ] = fetchMock.mock.calls[0] as unknown as [ string, RequestInit ]; + expect(url).toBe('https://monitor.blockscout.com/count'); + expect(JSON.parse(String(init.body))).toMatchObject({ hostname: 'eth.blockscout.com', uuid: 'existing-uuid' }); + }); + + it('skips the pageview ping for a bot', async() => { + realBrowser.isKnownBotRequest.mockReturnValueOnce(true); + const { context } = makeContext({ cookie: 'uuid=existing-uuid' }); + + await runBase([], context); + + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('skips the pageview ping when tracking is disabled', async() => { + vi.stubEnv('DISABLE_TRACKING', 'true'); + const { context } = makeContext({ cookie: 'uuid=existing-uuid' }); + + await runBase([], context); + + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); diff --git a/src/server/getServerSideProps/handlers.ts b/src/server/getServerSideProps/handlers.ts index 083dd38a3d2..744de55f8a0 100644 --- a/src/server/getServerSideProps/handlers.ts +++ b/src/server/getServerSideProps/handlers.ts @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { GetServerSidePropsContext, GetServerSidePropsResult } from 'next'; -import type { Route } from 'nextjs-routes'; import type { AdBannerProviders } from 'src/features/ads/banner/types/config'; @@ -10,12 +9,18 @@ import { CSP_NONCE_HEADER } from 'src/server/constants'; import type * as metadata from 'src/shell/metadata'; import config from 'src/config'; +import type { Route } from 'src/shared/router/routes'; import * as cookies from 'src/shared/storage/cookies'; +import { SECOND, YEAR } from 'src/toolkit/utils/consts'; + import { isLikelyHumanBrowser, isKnownBotRequest } from '../utils/checkRealBrowser'; const adBannerFeature = config.features.adsBanner; +const PAGEVIEW_PING_TIMEOUT = 2 * SECOND; +const UUID_COOKIE_MAX_AGE_SEC = YEAR / SECOND; + export interface Props<Pathname extends Route['pathname'] = never> { query: Route['query']; cookies: string; @@ -55,7 +60,11 @@ Promise<GetServerSidePropsResult<Props<Pathname>>> => { let uuid = cookies.getFromCookieString(req.headers.cookie || '', cookies.NAMES.UUID); if (!uuid && appProfile !== 'private') { uuid = crypto.randomUUID(); - res.setHeader('Set-Cookie', `${ cookies.NAMES.UUID }=${ uuid }; Path=/${ config.app.protocol === 'https' ? '; Secure' : '' }`); + // long-lived so that a returning browser keeps its analytics identity across browser sessions + res.setHeader( + 'Set-Cookie', + `${ cookies.NAMES.UUID }=${ uuid }; Path=/; Max-Age=${ UUID_COOKIE_MAX_AGE_SEC }${ config.app.protocol === 'https' ? '; Secure' : '' }`, + ); } const isTrackingDisabled = process.env.DISABLE_TRACKING === 'true' || appProfile === 'private'; @@ -81,7 +90,8 @@ Promise<GetServerSidePropsResult<Props<Pathname>>> => { publicRPC, uuid, }), - }); + signal: AbortSignal.timeout(PAGEVIEW_PING_TIMEOUT), + }).catch(() => {}); } } diff --git a/src/server/getServerSideProps/utils.ts b/src/server/getServerSideProps/utils.ts index 51e6a899de7..99a68a24d63 100644 --- a/src/server/getServerSideProps/utils.ts +++ b/src/server/getServerSideProps/utils.ts @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { GetServerSidePropsContext, GetServerSidePropsResult } from 'next'; -import type { Route } from 'nextjs-routes'; import multichainConfig from 'src/features/multichain/chains-config'; import config from 'src/config'; +import type { Route } from 'src/shared/router/routes'; import type { Guard } from './guards'; import * as handlers from './handlers'; diff --git a/src/server/middlewares/colorTheme.ts b/src/server/middlewares/colorTheme.ts index 515105fec2e..36a890cbddc 100644 --- a/src/server/middlewares/colorTheme.ts +++ b/src/server/middlewares/colorTheme.ts @@ -2,7 +2,12 @@ import type { NextRequest, NextResponse } from 'next/server'; +<<<<<<< HEAD import { getDefaultColorTheme, isColorThemeAvailable } from 'src/shell/top-bar/settings/color-theme/utils'; +======= +import { isConcreteColorTheme } from 'src/shell/top-bar/settings/fields/color-theme/config'; +import { getDefaultColorTheme, isColorThemeAvailable } from 'src/shell/top-bar/settings/fields/color-theme/utils'; +>>>>>>> v2.13.0 import appConfig from 'src/config'; import * as cookiesLib from 'src/shared/storage/cookies'; @@ -33,6 +38,13 @@ export default function colorThemeMiddleware(req: NextRequest, res: NextResponse return; } +<<<<<<< HEAD res.cookies.set(cookiesLib.NAMES.COLOR_MODE, nextTheme.colorMode, cookiesLib.getDefaultAttributes()); +======= + // the server cannot see the OS color scheme, so a system theme leaves the color mode to the client + if (isConcreteColorTheme(nextTheme)) { + res.cookies.set(cookiesLib.NAMES.COLOR_MODE, nextTheme.colorMode, cookiesLib.getDefaultAttributes()); + } +>>>>>>> v2.13.0 res.cookies.set(cookiesLib.NAMES.COLOR_THEME, nextTheme.id, cookiesLib.getDefaultAttributes()); } diff --git a/src/server/types.ts b/src/server/types.ts index 556e7853bf9..588e36159d2 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -1,9 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { NextPage } from 'next'; -import type { Route } from 'nextjs-routes'; import type React from 'react'; +import type { Route } from 'src/shared/router/routes'; + export type NextPageWithLayout<P = {}, IP = P> = NextPage<P, IP> & { getLayout?: (page: React.ReactElement) => React.ReactNode; }; diff --git a/src/server/utils/fetchProxy.ts b/src/server/utils/fetchProxy.ts index 94c9721c100..c9bfb6c22a6 100644 --- a/src/server/utils/fetchProxy.ts +++ b/src/server/utils/fetchProxy.ts @@ -27,6 +27,8 @@ export default function fetchFactory( 'x-csrf-token', 'recaptcha-v2-response', 'user-agent', + // some instances have a WAF rule that challenges API requests without a referer + 'referer', 'Authorization', // the old value, just in case 'authorization', // Node.js automatically lowercases headers 'show-scam-tokens', diff --git a/src/services/growthbook/init.ts b/src/services/growthbook/init.ts index a927df8c710..deb0fa56487 100644 --- a/src/services/growthbook/init.ts +++ b/src/services/growthbook/init.ts @@ -3,13 +3,12 @@ import { GrowthBook } from '@growthbook/growthbook-react'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import { STORAGE_KEY, STORAGE_LIMIT } from './consts'; export interface GrowthBookFeatures { test_value: string; - txns_view_exp: 'table_view' | 'list_view'; } export const initGrowthBook = (uuid: string) => { @@ -31,7 +30,7 @@ export const initGrowthBook = (uuid: string) => { } saveExperimentInStorage(experiment.key); - mixpanel.logEvent(mixpanel.EventTypes.EXPERIMENT_STARTED, { + analytics.logEvent(analytics.EventTypes.EXPERIMENT_STARTED, { 'Experiment name': experiment.key, 'Variant name': result.value, Source: 'growthbook', diff --git a/src/services/mixpanel/index.ts b/src/services/mixpanel/index.ts deleted file mode 100644 index 0fa9d8b449b..00000000000 --- a/src/services/mixpanel/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import getPageType, { PAGE_TYPE_DICT } from './get-page-type'; -import logEvent from './log-event'; -import reset from './reset'; -import useLogPageView from './useLogPageView'; -import useInit from './useMixpanelInit'; -import * as userProfile from './user-profile'; -export * from './utils'; - -export { - useInit, - useLogPageView, - logEvent, - getPageType, - userProfile, - reset, - PAGE_TYPE_DICT, -}; diff --git a/src/services/mixpanel/log-event.ts b/src/services/mixpanel/log-event.ts deleted file mode 100644 index 58aec8a9d8d..00000000000 --- a/src/services/mixpanel/log-event.ts +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { Mixpanel } from 'mixpanel-browser'; - -import { track } from './queue'; -import type { EventTypes, EventPayload } from './utils'; - -type TrackFnArgs = Parameters<Mixpanel['track']>; - -export default function logEvent<EventType extends EventTypes>( - type: EventType, - properties?: EventPayload<EventType>, - optionsOrCallback?: TrackFnArgs[2], - callback?: TrackFnArgs[3], -) { - track(type, properties, optionsOrCallback, callback); -} diff --git a/src/services/mixpanel/provider.spec.ts b/src/services/mixpanel/provider.spec.ts new file mode 100644 index 00000000000..5d4ac33d835 --- /dev/null +++ b/src/services/mixpanel/provider.spec.ts @@ -0,0 +1,90 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const sdk = vi.hoisted(() => ({ + init: vi.fn(), + track: vi.fn(), + identify: vi.fn(), + people: { set: vi.fn(), set_once: vi.fn() }, +})); +vi.mock('mixpanel-browser', () => ({ 'default': sdk })); + +const PROJECT_TOKEN = 'test-token'; +const CALL_TIME_MS = 1_752_600_000_000; +const CALL_TIME_S = 1_752_600_000; + +async function initProvider(envs: Array<[ string, string ]>, debug = false) { + return withEnvs(envs, async() => { + const { mixpanelProvider } = await import('./provider'); + await mixpanelProvider.init({ debug }); + return mixpanelProvider; + }); +} + +describe('mixpanel provider', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it('should initialize the SDK with the app defaults merged with the config overrides', async() => { + await initProvider([ + [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', PROJECT_TOKEN ], + [ 'NEXT_PUBLIC_MIXPANEL_CONFIG_OVERRIDES', '{"persistence":"cookie"}' ], + ], true); + + expect(sdk.init).toHaveBeenCalledWith(PROJECT_TOKEN, { + debug: true, + persistence: 'cookie', + api_host: 'https://api-eu.mixpanel.com', + }); + }); + + it('should reject when the project token is not configured', async() => { + await expect(initProvider([])).rejects.toThrow(); + expect(sdk.init).not.toHaveBeenCalled(); + }); + + it('should backdate a replayed event with its original call time in epoch seconds', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', PROJECT_TOKEN ] ]); + + provider.track('Button click', { Content: 'burger menu' }, { timestamp: CALL_TIME_MS }); + + expect(sdk.track).toHaveBeenCalledWith('Button click', { time: CALL_TIME_S, Content: 'burger menu' }, undefined); + }); + + it('should keep a caller-provided time property on replay', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', PROJECT_TOKEN ] ]); + + provider.track('Button click', { time: 1_600_000_000 }, { timestamp: CALL_TIME_MS }); + + expect(sdk.track).toHaveBeenCalledWith('Button click', { time: 1_600_000_000 }, undefined); + }); + + it('should send an event immediately when asked to', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', PROJECT_TOKEN ] ]); + + provider.track('Account access', { Action: 'Logged out' }, { sendImmediately: true }); + + expect(sdk.track).toHaveBeenCalledWith('Account access', { Action: 'Logged out' }, { send_immediately: true }); + }); + + it('should write profile props passed with identify through the people set and set-once slots', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', PROJECT_TOKEN ] ]); + + provider.identify('user-uuid', { set: { 'Device Type': 'Desktop' }, setOnce: { 'First Time Join': '2026-01-01T00:00:00.000Z' } }); + + expect(sdk.identify).toHaveBeenCalledWith('user-uuid'); + expect(sdk.people.set).toHaveBeenCalledWith({ 'Device Type': 'Desktop' }); + expect(sdk.people.set_once).toHaveBeenCalledWith({ 'First Time Join': '2026-01-01T00:00:00.000Z' }); + }); + + it('should not touch the people profile when identify carries no profile props', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', PROJECT_TOKEN ] ]); + + provider.identify('user-uuid'); + + expect(sdk.identify).toHaveBeenCalledWith('user-uuid'); + expect(sdk.people.set).not.toHaveBeenCalled(); + expect(sdk.people.set_once).not.toHaveBeenCalled(); + }); +}); diff --git a/src/services/mixpanel/provider.ts b/src/services/mixpanel/provider.ts new file mode 100644 index 00000000000..a0135f824bc --- /dev/null +++ b/src/services/mixpanel/provider.ts @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { Config, Mixpanel } from 'mixpanel-browser'; + +import config from 'src/config'; +import type { AnalyticsProvider } from 'src/shared/analytics/provider'; + +import { SECOND } from 'src/toolkit/utils/consts'; + +let sdk: Mixpanel | undefined; + +export const mixpanelProvider: AnalyticsProvider = { + init: async({ debug }) => { + const { projectToken, configOverrides } = config.services.mixpanel; + if (!projectToken) { + throw new Error('Mixpanel project token is not configured'); + } + + const mixpanel = (await import('mixpanel-browser')).default; + const mixpanelConfig: Partial<Config> = { + debug, + persistence: 'localStorage', + api_host: 'https://api-eu.mixpanel.com', + ...configOverrides, + }; + mixpanel.init(projectToken, mixpanelConfig); + sdk = mixpanel; + }, + track: (event, properties, { timestamp, sendImmediately }) => { + // `time` (epoch seconds) backdates a replayed event to when it was actually fired; + // a caller-provided `time` property still wins + const props = timestamp === undefined ? properties : { time: timestamp / SECOND, ...properties }; + sdk?.track(event, props, sendImmediately ? { send_immediately: true } : undefined); + }, + register: (superProps) => { + sdk?.register(superProps); + }, + identify: (distinctId, profile) => { + sdk?.identify(distinctId); + if (profile?.set) { + sdk?.people.set(profile.set); + } + if (profile?.setOnce) { + sdk?.people.set_once(profile.setOnce); + } + }, + peopleSet: (props) => { + sdk?.people.set(props); + }, + peopleSetOnce: (props) => { + sdk?.people.set_once(props); + }, + reset: () => { + sdk?.reset(); + }, +}; diff --git a/src/services/mixpanel/queue.spec.ts b/src/services/mixpanel/queue.spec.ts deleted file mode 100644 index 5d70c873003..00000000000 --- a/src/services/mixpanel/queue.spec.ts +++ /dev/null @@ -1,246 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; - -const mixpanelMock = vi.hoisted(() => ({ - init: vi.fn(), - track: vi.fn(), - register: vi.fn(), - identify: vi.fn(), - people: { - set: vi.fn(), - set_once: vi.fn(), - increment: vi.fn(), - }, - reset: vi.fn(), -})); - -const mockState = vi.hoisted(() => ({ - projectToken: 'test-token' as string | undefined, -})); - -vi.mock('mixpanel-browser', () => ({ 'default': mixpanelMock })); - -vi.mock('src/config', () => ({ - 'default': { - services: { - get mixpanel() { - return { projectToken: mockState.projectToken }; - }, - }, - }, -})); - -const PROJECT_TOKEN = 'test-token'; -const CALL_TIME_MS = 1_752_600_000_000; -const CALL_TIME_S = CALL_TIME_MS / 1_000; -const QUEUE_CAP = 100; - -const NOOP_SETUP = () => {}; - -// the module keeps its state (buffer, init promise) at module scope, so every test -// imports a fresh copy -async function importQueue() { - return await import('./queue'); -} - -describe('mixpanel queue', () => { - beforeEach(() => { - vi.resetModules(); - vi.resetAllMocks(); - mockState.projectToken = PROJECT_TOKEN; - vi.spyOn(Date, 'now').mockReturnValue(CALL_TIME_MS); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - describe('before init', () => { - it('should buffer calls and flush them only after setup has run', async() => { - const queue = await importQueue(); - const order: Array<string> = []; - mixpanelMock.register.mockImplementation(() => order.push('register')); - mixpanelMock.identify.mockImplementation(() => order.push('identify')); - mixpanelMock.track.mockImplementation((event: string) => order.push(`track:${ event }`)); - mixpanelMock.people.set.mockImplementation(() => order.push('people.set')); - - queue.track('Button click', { Content: 'burger menu' }); - queue.peopleSet({ 'With Account': true }); - expect(mixpanelMock.track).not.toHaveBeenCalled(); - - const isReady = await queue.init(PROJECT_TOKEN, { persistence: 'localStorage' }, (mixpanel) => { - mixpanel.register({ 'Chain id': '1' }); - mixpanel.identify('test-uuid'); - }); - - expect(isReady).toBe(true); - expect(mixpanelMock.init).toHaveBeenCalledWith(PROJECT_TOKEN, { persistence: 'localStorage' }); - expect(order).toEqual([ 'register', 'identify', 'track:Button click', 'people.set' ]); - }); - - it('should replay a buffered event with its original call time', async() => { - const queue = await importQueue(); - - queue.track('Button click', { Content: 'burger menu' }); - await queue.init(PROJECT_TOKEN, {}, NOOP_SETUP); - - expect(mixpanelMock.track).toHaveBeenCalledWith( - 'Button click', - { time: CALL_TIME_S, Content: 'burger menu' }, - undefined, - undefined, - ); - }); - - it('should keep a caller-provided time property on replay', async() => { - const queue = await importQueue(); - const customTime = 1_600_000_000; - - queue.track('Button click', { time: customTime }); - await queue.init(PROJECT_TOKEN, {}, NOOP_SETUP); - - expect(mixpanelMock.track).toHaveBeenCalledWith('Button click', { time: customTime }, undefined, undefined); - }); - - it('should buffer and flush people and reset calls', async() => { - const queue = await importQueue(); - - queue.peopleSetOnce({ 'First Time Join': '2026-07-16' }); - queue.peopleIncrement({ Visits: 1 }); - queue.reset(); - await queue.init(PROJECT_TOKEN, {}, NOOP_SETUP); - - expect(mixpanelMock.people.set_once).toHaveBeenCalledWith({ 'First Time Join': '2026-07-16' }); - expect(mixpanelMock.people.increment).toHaveBeenCalledWith({ Visits: 1 }); - expect(mixpanelMock.reset).toHaveBeenCalledOnce(); - }); - - it('should flush buffered calls of different types in call order', async() => { - const queue = await importQueue(); - const order: Array<string> = []; - mixpanelMock.track.mockImplementation((_event: string, props?: { Content?: string }) => order.push(`track:${ props?.Content }`)); - mixpanelMock.reset.mockImplementation(() => order.push('reset')); - - queue.track('Button click', { Content: 'before logout' }); - queue.reset(); - queue.track('Button click', { Content: 'after logout' }); - await queue.init(PROJECT_TOKEN, {}, NOOP_SETUP); - - expect(order).toEqual([ 'track:before logout', 'reset', 'track:after logout' ]); - }); - - it('should preserve request options and callback on replay', async() => { - const queue = await importQueue(); - const callback = vi.fn(); - - queue.track('Account access', { Action: 'Logged out' }, { send_immediately: true }, callback); - await queue.init(PROJECT_TOKEN, {}, NOOP_SETUP); - - expect(mixpanelMock.track).toHaveBeenCalledWith( - 'Account access', - { time: CALL_TIME_S, Action: 'Logged out' }, - { send_immediately: true }, - callback, - ); - }); - - it('should run setup (identity and profile writes) before a buffered reset', async() => { - const queue = await importQueue(); - const order: Array<string> = []; - mixpanelMock.people.set.mockImplementation(() => order.push('people.set')); - mixpanelMock.reset.mockImplementation(() => order.push('reset')); - - queue.reset(); - await queue.init(PROJECT_TOKEN, {}, (mixpanel) => { - mixpanel.people.set({ 'With Account': true }); - }); - - expect(order).toEqual([ 'people.set', 'reset' ]); - }); - - it('should drop calls above the buffer cap', async() => { - const queue = await importQueue(); - - for (let index = 0; index < QUEUE_CAP + 5; index++) { - queue.track('Button click', { Content: `${ index }` }); - } - await queue.init(PROJECT_TOKEN, {}, NOOP_SETUP); - - expect(mixpanelMock.track).toHaveBeenCalledTimes(QUEUE_CAP); - }); - }); - - describe('after init', () => { - it('should pass calls through to the SDK unchanged', async() => { - const queue = await importQueue(); - await queue.init(PROJECT_TOKEN, {}, NOOP_SETUP); - - queue.track('Button click', { Content: 'burger menu' }); - queue.peopleSet({ 'With Account': true }); - queue.peopleSetOnce({ 'First Time Join': '2026-07-16' }); - queue.peopleIncrement({ Visits: 1 }); - queue.reset(); - - expect(mixpanelMock.track).toHaveBeenCalledWith('Button click', { Content: 'burger menu' }); - expect(mixpanelMock.people.set).toHaveBeenCalledWith({ 'With Account': true }); - expect(mixpanelMock.people.set_once).toHaveBeenCalledWith({ 'First Time Join': '2026-07-16' }); - expect(mixpanelMock.people.increment).toHaveBeenCalledWith({ Visits: 1 }); - expect(mixpanelMock.reset).toHaveBeenCalledOnce(); - }); - - it('should share a single SDK init between concurrent and repeated init calls', async() => { - const queue = await importQueue(); - - const [ first, second ] = await Promise.all([ - queue.init(PROJECT_TOKEN, {}, NOOP_SETUP), - queue.init(PROJECT_TOKEN, {}, NOOP_SETUP), - ]); - const third = await queue.init(PROJECT_TOKEN, {}, NOOP_SETUP); - - expect(mixpanelMock.init).toHaveBeenCalledOnce(); - expect([ first, second, third ]).toEqual([ true, true, true ]); - }); - }); - - describe('failure handling', () => { - // a rejected `import('mixpanel-browser')` goes through the same catch as a throwing `init` - it('should resolve to false, drop the buffer and disable the wrapper when the SDK fails to initialize', async() => { - mixpanelMock.init.mockImplementation(() => { - throw new Error('init failed'); - }); - const queue = await importQueue(); - - queue.track('Button click', { Content: 'burger menu' }); - const isReady = await queue.init(PROJECT_TOKEN, {}, NOOP_SETUP); - - expect(isReady).toBe(false); - await expect(queue.init(PROJECT_TOKEN, {}, NOOP_SETUP)).resolves.toBe(false); - expect(() => queue.track('Button click', { Content: 'burger menu' })).not.toThrow(); - expect(mixpanelMock.track).not.toHaveBeenCalled(); - }); - - it('should treat a setup failure as init failure and drop buffered calls', async() => { - const queue = await importQueue(); - - queue.track('Button click', { Content: 'burger menu' }); - const isReady = await queue.init(PROJECT_TOKEN, {}, () => { - throw new Error('register failed'); - }); - - expect(isReady).toBe(false); - expect(mixpanelMock.track).not.toHaveBeenCalled(); - }); - }); - - describe('when the service is disabled', () => { - it('should ignore every call when the project token is not configured', async() => { - mockState.projectToken = undefined; - const queue = await importQueue(); - - queue.track('Button click', { Content: 'burger menu' }); - await queue.init(PROJECT_TOKEN, {}, NOOP_SETUP); - queue.track('Button click', { Content: 'burger menu' }); - - expect(mixpanelMock.track).not.toHaveBeenCalled(); - }); - }); -}); diff --git a/src/services/mixpanel/queue.ts b/src/services/mixpanel/queue.ts deleted file mode 100644 index 0cbd1dd0ef1..00000000000 --- a/src/services/mixpanel/queue.ts +++ /dev/null @@ -1,156 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { Config, Dict, Mixpanel } from 'mixpanel-browser'; - -import config from 'src/config'; - -import { SECOND } from 'src/toolkit/utils/consts'; - -type TrackFnArgs = Parameters<Mixpanel['track']>; - -type QueuedCall = { - method: 'track'; - args: TrackFnArgs; - timestamp: number; -} | { - method: 'people.set' | 'people.set_once' | 'people.increment'; - props: Dict; -} | { - method: 'reset'; -}; - -// events are user-driven and init takes a few seconds at most, so the cap only guards -// against unbounded growth when the SDK chunk hangs forever -const MAX_QUEUE_LENGTH = 100; - -let instance: Mixpanel | undefined; -let initPromise: Promise<boolean> | undefined; -let hasInitFailed = false; -const queue: Array<QueuedCall> = []; - -function isEnabled(): boolean { - return Boolean(config.services.mixpanel.projectToken) && !hasInitFailed; -} - -function enqueue(call: QueuedCall) { - if (queue.length >= MAX_QUEUE_LENGTH) { - return; - } - queue.push(call); -} - -/** - * Loads the SDK chunk, initializes it and replays every call buffered while it was loading. - * The queue is flushed only after `setup` has run, so super-props (`register`) and identity - * (`identify`) apply to the replayed events. - * - * Idempotent: concurrent and repeated calls share one SDK init. Never rejects — a chunk-load - * failure resolves to `false` and permanently disables the wrapper for this page load. - */ -export function init( - projectToken: string, - mixpanelConfig: Partial<Config>, - setup: (mixpanel: Mixpanel) => void, -): Promise<boolean> { - initPromise = initPromise ?? initOnce(projectToken, mixpanelConfig, setup); - return initPromise; -} - -async function initOnce( - projectToken: string, - mixpanelConfig: Partial<Config>, - setup: (mixpanel: Mixpanel) => void, -): Promise<boolean> { - try { - const mixpanel = (await import('mixpanel-browser')).default; - mixpanel.init(projectToken, mixpanelConfig); - setup(mixpanel); - instance = mixpanel; - } catch { - hasInitFailed = true; - queue.splice(0); - return false; - } - flushQueue(instance); - return true; -} - -export function track(...args: TrackFnArgs): void { - if (!isEnabled()) { - return; - } - if (instance) { - instance.track(...args); - return; - } - enqueue({ method: 'track', args, timestamp: Date.now() }); -} - -export function peopleSet(props: Dict): void { - if (!isEnabled()) { - return; - } - if (instance) { - instance.people.set(props); - return; - } - enqueue({ method: 'people.set', props }); -} - -export function peopleSetOnce(props: Dict): void { - if (!isEnabled()) { - return; - } - if (instance) { - instance.people.set_once(props); - return; - } - enqueue({ method: 'people.set_once', props }); -} - -export function peopleIncrement(props: Dict): void { - if (!isEnabled()) { - return; - } - if (instance) { - instance.people.increment(props); - return; - } - enqueue({ method: 'people.increment', props }); -} - -export function reset(): void { - if (!isEnabled()) { - return; - } - if (instance) { - instance.reset(); - return; - } - enqueue({ method: 'reset' }); -} - -function flushQueue(mixpanel: Mixpanel) { - for (const call of queue.splice(0)) { - switch (call.method) { - case 'track': { - const [ eventName, properties, optionsOrCallback, callback ] = call.args; - // `time` (epoch seconds) backdates the replayed event to when it was actually fired - mixpanel.track(eventName, { time: call.timestamp / SECOND, ...properties }, optionsOrCallback, callback); - break; - } - case 'people.set': - mixpanel.people.set(call.props); - break; - case 'people.set_once': - mixpanel.people.set_once(call.props); - break; - case 'people.increment': - mixpanel.people.increment(call.props); - break; - case 'reset': - mixpanel.reset(); - break; - } - } -} diff --git a/src/services/mixpanel/useLogPageView.tsx b/src/services/mixpanel/useLogPageView.tsx deleted file mode 100644 index 51e0b386606..00000000000 --- a/src/services/mixpanel/useLogPageView.tsx +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { usePathname } from 'next/navigation'; -import { useRouter } from 'next/router'; -import React from 'react'; - -import type { ColorThemeId } from 'src/shell/top-bar/settings/color-theme/config'; -import { getDefaultColorTheme } from 'src/shell/top-bar/settings/color-theme/utils'; - -import config from 'src/config'; -import getQueryParamString from 'src/shared/router/get-query-param-string'; -import * as cookies from 'src/shared/storage/cookies'; - -import { useColorMode } from 'src/toolkit/chakra/color-mode'; - -import getPageType from './get-page-type'; -import getTabName from './get-tab-name'; -import logEvent from './log-event'; -import { EventTypes } from './utils'; - -export default function useLogPageView(isInitialized: boolean) { - const router = useRouter(); - const pathname = usePathname(); - - const tab = getQueryParamString(router.query.tab); - const page = getQueryParamString(router.query.page); - const id = getQueryParamString(router.query.id); - const { colorMode } = useColorMode(); - - React.useEffect(() => { - if (!config.services.mixpanel.projectToken || !isInitialized) { - return; - } - - const cookieColorTheme = cookies.get(cookies.NAMES.COLOR_THEME) as ColorThemeId | undefined; - - logEvent(EventTypes.PAGE_VIEW, { - 'Page type': getPageType(router.pathname), - Tab: getTabName(tab), - Page: page || undefined, - Source: router.pathname === '/essential-dapps/[id]' ? id : undefined, - 'Color mode': colorMode, - 'Color theme': cookieColorTheme || getDefaultColorTheme(colorMode), - }); - // these are only deps that should trigger the effect - // in some scenarios page type is not changing (e.g navigation from one address page to another), - // but we still want to log page view - // so we use pathname from 'next/navigation' instead of router.pathname from 'next/router' as deps - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ isInitialized, page, pathname, tab, colorMode ]); -} diff --git a/src/services/mixpanel/useMixpanelInit.tsx b/src/services/mixpanel/useMixpanelInit.tsx deleted file mode 100644 index 9f00ca2cc00..00000000000 --- a/src/services/mixpanel/useMixpanelInit.tsx +++ /dev/null @@ -1,92 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { capitalize } from 'es-toolkit'; -import type { Config } from 'mixpanel-browser'; -import { useRouter } from 'next/router'; -import React from 'react'; -import { deviceType } from 'react-device-detect'; - -import config from 'src/config'; -import dayjs from 'src/shared/date-and-time/dayjs'; -import getQueryParamString from 'src/shared/router/get-query-param-string'; -import * as cookies from 'src/shared/storage/cookies'; - -import { SECOND } from 'src/toolkit/utils/consts'; - -import * as queue from './queue'; - -const multichainFeature = config.features.multichain; - -// upper bound for the idle-callback deferral, so init is not postponed indefinitely on busy pages -const IDLE_INIT_TIMEOUT = 2 * SECOND; - -export default function useMixpanelInit() { - const [ isInitialized, setIsInitialized ] = React.useState(false); - const router = useRouter(); - const debugFlagQuery = React.useRef(getQueryParamString(router.query._mixpanel_debug)); - - React.useEffect(() => { - const projectToken = config.services.mixpanel.projectToken; - if (!projectToken) { - return; - } - - // cookie-derived state is captured at mount so that the deferred init sees the same values - // a synchronous init would have (auth may change while init waits for an idle slot) - const debugFlagCookie = cookies.get(cookies.NAMES.MIXPANEL_DEBUG); - const isAuth = Boolean(cookies.get(cookies.NAMES.API_TOKEN)); - const uuid = cookies.get(cookies.NAMES.UUID); - - const startInit = async() => { - const mixpanelConfig: Partial<Config> = { - debug: Boolean(debugFlagQuery.current || debugFlagCookie), - persistence: 'localStorage', - api_host: 'https://api-eu.mixpanel.com', - ...config.services.mixpanel.configOverrides, - }; - - const isReady = await queue.init(projectToken, mixpanelConfig, (mixpanel) => { - mixpanel.register({ - 'Chain id': config.chain.id, - Environment: config.app.isDev ? 'Dev' : 'Prod', - Authorized: isAuth, - 'Viewport width': window.innerWidth, - 'Viewport height': window.innerHeight, - Language: window.navigator.language, - 'Device type': capitalize(deviceType), - 'User id': uuid, - ...(multichainFeature.isEnabled ? { 'Cluster name': multichainFeature.cluster } : {}), - }); - mixpanel.identify(uuid); - // profile writes belong before the queue flush — a buffered `reset` (logout during - // the deferral window) must not leave them on the anonymous post-reset profile - mixpanel.people.set({ - 'Device Type': capitalize(deviceType), - ...(isAuth ? { 'With Account': true } : {}), - }); - mixpanel.people.set_once({ - 'First Time Join': dayjs().toISOString(), - }); - }); - - if (!isReady) { - return; - } - - setIsInitialized(true); - if (debugFlagQuery.current && !debugFlagCookie) { - cookies.set(cookies.NAMES.MIXPANEL_DEBUG, 'true'); - } - }; - - if (typeof window.requestIdleCallback === 'function') { - const idleCallbackId = window.requestIdleCallback(startInit, { timeout: IDLE_INIT_TIMEOUT }); - return () => window.cancelIdleCallback(idleCallbackId); - } - - const timeoutId = window.setTimeout(startInit, 0); - return () => window.clearTimeout(timeoutId); - }, []); - - return isInitialized; -} diff --git a/src/services/mixpanel/user-profile.ts b/src/services/mixpanel/user-profile.ts deleted file mode 100644 index ca3cde9c41c..00000000000 --- a/src/services/mixpanel/user-profile.ts +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { PickByType } from 'src/shared/types/utils'; - -import { peopleIncrement, peopleSet, peopleSetOnce } from './queue'; - -interface UserProfileProperties { - 'With Account': boolean; - 'With Connected Wallet': boolean; - 'Device Type': string; - 'First Time Join': string; -} - -type UserProfilePropertiesNumerable = PickByType<UserProfileProperties, number>; - -export function set(props: Partial<UserProfileProperties>) { - peopleSet(props); -} - -export function setOnce(props: Partial<UserProfileProperties>) { - peopleSetOnce(props); -} - -export function increment(props: UserProfilePropertiesNumerable) { - peopleIncrement(props); -} diff --git a/src/services/mixpanel/utils.ts b/src/services/mixpanel/utils.ts deleted file mode 100644 index 905a67e317d..00000000000 --- a/src/services/mixpanel/utils.ts +++ /dev/null @@ -1,189 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { WalletType } from 'src/features/web3-wallet/types/config'; - -import type { ColorThemeId } from 'src/shell/top-bar/settings/color-theme/config'; - -export enum EventTypes { - PAGE_VIEW = 'Page view', - SEARCH_QUERY = 'Search query', - LOCAL_SEARCH = 'Local search', - ADD_TO_WALLET = 'Add to wallet', - ACCOUNT_ACCESS = 'Account access', - LOGIN = 'Login', - ACCOUNT_LINK_INFO = 'Account link info', - PRIVATE_TAG = 'Private tag', - VERIFY_ADDRESS = 'Verify address', - VERIFY_TOKEN = 'Verify token', - WALLET_CONNECT = 'Wallet connect', - WALLET_ACTION = 'Wallet action', - CONTRACT_INTERACTION = 'Contract interaction', - CONTRACT_VERIFICATION = 'Contract verification', - QR_CODE = 'QR code', - PAGE_WIDGET = 'Page widget', - TX_INTERPRETATION_INTERACTION = 'Transaction interpretation interaction', - EXPERIMENT_STARTED = 'Experiment started', - FILTERS = 'Filters', - BUTTON_CLICK = 'Button click', - PROMO_BANNER = 'Promo banner', - APP_FEEDBACK = 'App feedback', - ADDRESS_WIDGET = 'Address widget', -} - -/* eslint-disable @stylistic/indent */ -export type EventPayload<Type extends EventTypes> = -Type extends EventTypes.PAGE_VIEW ? -{ - 'Page type': string; - Tab: string; - Page?: string; - Source?: string; - 'Color mode': 'light' | 'dark'; - 'Color theme': ColorThemeId | undefined; -} : -Type extends EventTypes.SEARCH_QUERY ? { - 'Search query': string; - 'Source page type': string; - 'Result URL': string; -} : -Type extends EventTypes.LOCAL_SEARCH ? { - 'Search query': string; - Source: 'Marketplace'; -} : -Type extends EventTypes.ADD_TO_WALLET ? ( - { - Wallet: WalletType; - Target: 'network'; - Source: 'Footer' | 'Top bar' | 'Chain widget'; - } | { - Wallet: WalletType; - Target: 'token'; - Token: string; - } -) : -Type extends EventTypes.ACCOUNT_ACCESS ? { - Action: 'Dropdown open' | 'Logged out'; -} : -Type extends EventTypes.LOGIN ? ( - { - Action: 'Started'; - Source: string; - } | { - Action: 'Wallet' | 'Email'; - Source: 'Options selector'; - } | { - Action: 'OTP sent'; - Source: 'Email'; - } | { - Action: 'Success'; - Source: 'Email' | 'Wallet' | 'Dynamic'; - } -) : -Type extends EventTypes.ACCOUNT_LINK_INFO ? { - Source: 'Profile' | 'Login modal' | 'Profile dropdown' | 'Merits'; - Status: 'Started' | 'OTP sent' | 'Finished'; - Type: 'Email' | 'Wallet'; -} : -Type extends EventTypes.PRIVATE_TAG ? { - Action: 'Form opened' | 'Submit'; - 'Page type': string; - 'Tag type': 'Address' | 'Tx'; -} : -Type extends EventTypes.VERIFY_ADDRESS ? ( - { - Action: 'Form opened' | 'Address entered'; - 'Page type': string; - } | { - Action: 'Sign ownership'; - 'Page type': string; - 'Sign method': 'wallet' | 'manual'; - } -) : -Type extends EventTypes.VERIFY_TOKEN ? { - Action: 'Form opened' | 'Submit'; -} : -Type extends EventTypes.WALLET_CONNECT ? { - Source: 'Header' | 'Login' | 'Profile' | 'Profile dropdown' | 'Smart contracts' | 'Swap button' | 'Merits' | 'Essential dapps'; - Status: 'Started' | 'Connected'; -} : -Type extends EventTypes.WALLET_ACTION ? ( - { - Action: 'Open' | 'Address click'; - } | { - Action: 'Send Transaction' | 'Sign Message' | 'Sign Typed Data'; - Source: 'Dappscout' | 'Essential dapps'; - AppId: string; - Address?: string; - ChainId?: string; - } -) : -Type extends EventTypes.CONTRACT_INTERACTION ? { - 'Method type': 'Read' | 'Write'; - 'Method name': string; -} : -Type extends EventTypes.CONTRACT_VERIFICATION ? { - Method: string; - Status: 'Method selected' | 'Finished'; -} : -Type extends EventTypes.QR_CODE ? { - 'Page type': string; -} : -Type extends EventTypes.PAGE_WIDGET ? ( - { - Type: 'Tokens dropdown' | 'Tokens show all (icon)' | 'Add to watchlist' | 'Address actions (more button)'; - } | { - Type: 'Favorite app' | 'More button'; - Info: string; - Source: 'Discovery view' | 'App modal' | 'App page' | 'Banner'; - } | { - Type: 'Action button'; - Info: string; - Source: 'Txn' | 'NFT collection' | 'NFT item'; - } | { - Type: 'Address tag'; - Info: string; - URL: string; - } | { - Type: 'Share chart'; - Info: string; - } | { - Type: 'Chain switch'; - Info: string; - Source: 'Revoke essential dapp'; - } | { - Type: 'Txn view switch'; - Info: 'Table view' | 'List view'; - Source: 'Address page'; - } -) : -Type extends EventTypes.TX_INTERPRETATION_INTERACTION ? { - Type: 'Address click' | 'Token click' | 'Domain click'; -} : -Type extends EventTypes.EXPERIMENT_STARTED ? { - 'Experiment name': string; - 'Variant name': string; - Source: 'growthbook'; -} : -Type extends EventTypes.FILTERS ? { - Source: 'Marketplace'; - 'Filter name': string; -} : -Type extends EventTypes.BUTTON_CLICK ? { - Content: string; - Source: string; -} : -Type extends EventTypes.PROMO_BANNER ? { - Source: 'Marketplace'; - Link: string; -} : -Type extends EventTypes.APP_FEEDBACK ? { - Action: 'Rating'; - Source: 'Discovery' | 'App modal' | 'App page'; - AppId: string; - Score: number; -} : -Type extends EventTypes.ADDRESS_WIDGET ? { - Name: string; -} : -undefined; -/* eslint-enable @stylistic/indent */ diff --git a/src/services/posthog/config.ts b/src/services/posthog/config.ts new file mode 100644 index 00000000000..b1737aed495 --- /dev/null +++ b/src/services/posthog/config.ts @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import app from 'src/config/app'; +import { getEnvValue, parseEnvJson } from 'src/config/utils/envs'; +import usercentrics from 'src/services/usercentrics/config'; + +const apiKey = getEnvValue('NEXT_PUBLIC_POSTHOG_API_KEY'); +const configOverrides = (() => { + const value = getEnvValue('NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES'); + if (!value) { + return; + } + + return parseEnvJson<Readonly<Record<string, unknown>>>(value) || undefined; +})(); + +const config = Object.freeze({ + apiKey: !app.isPrivateMode && !(usercentrics && !usercentrics.consent?.posthog) ? apiKey : undefined, + configOverrides, +}); + +export default config; diff --git a/src/services/posthog/provider.spec.ts b/src/services/posthog/provider.spec.ts new file mode 100644 index 00000000000..30c0d6a50a5 --- /dev/null +++ b/src/services/posthog/provider.spec.ts @@ -0,0 +1,144 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const sdk = vi.hoisted(() => ({ + init: vi.fn(), + capture: vi.fn(), + identify: vi.fn(), + setPersonProperties: vi.fn(), +})); +vi.mock('posthog-js', () => ({ 'default': sdk })); + +const API_KEY = 'phc_test'; +const CALL_TIME_MS = 1_752_600_000_000; +const NO_TRACK_OPTIONS = {}; + +async function initProvider(envs: Array<[ string, string ]>, debug = false) { + return withEnvs(envs, async() => { + const { posthogProvider } = await import('./provider'); + await posthogProvider.init({ debug }); + return posthogProvider; + }); +} + +describe('posthog provider', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it('should initialize the SDK with the app defaults', async() => { + await initProvider([ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ] ], true); + + expect(sdk.init).toHaveBeenCalledWith(API_KEY, { + api_host: 'https://eu.i.posthog.com', + autocapture: false, + capture_pageview: false, + capture_pageleave: false, + disable_session_recording: true, + advanced_disable_flags: true, + persistence: 'localStorage', + debug: true, + }); + }); + + it('should let the config overrides win over the app defaults', async() => { + await initProvider([ + [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ], + [ 'NEXT_PUBLIC_POSTHOG_CONFIG_OVERRIDES', '{"disable_session_recording":false,"api_host":"https://us.i.posthog.com"}' ], + ]); + + expect(sdk.init).toHaveBeenCalledWith(API_KEY, expect.objectContaining({ + disable_session_recording: false, + api_host: 'https://us.i.posthog.com', + autocapture: false, + })); + }); + + it('should reject when the API key is not configured', async() => { + await expect(initProvider([])).rejects.toThrow(); + expect(sdk.init).not.toHaveBeenCalled(); + }); + + it('should send a page view as the native $pageview event with its properties unchanged', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ] ]); + const properties = { 'Page type': 'Homepage', Tab: 'Not applicable', 'Color mode': 'light', 'Color theme': 'light' }; + + provider.track('Page view', properties, NO_TRACK_OPTIONS); + + expect(sdk.capture).toHaveBeenCalledWith('$pageview', properties, undefined); + }); + + it('should send any other event under its own name', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ] ]); + + provider.track('Button click', { Content: 'burger menu' }, NO_TRACK_OPTIONS); + + expect(sdk.capture).toHaveBeenCalledWith('Button click', { Content: 'burger menu' }, undefined); + }); + + it('should backdate a replayed event with its original call time', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ] ]); + + provider.track('Button click', { Content: 'burger menu' }, { timestamp: CALL_TIME_MS }); + + expect(sdk.capture).toHaveBeenCalledWith('Button click', { Content: 'burger menu' }, { timestamp: new Date(CALL_TIME_MS) }); + }); + + it('should send a live event immediately without backdating it', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ] ]); + + provider.track('Account access', { Action: 'Logged out' }, { sendImmediately: true }); + + expect(sdk.capture).toHaveBeenCalledWith('Account access', { Action: 'Logged out' }, { send_instantly: true }); + }); + + it('should send a replayed event immediately with its original call time', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ] ]); + + provider.track('Account access', { Action: 'Logged out' }, { sendImmediately: true, timestamp: CALL_TIME_MS }); + + expect(sdk.capture).toHaveBeenCalledWith( + 'Account access', + { Action: 'Logged out' }, + { send_instantly: true, timestamp: new Date(CALL_TIME_MS) }, + ); + }); + + it('should write person properties through the set and set-once slots', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ] ]); + + provider.peopleSet({ 'Device Type': 'Desktop' }); + provider.peopleSetOnce({ 'First Time Join': '2026-01-01T00:00:00.000Z' }); + + expect(sdk.setPersonProperties).toHaveBeenNthCalledWith(1, { 'Device Type': 'Desktop' }); + expect(sdk.setPersonProperties).toHaveBeenNthCalledWith(2, undefined, { 'First Time Join': '2026-01-01T00:00:00.000Z' }); + }); + + it('should identify the user only when the distinct id is known', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ] ]); + + provider.identify(undefined); + provider.identify('user-uuid'); + + expect(sdk.identify).toHaveBeenCalledTimes(1); + expect(sdk.identify).toHaveBeenCalledWith('user-uuid', undefined, undefined); + }); + + it('should pass profile props into the identify call instead of separate person-property writes', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ] ]); + + provider.identify('user-uuid', { set: { 'Device Type': 'Desktop' }, setOnce: { 'First Time Join': '2026-01-01T00:00:00.000Z' } }); + + expect(sdk.identify).toHaveBeenCalledWith('user-uuid', { 'Device Type': 'Desktop' }, { 'First Time Join': '2026-01-01T00:00:00.000Z' }); + expect(sdk.setPersonProperties).not.toHaveBeenCalled(); + }); + + it('should fall back to a person-property write when there is no distinct id but there are profile props', async() => { + const provider = await initProvider([ [ 'NEXT_PUBLIC_POSTHOG_API_KEY', API_KEY ] ]); + + provider.identify(undefined, { set: { 'Device Type': 'Desktop' } }); + + expect(sdk.identify).not.toHaveBeenCalled(); + expect(sdk.setPersonProperties).toHaveBeenCalledWith({ 'Device Type': 'Desktop' }, undefined); + }); +}); diff --git a/src/services/posthog/provider.ts b/src/services/posthog/provider.ts new file mode 100644 index 00000000000..58c5e221d5f --- /dev/null +++ b/src/services/posthog/provider.ts @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { CaptureOptions, PostHog, PostHogConfig } from 'posthog-js'; + +import config from 'src/config'; +import { EventTypes } from 'src/shared/analytics/events'; +import type { AnalyticsProvider, TrackOptions } from 'src/shared/analytics/provider'; + +let sdk: PostHog | undefined; + +function getCaptureOptions({ timestamp, sendImmediately }: TrackOptions): CaptureOptions | undefined { + if (timestamp === undefined && !sendImmediately) { + return; + } + + return { + ...(timestamp === undefined ? {} : { timestamp: new Date(timestamp) }), + ...(sendImmediately ? { send_instantly: true } : {}), + }; +} + +export const posthogProvider: AnalyticsProvider = { + init: async({ debug }) => { + const { apiKey, configOverrides } = config.services.posthog; + if (!apiKey) { + throw new Error('PostHog API key is not configured'); + } + + const posthog = (await import('posthog-js')).default; + const posthogConfig: Partial<PostHogConfig> = { + api_host: 'https://eu.i.posthog.com', + autocapture: false, + capture_pageview: false, + capture_pageleave: false, + disable_session_recording: true, + // also skips the remote config fetch, so remotely enabled surveys, heatmaps, etc. stay off + advanced_disable_flags: true, + persistence: 'localStorage', + debug, + ...configOverrides, + }; + posthog.init(apiKey, posthogConfig); + sdk = posthog; + }, + track: (event, properties, options) => { + const eventName = event === EventTypes.PAGE_VIEW ? '$pageview' : event; + sdk?.capture(eventName, properties, getCaptureOptions(options)); + }, + register: (superProps) => { + sdk?.register(superProps); + }, + // every `setPersonProperties` call is its own `$set` event, so profile props travel inside `identify` + identify: (distinctId, profile) => { + if (distinctId) { + sdk?.identify(distinctId, profile?.set, profile?.setOnce); + return; + } + if (profile?.set || profile?.setOnce) { + sdk?.setPersonProperties(profile.set, profile.setOnce); + } + }, + peopleSet: (props) => { + sdk?.setPersonProperties(props); + }, + peopleSetOnce: (props) => { + sdk?.setPersonProperties(undefined, props); + }, + reset: () => { + sdk?.reset(); + }, +}; diff --git a/src/services/re-captcha/ReCaptcha.tsx b/src/services/re-captcha/ReCaptcha.tsx index 6e1e0f81102..455796b8ef8 100644 --- a/src/services/re-captcha/ReCaptcha.tsx +++ b/src/services/re-captcha/ReCaptcha.tsx @@ -18,7 +18,7 @@ interface Props { const ReCaptchaInvisible = ({ onInitError, hideWarning = false }: Props, ref: React.Ref<ReCaptcha>) => { const [ attempt, setAttempt ] = React.useState(0); const [ isError, setIsError ] = React.useState(false); - const [ , setIsVisible ] = React.useState(false); + const isVisibleRef = React.useRef(false); const multichainContext = useMultichainContext(); const chainConfig = multichainContext?.chain.app_config || config; @@ -35,12 +35,10 @@ const ReCaptchaInvisible = ({ onInitError, hideWarning = false }: Props, ref: Re const handleClick = React.useCallback(() => { const badge = window.document.querySelector('.grecaptcha-badge'); if (badge) { - setIsVisible((prev) => { - const nextValue = !prev; - (badge as HTMLElement).style.visibility = nextValue ? 'visible' : 'hidden'; - (badge as HTMLElement).style.right = nextValue ? '14px' : '-1000px'; - return nextValue; - }); + const nextValue = !isVisibleRef.current; + isVisibleRef.current = nextValue; + (badge as HTMLElement).style.visibility = nextValue ? 'visible' : 'hidden'; + (badge as HTMLElement).style.right = nextValue ? '14px' : '-1000px'; } }, [ ]); diff --git a/src/services/re-captcha/useReCaptcha.tsx b/src/services/re-captcha/useReCaptcha.ts similarity index 100% rename from src/services/re-captcha/useReCaptcha.tsx rename to src/services/re-captcha/useReCaptcha.ts diff --git a/src/services/rollbar/clientConfig.ts b/src/services/rollbar/clientConfig.ts index c3f3f497011..b624bc10b03 100644 --- a/src/services/rollbar/clientConfig.ts +++ b/src/services/rollbar/clientConfig.ts @@ -90,6 +90,12 @@ export function buildClientConfig(accessToken: string): Configuration { 'Proposal expired', 'Pairing expired', 'Session request expired', + + // The WalletConnect relay rejects the auth JWT its client SDK signs with the device clock when + // that clock is skewed ("not yet valid" when ahead, "expired" when behind), closing the socket + // with code 3000. A wrong system clock on the visitor's machine, not a fault we can fix; the + // timestamps in the message make every burst a new title, so match the shared relay prefix. + 'JWT validation error', ], maxItems: 10, // Max items per page load // uncaught / unhandledrejection coverage is owned by the early window listeners in queue.ts — diff --git a/src/services/rollbar/index.tsx b/src/services/rollbar/index.ts similarity index 100% rename from src/services/rollbar/index.tsx rename to src/services/rollbar/index.ts diff --git a/src/services/usercentrics/config.ts b/src/services/usercentrics/config.ts index b2df0a9326c..d7d3970a66f 100644 --- a/src/services/usercentrics/config.ts +++ b/src/services/usercentrics/config.ts @@ -7,10 +7,9 @@ import { getEnvValue, parseEnvJson } from 'src/config/utils/envs'; import { isBrowser } from 'src/toolkit/utils/isBrowser'; +import { STORAGE_KEY } from './consts'; import { CONSENT_RESULT_ALL_ACCEPTED } from './services'; -export const STORAGE_KEY = 'usercentrics-consent'; - interface UsercentricsConfig { readonly settingsId?: string; readonly rulesetId?: string; diff --git a/src/services/usercentrics/consts.ts b/src/services/usercentrics/consts.ts new file mode 100644 index 00000000000..692ff91052f --- /dev/null +++ b/src/services/usercentrics/consts.ts @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +export const STORAGE_KEY = 'usercentrics-consent'; diff --git a/src/services/usercentrics/services.ts b/src/services/usercentrics/services.ts index 87c25e2f2e6..ad00249b3c1 100644 --- a/src/services/usercentrics/services.ts +++ b/src/services/usercentrics/services.ts @@ -6,6 +6,9 @@ export const SERVICES = { mixpanel: { name: 'Mixpanel', }, + posthog: { + name: 'PostHog', + }, googleAnalytics: { name: 'Google Tag Manager', }, @@ -33,6 +36,7 @@ export const SERVICES_NAMES = Object.values(SERVICES).map(({ name }) => name); export const CONSENT_RESULT_ALL_ACCEPTED: UsercentricsConsentResult = { mixpanel: true, + posthog: true, googleAnalytics: true, rollbar: true, growthBook: true, diff --git a/src/services/usercentrics/useUpdateUsercentricsConsent.ts b/src/services/usercentrics/useUpdateUsercentricsConsent.ts index 6071acdd8d9..6ee261bd604 100644 --- a/src/services/usercentrics/useUpdateUsercentricsConsent.ts +++ b/src/services/usercentrics/useUpdateUsercentricsConsent.ts @@ -8,7 +8,7 @@ import type { UsercentricsConsentResult } from './types'; import config from 'src/config'; -import { STORAGE_KEY } from './config'; +import { STORAGE_KEY } from './consts'; import getConsentStatus from './get-consent-status'; export default function useUpdateUsercentricsConsent() { diff --git a/src/shared/analytics/events.ts b/src/shared/analytics/events.ts new file mode 100644 index 00000000000..1230ea27cb7 --- /dev/null +++ b/src/shared/analytics/events.ts @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { WalletType } from 'src/features/web3-wallet/types/config'; +import type { TokenTransferSurface } from 'src/slices/token-transfer/types/client'; + +import type { ColorThemeId } from 'src/shell/top-bar/settings/fields/color-theme/config'; + +import type { AppActionSource } from 'src/features/address-metadata/utils/build-app-action-url'; + +export enum EventTypes { + PAGE_VIEW = 'Page view', + SEARCH_QUERY = 'Search query', + LOCAL_SEARCH = 'Local search', + ADD_TO_WALLET = 'Add to wallet', + ACCOUNT_ACCESS = 'Account access', + LOGIN = 'Login', + ACCOUNT_LINK_INFO = 'Account link info', + PRIVATE_TAG = 'Private tag', + VERIFY_ADDRESS = 'Verify address', + VERIFY_TOKEN = 'Verify token', + WALLET_CONNECT = 'Wallet connect', + WALLET_ACTION = 'Wallet action', + CONTRACT_INTERACTION = 'Contract interaction', + CONTRACT_VERIFICATION = 'Contract verification', + QR_CODE = 'QR code', + PAGE_WIDGET = 'Page widget', + TX_INTERPRETATION_INTERACTION = 'Transaction interpretation interaction', + EXPERIMENT_STARTED = 'Experiment started', + FILTERS = 'Filters', + BUTTON_CLICK = 'Button click', + PROMO_BANNER = 'Promo banner', + APP_FEEDBACK = 'App feedback', + ADDRESS_WIDGET = 'Address widget', + TABLE_COLUMNS = 'Table columns', + RPC_NODE = 'RPC node', +} + +/* eslint-disable @stylistic/indent */ +export type EventPayload<Type extends EventTypes> = +Type extends EventTypes.PAGE_VIEW ? +{ + 'Page type': string; + Tab: string; + Page?: string; + Source?: string; + 'Color mode': 'light' | 'dark'; + 'Color theme': ColorThemeId | undefined; +} : +Type extends EventTypes.SEARCH_QUERY ? { + 'Search query': string; + 'Source page type': string; + 'Result URL': string; +} : +Type extends EventTypes.LOCAL_SEARCH ? { + 'Search query': string; + Source: 'Marketplace'; +} : +Type extends EventTypes.ADD_TO_WALLET ? ( + { + Wallet: WalletType; + Target: 'network'; + Source: 'Footer' | 'Top bar' | 'Chain widget'; + } | { + Wallet: WalletType; + Target: 'token'; + Token: string; + } +) : +Type extends EventTypes.ACCOUNT_ACCESS ? { + Action: 'Dropdown open' | 'Logged out'; +} : +Type extends EventTypes.LOGIN ? ( + { + Action: 'Started'; + Source: string; + } | { + Action: 'Wallet' | 'Email'; + Source: 'Options selector'; + } | { + Action: 'OTP sent'; + Source: 'Email'; + } | { + Action: 'Success'; + Source: 'Email' | 'Wallet' | 'Dynamic'; + } +) : +Type extends EventTypes.ACCOUNT_LINK_INFO ? { + Source: 'Profile' | 'Login modal' | 'Profile dropdown' | 'Merits'; + Status: 'Started' | 'OTP sent' | 'Finished'; + Type: 'Email' | 'Wallet'; +} : +Type extends EventTypes.PRIVATE_TAG ? { + Action: 'Form opened' | 'Submit'; + 'Page type': string; + 'Tag type': 'Address' | 'Tx'; +} : +Type extends EventTypes.VERIFY_ADDRESS ? ( + { + Action: 'Form opened' | 'Address entered'; + 'Page type': string; + } | { + Action: 'Sign ownership'; + 'Page type': string; + 'Sign method': 'wallet' | 'manual'; + } +) : +Type extends EventTypes.VERIFY_TOKEN ? { + Action: 'Form opened' | 'Submit'; +} : +Type extends EventTypes.WALLET_CONNECT ? { + Source: 'Header' | 'Login' | 'Profile' | 'Profile dropdown' | 'Smart contracts' | 'Swap button' | 'Merits' | 'Essential dapps'; + Status: 'Started' | 'Connected'; +} : +Type extends EventTypes.WALLET_ACTION ? ( + { + Action: 'Open' | 'Address click'; + } | { + Action: 'Send Transaction' | 'Sign Message' | 'Sign Typed Data'; + Source: 'Dappscout' | 'Essential dapps'; + AppId: string; + Address?: string; + ChainId?: string; + } +) : +Type extends EventTypes.CONTRACT_INTERACTION ? { + 'Method type': 'Read' | 'Write'; + 'Method name': string; +} : +Type extends EventTypes.CONTRACT_VERIFICATION ? { + Method: string; + Status: 'Method selected' | 'Finished'; +} : +Type extends EventTypes.QR_CODE ? { + 'Page type': string; +} : +Type extends EventTypes.PAGE_WIDGET ? ( + { + Type: 'Tokens dropdown' | 'Tokens show all (icon)' | 'Add to watchlist' | 'Address actions (more button)'; + } | { + Type: 'Favorite app' | 'More button'; + Info: string; + Source: 'Discovery view' | 'App modal' | 'App page' | 'Banner'; + } | { + Type: 'Action button'; + Info: string; + Source: AppActionSource; + } | { + Type: 'Address tag'; + Info: string; + URL: string; + } | { + Type: 'Share chart'; + Info: string; + } | { + Type: 'Chain switch'; + Info: string; + Source: 'Revoke essential dapp'; + } +) : +Type extends EventTypes.TX_INTERPRETATION_INTERACTION ? { + Type: 'Address click' | 'Token click' | 'Domain click'; +} : +Type extends EventTypes.EXPERIMENT_STARTED ? { + 'Experiment name': string; + 'Variant name': string; + Source: 'growthbook'; +} : +Type extends EventTypes.FILTERS ? { + Source: 'Marketplace'; + 'Filter name': string; +} : +Type extends EventTypes.BUTTON_CLICK ? { + Content: string; + Source: string; +} : +Type extends EventTypes.PROMO_BANNER ? { + Source: 'Marketplace' | 'Header'; + Link: string; +} : +Type extends EventTypes.APP_FEEDBACK ? { + Action: 'Rating'; + Source: 'Discovery' | 'App modal' | 'App page'; + AppId: string; + Score: number; +} : +Type extends EventTypes.ADDRESS_WIDGET ? { + Name: string; +} : +Type extends EventTypes.TABLE_COLUMNS ? ({ + Table: 'Token transfers'; + Surface: TokenTransferSurface; +} | { + Table: 'Advanced filter'; +}) & { + Column: string; + State: 'On' | 'Off' | 'Reset' | 'Moved up' | 'Moved down'; +} : +Type extends EventTypes.RPC_NODE ? { + Action: 'Set' | 'Reset' | 'Connect' | 'Disconnect'; +} : +undefined; +/* eslint-enable @stylistic/indent */ diff --git a/src/services/mixpanel/get-page-type.ts b/src/shared/analytics/get-page-type.ts similarity index 96% rename from src/services/mixpanel/get-page-type.ts rename to src/shared/analytics/get-page-type.ts index 5f3c6d7edc5..b64857bbb53 100644 --- a/src/services/mixpanel/get-page-type.ts +++ b/src/shared/analytics/get-page-type.ts @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { Route } from 'nextjs-routes'; +import type { Route } from 'src/shared/router/routes'; export const PAGE_TYPE_DICT: Record<Route['pathname'], string> = { '/': 'Homepage', @@ -68,7 +68,7 @@ export const PAGE_TYPE_DICT: Record<Route['pathname'], string> = { '/operations': 'Operations', '/operation/[id]': 'Operation details', '/cc/tx/[hash]': 'Cross-chain transaction details', - '/cross-chain-tx/[id]': 'Cross-chain transaction details', + '/bridge/[bridgeId]/cross-chain-tx/[id]': 'Cross-chain transaction details', '/ictt-users': 'ICTT users', // multichain routes diff --git a/src/services/mixpanel/get-tab-name.ts b/src/shared/analytics/get-tab-name.ts similarity index 100% rename from src/services/mixpanel/get-tab-name.ts rename to src/shared/analytics/get-tab-name.ts diff --git a/src/shared/analytics/index.ts b/src/shared/analytics/index.ts new file mode 100644 index 00000000000..ac6a9300833 --- /dev/null +++ b/src/shared/analytics/index.ts @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import getPageType, { PAGE_TYPE_DICT } from './get-page-type'; +import logEvent from './log-event'; +import reset from './reset'; +import useInit from './useInit'; +import useLogPageView from './useLogPageView'; +import * as userProfile from './user-profile'; +export * from './events'; + +export { + useInit, + useLogPageView, + logEvent, + getPageType, + userProfile, + reset, + PAGE_TYPE_DICT, +}; diff --git a/src/shared/analytics/log-event.ts b/src/shared/analytics/log-event.ts new file mode 100644 index 00000000000..06ea4eb0965 --- /dev/null +++ b/src/shared/analytics/log-event.ts @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { EventTypes, EventPayload } from './events'; +import type { TrackOptions } from './provider'; +import { track } from './queue'; + +type LogEventOptions = Pick<TrackOptions, 'sendImmediately'>; + +export default function logEvent<EventType extends EventTypes>( + type: EventType, + properties?: EventPayload<EventType>, + options?: LogEventOptions, +): void { + track(type, properties, options); +} diff --git a/src/shared/analytics/provider.ts b/src/shared/analytics/provider.ts new file mode 100644 index 00000000000..af02192014d --- /dev/null +++ b/src/shared/analytics/provider.ts @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +export type AnalyticsProperties = Readonly<Record<string, unknown>>; + +export interface ProviderInitOptions { + readonly debug: boolean; +} + +export interface TrackOptions { + // epoch milliseconds of the original call; present only when a buffered call is replayed + readonly timestamp?: number; + // set for events fired right before a full-page navigation, which would cancel a batched send + readonly sendImmediately?: boolean; +} + +export interface UserProfileUpdate { + readonly set?: AnalyticsProperties; + readonly setOnce?: AnalyticsProperties; +} + +export interface AnalyticsProvider { + init(options: ProviderInitOptions): Promise<void>; + track(event: string, properties: AnalyticsProperties | undefined, options: TrackOptions): void; + register(superProps: AnalyticsProperties): void; + identify(distinctId: string | undefined, profile?: UserProfileUpdate): void; + peopleSet(props: AnalyticsProperties): void; + peopleSetOnce(props: AnalyticsProperties): void; + reset(): void; +} diff --git a/src/shared/analytics/providers.ts b/src/shared/analytics/providers.ts new file mode 100644 index 00000000000..9d902e192cf --- /dev/null +++ b/src/shared/analytics/providers.ts @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import config from 'src/config'; +import { mixpanelProvider } from 'src/services/mixpanel/provider'; +import { posthogProvider } from 'src/services/posthog/provider'; + +import type { AnalyticsProvider } from './provider'; + +interface ProviderRegistration { + readonly provider: AnalyticsProvider; + readonly isEnabled: () => boolean; +} + +const PROVIDERS: ReadonlyArray<ProviderRegistration> = [ + { provider: mixpanelProvider, isEnabled: () => Boolean(config.services.mixpanel.projectToken) }, + { provider: posthogProvider, isEnabled: () => Boolean(config.services.posthog.apiKey) }, +]; + +export function getEnabledProviders(): Array<AnalyticsProvider> { + return PROVIDERS.filter(({ isEnabled }) => isEnabled()).map(({ provider }) => provider); +} diff --git a/src/shared/analytics/queue.spec.ts b/src/shared/analytics/queue.spec.ts new file mode 100644 index 00000000000..d5278f53ad0 --- /dev/null +++ b/src/shared/analytics/queue.spec.ts @@ -0,0 +1,260 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import type { AnalyticsProvider } from './provider'; + +const CALL_TIME_MS = 1_752_600_000_000; +const QUEUE_CAP = 100; +const NO_DEBUG = { debug: false }; + +const NOOP_SETUP = () => {}; + +const MIXPANEL_ENABLED: Array<[ string, string ]> = [ [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', 'test-token' ] ]; +const BOTH_ENABLED: Array<[ string, string ]> = [ ...MIXPANEL_ENABLED, [ 'NEXT_PUBLIC_POSTHOG_API_KEY', 'test-key' ] ]; +const NONE_ENABLED: Array<[ string, string ]> = []; + +interface FakeProvider extends AnalyticsProvider { + readonly calls: Array<string>; + readonly track: ReturnType<typeof vi.fn<AnalyticsProvider['track']>>; + readonly init: ReturnType<typeof vi.fn<AnalyticsProvider['init']>>; +} + +function createFakeProvider(): FakeProvider { + const calls: Array<string> = []; + return { + calls, + init: vi.fn<AnalyticsProvider['init']>(async() => {}), + track: vi.fn<AnalyticsProvider['track']>((event, properties) => { + calls.push(`track:${ event }:${ properties?.Content }`); + }), + register: () => calls.push('register'), + identify: (distinctId) => calls.push(`identify:${ distinctId }`), + peopleSet: () => calls.push('peopleSet'), + peopleSetOnce: () => calls.push('peopleSetOnce'), + reset: () => calls.push('reset'), + }; +} + +function entries(...providers: Array<AnalyticsProvider>) { + return providers.map((provider) => ({ provider, options: NO_DEBUG })); +} + +// the module keeps its state (buffer, init promise, live providers) at module scope, so every +// test imports a fresh copy; which providers are enabled is decided by the envs it is imported under +async function importQueue(envs = BOTH_ENABLED) { + return withEnvs(envs, () => import('./queue')); +} + +describe('analytics queue', () => { + let first: FakeProvider; + let second: FakeProvider; + + beforeEach(() => { + first = createFakeProvider(); + second = createFakeProvider(); + vi.spyOn(Date, 'now').mockReturnValue(CALL_TIME_MS); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe('before init', () => { + it('should buffer calls and replay them into every provider only after its setup has run', async() => { + const queue = await importQueue(); + + queue.track('Button click', { Content: 'burger menu' }); + queue.peopleSet({ 'With Account': true }); + expect(first.calls).toEqual([]); + + const isReady = await queue.init(entries(first, second), (provider) => { + provider.register({ 'Chain id': '1' }); + provider.identify('test-uuid'); + }); + + expect(isReady).toBe(true); + const expectedCalls = [ 'register', 'identify:test-uuid', 'track:Button click:burger menu', 'peopleSet' ]; + expect(first.calls).toEqual(expectedCalls); + expect(second.calls).toEqual(expectedCalls); + }); + + it('should pass the init options to each provider', async() => { + const queue = await importQueue(); + + await queue.init([ { provider: first, options: { debug: true } }, { provider: second, options: NO_DEBUG } ], NOOP_SETUP); + + expect(first.init).toHaveBeenCalledWith({ debug: true }); + expect(second.init).toHaveBeenCalledWith({ debug: false }); + }); + + it('should replay a buffered event with its original call time', async() => { + const queue = await importQueue(); + + queue.track('Button click', { Content: 'burger menu' }); + await queue.init(entries(first), NOOP_SETUP); + + expect(first.track).toHaveBeenCalledWith('Button click', { Content: 'burger menu' }, { timestamp: CALL_TIME_MS }); + }); + + it('should keep the send-immediately option on replay', async() => { + const queue = await importQueue(); + + queue.track('Account access', { Action: 'Logged out' }, { sendImmediately: true }); + await queue.init(entries(first), NOOP_SETUP); + + expect(first.track).toHaveBeenCalledWith( + 'Account access', + { Action: 'Logged out' }, + { sendImmediately: true, timestamp: CALL_TIME_MS }, + ); + }); + + it('should flush buffered calls of different types in call order', async() => { + const queue = await importQueue(); + + queue.track('Button click', { Content: 'before logout' }); + queue.reset(); + queue.peopleSetOnce({ 'First Time Join': '2026-07-16' }); + queue.track('Button click', { Content: 'after logout' }); + await queue.init(entries(first), NOOP_SETUP); + + expect(first.calls).toEqual([ 'track:Button click:before logout', 'reset', 'peopleSetOnce', 'track:Button click:after logout' ]); + }); + + it('should run setup (identity and profile writes) before a reset buffered during the deferral window', async() => { + const queue = await importQueue(); + + queue.reset(); + await queue.init(entries(first, second), (provider) => { + provider.peopleSet({ 'With Account': true }); + }); + + expect(first.calls).toEqual([ 'peopleSet', 'reset' ]); + expect(second.calls).toEqual([ 'peopleSet', 'reset' ]); + }); + + it('should drop calls above the buffer cap', async() => { + const queue = await importQueue(); + + for (let index = 0; index < QUEUE_CAP + 5; index++) { + queue.track('Button click', { Content: `${ index }` }); + } + await queue.init(entries(first), NOOP_SETUP); + + expect(first.track).toHaveBeenCalledTimes(QUEUE_CAP); + expect(first.calls.at(-1)).toBe(`track:Button click:${ QUEUE_CAP - 1 }`); + }); + }); + + describe('after init', () => { + it('should pass calls through to every provider without a timestamp', async() => { + const queue = await importQueue(); + await queue.init(entries(first, second), NOOP_SETUP); + + queue.track('Button click', { Content: 'burger menu' }); + queue.peopleSet({ 'With Account': true }); + queue.peopleSetOnce({ 'First Time Join': '2026-07-16' }); + queue.reset(); + + const expectedCalls = [ 'track:Button click:burger menu', 'peopleSet', 'peopleSetOnce', 'reset' ]; + expect(first.calls).toEqual(expectedCalls); + expect(second.calls).toEqual(expectedCalls); + expect(first.track).toHaveBeenCalledWith('Button click', { Content: 'burger menu' }, {}); + }); + + it('should share a single init between concurrent and repeated init calls', async() => { + const queue = await importQueue(); + + const [ firstResult, secondResult ] = await Promise.all([ + queue.init(entries(first), NOOP_SETUP), + queue.init(entries(first), NOOP_SETUP), + ]); + const thirdResult = await queue.init(entries(first), NOOP_SETUP); + + expect(first.init).toHaveBeenCalledOnce(); + expect([ firstResult, secondResult, thirdResult ]).toEqual([ true, true, true ]); + }); + }); + + describe('enabled providers', () => { + it('should send calls only to the initialized provider when just one is enabled', async() => { + const queue = await importQueue(MIXPANEL_ENABLED); + + queue.track('Button click', { Content: 'buffered' }); + await queue.init(entries(first), NOOP_SETUP); + queue.track('Button click', { Content: 'live' }); + + expect(first.calls).toEqual([ 'track:Button click:buffered', 'track:Button click:live' ]); + expect(second.calls).toEqual([]); + }); + + it('should not buffer anything when no provider is enabled', async() => { + const queue = await importQueue(NONE_ENABLED); + + queue.track('Button click', { Content: 'burger menu' }); + queue.peopleSet({ 'With Account': true }); + queue.reset(); + await queue.init(entries(first), NOOP_SETUP); + + expect(first.calls).toEqual([]); + }); + + it('should resolve to false and send nothing when initialized without providers', async() => { + const queue = await importQueue(); + + queue.track('Button click', { Content: 'burger menu' }); + const isReady = await queue.init([], NOOP_SETUP); + queue.track('Button click', { Content: 'burger menu' }); + + expect(isReady).toBe(false); + expect(first.calls).toEqual([]); + }); + }); + + describe('failure handling', () => { + it('should drop a provider whose SDK fails to load and still replay the buffer into the others', async() => { + const consoleError = vi.spyOn(console, 'error'); + first.init.mockRejectedValue(new Error('chunk load failed')); + const queue = await importQueue(); + + queue.track('Button click', { Content: 'buffered' }); + const isReady = await queue.init(entries(first, second), NOOP_SETUP); + queue.track('Button click', { Content: 'live' }); + + expect(isReady).toBe(true); + expect(first.calls).toEqual([]); + expect(second.calls).toEqual([ 'track:Button click:buffered', 'track:Button click:live' ]); + expect(consoleError).not.toHaveBeenCalled(); + }); + + it('should drop a provider whose setup throws without affecting the others', async() => { + const queue = await importQueue(); + + queue.track('Button click', { Content: 'buffered' }); + const isReady = await queue.init(entries(first, second), (provider) => { + if (provider === first) { + throw new Error('register failed'); + } + }); + + expect(isReady).toBe(true); + expect(first.calls).toEqual([]); + expect(second.calls).toEqual([ 'track:Button click:buffered' ]); + }); + + it('should resolve to false, discard the buffer and ignore later calls when every provider fails', async() => { + first.init.mockRejectedValue(new Error('chunk load failed')); + second.init.mockRejectedValue(new Error('chunk load failed')); + const queue = await importQueue(); + + queue.track('Button click', { Content: 'buffered' }); + const isReady = await queue.init(entries(first, second), NOOP_SETUP); + + expect(isReady).toBe(false); + await expect(queue.init(entries(first, second), NOOP_SETUP)).resolves.toBe(false); + expect(() => queue.track('Button click', { Content: 'live' })).not.toThrow(); + expect(first.calls).toEqual([]); + expect(second.calls).toEqual([]); + }); + }); +}); diff --git a/src/shared/analytics/queue.ts b/src/shared/analytics/queue.ts new file mode 100644 index 00000000000..715ea9a2734 --- /dev/null +++ b/src/shared/analytics/queue.ts @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { AnalyticsProperties, AnalyticsProvider, ProviderInitOptions, TrackOptions } from './provider'; +import { getEnabledProviders } from './providers'; + +type QueuedCall = { + readonly method: 'track'; + readonly event: string; + readonly properties: AnalyticsProperties | undefined; + readonly options: TrackOptions; +} | { + readonly method: 'peopleSet' | 'peopleSetOnce'; + readonly props: AnalyticsProperties; +} | { + readonly method: 'reset'; +}; + +export interface ProviderInitEntry { + readonly provider: AnalyticsProvider; + readonly options: ProviderInitOptions; +} + +// events are user-driven and init takes a few seconds at most, so the cap only guards +// against unbounded growth when an SDK chunk hangs forever +const MAX_QUEUE_LENGTH = 100; + +const NO_TRACK_OPTIONS: TrackOptions = {}; + +let initPromise: Promise<boolean> | undefined; +let liveProviders: ReadonlyArray<AnalyticsProvider> | undefined; +const queue: Array<QueuedCall> = []; + +/** + * The queue is flushed only after `setup` has run on a provider, so super-props and identity + * apply to the replayed events. A provider whose init or setup throws is dropped for this page + * load without affecting the others. + * + * Idempotent: concurrent and repeated calls share one init. Never rejects — resolves to `false` + * when no provider could be initialized, which permanently disables the queue for this page load. + */ +export function init( + providers: ReadonlyArray<ProviderInitEntry>, + setup: (provider: AnalyticsProvider) => void, +): Promise<boolean> { + initPromise = initPromise ?? initOnce(providers, setup); + return initPromise; +} + +async function initOnce( + providers: ReadonlyArray<ProviderInitEntry>, + setup: (provider: AnalyticsProvider) => void, +): Promise<boolean> { + const results = await Promise.allSettled(providers.map(async({ provider, options }) => { + await provider.init(options); + setup(provider); + return provider; + })); + + const initializedProviders = results + .filter((result) => result.status === 'fulfilled') + .map((result) => result.value); + + liveProviders = initializedProviders; + flushQueue(initializedProviders); + return initializedProviders.length > 0; +} + +export function track( + event: string, + properties: AnalyticsProperties | undefined, + options: TrackOptions = NO_TRACK_OPTIONS, +): void { + dispatch({ method: 'track', event, properties, options }); +} + +export function peopleSet(props: AnalyticsProperties): void { + dispatch({ method: 'peopleSet', props }); +} + +export function peopleSetOnce(props: AnalyticsProperties): void { + dispatch({ method: 'peopleSetOnce', props }); +} + +export function reset(): void { + dispatch({ method: 'reset' }); +} + +function dispatch(call: QueuedCall): void { + if (liveProviders) { + liveProviders.forEach((provider) => callProvider(provider, call)); + return; + } + if (queue.length >= MAX_QUEUE_LENGTH || getEnabledProviders().length === 0) { + return; + } + // Stryker disable next-line ConditionalExpression: only the track variant carries options; the check narrows the union, and other calls ignore options anyway + queue.push(call.method === 'track' ? { ...call, options: { ...call.options, timestamp: Date.now() } } : call); +} + +function flushQueue(providers: ReadonlyArray<AnalyticsProvider>): void { + for (const call of queue.splice(0)) { + providers.forEach((provider) => callProvider(provider, call)); + } +} + +function callProvider(provider: AnalyticsProvider, call: QueuedCall): void { + switch (call.method) { + case 'track': + provider.track(call.event, call.properties, call.options); + break; + case 'peopleSet': + provider.peopleSet(call.props); + break; + case 'peopleSetOnce': + provider.peopleSetOnce(call.props); + break; + case 'reset': + provider.reset(); + break; + } +} diff --git a/src/services/mixpanel/reset.ts b/src/shared/analytics/reset.ts similarity index 100% rename from src/services/mixpanel/reset.ts rename to src/shared/analytics/reset.ts diff --git a/src/shared/analytics/useInit.ts b/src/shared/analytics/useInit.ts new file mode 100644 index 00000000000..a4de8baff72 --- /dev/null +++ b/src/shared/analytics/useInit.ts @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { capitalize } from 'es-toolkit'; +import React from 'react'; +import { deviceType } from 'react-device-detect'; + +import config from 'src/config'; +import dayjs from 'src/shared/date-and-time/dayjs'; +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; +import * as cookies from 'src/shared/storage/cookies'; + +import { SECOND } from 'src/toolkit/utils/consts'; + +import type { AnalyticsProvider } from './provider'; +import { getEnabledProviders } from './providers'; +import * as queue from './queue'; + +const multichainFeature = config.features.multichain; + +// upper bound for the idle-callback deferral, so init is not postponed indefinitely on busy pages +const IDLE_INIT_TIMEOUT = 2 * SECOND; + +interface UserIdentity { + readonly isAuth: boolean; + readonly uuid: string | undefined; +} + +function setupProvider(provider: AnalyticsProvider, { isAuth, uuid }: UserIdentity): void { + provider.register({ + 'Chain id': config.chain.id, + Environment: config.app.isDev ? 'Dev' : 'Prod', + Authorized: isAuth, + 'Viewport width': window.innerWidth, + 'Viewport height': window.innerHeight, + Language: window.navigator.language, + 'Device type': capitalize(deviceType), + 'User id': uuid, + ...(multichainFeature.isEnabled ? { 'Cluster name': multichainFeature.cluster } : {}), + }); + // profile writes belong before the queue flush — a buffered `reset` (logout during + // the deferral window) must not leave them on the anonymous post-reset profile + provider.identify(uuid, { + set: { + 'Device Type': capitalize(deviceType), + ...(isAuth ? { 'With Account': true } : {}), + }, + setOnce: { + 'First Time Join': dayjs().toISOString(), + }, + }); +} + +export default function useInit(): boolean { + const [ isInitialized, setIsInitialized ] = React.useState(false); + const router = useRouter(); + const debugFlagQuery = React.useRef(getQueryParamString(router.query._analytics_debug)); + + React.useEffect(() => { + const providers = getEnabledProviders(); + if (providers.length === 0) { + return; + } + + // cookie-derived state is captured at mount so that the deferred init sees the same values + // a synchronous init would have (auth may change while init waits for an idle slot) + const debugFlagCookie = cookies.get(cookies.NAMES.ANALYTICS_DEBUG); + const identity: UserIdentity = { + isAuth: Boolean(cookies.get(cookies.NAMES.API_TOKEN)), + uuid: cookies.get(cookies.NAMES.UUID), + }; + + const startInit = async() => { + const options = { debug: Boolean(debugFlagQuery.current || debugFlagCookie) }; + const isReady = await queue.init( + providers.map((provider) => ({ provider, options })), + (provider) => setupProvider(provider, identity), + ); + + if (!isReady) { + return; + } + + setIsInitialized(true); + if (debugFlagQuery.current && !debugFlagCookie) { + cookies.set(cookies.NAMES.ANALYTICS_DEBUG, 'true'); + } + }; + + if (typeof window.requestIdleCallback === 'function') { + const idleCallbackId = window.requestIdleCallback(startInit, { timeout: IDLE_INIT_TIMEOUT }); + return () => window.cancelIdleCallback(idleCallbackId); + } + + const timeoutId = window.setTimeout(startInit, 0); + return () => window.clearTimeout(timeoutId); + }, []); + + return isInitialized; +} diff --git a/src/shared/analytics/useLogPageView.ts b/src/shared/analytics/useLogPageView.ts new file mode 100644 index 00000000000..23a748f5264 --- /dev/null +++ b/src/shared/analytics/useLogPageView.ts @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { ColorThemeId } from 'src/shell/top-bar/settings/fields/color-theme/config'; +import { getDefaultColorTheme } from 'src/shell/top-bar/settings/fields/color-theme/utils'; + +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { usePathname } from 'src/shared/router/usePathname'; +import { useRouter } from 'src/shared/router/useRouter'; +import * as cookies from 'src/shared/storage/cookies'; + +import { useColorMode } from 'src/toolkit/chakra/color-mode'; + +import { EventTypes } from './events'; +import getPageType from './get-page-type'; +import getTabName from './get-tab-name'; +import logEvent from './log-event'; + +export default function useLogPageView(isInitialized: boolean) { + const router = useRouter(); + const pathname = usePathname(); + + const tab = getQueryParamString(router.query.tab); + const page = getQueryParamString(router.query.page); + const id = getQueryParamString(router.query.id); + const { colorMode } = useColorMode(); + + React.useEffect(() => { + if (!isInitialized) { + return; + } + + const cookieColorTheme = cookies.get(cookies.NAMES.COLOR_THEME) as ColorThemeId | undefined; + + logEvent(EventTypes.PAGE_VIEW, { + 'Page type': getPageType(router.pathname), + Tab: getTabName(tab), + Page: page || undefined, + Source: router.pathname === '/essential-dapps/[id]' ? id : undefined, + 'Color mode': colorMode, + 'Color theme': cookieColorTheme || getDefaultColorTheme(colorMode), + }); + // these are only deps that should trigger the effect + // in some scenarios page type is not changing (e.g navigation from one address page to another), + // but we still want to log page view + // so we use the navigation pathname instead of router.pathname as deps + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ isInitialized, page, pathname, tab, colorMode ]); +} diff --git a/src/shared/analytics/user-profile.ts b/src/shared/analytics/user-profile.ts new file mode 100644 index 00000000000..2820730b646 --- /dev/null +++ b/src/shared/analytics/user-profile.ts @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { peopleSet, peopleSetOnce } from './queue'; + +interface UserProfileProperties { + 'With Account': boolean; + 'With Connected Wallet': boolean; + 'Device Type': string; + 'First Time Join': string; +} + +export function set(props: Partial<UserProfileProperties>) { + peopleSet(props); +} + +export function setOnce(props: Partial<UserProfileProperties>) { + peopleSetOnce(props); +} diff --git a/src/shared/buttons/InfoPopoverButton.tsx b/src/shared/buttons/InfoPopoverButton.tsx index 4161e7d9d3f..1ac1d95f79f 100644 --- a/src/shared/buttons/InfoPopoverButton.tsx +++ b/src/shared/buttons/InfoPopoverButton.tsx @@ -36,7 +36,7 @@ const InfoPopoverButton = ({ children, isLoading }: Props) => { if (isMobile) { return ( <DialogRoot size="full"> - <DialogTrigger> + <DialogTrigger asChild> { triggerButton } </DialogTrigger> <DialogContent> diff --git a/src/shared/code-editor/CodeEditor.tsx b/src/shared/code-editor/CodeEditor.tsx index 8bb0f293f6a..805de98a717 100644 --- a/src/shared/code-editor/CodeEditor.tsx +++ b/src/shared/code-editor/CodeEditor.tsx @@ -66,6 +66,7 @@ const CodeEditor = ({ data, remappings, libraries, language, mainFile, contractN const [ index, setIndex ] = React.useState(0); const [ tabs, setTabs ] = React.useState([ data[index].file_path ]); const [ isMetaPressed, setIsMetaPressed ] = React.useState(false); + const handleTabCloseRef = React.useRef<(path: string, isActive?: boolean) => void>(() => {}); const [ containerRect, containerNodeRef ] = useClientRect<HTMLDivElement>(); @@ -156,7 +157,7 @@ const CodeEditor = ({ data, remappings, libraries, language, mainFile, contractN const model = editor.getModel(); const path = model?.uri.path; if (path) { - handleTabClose(path, true); + handleTabCloseRef.current(path, true); } }, }); @@ -183,22 +184,24 @@ const CodeEditor = ({ data, remappings, libraries, language, mainFile, contractN }, [ data ]); const handleTabClose = React.useCallback((path: string, _isActive?: boolean) => { - setTabs((prev) => { - if (prev.length > 1) { - const tabIndex = prev.findIndex((item) => item === path); - const isActive = _isActive !== undefined ? _isActive : data[index].file_path === path; - - if (isActive) { - const nextActiveIndex = data.findIndex((item) => item.file_path === prev[(tabIndex === 0 ? 1 : tabIndex - 1)]); - setIndex(nextActiveIndex); - } + if (tabs.length <= 1) { + return; + } - return prev.filter((item) => item !== path); - } + const tabIndex = tabs.findIndex((item) => item === path); + const isActive = _isActive !== undefined ? _isActive : data[index].file_path === path; - return prev; - }); - }, [ data, index ]); + if (isActive) { + const nextActiveIndex = data.findIndex((item) => item.file_path === tabs[(tabIndex === 0 ? 1 : tabIndex - 1)]); + setIndex(nextActiveIndex); + } + + setTabs(tabs.filter((item) => item !== path)); + }, [ data, index, tabs ]); + + React.useEffect(() => { + handleTabCloseRef.current = handleTabClose; + }, [ handleTabClose ]); const handleClick = React.useCallback((event: React.MouseEvent) => { if (!isMetaPressed && !isMobile) { diff --git a/src/shared/code-editor/CodeEditorSearch.tsx b/src/shared/code-editor/CodeEditorSearch.tsx index 84459fe6972..d65c8689f85 100644 --- a/src/shared/code-editor/CodeEditorSearch.tsx +++ b/src/shared/code-editor/CodeEditorSearch.tsx @@ -27,9 +27,11 @@ interface Props { defaultValue: string; } +const EMPTY_RESULTS: Array<SearchResult> = []; + const CodeEditorSearch = ({ monaco, data, onFileSelect, isInputStuck, isActive, setActionBarRenderer, defaultValue }: Props) => { const [ searchTerm, changeSearchTerm ] = React.useState(''); - const [ searchResults, setSearchResults ] = React.useState<Array<SearchResult>>([]); + const [ searchResults, setSearchResults ] = React.useState<Array<SearchResult>>(EMPTY_RESULTS); const [ expandedSections, setExpandedSections ] = React.useState<Array<string>>([]); const [ isMatchCase, setMatchCase ] = React.useState(false); const [ isMatchWholeWord, setMatchWholeWord ] = React.useState(false); @@ -61,10 +63,6 @@ const CodeEditorSearch = ({ monaco, data, onFileSelect, isInputStuck, isActive, return; } - if (!debouncedSearchTerm) { - setSearchResults([]); - } - const models = monaco.editor.getModels(); const matches = models.map((model) => model.findMatches(debouncedSearchTerm, false, isMatchRegex, isMatchCase, isMatchWholeWord ? 'true' : null, false)); @@ -87,13 +85,10 @@ const CodeEditorSearch = ({ monaco, data, onFileSelect, isInputStuck, isActive, }) .filter(({ matches }) => matches.length > 0); - setSearchResults(result.length > 0 ? result : []); + setSearchResults(result.length > 0 ? result : EMPTY_RESULTS); + setExpandedSections(result.map((item) => item.file_path)); }, [ debouncedSearchTerm, isMatchCase, isMatchRegex, isMatchWholeWord, monaco ]); - React.useEffect(() => { - setExpandedSections(searchResults.map((item) => item.file_path)); - }, [ searchResults ]); - const handleSearchTermChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => { changeSearchTerm(event.target.value); }, []); diff --git a/src/shared/code-editor/CodeEditorSnippet.tsx b/src/shared/code-editor/CodeEditorSnippet.tsx index 44f80c0902b..8a4296f679e 100644 --- a/src/shared/code-editor/CodeEditorSnippet.tsx +++ b/src/shared/code-editor/CodeEditorSnippet.tsx @@ -27,7 +27,7 @@ const CodeEditorSnippet = ({ data, copyData, language, title, className, rightSl return ( <Box className={ className } as="section" title={ title }> - { (title || rightSlot) && ( + { Boolean(title || rightSlot) && ( <Flex justifyContent={ title ? 'space-between' : 'flex-end' } alignItems="center" mb={ 3 }> { title && <Skeleton loading={ isLoading } fontWeight={ 500 }>{ title }</Skeleton> } { rightSlot } diff --git a/src/shared/data/RawDataSnippet.tsx b/src/shared/data/RawDataSnippet.tsx index 2c2894fc14c..cd7fd838d5f 100644 --- a/src/shared/data/RawDataSnippet.tsx +++ b/src/shared/data/RawDataSnippet.tsx @@ -41,7 +41,7 @@ const RawDataSnippet = ({ const bgColor = { _light: '#f5f5f6', _dark: '#1a1b1b' }; return ( <Box className={ className } as="section" title={ title }> - { (title || rightSlot || showCopy) && ( + { Boolean(title || rightSlot || showCopy) && ( <Flex justifyContent={ title ? 'space-between' : 'flex-end' } alignItems="center" mb={{ base: 1, lg: 3 }}> { title && <Skeleton fontWeight={ 500 } loading={ isLoading }>{ title }</Skeleton> } { rightSlot } diff --git a/src/shared/date-and-time/TimeFormatToggle.tsx b/src/shared/date-and-time/TimeFormatToggle.tsx index e06d48f3126..74230641361 100644 --- a/src/shared/date-and-time/TimeFormatToggle.tsx +++ b/src/shared/date-and-time/TimeFormatToggle.tsx @@ -6,7 +6,7 @@ import React from 'react'; import { useSettingsContext } from 'src/shell/top-bar/settings/context'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { IconButton } from 'src/toolkit/chakra/icon-button'; @@ -20,7 +20,7 @@ const TimeFormatToggle = (props: Props) => { const handleClick = React.useCallback(() => { settings?.toggleTimeFormat(); - mixpanel.logEvent(mixpanel.EventTypes.BUTTON_CLICK, { Content: 'Switch time format', Source: 'Table header' }); + analytics.logEvent(analytics.EventTypes.BUTTON_CLICK, { Content: 'Switch time format', Source: 'Table header' }); }, [ settings ]); const text = (() => { diff --git a/src/shared/date-and-time/TimeWithTooltip.tsx b/src/shared/date-and-time/TimeWithTooltip.tsx index aaecfcf0b66..acc3f2dafb8 100644 --- a/src/shared/date-and-time/TimeWithTooltip.tsx +++ b/src/shared/date-and-time/TimeWithTooltip.tsx @@ -4,7 +4,7 @@ import { chakra } from '@chakra-ui/react'; import React from 'react'; import { useSettingsContext } from 'src/shell/top-bar/settings/context'; -import type { TimeFormat } from 'src/shell/top-bar/settings/time-format/utils'; +import type { TimeFormat } from 'src/shell/top-bar/settings/fields/time-format/utils'; import dayjs from 'src/shared/date-and-time/dayjs'; import useTimeAgoIncrement from 'src/shared/date-and-time/useTimeAgoIncrement'; diff --git a/src/shared/date-and-time/useTimeAgoIncrement.tsx b/src/shared/date-and-time/useTimeAgoIncrement.ts similarity index 100% rename from src/shared/date-and-time/useTimeAgoIncrement.tsx rename to src/shared/date-and-time/useTimeAgoIncrement.ts diff --git a/src/shared/detailed-info/DetailedInfo.tsx b/src/shared/detailed-info/DetailedInfo.tsx index 2aea868baf9..1d06ef3e67e 100644 --- a/src/shared/detailed-info/DetailedInfo.tsx +++ b/src/shared/detailed-info/DetailedInfo.tsx @@ -46,7 +46,7 @@ export const ItemLabel = ({ hint, children, isLoading, id, hasScroll, ...rest }: { ...rest } > <Flex columnGap={{ base: 1, lg: 2 }} alignItems="flex-start" w="100%"> - { hint && <Hint label={ hint } isLoading={ isLoading } my={{ base: '5px', lg: '6px' }}/> } + { Boolean(hint) && <Hint label={ hint } isLoading={ isLoading } my={{ base: '5px', lg: '6px' }}/> } <Skeleton loading={ isLoading } fontWeight={{ base: 700, lg: 500 }} py={{ base: '5px', lg: '4px' }} flexGrow={ 1 }> { children } { hasScroll && <ItemLabelScrollText/> } diff --git a/src/shared/detailed-info/DetailedInfoItemBreakdown.tsx b/src/shared/detailed-info/DetailedInfoItemBreakdown.tsx index 245d8264d27..d1f96c873cc 100644 --- a/src/shared/detailed-info/DetailedInfoItemBreakdown.tsx +++ b/src/shared/detailed-info/DetailedInfoItemBreakdown.tsx @@ -7,7 +7,7 @@ import React from 'react'; import type { CollapsibleDetailsProps } from 'src/toolkit/chakra/collapsible'; import { CollapsibleDetails } from 'src/toolkit/chakra/collapsible'; import { Hint } from 'src/toolkit/components/Hint/Hint'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface ContainerProps extends CollapsibleDetailsProps {} @@ -44,7 +44,7 @@ export const Row = ({ label, hint, children, ...rest }: RowProps) => { <> <GridItem color="text.secondary" display="flex" alignItems="center" { ...rest }> { hint && <Hint label={ hint } boxSize={ 4 } mr={ 1 }/> } - <TruncatedText text={ label } maxW={{ base: '130px', lg: 'unset' }}/> + <Truncate value={ label } type="end" maxW={{ base: '130px', lg: 'unset' }}/> </GridItem> { children } </> diff --git a/src/shared/detailed-info/DetailedInfoTimestamp.tsx b/src/shared/detailed-info/DetailedInfoTimestamp.tsx index 8054a247309..de67233addb 100644 --- a/src/shared/detailed-info/DetailedInfoTimestamp.tsx +++ b/src/shared/detailed-info/DetailedInfoTimestamp.tsx @@ -14,7 +14,7 @@ import { IconButton } from 'src/toolkit/chakra/icon-button'; import type { SelectOption } from 'src/toolkit/chakra/select'; import { SelectContent, SelectItem, SelectRoot, SelectControl } from 'src/toolkit/chakra/select'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const FORMAT_OPTIONS = [ { label: 'Local', value: 'local' as const }, @@ -99,11 +99,8 @@ const DetailedInfoTimestamp = ({ timestamp, isLoading, noRelativeTime, ...rest } )) } </SelectContent> </SelectRoot> - <TruncatedText - text={ timeText } - loading={ isLoading } - minW="0" - /> + <Truncate value={ timeText } type="end" loading={ isLoading } + minW="0"/> </HStack> </HStack> ); diff --git a/src/shared/entities/components.tsx b/src/shared/entities/components.tsx index 1080261339b..679cffc5e31 100644 --- a/src/shared/entities/components.tsx +++ b/src/shared/entities/components.tsx @@ -8,8 +8,6 @@ import type { ExternalChain } from 'src/shared/external-chains/types'; import type { Props as CopyToClipboardProps } from 'src/shared/texts/CopyToClipboard'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShorten from 'src/shared/texts/HashStringShorten'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import SpriteIcon from 'src/sprite/SpriteIcon'; import type { Props as SpriteIconProps } from 'src/sprite/SpriteIcon'; @@ -19,7 +17,8 @@ import type { LinkProps } from 'src/toolkit/chakra/link'; import { Link as LinkToolkit } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; +import type { TruncateTooltipConfig } from 'src/toolkit/components/truncation/Truncate'; import { getContentProps, getIconProps } from './utils'; @@ -225,24 +224,32 @@ const Content = chakra(({ tooltipContentAfter, noLink, }: ContentBaseProps) => { + const CONSTANT_LONG_MAX_SYMBOLS = 16; const styles = getContentProps(variant); - const tooltipContent = tooltipContentAfter ? ( - <> - { text } - { tooltipContentAfter } - </> - ) : undefined; + const tooltip = React.useMemo((): false | TruncateTooltipConfig => { + if (noTooltip) { + return false; + } + const content = tooltipContentAfter ? ( + <> + { text } + { tooltipContentAfter } + </> + ) : undefined; + // `tooltipContentAfter` carries actionable UI (e.g. the advanced-filter link), so the tooltip + // must stay reachable even when the value itself is not truncated. + return { content, interactive: tooltipInteractive, always: Boolean(tooltipContentAfter) }; + }, [ noTooltip, tooltipContentAfter, text, tooltipInteractive ]); if (truncation === 'tail') { return ( - <TruncatedText - text={ text } + <Truncate + value={ text } + type="end" loading={ isLoading } className={ className } - noTooltip={ noTooltip } - tooltipInteractive={ tooltipInteractive } - tooltipContent={ tooltipContent } + tooltip={ tooltip } { ...styles } /> ); @@ -252,36 +259,32 @@ const Content = chakra(({ switch (truncation) { case 'constant_long': return ( - <HashStringShorten - hash={ text } + <Truncate + value={ text } as={ asProp } - type="long" - noTooltip={ noTooltip } - tooltipInteractive={ tooltipInteractive } - tooltipContent={ tooltipContent } - maxSymbols={ truncationMaxSymbols } + type="middle-static" + maxSymbols={ truncationMaxSymbols ?? CONSTANT_LONG_MAX_SYMBOLS } + tooltip={ tooltip } /> ); case 'constant': return ( - <HashStringShorten - hash={ text } + <Truncate + value={ text } as={ asProp } - noTooltip={ noTooltip } - tooltipInteractive={ tooltipInteractive } - tooltipContent={ tooltipContent } + type="middle-static" maxSymbols={ truncationMaxSymbols } + tooltip={ tooltip } /> ); case 'dynamic': return ( - <HashStringShortenDynamic - hash={ text } + <Truncate + value={ text } as={ asProp } + type="middle" tailLength={ tailLength } - noTooltip={ noTooltip } - tooltipInteractive={ tooltipInteractive } - tooltipContent={ tooltipContent } + tooltip={ tooltip } /> ); case 'none': diff --git a/src/shared/errors/AppError.spec.tsx b/src/shared/errors/AppError.spec.tsx new file mode 100644 index 00000000000..63f31b1a422 --- /dev/null +++ b/src/shared/errors/AppError.spec.tsx @@ -0,0 +1,50 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const RATE_LIMIT_ERROR = { + message: 'Too many requests', + cause: { status: 429 }, + rateLimits: { bypassOptions: 'temporary_token', reset: '42000' }, +} as unknown as Error; + +interface RateLimitScreen { + readonly text: string | null; + readonly hasBypassButton: boolean; +} + +const renderRateLimitScreen = async(siteKey: string): Promise<RateLimitScreen> => { + return withEnvs([ [ 'NEXT_PUBLIC_RE_CAPTCHA_APP_SITE_KEY', siteKey ] ], async() => { + const { render, screen } = await import('vitest/lib'); + const { 'default': AppError } = await import('./AppError'); + + const view = render(<AppError error={ RATE_LIMIT_ERROR }/>); + try { + return { + text: screen.getByText(/^Rate limit exceeded/).textContent, + hasBypassButton: screen.queryByRole('button', { name: 'I\'m not a robot' }) !== null, + }; + } finally { + view.unmount(); + } + }); +}; + +describe('rate limit error screen', () => { + it('offers the wait only when the instance has no reCAPTCHA site key', async() => { + const screen = await renderRateLimitScreen(''); + + expect(screen.text).toBe('Rate limit exceeded. Please wait 00h 00m 42s before making another request.'); + expect(screen.hasBypassButton).toBe(false); + }); + + it('offers the wait or the human check when the instance has a reCAPTCHA site key', async() => { + const screen = await renderRateLimitScreen('site-key'); + + expect(screen.text).toBe('Rate limit exceeded. Please wait 00h 00m 42s OR verify you\'re human before making another request.'); + expect(screen.hasBypassButton).toBe(true); + }); +}); diff --git a/src/shared/errors/AppError.tsx b/src/shared/errors/AppError.tsx index 3c0f8c06a2b..8a599f2d331 100644 --- a/src/shared/errors/AppError.tsx +++ b/src/shared/errors/AppError.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import AdBanner from 'src/features/ads/banner/components/AdBanner'; @@ -11,6 +10,7 @@ import getErrorCauseStatusCode from 'src/shared/errors/get-error-cause-status-co import getErrorObjStatusCode from 'src/shared/errors/get-error-obj-status-code'; import getErrorProp from 'src/shared/errors/get-error-prop'; import getResourceErrorPayload from 'src/shared/errors/get-resource-error-payload'; +import { route } from 'src/shared/router/routes'; import { Button } from 'src/toolkit/chakra/button'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/shared/errors/ErrorBoundary.tsx b/src/shared/errors/ErrorBoundary.tsx index 5d1d58e0a32..f35b7a538b3 100644 --- a/src/shared/errors/ErrorBoundary.tsx +++ b/src/shared/errors/ErrorBoundary.tsx @@ -1,9 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { NextRouter } from 'next/router'; -import { useRouter } from 'next/router'; import React from 'react'; +import type { Router } from 'src/shared/router/useRouter'; +import { useRouter } from 'src/shared/router/useRouter'; + interface Props { children: React.ReactNode; renderErrorScreen: (error?: Error) => React.ReactNode; @@ -11,7 +12,7 @@ interface Props { } interface PropsWithRouter extends Props { - router: NextRouter; + router: Router; } interface State { diff --git a/src/shared/errors/__screenshots__/AppError.pw.tsx_mobile_too-many-requests-mobile-1.png b/src/shared/errors/__screenshots__/AppError.pw.tsx_mobile_too-many-requests-mobile-1.png index 4be0eb1bbb5..f1352ec105b 100644 Binary files a/src/shared/errors/__screenshots__/AppError.pw.tsx_mobile_too-many-requests-mobile-1.png and b/src/shared/errors/__screenshots__/AppError.pw.tsx_mobile_too-many-requests-mobile-1.png differ diff --git a/src/shared/errors/custom/AppErrorBlockConsensus.tsx b/src/shared/errors/custom/AppErrorBlockConsensus.tsx index adb0d83d339..5bc7c14a099 100644 --- a/src/shared/errors/custom/AppErrorBlockConsensus.tsx +++ b/src/shared/errors/custom/AppErrorBlockConsensus.tsx @@ -1,8 +1,9 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { route } from 'nextjs-routes'; import React from 'react'; +import { route } from 'src/shared/router/routes'; + import { Button } from 'src/toolkit/chakra/button'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/shared/errors/custom/AppErrorTooManyRequests.tsx b/src/shared/errors/custom/AppErrorTooManyRequests.tsx index e2002122ce3..4db8a38a1d9 100644 --- a/src/shared/errors/custom/AppErrorTooManyRequests.tsx +++ b/src/shared/errors/custom/AppErrorTooManyRequests.tsx @@ -85,40 +85,34 @@ const AppErrorTooManyRequests = ({ bypassOptions, reset }: Props) => { }, [ recaptcha ]); React.useEffect(() => { - if (reset === undefined) { + if (timeLeft === undefined) { return; } - const interval = window.setInterval(() => { - setTimeLeft((prev) => { - if (prev && prev > 1) { - return prev - 1; - } - - window.clearInterval(interval); + const timeout = window.setTimeout(() => { + if (timeLeft <= 1) { window.location.reload(); + return; + } - return 0; - }); + setTimeLeft(timeLeft - 1); }, SECOND); return () => { - window.clearInterval(interval); + window.clearTimeout(timeout); }; - }, [ reset ]); + }, [ timeLeft ]); - if (!config.services.reCaptcha.siteKey) { - throw new Error('reCAPTCHA V2 site key is not set'); - } + const isBypassAvailable = Boolean(config.services.reCaptcha.siteKey) && bypassOptions !== 'no_bypass'; const text = (() => { - if (timeLeft === undefined && bypassOptions === 'no_bypass') { + if (timeLeft === undefined && !isBypassAvailable) { return 'Rate limit exceeded.'; } const timeLeftText = timeLeft !== undefined ? `wait ${ formatTimeLeft(timeLeft) } ` : ''; - const bypassText = bypassOptions !== 'no_bypass' ? `verify you${ apos }re human ` : ''; - const orText = timeLeft !== undefined && bypassOptions !== 'no_bypass' ? 'OR ' : ''; + const bypassText = isBypassAvailable ? `verify you${ apos }re human ` : ''; + const orText = timeLeft !== undefined && isBypassAvailable ? 'OR ' : ''; return `Rate limit exceeded. Please ${ timeLeftText }${ orText }${ bypassText }before making another request.`; })(); @@ -131,7 +125,7 @@ const AppErrorTooManyRequests = ({ bypassOptions, reset }: Props) => { { text } </Text> <ReCaptcha { ...recaptcha }/> - { bypassOptions !== 'no_bypass' && <Button onClick={ handleSubmit } disabled={ recaptcha.isInitError } mt={ 8 }>I'm not a robot</Button> } + { isBypassAvailable && <Button onClick={ handleSubmit } disabled={ recaptcha.isInitError } mt={ 8 }>I'm not a robot</Button> } </> ); }; diff --git a/src/shared/errors/custom/AppErrorTxNotFound.tsx b/src/shared/errors/custom/AppErrorTxNotFound.tsx index e781fee1139..c9dad754408 100644 --- a/src/shared/errors/custom/AppErrorTxNotFound.tsx +++ b/src/shared/errors/custom/AppErrorTxNotFound.tsx @@ -2,11 +2,11 @@ /* eslint-disable max-len */ import { Box, Flex, List, chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import Puzzle15 from 'src/features/easter-eggs/components/puzzle-15/Puzzle15'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; diff --git a/src/shared/external-chains/ChainSnippetList.tsx b/src/shared/external-chains/ChainSnippetList.tsx index 5a8869e025f..97406b36613 100644 --- a/src/shared/external-chains/ChainSnippetList.tsx +++ b/src/shared/external-chains/ChainSnippetList.tsx @@ -10,7 +10,7 @@ import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import ChainIcon from './ChainIcon'; @@ -21,8 +21,8 @@ interface Props extends StackProps { const ChainSnippetList = ({ data, isLoading, ...rest }: Props) => { return ( - <HStack gap={ 3 } justifyContent={{ base: 'space-between', lg: 'flex-start' }} { ...rest }> - <HStack maxW={{ base: '50%', lg: '100%' }}> + <HStack gap={ 3 } justifyContent="flex-start" { ...rest }> + <HStack maxW={{ base: '70%', lg: '100%' }}> <ChainIcon data={ data } isLoading={ isLoading }/> { data.explorer_url ? ( <Link @@ -32,7 +32,7 @@ const ChainSnippetList = ({ data, isLoading, ...rest }: Props) => { loading={ isLoading } maxW="calc(100% - 28px)" > - <TruncatedText text={ data?.name ?? 'Unknown chain' } loading={ isLoading }/> + <Truncate value={ data?.name ?? 'Unknown chain' } type="end" loading={ isLoading }/> </Link> ) : ( <Skeleton loading={ isLoading } fontWeight={ 700 } maxW="calc(100% - 28px)"><span>{ data?.name ?? 'Unknown chain' }</span></Skeleton> diff --git a/src/shared/filters/ColumnFilter.tsx b/src/shared/filters/ColumnFilter.tsx new file mode 100644 index 00000000000..0f39c4c0ee3 --- /dev/null +++ b/src/shared/filters/ColumnFilter.tsx @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { chakra } from '@chakra-ui/react'; +import React from 'react'; + +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { Button } from 'src/toolkit/chakra/button'; +import type { PopoverContentProps, PopoverRootProps } from 'src/toolkit/chakra/popover'; +import { PopoverBody, PopoverContent, PopoverRoot, PopoverTrigger } from 'src/toolkit/chakra/popover'; + +interface Props { + columnName: string; + isLoading?: boolean; + selected?: boolean; + contentProps?: PopoverContentProps; + rootProps?: Omit<PopoverRootProps, 'children'>; + children: React.ReactNode; + value?: string; +} + +const ColumnFilter = ({ columnName, contentProps, rootProps, children, isLoading, selected, value }: Props) => { + return ( + <PopoverRoot { ...rootProps }> + <PopoverTrigger> + <Button + display="inline-flex" + aria-label={ `filter by ${ columnName }` } + variant="icon_secondary" + borderWidth="0" + h="20px" + minW="auto" + disabled={ isLoading } + selected={ selected } + borderRadius="4px" + size="sm" + textStyle="sm" + fontWeight={ 500 } + padding={ 0 } + > + <SpriteIcon name="filter" w="19px" h="19px"/> + { Boolean(value) && <chakra.span>{ value }</chakra.span> } + </Button> + </PopoverTrigger> + <PopoverContent w="382px" { ...contentProps }> + <PopoverBody> + { children } + </PopoverBody> + </PopoverContent> + </PopoverRoot> + ); +}; + +export default ColumnFilter; diff --git a/src/shared/filters/ColumnFilterContent.tsx b/src/shared/filters/ColumnFilterContent.tsx new file mode 100644 index 00000000000..a373f5bf7b3 --- /dev/null +++ b/src/shared/filters/ColumnFilterContent.tsx @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Flex } from '@chakra-ui/react'; +import React from 'react'; + +import { Button } from 'src/toolkit/chakra/button'; +import { PopoverCloseTriggerWrapper } from 'src/toolkit/chakra/popover'; + +type Props = { + isTouched?: boolean; + onFilter: () => void; + children: React.ReactNode; +}; + +const ColumnFilterContent = ({ isTouched, onFilter, children }: Props) => { + const handleFilterClick = React.useCallback(() => { + onFilter(); + }, [ onFilter ]); + + return ( + <Flex flexDir="column" rowGap={ 6 }> + { children } + <PopoverCloseTriggerWrapper> + <Button + disabled={ !isTouched } + onClick={ handleFilterClick } + w="fit-content" + size="sm" + > + Filter + </Button> + </PopoverCloseTriggerWrapper> + </Flex> + ); +}; + +export default ColumnFilterContent; diff --git a/src/shared/filters/ColumnFilterContentSection.tsx b/src/shared/filters/ColumnFilterContentSection.tsx new file mode 100644 index 00000000000..4e3fb5fe1f8 --- /dev/null +++ b/src/shared/filters/ColumnFilterContentSection.tsx @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Text, Flex } from '@chakra-ui/react'; +import React from 'react'; + +import { Button } from 'src/toolkit/chakra/button'; + +interface Props { + title: string; + onReset?: () => void; + isFilled?: boolean; + children: React.ReactNode; +} + +const ColumnFilterContentSection = ({ title, onReset, isFilled, children }: Props) => { + return ( + <Flex flexDir="column" rowGap={ 3 }> + <Flex alignItems="center" justifyContent="space-between" columnGap={ 6 }> + <Text color="text.secondary" fontWeight="600">{ title }</Text> + { onReset && ( + <Button + variant="link" + onClick={ onReset } + disabled={ !isFilled } + textStyle="sm" + > + Reset + </Button> + ) } + </Flex> + { children } + </Flex> + ); +}; + +export default React.memo(ColumnFilterContentSection); diff --git a/src/shared/filters/FilterTagsRow.tsx b/src/shared/filters/FilterTagsRow.tsx new file mode 100644 index 00000000000..caf621a300a --- /dev/null +++ b/src/shared/filters/FilterTagsRow.tsx @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { FlexProps } from '@chakra-ui/react'; +import { Flex } from '@chakra-ui/react'; +import React from 'react'; + +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { Link } from 'src/toolkit/chakra/link'; +import { Tag } from 'src/toolkit/chakra/tag'; + +export interface FilterTag<TKey extends string> { + readonly key: TKey; + readonly name: string; + readonly value: string; + readonly isLoading?: boolean; +} + +interface Props<TKey extends string> extends FlexProps { + tags: ReadonlyArray<FilterTag<TKey>>; + onClear: (key: TKey) => void; + onClearAll: () => void; + leadingTags?: React.ReactNode; + placeholderTags?: React.ReactNode; +} + +const FilterTagsRow = <TKey extends string>({ tags, onClear, onClearAll, leadingTags, placeholderTags, ...rest }: Props<TKey>) => { + const handleClear = React.useCallback((key: TKey) => () => onClear(key), [ onClear ]); + + const hasClosableTags = tags.length > 0; + const placeholder = hasClosableTags ? null : placeholderTags; + + if (!hasClosableTags && !leadingTags && !placeholder) { + return null; + } + + return ( + <Flex alignItems="center" flexWrap="wrap" columnGap={ 3 } rowGap={ 2 } { ...rest }> + <Flex alignItems="center" flexWrap="wrap" gap={ 2 } minW={ 0 }> + { leadingTags } + { tags.map((tag) => ( + <Tag key={ tag.key } variant="filter" label={ tag.name } onClose={ handleClear(tag.key) } closable loading={ tag.isLoading }> + { tag.value } + </Tag> + )) } + { placeholder } + </Flex> + { hasClosableTags && ( + <Link onClick={ onClearAll } display="flex" alignItems="center" gap={ 1 } textStyle="sm" whiteSpace="nowrap"> + <SpriteIcon name="repeat" boxSize={ 5 }/> + Reset all + </Link> + ) } + </Flex> + ); +}; + +export default FilterTagsRow; diff --git a/src/shared/filters/TableColumnFilter.tsx b/src/shared/filters/TableColumnFilter.tsx deleted file mode 100644 index d313cf74840..00000000000 --- a/src/shared/filters/TableColumnFilter.tsx +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { - chakra, - Flex, - Text, -} from '@chakra-ui/react'; -import React from 'react'; - -import { Button } from 'src/toolkit/chakra/button'; -import { PopoverCloseTriggerWrapper } from 'src/toolkit/chakra/popover'; - -type Props = { - title: string; - isFilled?: boolean; - isTouched?: boolean; - hasReset?: boolean; - onFilter: () => void; - onReset?: () => void; - children: React.ReactNode; -}; - -const TableColumnFilter = ({ title, isFilled, isTouched, hasReset, onFilter, onReset, children }: Props) => { - const onFilterClick = React.useCallback(() => { - onFilter(); - }, [ onFilter ]); - return ( - <> - <Flex alignItems="center" justifyContent="space-between" columnGap={ 6 }> - <Text color="text.secondary" fontWeight="600">{ title }</Text> - { hasReset && ( - <Button - variant="link" - onClick={ onReset } - disabled={ !isFilled } - textStyle="sm" - > - Reset - </Button> - ) } - </Flex> - { children } - <PopoverCloseTriggerWrapper> - <Button - disabled={ !isTouched } - onClick={ onFilterClick } - w="fit-content" - > - Filter - </Button> - </PopoverCloseTriggerWrapper> - </> - ); -}; - -export default chakra(TableColumnFilter); diff --git a/src/shared/filters/TableColumnFilterWrapper.tsx b/src/shared/filters/TableColumnFilterWrapper.tsx deleted file mode 100644 index 057e685e4e4..00000000000 --- a/src/shared/filters/TableColumnFilterWrapper.tsx +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { chakra } from '@chakra-ui/react'; -import React from 'react'; - -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import { Button } from 'src/toolkit/chakra/button'; -import { PopoverBody, PopoverContent, PopoverRoot, PopoverTrigger } from 'src/toolkit/chakra/popover'; - -interface Props { - columnName: string; - isLoading?: boolean; - selected?: boolean; - className?: string; - children: React.ReactNode; - value?: string; -} - -const TableColumnFilterWrapper = ({ columnName, className, children, isLoading, selected, value }: Props) => { - return ( - <PopoverRoot> - <PopoverTrigger> - <Button - display="inline-flex" - aria-label={ `filter by ${ columnName }` } - variant="icon_secondary" - borderWidth="0" - h="20px" - minW="auto" - disabled={ isLoading } - selected={ selected } - borderRadius="4px" - size="sm" - textStyle="sm" - fontWeight={ 500 } - padding={ 0 } - > - <SpriteIcon name="filter" w="19px" h="19px"/> - { Boolean(value) && <chakra.span>{ value }</chakra.span> } - </Button> - </PopoverTrigger> - <PopoverContent className={ className }> - <PopoverBody display="flex" flexDir="column" rowGap={ 3 }> - { children } - </PopoverBody> - </PopoverContent> - </PopoverRoot> - ); -}; - -export default chakra(TableColumnFilterWrapper); diff --git a/src/shared/hooks/useDebounce.tsx b/src/shared/hooks/useDebounce.ts similarity index 100% rename from src/shared/hooks/useDebounce.tsx rename to src/shared/hooks/useDebounce.ts diff --git a/src/shared/hooks/useIsInitialLoading.tsx b/src/shared/hooks/useIsInitialLoading.ts similarity index 100% rename from src/shared/hooks/useIsInitialLoading.tsx rename to src/shared/hooks/useIsInitialLoading.ts diff --git a/src/shared/hooks/useIsMobile.tsx b/src/shared/hooks/useIsMobile.ts similarity index 100% rename from src/shared/hooks/useIsMobile.tsx rename to src/shared/hooks/useIsMobile.ts diff --git a/src/shared/hooks/useIsMounted.ts b/src/shared/hooks/useIsMounted.ts new file mode 100644 index 00000000000..75c89bf0e1c --- /dev/null +++ b/src/shared/hooks/useIsMounted.ts @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +export default function useIsMounted() { + const [ isMounted, setIsMounted ] = React.useState(false); + + React.useEffect(() => { + // react-doctor-disable-next-line react-doctor/no-initialize-state -- hydration guard: server and first client render must both see false + setIsMounted(true); + }, [ ]); + + return isMounted; +} diff --git a/src/shared/hooks/useIsMounted.tsx b/src/shared/hooks/useIsMounted.tsx deleted file mode 100644 index eb9589d72ca..00000000000 --- a/src/shared/hooks/useIsMounted.tsx +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -export default function useIsMounted() { - const [ isMounted, setIsMounted ] = React.useState(false); - - React.useEffect(() => { - setIsMounted(true); - }, [ ]); - - return isMounted; -} diff --git a/src/shared/hooks/usePreventFocusAfterModalClosing.tsx b/src/shared/hooks/usePreventFocusAfterModalClosing.ts similarity index 100% rename from src/shared/hooks/usePreventFocusAfterModalClosing.tsx rename to src/shared/hooks/usePreventFocusAfterModalClosing.ts diff --git a/src/shared/hooks/useShallowStable.spec.ts b/src/shared/hooks/useShallowStable.spec.ts new file mode 100644 index 00000000000..60c2d53549a --- /dev/null +++ b/src/shared/hooks/useShallowStable.spec.ts @@ -0,0 +1,46 @@ +// @vitest-environment jsdom + +import { describe, it, expect } from 'vitest'; +import { renderHook } from 'vitest/lib'; + +import { useShallowStable } from './useShallowStable'; + +describe('useShallowStable', () => { + it('keeps the first object while every property is identical', () => { + const data = { items: [ 1 ] }; + const { result, rerender } = renderHook((value: object) => useShallowStable(value), { initialProps: { data, count: 1 } }); + const first = result.current; + + rerender({ data, count: 1 }); + + expect(result.current).toBe(first); + }); + + it('returns the new object when a property value changes', () => { + const { result, rerender } = renderHook((value: object) => useShallowStable(value), { initialProps: { count: 1 } }); + const first = result.current; + + rerender({ count: 2 }); + + expect(result.current).not.toBe(first); + expect(result.current).toEqual({ count: 2 }); + }); + + it('returns the new object when the set of keys changes', () => { + const { result, rerender } = renderHook((value: object) => useShallowStable(value), { initialProps: { count: 1 } as object }); + const first = result.current; + + rerender({ count: 1, extra: true }); + + expect(result.current).not.toBe(first); + }); + + it('treats NaN as equal to itself', () => { + const { result, rerender } = renderHook((value: object) => useShallowStable(value), { initialProps: { value: NaN } }); + const first = result.current; + + rerender({ value: NaN }); + + expect(result.current).toBe(first); + }); +}); diff --git a/src/shared/hooks/useShallowStable.ts b/src/shared/hooks/useShallowStable.ts new file mode 100644 index 00000000000..3a388966782 --- /dev/null +++ b/src/shared/hooks/useShallowStable.ts @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +function isShallowEqual(a: object, b: object): boolean { + const keysA = Object.keys(a); + const keysB = Object.keys(b); + if (keysA.length !== keysB.length) { + return false; + } + return keysA.every((key) => Object.is(a[key as keyof typeof a], b[key as keyof typeof b])); +} + +// Keeps the previous object while every own property is identical, so consumers memoized on the +// object (React.memo, useMemo deps) are not invalidated by a re-render that changed nothing. +export function useShallowStable<T extends object>(value: T): T { + const stableRef = React.useRef(value); + if (!isShallowEqual(stableRef.current, value)) { + stableRef.current = value; + } + return stableRef.current; +} diff --git a/src/shared/hooks/useUpdateValueEffect.tsx b/src/shared/hooks/useUpdateValueEffect.ts similarity index 100% rename from src/shared/hooks/useUpdateValueEffect.tsx rename to src/shared/hooks/useUpdateValueEffect.ts diff --git a/src/shared/links/VerifyWith.tsx b/src/shared/links/VerifyWith.tsx index cfc9297329a..cbc4da01453 100644 --- a/src/shared/links/VerifyWith.tsx +++ b/src/shared/links/VerifyWith.tsx @@ -22,7 +22,13 @@ const VerifyWith = ({ className, links, label, longText, shortText }: Props) => const popover = useDisclosure(); return ( - <PopoverRoot open={ popover.open } onOpenChange={ popover.onOpenChange }> + <PopoverRoot + open={ popover.open } + onOpenChange={ popover.onOpenChange } + // We render links to the partner pages in the popover body. + // So it has to be mounted immediately, so search engines can index the links. + lazyMount={ false } + > <Tooltip content={ label } disabled={ popover.open } disableOnMobile closeOnClick> <Box className={ className }> <PopoverTrigger> diff --git a/src/shared/lists/CONTEXT.md b/src/shared/lists/CONTEXT.md new file mode 100644 index 00000000000..dc95e731773 --- /dev/null +++ b/src/shared/lists/CONTEXT.md @@ -0,0 +1,15 @@ +# Lists — context + +Helpers shared by the data lists (tables and their mobile counterparts) that are not about paging. + +## What an editor of a list component must keep true + +- **Row keys come from `useUniqueKeys`, never from a hand-built string.** Any key assembled from item + fields is a guess at uniqueness, and the API has disproved every such guess so far. A duplicated key + is not cosmetic: React never unmounts the shadowed row, so it stays on screen through every subsequent + page (issue #3628). +- **Compute the keys over the full list, then slice.** `useLazyRenderedList` renders a growing window of + the list; keys taken from the sliced array shift as the window grows. +- **A base key must not include the loading state or the array index.** Placeholder rows share a base + key and the ordinal already tells them apart; an index suffix re-introduces the instability under socket + prepends that the ordinal exists to avoid. diff --git a/src/shared/lists/DataList.tsx b/src/shared/lists/DataList.tsx index 3dc12844f11..f40f2eb47cb 100644 --- a/src/shared/lists/DataList.tsx +++ b/src/shared/lists/DataList.tsx @@ -19,6 +19,7 @@ export type Props = { className?: string; hasActiveFilters?: boolean; emptyStateProps?: EmptyStateProps; + isTransitioning?: boolean; }; const DataList = (props: Props) => { @@ -48,7 +49,7 @@ const DataList = (props: Props) => { return ( <> { props.showActionBarIfEmpty && props.actionBar } - { props.emptyText && <Text className={ props.className }>{ props.emptyText }</Text> } + { Boolean(props.emptyText) && <Text className={ props.className }>{ props.emptyText }</Text> } </> ); } @@ -56,7 +57,14 @@ const DataList = (props: Props) => { return ( <Box className={ props.className }> { props.actionBar } - { props.children } + { /* TODO: page-transition look, currently never active — https://github.com/blockscout/frontend/issues/3704 */ } + <Box + opacity={ props.isTransitioning ? 'control.disabled' : undefined } + pointerEvents={ props.isTransitioning ? 'none' : undefined } + aria-busy={ props.isTransitioning || undefined } + > + { props.children } + </Box> </Box> ); }; diff --git a/src/shared/lists/ListItemMobile.tsx b/src/shared/lists/ListItemMobile.tsx deleted file mode 100644 index 5e90cc19047..00000000000 --- a/src/shared/lists/ListItemMobile.tsx +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, chakra } from '@chakra-ui/react'; -import React from 'react'; - -interface Props { - children: React.ReactNode; - className?: string; - animation?: string; -} - -const ListItemMobile = ({ children, className, animation }: Props) => { - return ( - <Flex - animation={ animation } - rowGap={ 6 } - alignItems="flex-start" - flexDirection="column" - paddingY={ 6 } - borderColor="border.divider" - borderTopWidth="1px" - _last={{ - borderBottomWidth: '1px', - }} - className={ className } - fontSize="16px" - lineHeight="20px" - > - { children } - </Flex> - ); -}; - -export default chakra(ListItemMobile); diff --git a/src/shared/lists/ListItemMobileGrid.tsx b/src/shared/lists/ListItemMobileGrid.tsx deleted file mode 100644 index ae3884b9092..00000000000 --- a/src/shared/lists/ListItemMobileGrid.tsx +++ /dev/null @@ -1,81 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Grid, chakra, GridItem } from '@chakra-ui/react'; -import React from 'react'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface ContainerProps { - className?: string; - animation?: string; - children: React.ReactNode; -} - -const Container = chakra(({ animation, children, className }: ContainerProps) => { - return ( - <Grid - w="100%" - animation={ animation } - rowGap={ 2 } - columnGap={ 2 } - gridTemplateColumns="86px auto" - alignItems="start" - paddingY={ 4 } - borderColor="border.divider" - borderTopWidth="1px" - _last={{ - borderBottomWidth: '1px', - }} - className={ className } - textStyle="sm" - > - { children } - </Grid> - ); -}); - -interface LabelProps { - className?: string; - children: React.ReactNode; - isLoading?: boolean; -} - -const Label = chakra(({ children, className, isLoading }: LabelProps) => { - return ( - <Skeleton - className={ className } - loading={ isLoading } - fontWeight={ 500 } - my="5px" - justifySelf="start" - > - { children } - </Skeleton> - ); -}); - -interface ValueProps { - className?: string; - children: React.ReactNode; -} - -const Value = chakra(({ children, className }: ValueProps) => { - return ( - <GridItem - className={ className } - py="5px" - color="text.secondary" - overflow="hidden" - > - { children } - </GridItem> - ); -}); - -const ListItemMobileGrid = { - Container, - Label, - Value, -}; - -export default ListItemMobileGrid; diff --git a/src/shared/lists/TableViewToggleButton.tsx b/src/shared/lists/TableViewToggleButton.tsx deleted file mode 100644 index 1bc831a08f5..00000000000 --- a/src/shared/lists/TableViewToggleButton.tsx +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -// TODO: remove this component once tables in mobile are finalized -import React from 'react'; - -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import { IconButton } from 'src/toolkit/chakra/icon-button'; - -interface Props { - value: boolean; - onClick: () => void; - loading?: boolean; -} - -const TableViewToggleButton = ({ value, onClick, loading }: Props) => { - return ( - <IconButton - size="md" - variant="dropdown" - onClick={ onClick } - selected={ !value } - loadingSkeleton={ loading } - > - <SpriteIcon name="list_view"/> - </IconButton> - ); -}; - -export default React.memo(TableViewToggleButton); diff --git a/src/shared/lists/columns/ColumnListRow.tsx b/src/shared/lists/columns/ColumnListRow.tsx new file mode 100644 index 00000000000..a968377cc04 --- /dev/null +++ b/src/shared/lists/columns/ColumnListRow.tsx @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { HTMLChakraProps } from '@chakra-ui/react'; +import { chakra, Flex } from '@chakra-ui/react'; +import React from 'react'; + +import type { TableColumn } from './types'; + +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { Checkbox } from 'src/toolkit/chakra/checkbox'; + +interface Props { + readonly column: TableColumn; + readonly rowRef?: React.Ref<HTMLDivElement>; + readonly rowStyle?: React.CSSProperties; + readonly handleRef?: React.Ref<HTMLSpanElement>; + readonly handleProps?: HTMLChakraProps<'span'>; + readonly isDragging?: boolean; +} + +const ColumnListRow = ({ column, rowRef, rowStyle, handleRef, handleProps, isDragging }: Props) => { + return ( + <Flex + ref={ rowRef } + style={ rowStyle } + alignItems="center" + gap={ 3 } + position="relative" + zIndex={ isDragging ? 1 : undefined } + bgColor={ isDragging ? 'popover.bg' : undefined } + boxShadow={ isDragging ? 'size.lg' : undefined } + borderRadius="sm" + ml={ -1 } + pl={ 1 } + > + <Checkbox value={ column.id } size="md" w="100%"> + { column.name } + </Checkbox> + <chakra.span + ref={ handleRef } + display="inline-flex" + flexShrink={ 0 } + color={ isDragging ? 'hover' : 'icon.secondary' } + _hover={ handleProps ? { color: 'hover' } : undefined } + cursor={ isDragging ? 'grabbing' : 'grab' } + touchAction="none" + borderRadius="sm" + aria-hidden={ handleProps ? undefined : true } + { ...handleProps } + p={ 1.5 } + > + <SpriteIcon name="move" boxSize={ 5 }/> + </chakra.span> + </Flex> + ); +}; + +export default React.memo(ColumnListRow); diff --git a/src/shared/lists/columns/ColumnListSortable.tsx b/src/shared/lists/columns/ColumnListSortable.tsx new file mode 100644 index 00000000000..3571a87cdad --- /dev/null +++ b/src/shared/lists/columns/ColumnListSortable.tsx @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { DragEndEvent, Modifier } from '@dnd-kit/core'; +import { closestCenter, DndContext, KeyboardSensor, MouseSensor, TouchSensor, useSensor, useSensors } from '@dnd-kit/core'; +import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'; +import { CSS } from '@dnd-kit/utilities'; +import React from 'react'; + +import type { TableColumn } from './types'; + +import ColumnListRow from './ColumnListRow'; + +const MOUSE_ACTIVATION_CONSTRAINT = { distance: 5 }; +const TOUCH_ACTIVATION_CONSTRAINT = { delay: 250, tolerance: 5 }; + +const restrictToVerticalAxis: Modifier = ({ transform }) => ({ ...transform, x: 0 }); +const MODIFIERS = [ restrictToVerticalAxis ]; + +interface Props { + readonly columns: ReadonlyArray<TableColumn>; + readonly onMove: (fromIndex: number, toIndex: number) => void; +} + +interface RowProps { + readonly column: TableColumn; +} + +const ColumnListSortableRow = ({ column }: RowProps) => { + const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id: column.id }); + + const rowStyle = React.useMemo(() => ({ transform: CSS.Translate.toString(transform), transition }), [ transform, transition ]); + const handleProps = React.useMemo( + () => ({ ...attributes, ...listeners, 'aria-label': `Reorder ${ column.name }` }), + [ attributes, listeners, column.name ], + ); + + return ( + <ColumnListRow + column={ column } + rowRef={ setNodeRef } + rowStyle={ rowStyle } + handleRef={ setActivatorNodeRef } + handleProps={ handleProps } + isDragging={ isDragging } + /> + ); +}; + +const ColumnListSortable = ({ columns, onMove }: Props) => { + const id = React.useId(); + const sensors = useSensors( + useSensor(MouseSensor, { activationConstraint: MOUSE_ACTIVATION_CONSTRAINT }), + useSensor(TouchSensor, { activationConstraint: TOUCH_ACTIVATION_CONSTRAINT }), + useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), + ); + + const ids = React.useMemo(() => columns.map((column) => column.id), [ columns ]); + + const handleDragEnd = React.useCallback(({ active, over }: DragEndEvent) => { + const fromIndex = ids.indexOf(String(active.id)); + const toIndex = over ? ids.indexOf(String(over.id)) : -1; + if (fromIndex === -1 || toIndex === -1 || fromIndex === toIndex) { + return; + } + onMove(fromIndex, toIndex); + }, [ ids, onMove ]); + + return ( + <DndContext id={ id } sensors={ sensors } collisionDetection={ closestCenter } modifiers={ MODIFIERS } onDragEnd={ handleDragEnd }> + <SortableContext items={ ids } strategy={ verticalListSortingStrategy }> + { columns.map((column) => <ColumnListSortableRow key={ column.id } column={ column }/>) } + </SortableContext> + </DndContext> + ); +}; + +export default ColumnListSortable; diff --git a/src/shared/lists/columns/ColumnListStatic.tsx b/src/shared/lists/columns/ColumnListStatic.tsx new file mode 100644 index 00000000000..68d96135b4f --- /dev/null +++ b/src/shared/lists/columns/ColumnListStatic.tsx @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { TableColumn } from './types'; + +import ColumnListRow from './ColumnListRow'; + +interface Props { + readonly columns: ReadonlyArray<TableColumn>; +} + +const ColumnListStatic = ({ columns }: Props) => { + return columns.map((column) => <ColumnListRow key={ column.id } column={ column }/>); +}; + +export default ColumnListStatic; diff --git a/src/shared/lists/columns/ColumnsButton.spec.tsx b/src/shared/lists/columns/ColumnsButton.spec.tsx new file mode 100644 index 00000000000..7daa41fb28b --- /dev/null +++ b/src/shared/lists/columns/ColumnsButton.spec.tsx @@ -0,0 +1,199 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor } from 'vitest/lib'; +import flushPromises from 'vitest/utils/flushPromises'; + +import ColumnsButton from './ColumnsButton'; + +type ColumnId = 'hash' | 'from' | 'amount'; + +const TABLE_COLUMNS = [ + { id: 'hash' as const, name: 'Txn hash' }, + { id: 'from' as const, name: 'From' }, + { id: 'amount' as const, name: 'Amount' }, +]; + +const ROW_PITCH = 40; + +const renderOpened = (columns: Record<ColumnId, boolean>) => { + const onChange = vi.fn(); + const onOrderChange = vi.fn(); + render(<ColumnsButton tableColumns={ TABLE_COLUMNS } columns={ columns } onChange={ onChange } onOrderChange={ onOrderChange }/>); + fireEvent.click(screen.getByRole('button', { name: 'Columns' })); + return { onChange, onOrderChange }; +}; + +const renderOpenedWithReset = (selected: boolean) => { + const onReset = vi.fn(); + render( + <ColumnsButton + tableColumns={ TABLE_COLUMNS } + columns={{ hash: true, from: false, amount: true }} + onChange={ vi.fn() } + onOrderChange={ vi.fn() } + selected={ selected } + onReset={ onReset } + />, + ); + fireEvent.click(screen.getByRole('button', { name: 'Columns' })); + return { onReset }; +}; + +const findResetButton = (): Promise<HTMLButtonElement> => screen.findByRole('button', { name: 'Reset', hidden: true }); + +const getCheckbox = (name: string): HTMLInputElement => screen.getByRole('checkbox', { name, hidden: true }); +const isChecked = (name: string): boolean => getCheckbox(name).checked; + +const findSortableHandle = async(name: string): Promise<HTMLElement> => { + const handle = await screen.findByRole('button', { name: `Reorder ${ name }`, hidden: true }); + await waitFor(() => expect(handle.getAttribute('aria-roledescription')).toBe('sortable')); + return handle; +}; + +const pressKey = (element: HTMLElement, code: string) => { + fireEvent.keyDown(element, { code }); +}; + +// the keyboard sensor starts listening for the move and drop keys on the next tick after the pick-up +const pickUp = async(handle: HTMLElement) => { + handle.focus(); + pressKey(handle, 'Space'); + await act(flushPromises); +}; + +const getRowNames = (): Array<string> => screen + .getAllByRole('checkbox', { hidden: true }) + .map((checkbox) => checkbox.closest('label')?.textContent ?? ''); + +// jsdom has no layout, and the keyboard sensor finds the next row by its position +function stackRowsVertically(this: HTMLElement): DOMRect { + const index = this.parentElement ? Array.from(this.parentElement.children).indexOf(this) : 0; + return new DOMRect(0, index * ROW_PITCH, 200, ROW_PITCH - 8); +} + +describe('ColumnsButton', () => { + beforeEach(() => { + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(stackRowsVertically); + }); + + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + }); + + it('renders an icon-only trigger without a text label', () => { + render(<ColumnsButton tableColumns={ TABLE_COLUMNS } columns={{ hash: true, from: true, amount: true }} onChange={ vi.fn() } onOrderChange={ vi.fn() }/>); + + const trigger = screen.getByRole('button', { name: 'Columns' }); + expect(trigger.textContent).toBe(''); + }); + + it('marks the trigger as selected only when asked to', () => { + const { rerender } = render( + <ColumnsButton tableColumns={ TABLE_COLUMNS } columns={{ hash: true }} onChange={ vi.fn() } onOrderChange={ vi.fn() } selected/>, + ); + expect(screen.getByRole('button', { name: 'Columns' }).hasAttribute('data-selected')).toBe(true); + + rerender(<ColumnsButton tableColumns={ TABLE_COLUMNS } columns={{ hash: true }} onChange={ vi.fn() } onOrderChange={ vi.fn() }/>); + expect(screen.getByRole('button', { name: 'Columns' }).hasAttribute('data-selected')).toBe(false); + }); + + it('offers every table column by its display name, checked per the current selection', async() => { + renderOpened({ hash: true, from: false, amount: true }); + + await screen.findByText('Txn hash'); + expect(isChecked('Txn hash')).toBe(true); + expect(isChecked('From')).toBe(false); + expect(isChecked('Amount')).toBe(true); + }); + + it('emits the selection with a column switched off', async() => { + const { onChange } = renderOpened({ hash: true, from: true, amount: true }); + + await screen.findByText('From'); + fireEvent.click(getCheckbox('From')); + + await waitFor(() => expect(onChange).toHaveBeenLastCalledWith({ hash: true, from: false, amount: true })); + }); + + it('emits the selection with a column switched on', async() => { + const { onChange } = renderOpened({ hash: true, from: false, amount: false }); + + await screen.findByText('Amount'); + fireEvent.click(getCheckbox('Amount')); + + await waitFor(() => expect(onChange).toHaveBeenLastCalledWith({ hash: true, from: false, amount: true })); + }); + + it('offers no Reset without a reset handler', async() => { + renderOpened({ hash: true, from: true, amount: true }); + + await screen.findByText('Txn hash'); + expect(screen.queryByRole('button', { name: 'Reset', hidden: true })).toBeNull(); + }); + + it('resets the columns from the selector when they are customized', async() => { + const { onReset } = renderOpenedWithReset(true); + + const resetButton = await findResetButton(); + expect(resetButton.disabled).toBe(false); + fireEvent.click(resetButton); + + expect(onReset).toHaveBeenCalledTimes(1); + }); + + it('disables Reset while the columns are the defaults', async() => { + renderOpenedWithReset(false); + + expect((await findResetButton()).disabled).toBe(true); + }); + + it('lists the columns in the given order, one handle per row', async() => { + renderOpened({ hash: true, from: false, amount: true }); + + await findSortableHandle('Txn hash'); + expect(getRowNames()).toEqual([ 'Txn hash', 'From', 'Amount' ]); + expect(screen.getAllByRole('button', { name: /^Reorder/, hidden: true })).toHaveLength(TABLE_COLUMNS.length); + }); + + it('moves a column down with the keyboard and reports the new order', async() => { + const { onOrderChange } = renderOpened({ hash: true, from: true, amount: true }); + + const handle = await findSortableHandle('Txn hash'); + await pickUp(handle); + pressKey(handle, 'ArrowDown'); + pressKey(handle, 'Space'); + + await waitFor(() => expect(onOrderChange).toHaveBeenCalledWith([ 'from', 'hash', 'amount' ], 'hash')); + expect(onOrderChange).toHaveBeenCalledTimes(1); + }); + + it('moves a hidden column up with the keyboard', async() => { + const { onOrderChange } = renderOpened({ hash: true, from: true, amount: false }); + + const handle = await findSortableHandle('Amount'); + await pickUp(handle); + pressKey(handle, 'ArrowUp'); + pressKey(handle, 'ArrowUp'); + pressKey(handle, 'Space'); + + await waitFor(() => expect(onOrderChange).toHaveBeenCalledWith([ 'amount', 'hash', 'from' ], 'amount')); + }); + + it('reports nothing when a column is dropped where it was picked up', async() => { + const { onOrderChange, onChange } = renderOpened({ hash: true, from: true, amount: true }); + + const handle = await findSortableHandle('From'); + await pickUp(handle); + pressKey(handle, 'ArrowDown'); + pressKey(handle, 'ArrowUp'); + pressKey(handle, 'Space'); + + await waitFor(() => expect(handle.getAttribute('aria-pressed')).not.toBe('true')); + expect(onOrderChange).not.toHaveBeenCalled(); + expect(onChange).not.toHaveBeenCalled(); + }); +}); diff --git a/src/shared/lists/columns/ColumnsButton.tsx b/src/shared/lists/columns/ColumnsButton.tsx new file mode 100644 index 00000000000..1693ba4ebbe --- /dev/null +++ b/src/shared/lists/columns/ColumnsButton.tsx @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Box, Flex } from '@chakra-ui/react'; +import dynamic from 'next/dynamic'; +import React from 'react'; + +import type { ColumnVisibility, TableColumn } from './types'; + +import useIsMobile from 'src/shared/hooks/useIsMobile'; +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { Button } from 'src/toolkit/chakra/button'; +import { CheckboxGroup } from 'src/toolkit/chakra/checkbox'; +import { DrawerBody, DrawerCloseTrigger, DrawerContent, DrawerHeader, DrawerRoot, DrawerTitle, DrawerTrigger } from 'src/toolkit/chakra/drawer'; +import { IconButton } from 'src/toolkit/chakra/icon-button'; +import { PopoverBody, PopoverContent, PopoverRoot, PopoverTrigger } from 'src/toolkit/chakra/popover'; + +import ColumnListStatic from './ColumnListStatic'; + +const ColumnListContext = React.createContext<ReadonlyArray<TableColumn>>([]); + +const ColumnListLoading = () => <ColumnListStatic columns={ React.useContext(ColumnListContext) }/>; + +const ColumnListSortable = dynamic(() => import('./ColumnListSortable'), { ssr: false, loading: ColumnListLoading }); + +interface Props<TColumnId extends string> { + readonly tableColumns: ReadonlyArray<TableColumn<TColumnId>>; + readonly columns: ColumnVisibility<TColumnId>; + readonly onChange: (checkedColumns: ColumnVisibility<TColumnId>) => void; + readonly onOrderChange: (ids: Array<TColumnId>, movedId: TColumnId) => void; + readonly selected?: boolean; + readonly onReset?: () => void; + readonly isLoading?: boolean; +} + +const ColumnsButton = <TColumnId extends string>({ + tableColumns, + columns, + onChange, + onOrderChange, + selected, + onReset, + isLoading, +}: Props<TColumnId>) => { + + const isMobile = useIsMobile(); + + const handleValueChange = React.useCallback((value: Array<string>) => { + const checkedColumns: ColumnVisibility<TColumnId> = {}; + tableColumns.forEach(({ id }) => { + checkedColumns[id] = value.includes(id); + }); + onChange(checkedColumns); + }, [ tableColumns, onChange ]); + + const handleMove = React.useCallback((fromIndex: number, toIndex: number) => { + const ids = tableColumns.map(({ id }) => id); + const [ movedId ] = ids.splice(fromIndex, 1); + ids.splice(toIndex, 0, movedId); + onOrderChange(ids, movedId); + }, [ tableColumns, onOrderChange ]); + + const value = React.useMemo(() => tableColumns.filter(({ id }) => columns[id]).map(({ id }) => id), [ tableColumns, columns ]); + + const resetButton = onReset && ( + <Button + variant="link" + onClick={ onReset } + disabled={ !selected } + textStyle="sm" + > + Reset + </Button> + ); + + const checkboxes = ( + <CheckboxGroup value={ value } onValueChange={ handleValueChange } gap={ 2 } w={{ base: 'full', lg: '200px' }}> + <ColumnListContext.Provider value={ tableColumns }> + <ColumnListSortable columns={ tableColumns } onMove={ handleMove }/> + </ColumnListContext.Provider> + </CheckboxGroup> + ); + + const trigger = ( + <IconButton + variant="dropdown" + size="md" + aria-label="Columns" + selected={ selected } + loadingSkeleton={ isLoading } + > + <SpriteIcon name="columns"/> + </IconButton> + ); + + if (isMobile) { + return ( + <DrawerRoot placement="bottom"> + <DrawerTrigger> + { trigger } + </DrawerTrigger> + <DrawerContent> + <DrawerHeader> + <DrawerTitle> + <Flex justifyContent="space-between"> + Columns + { resetButton } + </Flex> + </DrawerTitle> + <DrawerCloseTrigger/> + </DrawerHeader> + <DrawerBody> + { checkboxes } + </DrawerBody> + </DrawerContent> + </DrawerRoot> + ); + } + + return ( + <PopoverRoot> + <PopoverTrigger> + { trigger } + </PopoverTrigger> + <PopoverContent> + <PopoverBody> + <Flex justifyContent="space-between" textStyle="sm" mb={ 3 }> + <Box fontWeight={ 600 } color="text.secondary">Columns</Box> + { resetButton } + </Flex> + { checkboxes } + </PopoverBody> + </PopoverContent> + </PopoverRoot> + ); +}; + +export default ColumnsButton; diff --git a/src/shared/lists/columns/column-overrides.spec.ts b/src/shared/lists/columns/column-overrides.spec.ts new file mode 100644 index 00000000000..79950c10e2d --- /dev/null +++ b/src/shared/lists/columns/column-overrides.spec.ts @@ -0,0 +1,188 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { ColumnStates } from './types'; + +import { describe, expect, it } from 'vitest'; + +import { + getAvailableColumns, + getDefaultColumnIds, + getOrderedColumns, + getVisibleColumnIds, + parseColumnOverrides, + serializeColumnOverrides, + setColumnOrder, + setColumnVisibility, +} from './column-overrides'; + +type ColumnId = 'hash' | 'block' | 'from' | 'amount' | 'fee'; + +const COLUMNS = [ + { id: 'hash' as const, name: 'Hash' }, + { id: 'block' as const, name: 'Block' }, + { id: 'from' as const, name: 'From' }, + { id: 'amount' as const, name: 'Amount' }, + { id: 'fee' as const, name: 'Fee' }, +]; +const COLUMN_IDS = COLUMNS.map(({ id }) => id); + +const STATES: ColumnStates<ColumnId> = { hash: 'on', block: 'off', from: 'on', amount: 'on', fee: 'unavailable' }; +const AVAILABLE_COLUMNS = getAvailableColumns(COLUMNS, STATES); + +const getOrderedIds = (order: ReadonlyArray<ColumnId> | undefined) => getOrderedColumns(AVAILABLE_COLUMNS, order).map(({ id }) => id); + +describe('parseColumnOverrides', () => { + it('reads nothing stored as no overrides', () => { + expect(parseColumnOverrides(null, COLUMN_IDS)).toBeUndefined(); + expect(parseColumnOverrides('', COLUMN_IDS)).toBeUndefined(); + }); + + it('reads invalid JSON or a non-object value as no overrides', () => { + expect(parseColumnOverrides('{not json', COLUMN_IDS)).toBeUndefined(); + expect(parseColumnOverrides('[ "block" ]', COLUMN_IDS)).toBeUndefined(); + expect(parseColumnOverrides('42', COLUMN_IDS)).toBeUndefined(); + expect(parseColumnOverrides('null', COLUMN_IDS)).toBeUndefined(); + }); + + it('drops unknown columns and non-boolean states', () => { + const value = JSON.stringify({ visibility: { block: true, foo: true, amount: 'off', from: false } }); + + expect(parseColumnOverrides(value, COLUMN_IDS)).toEqual({ visibility: { block: true, from: false } }); + }); + + it('reads the stored order without unknown or repeated columns', () => { + const value = JSON.stringify({ order: [ 'amount', 'foo', 'hash', 'amount', 42 ] }); + + expect(parseColumnOverrides(value, COLUMN_IDS)).toEqual({ order: [ 'amount', 'hash' ] }); + }); + + it('keeps a known column unavailable today, so the setting survives where it is available', () => { + expect(parseColumnOverrides(JSON.stringify({ visibility: { fee: false }, order: [ 'fee' ] }), COLUMN_IDS)).toEqual({ + visibility: { fee: false }, + order: [ 'fee' ], + }); + }); + + it('reads a value with nothing valid left as no overrides', () => { + expect(parseColumnOverrides(JSON.stringify({ visibility: { foo: true }, order: 'amount' }), COLUMN_IDS)).toBeUndefined(); + expect(parseColumnOverrides(JSON.stringify({ order: [ 'foo' ] }), COLUMN_IDS)).toBeUndefined(); + }); + + it('reads back what was serialised', () => { + const overrides = { visibility: { block: true, hash: false }, order: [ 'amount' as const, 'hash' as const ] }; + + expect(parseColumnOverrides(serializeColumnOverrides(overrides), COLUMN_IDS)).toEqual(overrides); + }); +}); + +describe('getAvailableColumns', () => { + it('offers every column but the unavailable ones, in registry order', () => { + expect(AVAILABLE_COLUMNS.map(({ id }) => id)).toEqual([ 'hash', 'block', 'from', 'amount' ]); + }); +}); + +describe('getDefaultColumnIds', () => { + it('shows only the on-by-default columns, in registry order', () => { + expect(getDefaultColumnIds(COLUMNS, STATES)).toEqual([ 'hash', 'from', 'amount' ]); + }); +}); + +describe('setColumnVisibility', () => { + it('records hiding an on-by-default column', () => { + expect(setColumnVisibility(undefined, STATES, 'hash', false)).toEqual({ visibility: { hash: false } }); + }); + + it('records showing an off-by-default column', () => { + expect(setColumnVisibility(undefined, STATES, 'block', true)).toEqual({ visibility: { block: true } }); + }); + + it('drops the entry when a column returns to its default', () => { + expect(setColumnVisibility({ visibility: { block: true, hash: false } }, STATES, 'block', false)).toEqual({ + visibility: { hash: false }, + }); + }); + + it('leaves nothing stored when the last override returns to the default', () => { + expect(setColumnVisibility({ visibility: { block: true } }, STATES, 'block', false)).toBeUndefined(); + }); + + it('keeps the order when the visibility returns to the default', () => { + expect(setColumnVisibility({ visibility: { block: true }, order: [ 'amount' ] }, STATES, 'block', false)).toEqual({ + order: [ 'amount' ], + }); + }); +}); + +describe('setColumnOrder', () => { + it('records the full order of the available columns', () => { + expect(setColumnOrder(undefined, AVAILABLE_COLUMNS, [ 'amount', 'hash', 'block', 'from' ])).toEqual({ + order: [ 'amount', 'hash', 'block', 'from' ], + }); + }); + + it('completes a partial order with the remaining columns at their default positions', () => { + expect(setColumnOrder(undefined, AVAILABLE_COLUMNS, [ 'amount', 'hash' ])).toEqual({ + order: [ 'amount', 'hash', 'block', 'from' ], + }); + }); + + it('drops the order when it matches the default, keeping the visibility', () => { + expect(setColumnOrder({ visibility: { hash: false }, order: [ 'amount' ] }, AVAILABLE_COLUMNS, [ 'hash', 'block', 'from', 'amount' ])).toEqual({ + visibility: { hash: false }, + }); + }); + + it('leaves nothing stored when the default order is the only override', () => { + expect(setColumnOrder({ order: [ 'amount' ] }, AVAILABLE_COLUMNS, [])).toBeUndefined(); + }); +}); + +describe('getOrderedColumns', () => { + it('returns the available columns in default order without a stored order', () => { + expect(getOrderedIds(undefined)).toEqual([ 'hash', 'block', 'from', 'amount' ]); + }); + + it('follows the stored order', () => { + expect(getOrderedIds([ 'amount', 'from', 'block', 'hash' ])).toEqual([ 'amount', 'from', 'block', 'hash' ]); + }); + + it('drops stored columns that are unavailable', () => { + expect(getOrderedIds([ 'fee', 'amount', 'hash', 'block', 'from' ])).toEqual([ 'amount', 'hash', 'block', 'from' ]); + }); + + it('puts a column missing from the stored order back after its default predecessor', () => { + expect(getOrderedIds([ 'amount', 'block', 'hash' ])).toEqual([ 'amount', 'block', 'from', 'hash' ]); + }); + + it('puts a column without a default predecessor back first', () => { + expect(getOrderedIds([ 'amount', 'from', 'block' ])).toEqual([ 'hash', 'amount', 'from', 'block' ]); + }); + + it('keeps consecutive missing columns together in default order', () => { + expect(getOrderedIds([ 'amount', 'hash' ])).toEqual([ 'amount', 'hash', 'block', 'from' ]); + }); +}); + +describe('getVisibleColumnIds', () => { + it('returns the defaults when there are no overrides', () => { + expect(getVisibleColumnIds(AVAILABLE_COLUMNS, STATES, undefined)).toEqual([ 'hash', 'from', 'amount' ]); + }); + + it('lets columns absent from the overrides follow the current defaults', () => { + expect(getVisibleColumnIds(AVAILABLE_COLUMNS, STATES, { visibility: { block: true, amount: false } })).toEqual( + [ 'hash', 'block', 'from' ], + ); + }); + + it('applies the visibility and the order together', () => { + expect(getVisibleColumnIds(AVAILABLE_COLUMNS, STATES, { visibility: { block: true, hash: false }, order: [ 'amount', 'block' ] })).toEqual( + [ 'amount', 'block', 'from' ], + ); + }); + + it('never shows an unavailable column', () => { + expect(getVisibleColumnIds(AVAILABLE_COLUMNS, STATES, { visibility: { fee: true }, order: [ 'fee' ] })).toEqual( + [ 'hash', 'from', 'amount' ], + ); + }); +}); diff --git a/src/shared/lists/columns/column-overrides.ts b/src/shared/lists/columns/column-overrides.ts new file mode 100644 index 00000000000..59e2c467523 --- /dev/null +++ b/src/shared/lists/columns/column-overrides.ts @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { isEqual, isPlainObject, omit, uniq } from 'es-toolkit'; + +import type { ColumnOverrides, ColumnStates, ColumnVisibility, TableColumn } from './types'; + +const NO_VISIBILITY: ColumnVisibility<string> = {}; + +type ColumnIdGuard<TColumnId extends string> = (key: unknown) => key is TColumnId; + +function parseVisibility<TColumnId extends string>( + value: unknown, + isColumnId: ColumnIdGuard<TColumnId>, +): ColumnVisibility<TColumnId> | undefined { + if (!isPlainObject(value)) { + return; + } + + const entries = Object.entries(value).filter(([ key, isVisible ]) => isColumnId(key) && typeof isVisible === 'boolean'); + return Object.fromEntries(entries) as ColumnVisibility<TColumnId>; +} + +function parseOrder<TColumnId extends string>( + value: unknown, + isColumnId: ColumnIdGuard<TColumnId>, +): ReadonlyArray<TColumnId> | undefined { + if (!Array.isArray(value)) { + return; + } + + const order = uniq(value.filter(isColumnId)); + return order.length > 0 ? order : undefined; +} + +function buildOverrides<TColumnId extends string>( + visibility: ColumnVisibility<TColumnId> | undefined, + order: ReadonlyArray<TColumnId> | undefined, +): ColumnOverrides<TColumnId> | undefined { + const hasVisibility = visibility !== undefined && Object.keys(visibility).length > 0; + if (!hasVisibility && !order) { + return; + } + + return { + ...(hasVisibility ? { visibility } : {}), + ...(order ? { order } : {}), + }; +} + +export function parseColumnOverrides<TColumnId extends string>( + rawValue: string | null, + columnIds: ReadonlyArray<TColumnId>, +): ColumnOverrides<TColumnId> | undefined { + // Stryker disable next-line ConditionalExpression: narrows `string | null` for JSON.parse; null and '' read as no overrides either way + if (!rawValue) { + return; + } + + const isColumnId = (key: unknown): key is TColumnId => columnIds.includes(key as TColumnId); + + try { + const parsed: unknown = JSON.parse(rawValue); + // Stryker disable next-line ConditionalExpression: narrows `unknown` for the property reads below; a non-object reads as no overrides either way + if (!isPlainObject(parsed)) { + return; + } + + return buildOverrides(parseVisibility(parsed.visibility, isColumnId), parseOrder(parsed.order, isColumnId)); + } catch { + return; + } +} + +export function serializeColumnOverrides<TColumnId extends string>(overrides: ColumnOverrides<TColumnId>): string { + return JSON.stringify(overrides); +} + +export function getAvailableColumns<TColumn extends TableColumn<TColumnId>, TColumnId extends string = TColumn['id']>( + columns: ReadonlyArray<TColumn>, + states: ColumnStates<NoInfer<TColumnId>>, +): ReadonlyArray<TColumn> { + return columns.filter(({ id }) => states[id] !== 'unavailable'); +} + +export function getDefaultColumnIds<TColumn extends TableColumn<TColumnId>, TColumnId extends string = TColumn['id']>( + columns: ReadonlyArray<TColumn>, + states: ColumnStates<NoInfer<TColumnId>>, +): ReadonlyArray<TColumnId> { + return columns.filter(({ id }) => states[id] === 'on').map(({ id }) => id); +} + +export function getOrderedColumns<TColumn extends TableColumn<TColumnId>, TColumnId extends string = TColumn['id']>( + availableColumns: ReadonlyArray<TColumn>, + order: ReadonlyArray<NoInfer<TColumnId>> | undefined, +): ReadonlyArray<TColumn> { + if (!order) { + return availableColumns; + } + + const orderedColumns = order + .map((id) => availableColumns.find((column) => column.id === id)) + .filter((column) => column !== undefined); + + availableColumns.forEach((column, defaultIndex) => { + if (order.includes(column.id)) { + return; + } + + const precedingColumn = availableColumns.slice(0, defaultIndex).findLast((item) => orderedColumns.includes(item)); + orderedColumns.splice(precedingColumn ? orderedColumns.indexOf(precedingColumn) + 1 : 0, 0, column); + }); + + return orderedColumns; +} + +export function getVisibleColumnIds<TColumn extends TableColumn<TColumnId>, TColumnId extends string = TColumn['id']>( + availableColumns: ReadonlyArray<TColumn>, + states: ColumnStates<NoInfer<TColumnId>>, + overrides: ColumnOverrides<NoInfer<TColumnId>> | undefined, +): ReadonlyArray<TColumnId> { + const visibility: ColumnVisibility<TColumnId> = overrides?.visibility ?? NO_VISIBILITY; + return getOrderedColumns(availableColumns, overrides?.order) + .filter(({ id }) => visibility[id] ?? states[id] === 'on') + .map(({ id }) => id); +} + +export function setColumnVisibility<TColumnId extends string>( + overrides: ColumnOverrides<NoInfer<TColumnId>> | undefined, + states: ColumnStates<TColumnId>, + columnId: NoInfer<TColumnId>, + isVisible: boolean, +): ColumnOverrides<TColumnId> | undefined { + const currentVisibility: ColumnVisibility<TColumnId> = overrides?.visibility ?? NO_VISIBILITY; + const otherColumns = omit(currentVisibility, [ columnId ]) as ColumnVisibility<TColumnId>; + const isDefault = isVisible === (states[columnId] === 'on'); + const visibility: ColumnVisibility<TColumnId> = isDefault ? otherColumns : { ...otherColumns, [columnId]: isVisible }; + + return buildOverrides(visibility, overrides?.order); +} + +export function setColumnOrder<TColumn extends TableColumn<TColumnId>, TColumnId extends string = TColumn['id']>( + overrides: ColumnOverrides<NoInfer<TColumnId>> | undefined, + availableColumns: ReadonlyArray<TColumn>, + order: ReadonlyArray<NoInfer<TColumnId>>, +): ColumnOverrides<TColumnId> | undefined { + const nextOrder = getOrderedColumns(availableColumns, order).map(({ id }) => id); + const isDefault = isEqual(nextOrder, availableColumns.map(({ id }) => id)); + + return buildOverrides(overrides?.visibility, isDefault ? undefined : nextOrder); +} diff --git a/src/shared/lists/columns/column-storage.spec.ts b/src/shared/lists/columns/column-storage.spec.ts new file mode 100644 index 00000000000..0f15d2c03fc --- /dev/null +++ b/src/shared/lists/columns/column-storage.spec.ts @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { readColumnStorage, subscribeToColumnStorage, writeColumnStorage } from './column-storage'; + +const KEY = 'table_columns_test'; +const OTHER_KEY = 'table_columns_other'; + +afterEach(() => { + vi.restoreAllMocks(); + writeColumnStorage(KEY, null); + writeColumnStorage(OTHER_KEY, null); +}); + +describe('column storage', () => { + it('reads back a written value and nothing after it is removed', () => { + writeColumnStorage(KEY, '{"order":["a"]}'); + expect(readColumnStorage(KEY)).toBe('{"order":["a"]}'); + expect(window.localStorage.getItem(KEY)).toBe('{"order":["a"]}'); + + writeColumnStorage(KEY, null); + expect(readColumnStorage(KEY)).toBeNull(); + expect(window.localStorage.getItem(KEY)).toBeNull(); + }); + + it('notifies the subscribers of the written key only', () => { + const listener = vi.fn(); + const otherListener = vi.fn(); + subscribeToColumnStorage(KEY, listener); + subscribeToColumnStorage(OTHER_KEY, otherListener); + + writeColumnStorage(KEY, '{}'); + + expect(listener).toHaveBeenCalledTimes(1); + expect(otherListener).not.toHaveBeenCalled(); + }); + + it('notifies every subscriber of the same key', () => { + const first = vi.fn(); + const second = vi.fn(); + subscribeToColumnStorage(KEY, first); + subscribeToColumnStorage(KEY, second); + + writeColumnStorage(KEY, '{}'); + + expect(first).toHaveBeenCalledTimes(1); + expect(second).toHaveBeenCalledTimes(1); + }); + + it('stops notifying after unsubscribe', () => { + const listener = vi.fn(); + const unsubscribe = subscribeToColumnStorage(KEY, listener); + unsubscribe(); + + writeColumnStorage(KEY, '{}'); + window.dispatchEvent(new StorageEvent('storage', { key: KEY })); + + expect(listener).not.toHaveBeenCalled(); + }); + + it('notifies on a change of the key made in another tab, or on a storage clear', () => { + const listener = vi.fn(); + subscribeToColumnStorage(KEY, listener); + + window.dispatchEvent(new StorageEvent('storage', { key: OTHER_KEY })); + expect(listener).not.toHaveBeenCalled(); + + window.dispatchEvent(new StorageEvent('storage', { key: KEY })); + window.dispatchEvent(new StorageEvent('storage', { key: null })); + expect(listener).toHaveBeenCalledTimes(2); + }); + + it('keeps the value for the session when storage refuses the write', () => { + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('quota', 'QuotaExceededError'); + }); + const listener = vi.fn(); + subscribeToColumnStorage(KEY, listener); + + writeColumnStorage(KEY, '{"order":["a"]}'); + + expect(readColumnStorage(KEY)).toBe('{"order":["a"]}'); + expect(listener).toHaveBeenCalledTimes(1); + }); + + it('keeps the removal for the session when storage refuses it', () => { + writeColumnStorage(KEY, '{}'); + vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => { + throw new DOMException('denied', 'SecurityError'); + }); + + writeColumnStorage(KEY, null); + + expect(readColumnStorage(KEY)).toBeNull(); + }); + + it('reads nothing stored when storage access throws', () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new DOMException('denied', 'SecurityError'); + }); + + expect(readColumnStorage(KEY)).toBeNull(); + }); + + it('returns to storage once a write succeeds again', () => { + const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementationOnce(() => { + throw new DOMException('quota', 'QuotaExceededError'); + }); + writeColumnStorage(KEY, '{"order":["a"]}'); + setItem.mockRestore(); + + writeColumnStorage(KEY, '{"order":["b"]}'); + window.localStorage.setItem(KEY, '{"order":["c"]}'); + + expect(readColumnStorage(KEY)).toBe('{"order":["c"]}'); + }); +}); diff --git a/src/shared/lists/columns/column-storage.ts b/src/shared/lists/columns/column-storage.ts new file mode 100644 index 00000000000..cbe3d82c4d1 --- /dev/null +++ b/src/shared/lists/columns/column-storage.ts @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +type Listener = () => void; + +// Safari private mode and storage-disabled browsers throw on access or on write; +// the session then keeps its values here instead +const memoryStore = new Map<string, string | null>(); +const listeners = new Map<string, Set<Listener>>(); + +function notify(key: string): void { + listeners.get(key)?.forEach((listener) => listener()); +} + +export function readColumnStorage(key: string): string | null { + if (memoryStore.has(key)) { + return memoryStore.get(key) ?? null; + } + + try { + return window.localStorage.getItem(key); + } catch { + return null; + } +} + +export function writeColumnStorage(key: string, value: string | null): void { + try { + if (value === null) { + window.localStorage.removeItem(key); + } else { + window.localStorage.setItem(key, value); + } + memoryStore.delete(key); + } catch { + memoryStore.set(key, value); + } + notify(key); +} + +export function subscribeToColumnStorage(key: string, listener: Listener): () => void { + const keyListeners = listeners.get(key) ?? new Set<Listener>(); + keyListeners.add(listener); + listeners.set(key, keyListeners); + + const handleStorage = (event: StorageEvent) => { + if (event.key === key || event.key === null) { + listener(); + } + }; + window.addEventListener('storage', handleStorage); + + return () => { + keyListeners.delete(listener); + window.removeEventListener('storage', handleStorage); + }; +} diff --git a/src/shared/lists/columns/types.ts b/src/shared/lists/columns/types.ts new file mode 100644 index 00000000000..cd8580f5154 --- /dev/null +++ b/src/shared/lists/columns/types.ts @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +export interface TableColumn<TColumnId extends string = string> { + readonly id: TColumnId; + readonly name: string; +} + +export type ColumnState = 'on' | 'off' | 'unavailable'; + +export type ColumnStates<TColumnId extends string> = Readonly<Record<TColumnId, ColumnState>>; + +export type ColumnVisibility<TColumnId extends string> = Partial<Record<TColumnId, boolean>>; + +export interface ColumnOverrides<TColumnId extends string> { + readonly visibility?: ColumnVisibility<TColumnId>; + readonly order?: ReadonlyArray<TColumnId>; +} diff --git a/src/shared/lists/columns/usePersistedColumns.spec.tsx b/src/shared/lists/columns/usePersistedColumns.spec.tsx new file mode 100644 index 00000000000..feb21908a11 --- /dev/null +++ b/src/shared/lists/columns/usePersistedColumns.spec.tsx @@ -0,0 +1,357 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import mixpanel from 'mixpanel-browser'; +import React from 'react'; +import { hydrateRoot } from 'react-dom/client'; +import { renderToString } from 'react-dom/server'; + +import type { ColumnStates } from './types'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, renderHook } from 'vitest/lib'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import type { TableColumnsAnalytics } from './usePersistedColumns'; + +vi.mock('mixpanel-browser', () => ({ 'default': { init: vi.fn(), track: vi.fn() } })); + +type ColumnId = 'hash' | 'block' | 'from' | 'amount' | 'fee'; + +const STORAGE_KEY = 'table_columns_test'; + +const COLUMNS = [ + { id: 'hash' as const, name: 'Hash' }, + { id: 'block' as const, name: 'Block' }, + { id: 'from' as const, name: 'From' }, + { id: 'amount' as const, name: 'Amount' }, + { id: 'fee' as const, name: 'Fee' }, +]; + +const STATES: ColumnStates<ColumnId> = { hash: 'on', block: 'off', from: 'on', amount: 'on', fee: 'unavailable' }; + +const TABLE_ANALYTICS: TableColumnsAnalytics = { Table: 'Advanced filter' }; +const SURFACE_ANALYTICS: TableColumnsAnalytics = { Table: 'Token transfers', Surface: 'index' }; + +const store = (value: unknown) => { + window.localStorage.setItem(STORAGE_KEY, typeof value === 'string' ? value : JSON.stringify(value)); +}; + +const readStored = () => window.localStorage.getItem(STORAGE_KEY); + +const withMixpanel = (run: () => Promise<void>) => withEnvs([ [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', 'test-mixpanel' ] ], run); + +const importHook = async() => { + const { init } = await import('src/shared/analytics/queue'); + const { getEnabledProviders } = await import('src/shared/analytics/providers'); + await init(getEnabledProviders().map((provider) => ({ provider, options: { debug: false } })), () => {}); + return (await import('./usePersistedColumns')).usePersistedColumns; +}; + +const renderColumnsHook = async(analytics: TableColumnsAnalytics = TABLE_ANALYTICS) => { + const usePersistedColumns = await importHook(); + return renderHook(() => usePersistedColumns({ storageKey: STORAGE_KEY, columns: COLUMNS, states: STATES, analytics })); +}; + +const renderColumnsProbe = async() => { + const usePersistedColumns = await importHook(); + const ColumnsProbe = () => { + const { columns } = usePersistedColumns({ storageKey: STORAGE_KEY, columns: COLUMNS, states: STATES, analytics: TABLE_ANALYTICS }); + return <div data-testid="columns">{ columns.join(',') }</div>; + }; + return ColumnsProbe; +}; + +afterEach(() => { + cleanup(); + window.localStorage.clear(); + vi.restoreAllMocks(); + vi.clearAllMocks(); +}); + +describe('usePersistedColumns', () => { + it('shows the defaults and offers only the available columns when nothing is stored', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + + expect(result.current.columns).toEqual([ 'hash', 'from', 'amount' ]); + expect(result.current.selectableColumns.map(({ id }) => id)).toEqual([ 'hash', 'block', 'from', 'amount' ]); + expect(result.current.checkedColumns).toEqual({ hash: true, from: true, amount: true }); + expect(result.current.isCustomized).toBe(false); + }); + }); + + it('renders the defaults on the server whatever is stored', async() => { + store({ visibility: { hash: false }, order: [ 'amount', 'hash', 'block', 'from' ] }); + + await withMixpanel(async() => { + const ColumnsProbe = await renderColumnsProbe(); + + expect(renderToString(<ColumnsProbe/>)).toContain('hash,from,amount'); + }); + }); + + it('hydrates the server markup without a warning and switches to the stored columns', async() => { + store({ visibility: { hash: false }, order: [ 'amount', 'hash', 'block', 'from' ] }); + const consoleError = vi.spyOn(console, 'error'); + + await withMixpanel(async() => { + const ColumnsProbe = await renderColumnsProbe(); + const container = document.createElement('div'); + container.innerHTML = renderToString(<ColumnsProbe/>); + document.body.appendChild(container); + + const root = await act(async() => hydrateRoot(container, <ColumnsProbe/>, { onRecoverableError: consoleError })); + + expect(container.textContent).toBe('amount,from'); + expect(consoleError).not.toHaveBeenCalled(); + act(() => root.unmount()); + container.remove(); + }); + }); + + it('starts from the stored columns on the first client render', async() => { + store({ visibility: { block: true }, order: [ 'amount', 'block', 'hash', 'from' ] }); + + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + + expect(result.current.columns).toEqual([ 'amount', 'block', 'hash', 'from' ]); + expect(result.current.isCustomized).toBe(true); + }); + }); + + it('reads invalid JSON as no overrides', async() => { + store('{not json'); + + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + + expect(result.current.columns).toEqual([ 'hash', 'from', 'amount' ]); + expect(result.current.isCustomized).toBe(false); + }); + }); + + it('stores a toggle and shows it in every table using the same key', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + const { result: otherTable } = await renderColumnsHook(); + + act(() => { + result.current.onColumnsChange({ ...result.current.checkedColumns, block: true }); + }); + + expect(result.current.columns).toEqual([ 'hash', 'block', 'from', 'amount' ]); + expect(otherTable.current.columns).toEqual([ 'hash', 'block', 'from', 'amount' ]); + expect(JSON.parse(readStored() ?? '')).toEqual({ visibility: { block: true } }); + }); + }); + + it('applies a change made in another tab', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + + act(() => { + store({ visibility: { from: false } }); + window.dispatchEvent(new StorageEvent('storage', { key: STORAGE_KEY })); + }); + + expect(result.current.columns).toEqual([ 'hash', 'amount' ]); + }); + }); + + it('removes the key once the columns are switched back to the defaults', async() => { + store({ visibility: { block: true } }); + + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsChange({ ...result.current.checkedColumns, block: false }); + }); + + expect(readStored()).toBeNull(); + expect(result.current.isCustomized).toBe(false); + }); + }); + + it('moves a column and stores the full order', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsReorder([ 'amount', 'hash', 'block', 'from' ], 'amount'); + }); + + expect(result.current.columns).toEqual([ 'amount', 'hash', 'from' ]); + expect(result.current.selectableColumns.map(({ id }) => id)).toEqual([ 'amount', 'hash', 'block', 'from' ]); + expect(JSON.parse(readStored() ?? '')).toEqual({ order: [ 'amount', 'hash', 'block', 'from' ] }); + expect(result.current.isCustomized).toBe(true); + }); + }); + + it('counts moving a hidden column as a customization', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsReorder([ 'block', 'hash', 'from', 'amount' ], 'block'); + }); + + expect(result.current.columns).toEqual([ 'hash', 'from', 'amount' ]); + expect(result.current.isCustomized).toBe(true); + }); + }); + + it('neither logs nor stores a move of a column the selector does not offer', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsReorder([ 'fee', 'hash', 'block', 'from', 'amount' ], 'fee'); + }); + + expect(readStored()).toBeNull(); + expect(mixpanel.track).not.toHaveBeenCalled(); + }); + }); + + it('neither logs nor stores a move whose order lacks the moved column', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsReorder([ 'hash', 'block', 'amount' ], 'from'); + }); + + expect(readStored()).toBeNull(); + expect(mixpanel.track).not.toHaveBeenCalled(); + }); + }); + + it('neither logs nor stores a move that leaves the column in place', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsReorder([ 'hash', 'block', 'from', 'amount' ], 'from'); + }); + + expect(readStored()).toBeNull(); + expect(mixpanel.track).not.toHaveBeenCalled(); + }); + }); + + it('resets by removing the key', async() => { + store({ visibility: { hash: false }, order: [ 'amount', 'hash', 'block', 'from' ] }); + + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsReset(); + }); + + expect(readStored()).toBeNull(); + expect(result.current.columns).toEqual([ 'hash', 'from', 'amount' ]); + expect(result.current.isCustomized).toBe(false); + }); + }); + + it('does nothing on reset while the columns match the defaults', async() => { + store({ visibility: { hash: true } }); + + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsReset(); + }); + + expect(readStored()).not.toBeNull(); + expect(mixpanel.track).not.toHaveBeenCalled(); + }); + }); + + it('keeps working within the session when storage throws', async() => { + await withMixpanel(async() => { + const usePersistedColumns = await importHook(); + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new DOMException('denied', 'SecurityError'); + }); + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('denied', 'SecurityError'); + }); + + const { result } = renderHook(() => usePersistedColumns({ storageKey: STORAGE_KEY, columns: COLUMNS, states: STATES, analytics: TABLE_ANALYTICS })); + expect(result.current.columns).toEqual([ 'hash', 'from', 'amount' ]); + + act(() => { + result.current.onColumnsChange({ ...result.current.checkedColumns, hash: false }); + }); + expect(result.current.columns).toEqual([ 'from', 'amount' ]); + + act(() => { + result.current.onColumnsReorder([ 'amount', 'hash', 'block', 'from' ], 'amount'); + }); + expect(result.current.columns).toEqual([ 'amount', 'from' ]); + }); + }); + + it('logs one event per toggled column with the column id and the table only', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsChange({ hash: true, block: true, amount: true }); + }); + + expect(mixpanel.track).toHaveBeenCalledTimes(2); + expect(mixpanel.track).toHaveBeenNthCalledWith(1, 'Table columns', { Table: 'Advanced filter', Column: 'block', State: 'On' }, undefined); + expect(mixpanel.track).toHaveBeenNthCalledWith(2, 'Table columns', { Table: 'Advanced filter', Column: 'from', State: 'Off' }, undefined); + }); + }); + + it('forwards the surface in the payload of every event', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(SURFACE_ANALYTICS); + act(() => { + result.current.onColumnsReorder([ 'hash', 'block', 'amount', 'from' ], 'from'); + }); + act(() => { + result.current.onColumnsReorder([ 'amount', 'hash', 'block', 'from' ], 'amount'); + }); + act(() => { + result.current.onColumnsReset(); + }); + + expect(mixpanel.track).toHaveBeenCalledTimes(3); + expect(mixpanel.track).toHaveBeenNthCalledWith( + 1, 'Table columns', { Table: 'Token transfers', Surface: 'index', Column: 'from', State: 'Moved down' }, undefined, + ); + expect(mixpanel.track).toHaveBeenNthCalledWith( + 2, 'Table columns', { Table: 'Token transfers', Surface: 'index', Column: 'amount', State: 'Moved up' }, undefined, + ); + expect(mixpanel.track).toHaveBeenNthCalledWith( + 3, 'Table columns', { Table: 'Token transfers', Surface: 'index', Column: 'All', State: 'Reset' }, undefined, + ); + }); + }); + + it('logs nothing when the selection does not change', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsChange({ ...result.current.checkedColumns }); + }); + + expect(mixpanel.track).not.toHaveBeenCalled(); + expect(readStored()).toBeNull(); + }); + }); + + it('leaves the stored value as it is when the selection does not change', async() => { + const stored = JSON.stringify({ visibility: { block: true, retired: true } }); + store(stored); + + await withMixpanel(async() => { + const { result } = await renderColumnsHook(); + act(() => { + result.current.onColumnsChange({ ...result.current.checkedColumns }); + }); + + expect(readStored()).toBe(stored); + }); + }); +}); diff --git a/src/shared/lists/columns/usePersistedColumns.ts b/src/shared/lists/columns/usePersistedColumns.ts new file mode 100644 index 00000000000..567a2849b06 --- /dev/null +++ b/src/shared/lists/columns/usePersistedColumns.ts @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { isEqual } from 'es-toolkit'; +import React from 'react'; + +import type { ColumnOverrides, ColumnStates, ColumnVisibility, TableColumn } from './types'; +import type { DistributiveOmit } from 'src/shared/types/utils'; + +import type { EventPayload } from 'src/shared/analytics'; +import { EventTypes, logEvent } from 'src/shared/analytics'; + +import { + getAvailableColumns, + getDefaultColumnIds, + getOrderedColumns, + getVisibleColumnIds, + parseColumnOverrides, + serializeColumnOverrides, + setColumnOrder, + setColumnVisibility, +} from './column-overrides'; +import { readColumnStorage, subscribeToColumnStorage, writeColumnStorage } from './column-storage'; + +export type TableColumnsAnalytics = DistributiveOmit<EventPayload<EventTypes.TABLE_COLUMNS>, 'Column' | 'State'>; + +interface Params<TColumn extends TableColumn<TColumnId>, TColumnId extends string = TColumn['id']> { + readonly storageKey: string; + readonly columns: ReadonlyArray<TColumn>; + readonly states: ColumnStates<NoInfer<TColumnId>>; + readonly analytics: TableColumnsAnalytics; +} + +export interface PersistedColumnsState<TColumn extends TableColumn<TColumnId>, TColumnId extends string = TColumn['id']> { + readonly columns: ReadonlyArray<TColumnId>; + readonly selectableColumns: ReadonlyArray<TColumn>; + readonly checkedColumns: ColumnVisibility<TColumnId>; + readonly isCustomized: boolean; + readonly onColumnsChange: (checkedColumns: ColumnVisibility<TColumnId>) => void; + readonly onColumnsReorder: (order: Array<TColumnId>, movedId: TColumnId) => void; + readonly onColumnsReset: () => void; +} + +const getServerSnapshot = (): string | null => null; + +export function usePersistedColumns<TColumn extends TableColumn<TColumnId>, TColumnId extends string = TColumn['id']>({ + storageKey, + columns, + states, + analytics, +}: Params<TColumn, TColumnId>): PersistedColumnsState<TColumn, TColumnId> { + const subscribe = React.useCallback((listener: () => void) => subscribeToColumnStorage(storageKey, listener), [ storageKey ]); + const getSnapshot = React.useCallback(() => readColumnStorage(storageKey), [ storageKey ]); + const rawOverrides = React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + + const columnIds = React.useMemo(() => columns.map(({ id }) => id), [ columns ]); + const overrides = React.useMemo(() => parseColumnOverrides(rawOverrides, columnIds), [ rawOverrides, columnIds ]); + + const availableColumns = React.useMemo(() => getAvailableColumns(columns, states), [ columns, states ]); + const defaultColumnIds = React.useMemo(() => getDefaultColumnIds(columns, states), [ columns, states ]); + const selectableColumns = React.useMemo(() => getOrderedColumns(availableColumns, overrides?.order), [ availableColumns, overrides ]); + const visibleColumnIds = React.useMemo(() => getVisibleColumnIds(availableColumns, states, overrides), [ availableColumns, states, overrides ]); + const checkedColumns = React.useMemo( + () => Object.fromEntries(visibleColumnIds.map((id) => [ id, true ])) as ColumnVisibility<TColumnId>, + [ visibleColumnIds ], + ); + const isCustomized = !isEqual(visibleColumnIds, defaultColumnIds) || !isEqual(selectableColumns, availableColumns); + + const readOverrides = React.useCallback( + () => parseColumnOverrides(readColumnStorage(storageKey), columnIds), + [ storageKey, columnIds ], + ); + const writeOverrides = React.useCallback((nextOverrides: ColumnOverrides<TColumnId> | undefined) => { + writeColumnStorage(storageKey, nextOverrides ? serializeColumnOverrides(nextOverrides) : null); + }, [ storageKey ]); + + const onColumnsChange = React.useCallback((nextCheckedColumns: ColumnVisibility<TColumnId>) => { + const toggledColumns = selectableColumns.filter(({ id }) => Boolean(nextCheckedColumns[id]) !== visibleColumnIds.includes(id)); + if (toggledColumns.length === 0) { + return; + } + + writeOverrides(toggledColumns.reduce( + (result, { id }) => setColumnVisibility(result, states, id, Boolean(nextCheckedColumns[id])), + readOverrides(), + )); + + toggledColumns.forEach(({ id }) => { + logEvent(EventTypes.TABLE_COLUMNS, { ...analytics, Column: id, State: nextCheckedColumns[id] ? 'On' : 'Off' }); + }); + }, [ selectableColumns, visibleColumnIds, states, analytics, readOverrides, writeOverrides ]); + + const onColumnsReorder = React.useCallback((order: Array<TColumnId>, movedId: TColumnId) => { + const fromIndex = selectableColumns.findIndex(({ id }) => id === movedId); + const toIndex = order.indexOf(movedId); + if (fromIndex === -1 || toIndex === -1 || fromIndex === toIndex) { + return; + } + + writeOverrides(setColumnOrder(readOverrides(), availableColumns, order)); + + // Stryker disable next-line EqualityOperator: toIndex === fromIndex has already returned above + logEvent(EventTypes.TABLE_COLUMNS, { ...analytics, Column: movedId, State: toIndex < fromIndex ? 'Moved up' : 'Moved down' }); + }, [ selectableColumns, availableColumns, analytics, readOverrides, writeOverrides ]); + + const onColumnsReset = React.useCallback(() => { + if (!isCustomized) { + return; + } + + writeOverrides(undefined); + + logEvent(EventTypes.TABLE_COLUMNS, { ...analytics, Column: 'All', State: 'Reset' }); + }, [ isCustomized, analytics, writeOverrides ]); + + return React.useMemo(() => ({ + columns: visibleColumnIds, + selectableColumns, + checkedColumns, + isCustomized, + onColumnsChange, + onColumnsReorder, + onColumnsReset, + }), [ visibleColumnIds, selectableColumns, checkedColumns, isCustomized, onColumnsChange, onColumnsReorder, onColumnsReset ]); +} diff --git a/src/shared/lists/get-unique-keys.spec.ts b/src/shared/lists/get-unique-keys.spec.ts new file mode 100644 index 00000000000..29fd845255e --- /dev/null +++ b/src/shared/lists/get-unique-keys.spec.ts @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; + +import { getUniqueKeys } from './get-unique-keys'; + +const byId = (item: { id: string }) => item.id; + +describe('getUniqueKeys', () => { + it('returns the base key when all items are distinct', () => { + expect(getUniqueKeys([ { id: 'a' }, { id: 'b' } ], byId)).toEqual([ 'a', 'b' ]); + }); + + it('returns an empty list when there are no items yet', () => { + expect(getUniqueKeys(undefined, byId)).toEqual([]); + }); + + it('appends an occurrence ordinal to every repeat of a base key', () => { + expect(getUniqueKeys([ { id: 'a' }, { id: 'a' }, { id: 'b' }, { id: 'a' } ], byId)).toEqual([ 'a', 'a_1', 'b', 'a_2' ]); + }); + + it('keeps the keys of existing items when a new item is prepended', () => { + const page = [ { id: 'a' }, { id: 'a' }, { id: 'b' } ]; + const before = getUniqueKeys(page, byId); + const after = getUniqueKeys([ { id: 'c' }, ...page ], byId); + + expect(after.slice(1)).toEqual(before); + }); + + it('assigns the prepended item the first ordinal of its group', () => { + const page = [ { id: 'a' }, { id: 'b' } ]; + + expect(getUniqueKeys([ { id: 'a' }, ...page ], byId)).toEqual([ 'a', 'a_1', 'b' ]); + }); + + it('yields keys that are all distinct', () => { + const keys = getUniqueKeys([ { id: 'a' }, { id: 'a' }, { id: 'a' }, { id: 'b' }, { id: 'b' } ], byId); + + expect(new Set(keys).size).toBe(keys.length); + }); +}); diff --git a/src/shared/lists/get-unique-keys.ts b/src/shared/lists/get-unique-keys.ts new file mode 100644 index 00000000000..f89e61a4ad6 --- /dev/null +++ b/src/shared/lists/get-unique-keys.ts @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +// React tracks pending removals in a key -> fiber map, so rows that share a key are never +// unmounted and stay in the DOM through every subsequent page. No per-entity key is immune: +// an ERC-1155 batch may legally transfer the same token id twice in one log. +// https://github.com/blockscout/frontend/issues/3631 +// +// Collisions get an ordinal by position within their group, not within the list, so prepending +// items (socket updates) leaves the keys of the existing rows unchanged. +export function getUniqueKeys<T>(items: ReadonlyArray<T> | undefined, getBaseKey: (item: T) => string): Array<string> { + if (!items) { + return []; + } + + const occurrences = new Map<string, number>(); + + return items.map((item) => { + const baseKey = getBaseKey(item); + const occurrence = occurrences.get(baseKey) ?? 0; + occurrences.set(baseKey, occurrence + 1); + + return occurrence === 0 ? baseKey : `${ baseKey }_${ occurrence }`; + }); +} + +export function useUniqueKeys<T>(items: ReadonlyArray<T> | undefined, getBaseKey: (item: T) => string): Array<string> { + return React.useMemo(() => getUniqueKeys(items, getBaseKey), [ items, getBaseKey ]); +} diff --git a/src/shared/lists/useTableViewValue.ts b/src/shared/lists/useTableViewValue.ts deleted file mode 100644 index c42252b6506..00000000000 --- a/src/shared/lists/useTableViewValue.ts +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -// TODO: remove this component once tables in mobile are finalized -import React from 'react'; - -import useFeatureValue from 'src/services/growthbook/useFeatureValue'; -import * as mixpanel from 'src/services/mixpanel'; -import * as cookies from 'src/shared/storage/cookies'; - -export default function useTableViewValue() { - const cookieValue = cookies.get(cookies.NAMES.TABLE_VIEW_ON_MOBILE); - const [ value, setValue ] = React.useState<boolean | undefined>(cookieValue ? cookieValue === 'true' : undefined); - const { value: featureFlag, isLoading: isFeatureLoading } = useFeatureValue('txns_view_exp', 'list_view'); - - const onToggle = React.useCallback(() => { - setValue((prev) => { - const nextValue = !prev; - cookies.set(cookies.NAMES.TABLE_VIEW_ON_MOBILE, nextValue ? 'true' : 'false'); - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { - Type: 'Txn view switch', - Info: nextValue ? 'Table view' : 'List view', - Source: 'Address page', - }); - return nextValue; - }); - }, []); - - React.useEffect(() => { - if (!isFeatureLoading) { - setValue((prev) => { - if (prev === undefined) { - return featureFlag === 'table_view'; - } - return prev; - }); - } - }, [ featureFlag, isFeatureLoading ]); - - return React.useMemo(() => { - if (value !== undefined) { - return { - value, - isLoading: false, - onToggle, - }; - } - - return { value: featureFlag === 'table_view', isLoading: isFeatureLoading, onToggle }; - }, [ featureFlag, isFeatureLoading, onToggle, value ]); -} diff --git a/src/shared/pagination/CONTEXT.md b/src/shared/pagination/CONTEXT.md new file mode 100644 index 00000000000..452f78c5690 --- /dev/null +++ b/src/shared/pagination/CONTEXT.md @@ -0,0 +1,60 @@ +# Pagination — context + +Everything a paginated list needs that is not the list itself. Two paging models live here and do not share code: cursor pages +driven by the URL (most lists) and infinite scroll (`useLazyLoadedList.ts`). + +## Cursor model + +### Files + +| File | Role | +|---|---| +| `types.ts` | `PaginationParams`, the object a hook returns and a control consumes. | +| `Pagination.tsx`, `StickyPaginationWithText.tsx` | The controls. | +| `utils.ts` | `generateListStub` (a placeholder page from one stub row, for `placeholderData`) and `emptyPagination` (a `PaginationParams` for lists that page locally or not at all). | +| `usePaginationParams.ts` | URL → page, cursor, filters, sorting. Pure derivation; filters come from the resource's `filterFields`. | +| `usePaginationActions.ts` | The next / prev / first / filter / sorting handlers. Each is one shallow `router.push`. | +| `useApiPaginatedQuery.ts` | Composes the two above with `useApiQuery` into the object list components consume. | +| `useDebouncedFilterChange.ts` | Search-box-to-URL debounce, shared by the lists with a free-text filter. | + +### What an editor of the cursor hooks must keep true + +- **The URL is the only list state.** Page, cursor, filters, sorting and (multichain) selected chain are + read from `router.query` on every render. No hook here holds React state that mirrors a URL value and no + effect re-syncs from the URL. A handler pushes once and returns; anything it needs afterwards is read on + the next render. +- **The previous-page cursors are the one in-memory exception.** The API only hands out the *next* cursor, + so "Prev" needs the cursors of the pages already visited. They live in a ref keyed by page number inside + `usePaginationActions.ts`, filled on "Next" and seeded from the URL on mount. After a deep link into + page 3 the ref knows page 3 only, so "Prev" is disabled until a page has been reached via "Next"; that + is expected, not a bug. +- **The returned object is referentially stable.** `pagination`, every handler and the result itself keep + their identity while their inputs are unchanged, and the spec asserts it. +- **`isInitialLoading` and `isTransitioning` are the two placeholder cases.** The first means the caller's + stub is on screen (first load, filter or sort change) and rows render skeletons. The second means the + previous page's rows are on screen while the next page loads, and the `DataList` body dims them. Rows + take `isLoading={ isInitialLoading }`; the wrapper takes `isTransitioning`; `pagination.isLoading` is + true in both cases and only drives the buttons. +- **Fixed filters go in `queryParams`, not the URL.** A value the user cannot change is passed as `queryParams` and wins over a URL field of the same name. Only user-changeable + values belong in the resource's `filterFields`. + +## Composing the pieces yourself + +Most callers use `useApiPaginatedQuery` unchanged. When a list needs a URL value *before* it can call the +hook — the resource depends on a filter, or another query keys on a filter — call `usePaginationParams` +with the same resource name to read that value on the same render, then pass the result on. The value is +derived from the same `router.query`, so both reads agree. + +The selected chain on multichain instances is the same shape as a filter but is not one: it is read and +pushed by `src/features/multichain/hooks/useChainValue.ts`, and only lists that opt in pay for it. + +## Gotchas + +- **A caller must not keep its own copy of a filter or sort value.** The tab switch strips list params + from the URL to reset the list; a local copy survives the switch and the next push re-applies the stale + value. Read `filters` / `sorting` from the hook and call its handlers. +- **Row keys follow `src/shared/lists/CONTEXT.md`.** A key that mixes in the loading flag for real data + remounts every row on a page transition, which is what the dimmed state exists to avoid. +- **`queryHash` is the reset key for the lazy-render window.** It changes on page, filter, sort and chain + changes and stays put on a socket prepend into page 1 — the two cases the window must and must not reset + on. Do not key the window on `data`. diff --git a/src/shared/pagination/StickyPaginationWithText.tsx b/src/shared/pagination/StickyPaginationWithText.tsx index ff0559e0767..0c29d0c4667 100644 --- a/src/shared/pagination/StickyPaginationWithText.tsx +++ b/src/shared/pagination/StickyPaginationWithText.tsx @@ -16,7 +16,7 @@ type Props = { const StickyPaginationWithText = ({ pagination, text }: Props) => { if (!pagination.isVisible) { - return <Box mb={ 6 }>{ text }</Box>; + return text ? <Box mb={ 6 }>{ text }</Box> : null; } return ( diff --git a/src/shared/pagination/__screenshots__/Pagination.pw.tsx_default_default-view-1.png b/src/shared/pagination/__screenshots__/Pagination.pw.tsx_default_default-view-1.png index 40b1d8ddc3e..737d7c60499 100644 Binary files a/src/shared/pagination/__screenshots__/Pagination.pw.tsx_default_default-view-1.png and b/src/shared/pagination/__screenshots__/Pagination.pw.tsx_default_default-view-1.png differ diff --git a/src/shared/pagination/types.ts b/src/shared/pagination/types.ts index 9550ab9d29d..d62f9c12994 100644 --- a/src/shared/pagination/types.ts +++ b/src/shared/pagination/types.ts @@ -1,13 +1,15 @@ // SPDX-License-Identifier: LicenseRef-Blockscout +export type NextPageParams = Record<string, unknown>; + export interface PaginationParams { - page: number; - onNextPageClick: () => void; - onPrevPageClick: () => void; - resetPage: () => void; - hasPages: boolean; - hasNextPage: boolean; - canGoBackwards: boolean; - isLoading: boolean; - isVisible: boolean; + readonly page: number; + readonly onNextPageClick: () => void; + readonly onPrevPageClick: () => void; + readonly resetPage: () => void; + readonly hasPages: boolean; + readonly hasNextPage: boolean; + readonly canGoBackwards: boolean; + readonly isLoading: boolean; + readonly isVisible: boolean; } diff --git a/src/shared/pagination/useApiPaginatedQuery.spec.ts b/src/shared/pagination/useApiPaginatedQuery.spec.ts new file mode 100644 index 00000000000..927b4b34b8b --- /dev/null +++ b/src/shared/pagination/useApiPaginatedQuery.spec.ts @@ -0,0 +1,856 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import * as addressParamMock from 'src/slices/address/mocks/address-param'; +import { TX_ITEM } from 'src/slices/tx/stubs/tx'; + +import { chainA } from 'src/features/multichain/mocks/chains'; + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { renderHook, render, act, cleanup } from 'vitest/lib'; +import flushPromises from 'vitest/utils/flushPromises'; +import { routerStandIn, RouterStandInProvider } from 'vitest/utils/routerStandIn'; + +const { mockScrollToTop } = vi.hoisted(() => ({ + mockScrollToTop: vi.fn(), +})); + +vi.mock('react-scroll', () => ({ animateScroll: { scrollToTop: mockScrollToTop } })); + +import type { Params, ApiPaginatedQueryResult } from './useApiPaginatedQuery'; +import useApiPaginatedQuery from './useApiPaginatedQuery'; +import { generateListStub } from './utils'; + +const responses = { + page_empty: { + items: [], + next_page_params: null, + }, + page_1: { + items: [ { hash: '11' }, { hash: '12' } ], + next_page_params: { + block_number: 11, + index: 12, + items_count: 13, + }, + }, + page_2: { + items: [ { hash: '21' }, { hash: '22' } ], + next_page_params: { + block_number: 21, + index: 22, + items_count: 23, + }, + }, + page_3: { + items: [ { hash: '31' }, { hash: '32' } ], + next_page_params: null, + }, + page_filtered: { + items: [ { hash: '41' }, { hash: '42' } ], + next_page_params: { + block_number: 41, + index: 42, + items_count: 43, + }, + }, + page_sorted: { + items: [ { hash: '61' }, { hash: '62' } ], + next_page_params: null, + }, +}; + +const responseInit = { + headers: { + 'Content-Type': 'application/json', + }, +}; + +const encodePageParams = (pageParams: object) => encodeURIComponent(JSON.stringify(pageParams)); + +// one render for the URL push, one when the response lands +const RENDERS_PER_NAVIGATION = 2; + +const params: Params<'core:address_txs'> = { + resourceName: 'core:address_txs', + pathParams: { hash: addressParamMock.hash }, +}; + +beforeEach(() => { + fetchMock.resetMocks(); + mockScrollToTop.mockClear(); + routerStandIn.reset({ pathname: '/blocks' }); +}); + +afterEach(cleanup); + +it('returns correct data if there is only one page', async() => { + fetchMock.mockResponse(JSON.stringify(responses.page_empty), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_empty); + expect(result.current.pagination).toMatchObject({ + page: 1, + canGoBackwards: false, + hasNextPage: false, + isLoading: false, + isVisible: false, + hasPages: false, + }); +}); + +describe('if there are multiple pages', () => { + it('return correct data for the first page', async() => { + fetchMock.mockResponse(JSON.stringify(responses.page_1), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_1); + expect(result.current.pagination).toMatchObject({ + page: 1, + canGoBackwards: false, + hasNextPage: true, + isLoading: false, + isVisible: true, + }); + }); + + describe('correctly navigates forward and backward', () => { + let result: { + current: ApiPaginatedQueryResult<'core:address_txs'>; + }; + + beforeEach(async() => { + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + fetchMock.once(JSON.stringify(responses.page_2), responseInit); + fetchMock.once(JSON.stringify(responses.page_3), responseInit); + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + + const { result: r } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + result = r; + await waitForApiResponse(); + }); + + it('from page 1 to page 2', async() => { + await act(() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_2); + expect(result.current.pagination).toMatchObject({ + page: 2, + canGoBackwards: true, + hasNextPage: true, + isLoading: false, + isVisible: true, + hasPages: true, + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(1); + expect(routerStandIn.push).toHaveBeenLastCalledWith(expect.anything(), { shallow: true }); + expect(routerStandIn.pathname).toBe('/blocks'); + expect(routerStandIn.query).toEqual({ + next_page_params: encodePageParams(responses.page_1.next_page_params), + page: '2', + }); + + expect(mockScrollToTop).toHaveBeenCalledTimes(1); + expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); + }); + + it('from page 2 to page 3', async() => { + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_3); + expect(result.current.pagination).toMatchObject({ + page: 3, + canGoBackwards: true, + hasNextPage: false, + isLoading: false, + isVisible: true, + hasPages: true, + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(2); + expect(routerStandIn.query).toEqual({ + next_page_params: encodePageParams(responses.page_2.next_page_params), + page: '3', + }); + + expect(mockScrollToTop).toHaveBeenCalledTimes(2); + expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); + }); + + it('from page 3 to page 2', async() => { + await act(() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + await act(() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + await act(() => { + result.current.pagination.onPrevPageClick(); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_2); + expect(result.current.pagination).toMatchObject({ + page: 2, + canGoBackwards: true, + hasNextPage: true, + isLoading: false, + isVisible: true, + hasPages: true, + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(3); + expect(routerStandIn.query).toEqual({ + next_page_params: encodePageParams(responses.page_1.next_page_params), + page: '2', + }); + + expect(mockScrollToTop).toHaveBeenCalledTimes(3); + expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); + }); + + it('from page 2 to page 1', async() => { + await act(() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + await act(() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + await act(() => { + result.current.pagination.onPrevPageClick(); + }); + await waitForApiResponse(); + + await act(() => { + result.current.pagination.onPrevPageClick(); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_1); + expect(result.current.pagination).toMatchObject({ + page: 1, + canGoBackwards: false, + hasNextPage: true, + isLoading: false, + isVisible: true, + hasPages: false, + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(4); + expect(routerStandIn.query).toEqual({}); + + expect(mockScrollToTop).toHaveBeenCalledTimes(4); + expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); + }); + }); + + it('correctly resets the page', async() => { + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + fetchMock.once(JSON.stringify(responses.page_2), responseInit); + fetchMock.once(JSON.stringify(responses.page_3), responseInit); + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + await act(async() => { + result.current.pagination.resetPage(); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_1); + expect(result.current.pagination).toMatchObject({ + page: 1, + canGoBackwards: false, + hasNextPage: true, + isLoading: false, + isVisible: true, + hasPages: false, + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(3); + expect(routerStandIn.query).toEqual({}); + + expect(mockScrollToTop).toHaveBeenCalledTimes(3); + expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); + }); + + it('when navigates between pages can scroll to custom element', async() => { + const scrollRef = { + current: { + scrollIntoView: vi.fn(), + }, + }; + const paramsWithScrollRef: Params<'core:address_txs'> = { + ...params, + scrollRef: scrollRef as unknown as React.RefObject<HTMLDivElement>, + }; + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + fetchMock.once(JSON.stringify(responses.page_2), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(paramsWithScrollRef), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + expect(scrollRef.current.scrollIntoView).toHaveBeenCalledTimes(1); + expect(scrollRef.current.scrollIntoView).toHaveBeenCalledWith(true); + }); +}); + +describe('if there is page query param in URL', () => { + it('sets this param as the page number', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { page: '3' } }); + fetchMock.mockResponse(JSON.stringify(responses.page_empty), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_empty); + expect(result.current.pagination).toMatchObject({ + page: 3, + canGoBackwards: false, + hasNextPage: false, + isLoading: false, + isVisible: true, + hasPages: true, + }); + }); + + it('correctly navigates to the following pages', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { page: '2' } }); + fetchMock.once(JSON.stringify(responses.page_2), responseInit); + fetchMock.once(JSON.stringify(responses.page_3), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_3); + expect(result.current.pagination).toMatchObject({ + page: 3, + canGoBackwards: true, + hasNextPage: false, + isLoading: false, + isVisible: true, + hasPages: true, + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(1); + expect(routerStandIn.query).toEqual({ + next_page_params: encodePageParams(responses.page_2.next_page_params), + page: '3', + }); + }); +}); + +describe('queries with filters', () => { + it('reset page, keep sorting when filter is changed', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { foo: 'bar', sort: 'val-desc' } }); + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + fetchMock.once(JSON.stringify(responses.page_2), responseInit); + fetchMock.once(JSON.stringify(responses.page_filtered), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + await act(async() => { + result.current.onFilterChange({ filter: 'from' }); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_filtered); + expect(result.current.pagination).toMatchObject({ + page: 1, + canGoBackwards: false, + hasNextPage: true, + isLoading: false, + isVisible: true, + hasPages: false, + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(2); + expect(routerStandIn.query).toEqual({ filter: 'from', foo: 'bar', sort: 'val-desc' }); + + expect(mockScrollToTop).toHaveBeenCalledTimes(2); + expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); + }); + + it('saves filter params in query when navigating between pages', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { filter: 'from', foo: 'bar' } }); + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + fetchMock.once(JSON.stringify(responses.page_2), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + expect(routerStandIn.push).toHaveBeenCalledTimes(1); + expect(routerStandIn.query).toEqual({ + filter: 'from', + foo: 'bar', + next_page_params: encodePageParams(responses.page_1.next_page_params), + page: '2', + }); + }); +}); + +describe('queries with sorting', () => { + it('reset page, save filter when sorting is changed', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { foo: 'bar', filter: 'from' } }); + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + fetchMock.once(JSON.stringify(responses.page_2), responseInit); + fetchMock.once(JSON.stringify(responses.page_sorted), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + await act(async() => { + // @ts-ignore: + result.current.onSortingChange({ sort: 'val-desc' }); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_sorted); + expect(result.current.pagination).toMatchObject({ + page: 1, + canGoBackwards: false, + hasNextPage: false, + isLoading: false, + isVisible: false, + hasPages: false, + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(2); + expect(routerStandIn.query).toEqual({ filter: 'from', foo: 'bar', sort: 'val-desc' }); + + expect(mockScrollToTop).toHaveBeenCalledTimes(2); + expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); + }); + + it('saves sorting params in query when navigating between pages', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { foo: 'bar', sort: 'val-desc' } }); + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + fetchMock.once(JSON.stringify(responses.page_2), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + expect(routerStandIn.push).toHaveBeenCalledTimes(1); + expect(routerStandIn.query).toEqual({ + sort: 'val-desc', + foo: 'bar', + next_page_params: encodePageParams(responses.page_1.next_page_params), + page: '2', + }); + }); +}); + +describe('router query changes', () => { + it('refetches correct page when page number changes in URL', async() => { + routerStandIn.reset({ + pathname: '/blocks', + query: { + page: '3', + next_page_params: encodePageParams(responses.page_2.next_page_params), + }, + }); + fetchMock.once(JSON.stringify(responses.page_3), responseInit); + fetchMock.once(JSON.stringify(responses.page_2), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_3); + expect(result.current.pagination.page).toBe(3); + + act(() => { + routerStandIn.setQuery({ + page: '2', + next_page_params: encodePageParams(responses.page_1.next_page_params), + }); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_2); + expect(result.current.pagination).toMatchObject({ + page: 2, + canGoBackwards: false, + hasNextPage: true, + isLoading: false, + isVisible: true, + }); + }); +}); + +describe('values derived from the URL', () => { + it('reads filters and sorting from the URL', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { filter: 'to', sort: 'value', order: 'desc', foo: 'bar' } }); + fetchMock.mockResponse(JSON.stringify(responses.page_1), responseInit); + + const { result } = renderHook(() => useApiPaginatedQuery(params), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + expect(result.current.filters).toEqual({ filter: 'to' }); + expect(result.current.sorting).toEqual({ sort: 'value', order: 'desc' }); + expect(new URL(String(fetchMock.mock.calls[0][0])).search).toBe('?filter=to&sort=value&order=desc'); + }); + + it('lets fixed queryParams win over a URL filter field of the same name', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { filter: 'to', page: '2', next_page_params: encodePageParams(responses.page_1.next_page_params) } }); + fetchMock.mockResponse(JSON.stringify(responses.page_2), responseInit); + const paramsWithFixedFilter: Params<'core:address_txs'> = { + ...params, + queryParams: { filter: 'validated' }, + }; + + const { result } = renderHook(() => useApiPaginatedQuery(paramsWithFixedFilter), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + expect(new URL(String(fetchMock.mock.calls[0][0])).searchParams.get('filter')).toBe('validated'); + expect(new URL(String(fetchMock.mock.calls[0][0])).searchParams.get('block_number')).toBe('11'); + expect(result.current.pagination.page).toBe(2); + }); + + it('targets the given chain and folds it into the query hash', async() => { + fetchMock.mockResponse(JSON.stringify(responses.page_1), responseInit); + + const { result, rerender } = renderHook((hookParams: Params<'core:address_txs'>) => useApiPaginatedQuery(hookParams), { + wrapper: routerStandIn.appWrapper, + initialProps: params, + }); + await waitForApiResponse(); + const hashWithoutChain = result.current.queryHash; + + rerender({ ...params, chain: chainA }); + await waitForApiResponse(); + + expect(new URL(String(fetchMock.mock.calls[1][0])).origin).toBe(chainA.app_config.apis.core?.endpoint); + expect(result.current.queryHash).not.toBe(hashWithoutChain); + }); + + it('exposes the loading flags for the list body', async() => { + fetchMock.mockResponse(JSON.stringify(responses.page_1), responseInit); + const paramsWithStub: Params<'core:address_txs'> = { + ...params, + options: { placeholderData: generateListStub<'core:address_txs'>(TX_ITEM, 1, { next_page_params: null }) }, + }; + + const { result } = renderHook(() => useApiPaginatedQuery(paramsWithStub), { wrapper: routerStandIn.appWrapper }); + expect(result.current.isInitialLoading).toBe(true); + expect(result.current.isTransitioning).toBe(false); + expect(result.current.pagination.isLoading).toBe(true); + + await waitForApiResponse(); + + expect(result.current.isInitialLoading).toBe(false); + expect(result.current.isTransitioning).toBe(false); + expect(result.current.pagination.isLoading).toBe(false); + }); + + it('renders the stub, not the previous rows, while the next page loads', async() => { + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + const releasePages: Array<() => void> = []; + for (const pageResponse of [ responses.page_2, responses.page_3 ]) { + let release!: () => void; + const pending = new Promise<void>((resolve) => { + release = resolve; + }); + fetchMock.once(async() => { + await pending; + return JSON.stringify(pageResponse); + }, responseInit); + releasePages.push(release); + } + const stub = generateListStub<'core:address_txs'>(TX_ITEM, 1, { next_page_params: null }); + const paramsWithStub: Params<'core:address_txs'> = { + ...params, + options: { placeholderData: stub }, + }; + + const { result } = renderHook(() => useApiPaginatedQuery(paramsWithStub), { wrapper: routerStandIn.appWrapper }); + await waitForApiResponse(); + + for (const expectedPage of [ 2, 3 ]) { + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + + expect(result.current.pagination.page).toBe(expectedPage); + expect(result.current.data).toEqual(stub); + expect(result.current.isInitialLoading).toBe(true); + expect(result.current.isTransitioning).toBe(false); + expect(result.current.pagination.isLoading).toBe(true); + + releasePages[expectedPage - 2](); + await waitForApiResponse(); + + expect(result.current.isInitialLoading).toBe(false); + expect(result.current.pagination.isLoading).toBe(false); + } + + expect(result.current.data).toEqual(responses.page_3); + }); +}); + +describe('referential stability', () => { + it('keeps the result, pagination and callbacks across a re-render with the same inputs', async() => { + fetchMock.mockResponse(JSON.stringify(responses.page_1), responseInit); + + const { result, rerender } = renderHook((hookParams: Params<'core:address_txs'>) => useApiPaginatedQuery(hookParams), { + wrapper: routerStandIn.appWrapper, + initialProps: params, + }); + await waitForApiResponse(); + const before = result.current; + + rerender(params); + + expect(result.current).toBe(before); + expect(result.current.pagination).toBe(before.pagination); + expect(result.current.pagination.onNextPageClick).toBe(before.pagination.onNextPageClick); + expect(result.current.pagination.onPrevPageClick).toBe(before.pagination.onPrevPageClick); + expect(result.current.pagination.resetPage).toBe(before.pagination.resetPage); + expect(result.current.onFilterChange).toBe(before.onFilterChange); + expect(result.current.onSortingChange).toBe(before.onSortingChange); + }); + + it('keeps the same query hash across a re-render and changes it on a page change', async() => { + fetchMock.once(JSON.stringify(responses.page_1), responseInit); + fetchMock.once(JSON.stringify(responses.page_2), responseInit); + + const { result, rerender } = renderHook((hookParams: Params<'core:address_txs'>) => useApiPaginatedQuery(hookParams), { + wrapper: routerStandIn.appWrapper, + initialProps: params, + }); + await waitForApiResponse(); + const hashBefore = result.current.queryHash; + + rerender(params); + expect(result.current.queryHash).toBe(hashBefore); + + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + + expect(result.current.queryHash).not.toBe(hashBefore); + }); +}); + +describe('cost of one user action', () => { + const paramsWithStub: Params<'core:address_txs'> = { + ...params, + options: { placeholderData: generateListStub<'core:address_txs'>(TX_ITEM, 1, { next_page_params: null }) }, + }; + + interface RenderSnapshot { + readonly page: number; + readonly isLoading: boolean; + } + + const requestSearch = (url: string) => new URL(url).search; + + const respondByCursor = (request: Request) => { + const search = requestSearch(request.url); + if (search.includes('filter=from')) { + return Promise.resolve({ body: JSON.stringify(responses.page_filtered), ...responseInit }); + } + if (search.includes(`block_number=${ responses.page_2.next_page_params.block_number }`)) { + return Promise.resolve({ body: JSON.stringify(responses.page_3), ...responseInit }); + } + if (search.includes(`block_number=${ responses.page_1.next_page_params.block_number }`)) { + return Promise.resolve({ body: JSON.stringify(responses.page_2), ...responseInit }); + } + return Promise.resolve({ body: JSON.stringify(responses.page_1), ...responseInit }); + }; + + async function renderOnPage(pageNumber: number) { + fetchMock.mockResponse(respondByCursor); + const renderLog: Array<RenderSnapshot> = []; + let consumerRenders = 0; + let rendersAtMark = 0; + let consumerRendersAtMark = 0; + let requestsAtMark = 0; + + const Consumer = React.memo(function Consumer(props: { query: ApiPaginatedQueryResult<'core:address_txs'> }) { + consumerRenders++; + return React.createElement('span', null, props.query.pagination.page); + }); + + const result: { current: ApiPaginatedQueryResult<'core:address_txs'> } = { current: undefined as never }; + const Host = (hookParams: Params<'core:address_txs'>) => { + const hookResult = useApiPaginatedQuery(hookParams); + renderLog.push({ page: hookResult.pagination.page, isLoading: hookResult.pagination.isLoading }); + result.current = hookResult; + return React.createElement(Consumer, { query: hookResult }); + }; + + render(React.createElement(RouterStandInProvider, null, React.createElement(Host, paramsWithStub))); + await waitForApiResponse(); + + for (let page = 1; page < pageNumber; page++) { + await act(async() => { + result.current.pagination.onNextPageClick(); + }); + await waitForApiResponse(); + } + expect(result.current.pagination.page).toBe(pageNumber); + + return { + result, + mark: () => { + rendersAtMark = renderLog.length; + consumerRendersAtMark = consumerRenders; + requestsAtMark = fetchMock.mock.calls.length; + }, + rendersSinceMark: () => renderLog.slice(rendersAtMark), + consumerRendersSinceMark: () => consumerRenders - consumerRendersAtMark, + requestsSinceMark: () => fetchMock.mock.calls.slice(requestsAtMark).map(([ url ]) => requestSearch(String(url))), + }; + } + + it('"First" from page 3', async() => { + const { result, mark, rendersSinceMark, requestsSinceMark } = await renderOnPage(3); + + mark(); + await act(async() => { + result.current.pagination.resetPage(); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_1); + expect(result.current.pagination).toMatchObject({ page: 1, isLoading: false }); + expect(routerStandIn.push).toHaveBeenCalledTimes(3); + // parent spec row "First" from page 3 — cached page 1 is shown at once, no page-3 skeleton + expect(rendersSinceMark()[0]).toEqual({ page: 1, isLoading: false }); + // parent spec row "First" from page 3 — API requests (page 1 refreshed in the background only) + expect(requestsSinceMark()).toEqual([ '' ]); + // parent spec row "First" from page 3 — renders + expect(rendersSinceMark()).toHaveLength(RENDERS_PER_NAVIGATION); + }); + + it('filter change while on page 3', async() => { + const { result, mark, rendersSinceMark, requestsSinceMark } = await renderOnPage(3); + + mark(); + await act(async() => { + result.current.onFilterChange({ filter: 'from' }); + }); + await waitForApiResponse(); + + expect(result.current.data).toEqual(responses.page_filtered); + expect(result.current.pagination).toMatchObject({ page: 1, isLoading: false }); + expect(routerStandIn.query).toEqual({ filter: 'from' }); + // parent spec row "Filter change while on page 3" — API requests (the new filter on page 1 only) + expect(requestsSinceMark()).toEqual([ '?filter=from' ]); + // parent spec row "Filter change while on page 3" — renders + expect(rendersSinceMark()).toHaveLength(RENDERS_PER_NAVIGATION); + }); + + it('"Prev" from page 2 to page 1', async() => { + const { result, mark, rendersSinceMark, requestsSinceMark } = await renderOnPage(2); + + mark(); + await act(async() => { + result.current.pagination.onPrevPageClick(); + }); + + // parent spec row "Prev" from page 2 to page 1 — cached rows shown at once, no skeleton + expect(result.current.data).toEqual(responses.page_1); + expect(result.current.isPlaceholderData).toBe(false); + expect(rendersSinceMark()[0]).toEqual({ page: 1, isLoading: false }); + + await waitForApiResponse(); + + expect(result.current.pagination).toMatchObject({ page: 1, isLoading: false }); + // parent spec row "Prev" from page 2 to page 1 — API requests (background refresh of page 1 only) + expect(requestsSinceMark()).toEqual([ '' ]); + // parent spec row "Prev" from page 2 to page 1 — renders + expect(rendersSinceMark()).toHaveLength(RENDERS_PER_NAVIGATION); + }); + + it('unrelated router.query change', async() => { + const { result, mark, consumerRendersSinceMark, requestsSinceMark } = await renderOnPage(2); + const dataBefore = result.current.data; + const resultBefore = result.current; + + mark(); + act(() => { + routerStandIn.setQuery({ ...routerStandIn.query, tab: 'txs' }); + }); + await waitForApiResponse(); + + expect(result.current.data).toBe(dataBefore); + expect(result.current).toBe(resultBefore); + expect(requestsSinceMark()).toEqual([]); + // parent spec row "Unrelated router.query change" — re-renders of a memoized consumer + expect(consumerRendersSinceMark()).toBe(0); + }); +}); + +async function waitForApiResponse() { + await flushPromises(); + await act(flushPromises); +} diff --git a/src/shared/pagination/useApiPaginatedQuery.ts b/src/shared/pagination/useApiPaginatedQuery.ts new file mode 100644 index 00000000000..ef7516facfb --- /dev/null +++ b/src/shared/pagination/useApiPaginatedQuery.ts @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { UseQueryResult } from '@tanstack/react-query'; +import { hashKey } from '@tanstack/react-query'; +import React from 'react'; + +import type { NextPageParams, PaginationParams } from './types'; +import type { ExternalChainExtended } from 'src/shared/external-chains/types'; + +import type { Params as UseApiQueryParams } from 'src/api/hooks/useApiQuery'; +import useApiQuery, { getResourceKey } from 'src/api/hooks/useApiQuery'; +import type { PaginatedResourceName, ResourceError, ResourcePayload } from 'src/api/resources'; + +import { useShallowStable } from 'src/shared/hooks/useShallowStable'; + +import type { PaginationActions } from './usePaginationActions'; +import { usePaginationActions } from './usePaginationActions'; +import type { PaginationUrlParams } from './usePaginationParams'; +import { usePaginationParams } from './usePaginationParams'; + +export interface Params<Resource extends PaginatedResourceName> { + readonly resourceName: Resource; + readonly options?: UseApiQueryParams<Resource>['queryOptions']; + readonly queryParams?: UseApiQueryParams<Resource>['queryParams']; + readonly pathParams?: UseApiQueryParams<Resource>['pathParams']; + readonly scrollRef?: React.RefObject<HTMLDivElement | null>; + readonly hasNextPageFn?: (nextPageParams: NextPageParams) => boolean; + readonly chain?: ExternalChainExtended; + readonly noScroll?: boolean; +} + +export type ApiPaginatedQueryResult<Resource extends PaginatedResourceName> = + UseQueryResult<ResourcePayload<Resource>, ResourceError<unknown>> & + Pick<PaginationUrlParams<Resource>, 'filters' | 'sorting'> & + Pick<PaginationActions<Resource>, 'onFilterChange' | 'onSortingChange'> & + { + readonly pagination: PaginationParams; + readonly queryHash: string; + readonly isInitialLoading: boolean; + readonly isTransitioning: boolean; + }; + +type ResourceQueryParams = NonNullable<UseApiQueryParams<PaginatedResourceName>['queryParams']>; + +function getNextPageParams<R extends PaginatedResourceName>(data: ResourcePayload<R> | undefined): NextPageParams | undefined { + if (!data || typeof data !== 'object' || !('next_page_params' in data)) { + return; + } + + return (data.next_page_params ?? undefined) as NextPageParams | undefined; +} + +function hasMoreItems(nextPageParams: NextPageParams | undefined, hasNextPageFn: Params<PaginatedResourceName>['hasNextPageFn']): boolean { + if (!nextPageParams) { + return false; + } + + return hasNextPageFn ? hasNextPageFn(nextPageParams) : Object.keys(nextPageParams).length > 0; +} + +export default function useApiPaginatedQuery<Resource extends PaginatedResourceName>({ + resourceName, + options, + pathParams, + queryParams: queryParamsFromProps, + scrollRef, + noScroll, + hasNextPageFn, + chain, +}: Params<Resource>): ApiPaginatedQueryResult<Resource> { + const { page, cursor, filters, sorting } = usePaginationParams(resourceName); + + const queryParams = { ...cursor, ...filters, ...sorting, ...queryParamsFromProps } as ResourceQueryParams; + const resolvedQueryParams = Object.keys(queryParams).length ? queryParams : undefined; + + const queryHash = hashKey(getResourceKey(resourceName, { + pathParams, + queryParams: resolvedQueryParams, + chainId: chain?.id, + })); + + const queryResult = useApiQuery(resourceName, { + pathParams, + queryParams: resolvedQueryParams, + queryOptions: { + staleTime: page === 1 ? 0 : Infinity, + ...options, + }, + chain, + }); + const nextPageParams = getNextPageParams(queryResult.data); + + const { canGoBackwards, onNextPageClick, onPrevPageClick, resetPage, onFilterChange, onSortingChange } = usePaginationActions({ + resourceName, + page, + cursor, + nextPageParams, + scrollRef, + noScroll, + }); + + const hasNextPage = hasMoreItems(nextPageParams, hasNextPageFn); + const hasPages = page > 1; + const isLoading = queryResult.isPlaceholderData; + + const pagination = React.useMemo<PaginationParams>(() => ({ + page, + onNextPageClick, + onPrevPageClick, + resetPage, + hasPages, + hasNextPage, + canGoBackwards, + isLoading, + isVisible: hasPages || hasNextPage, + }), [ page, onNextPageClick, onPrevPageClick, resetPage, hasPages, hasNextPage, canGoBackwards, isLoading ]); + + return useShallowStable({ + ...queryResult, + pagination, + onFilterChange, + onSortingChange, + filters, + sorting, + queryHash, + isInitialLoading: isLoading, + isTransitioning: false, + }); +} diff --git a/src/shared/pagination/useDebouncedFilterChange.spec.ts b/src/shared/pagination/useDebouncedFilterChange.spec.ts new file mode 100644 index 00000000000..410da46fedd --- /dev/null +++ b/src/shared/pagination/useDebouncedFilterChange.spec.ts @@ -0,0 +1,74 @@ +// @vitest-environment jsdom + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { renderHook, act, cleanup } from 'vitest/lib'; + +import { DELAY, useDebouncedFilterChange } from './useDebouncedFilterChange'; + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +describe('useDebouncedFilterChange', () => { + it('pushes only the last value once the debounce delay has passed', () => { + const onFilterChange = vi.fn(); + const { result } = renderHook(() => useDebouncedFilterChange(onFilterChange)); + + act(() => { + result.current('a'); + result.current('ab'); + result.current('abc'); + }); + + expect(onFilterChange).not.toHaveBeenCalled(); + + act(() => { + vi.advanceTimersByTime(DELAY); + }); + + expect(onFilterChange).toHaveBeenCalledTimes(1); + expect(onFilterChange).toHaveBeenCalledWith('abc'); + }); + + it('drops a pending push when the component unmounts', () => { + const onFilterChange = vi.fn(); + const { result, unmount } = renderHook(() => useDebouncedFilterChange(onFilterChange)); + + act(() => { + result.current('abc'); + }); + unmount(); + + act(() => { + vi.advanceTimersByTime(DELAY); + }); + + expect(onFilterChange).not.toHaveBeenCalled(); + }); + + it('keeps one identity across renders and fires the latest handler', () => { + const first = vi.fn(); + const second = vi.fn(); + const { result, rerender } = renderHook(({ handler }) => useDebouncedFilterChange(handler), { initialProps: { handler: first } }); + const initial = result.current; + + act(() => { + result.current('abc'); + }); + rerender({ handler: second }); + + expect(result.current).toBe(initial); + + act(() => { + vi.advanceTimersByTime(DELAY); + }); + + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledWith('abc'); + }); +}); diff --git a/src/shared/pagination/useDebouncedFilterChange.ts b/src/shared/pagination/useDebouncedFilterChange.ts new file mode 100644 index 00000000000..69a936b010f --- /dev/null +++ b/src/shared/pagination/useDebouncedFilterChange.ts @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { debounce } from 'es-toolkit'; +import React from 'react'; + +import { SECOND } from 'src/toolkit/utils/consts'; + +export const DELAY = 0.3 * SECOND; + +export type FilterChangeHandler = (value: string) => void; + +// The latest handler is read when the debounce fires, so the returned function keeps one identity while the +// caller's merged filters (the ones it closes over) change between renders. +export function useDebouncedFilterChange(onFilterChange: FilterChangeHandler): FilterChangeHandler { + const latest = React.useRef(onFilterChange); + latest.current = onFilterChange; + + const debounced = React.useMemo(() => debounce((value: string) => latest.current(value), DELAY), []); + React.useEffect(() => () => debounced.cancel(), [ debounced ]); + + return debounced; +} diff --git a/src/shared/pagination/useLazyLoadedList.tsx b/src/shared/pagination/useLazyLoadedList.ts similarity index 100% rename from src/shared/pagination/useLazyLoadedList.tsx rename to src/shared/pagination/useLazyLoadedList.ts diff --git a/src/shared/pagination/usePaginationActions.spec.ts b/src/shared/pagination/usePaginationActions.spec.ts new file mode 100644 index 00000000000..3fa95eb9d9a --- /dev/null +++ b/src/shared/pagination/usePaginationActions.spec.ts @@ -0,0 +1,289 @@ +// @vitest-environment jsdom + +import type React from 'react'; + +import type { NextPageParams } from './types'; + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { renderHook, act, cleanup } from 'vitest/lib'; +import { routerStandIn } from 'vitest/utils/routerStandIn'; + +const { mockScrollToTop } = vi.hoisted(() => ({ + mockScrollToTop: vi.fn(), +})); + +vi.mock('react-scroll', () => ({ animateScroll: { scrollToTop: mockScrollToTop } })); + +import type { PaginationActionsParams } from './usePaginationActions'; +import { usePaginationActions } from './usePaginationActions'; +import { usePaginationParams } from './usePaginationParams'; + +const PAGE_1_CURSOR = { block_number: 11, index: 12, items_count: 13 }; +const PAGE_2_CURSOR = { block_number: 21, index: 22, items_count: 23 }; + +const encodeCursor = (cursor: object) => encodeURIComponent(JSON.stringify(cursor)); + +type Overrides = Partial<Pick<PaginationActionsParams<'core:address_txs'>, 'scrollRef' | 'noScroll'>>; + +interface HookProps { + nextPageParams: NextPageParams | undefined; + overrides?: Overrides; +} + +function renderActions(nextPageParams: NextPageParams | undefined, overrides: Overrides = {}) { + const initialProps: HookProps = { nextPageParams, overrides }; + return renderHook(({ nextPageParams, overrides }: HookProps) => { + const { page, cursor } = usePaginationParams('core:address_txs'); + return usePaginationActions({ + resourceName: 'core:address_txs', + page, + cursor, + nextPageParams, + scrollRef: undefined, + noScroll: undefined, + ...overrides, + }); + }, { initialProps, wrapper: routerStandIn.wrapper }); +} + +beforeEach(() => { + mockScrollToTop.mockClear(); + routerStandIn.reset({ pathname: '/blocks' }); +}); + +afterEach(cleanup); + +describe('next page', () => { + it('pushes the next page number and the encoded cursor, keeping other params', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { tab: 'txs', filter: 'from' } }); + const { result } = renderActions(PAGE_1_CURSOR); + + await act(async() => { + result.current.onNextPageClick(); + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(1); + expect(routerStandIn.push).toHaveBeenLastCalledWith(expect.anything(), { shallow: true }); + expect(routerStandIn.query).toEqual({ tab: 'txs', filter: 'from', page: '2', next_page_params: encodeCursor(PAGE_1_CURSOR) }); + expect(mockScrollToTop).toHaveBeenCalledTimes(1); + }); + + it('does nothing when there is no cursor for the next page', async() => { + const { result } = renderActions(undefined); + + await act(async() => { + result.current.onNextPageClick(); + }); + + expect(routerStandIn.push).not.toHaveBeenCalled(); + expect(mockScrollToTop).not.toHaveBeenCalled(); + }); +}); + +describe('previous page', () => { + it('returns to the cursor recorded when the page was entered', async() => { + const { result, rerender } = renderActions(PAGE_1_CURSOR); + + await act(async() => { + result.current.onNextPageClick(); + }); + rerender({ nextPageParams: PAGE_2_CURSOR }); + await act(async() => { + result.current.onNextPageClick(); + }); + expect(routerStandIn.query).toMatchObject({ page: '3' }); + + await act(async() => { + result.current.onPrevPageClick(); + }); + + expect(routerStandIn.query).toEqual({ page: '2', next_page_params: encodeCursor(PAGE_1_CURSOR) }); + expect(result.current.canGoBackwards).toBe(true); + }); + + it('strips the page params when returning to the first page', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { filter: 'from' } }); + const { result } = renderActions(PAGE_1_CURSOR); + + await act(async() => { + result.current.onNextPageClick(); + }); + await act(async() => { + result.current.onPrevPageClick(); + }); + + expect(routerStandIn.query).toEqual({ filter: 'from' }); + expect(result.current.canGoBackwards).toBe(false); + expect(mockScrollToTop).toHaveBeenCalledTimes(2); + }); + + it('cannot go backwards from a deep page reached by URL', () => { + routerStandIn.reset({ pathname: '/blocks', query: { page: '3', next_page_params: encodeCursor(PAGE_2_CURSOR) } }); + const { result } = renderActions(undefined); + + expect(result.current.canGoBackwards).toBe(false); + }); + + it('can go backwards after moving forward from a page reached by URL', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { page: '2', next_page_params: encodeCursor(PAGE_1_CURSOR) } }); + const { result } = renderActions(PAGE_2_CURSOR); + + await act(async() => { + result.current.onNextPageClick(); + }); + expect(result.current.canGoBackwards).toBe(true); + + await act(async() => { + result.current.onPrevPageClick(); + }); + + expect(routerStandIn.query).toEqual({ page: '2', next_page_params: encodeCursor(PAGE_1_CURSOR) }); + }); +}); + +describe('first page', () => { + it('strips the page params and keeps everything else', async() => { + routerStandIn.reset({ + pathname: '/blocks', + query: { page: '3', next_page_params: encodeCursor(PAGE_2_CURSOR), filter: 'from', sort: 'value' }, + }); + const { result } = renderActions(undefined); + + await act(async() => { + result.current.resetPage(); + }); + + expect(routerStandIn.push).toHaveBeenCalledTimes(1); + expect(routerStandIn.query).toEqual({ filter: 'from', sort: 'value' }); + expect(mockScrollToTop).toHaveBeenCalledTimes(1); + }); +}); + +describe('filter change', () => { + it('replaces the resource filter fields and resets the page', async() => { + routerStandIn.reset({ + pathname: '/blocks', + query: { page: '2', next_page_params: encodeCursor(PAGE_1_CURSOR), filter: 'from', sort: 'value', foo: 'bar' }, + }); + const { result } = renderActions(undefined); + + await act(async() => { + result.current.onFilterChange({ filter: 'to' }); + }); + + expect(routerStandIn.query).toEqual({ filter: 'to', sort: 'value', foo: 'bar' }); + expect(mockScrollToTop).toHaveBeenCalledTimes(1); + }); + + it('drops empty values, joins arrays and keeps booleans', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { filter: 'from', type: 'coin_transfer' } }); + const { result } = renderHook(() => { + const { page, cursor } = usePaginationParams('core:txs'); + return usePaginationActions({ + resourceName: 'core:txs', + page, + cursor, + nextPageParams: undefined, + scrollRef: undefined, + noScroll: undefined, + }); + }, { wrapper: routerStandIn.wrapper }); + + await act(async() => { + // @ts-expect-error -- the URL encoding rules are what is under test, not the per-resource filter types + result.current.onFilterChange({ filter: '', type: [ 'coin_transfer', 'token_transfer' ], only_verified: true }); + }); + + expect(routerStandIn.query).toEqual({ type: 'coin_transfer,token_transfer', only_verified: 'true' }); + }); + + it('clears the filters when called without a value', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { filter: 'from', foo: 'bar' } }); + const { result } = renderActions(undefined); + + await act(async() => { + result.current.onFilterChange(undefined); + }); + + expect(routerStandIn.query).toEqual({ foo: 'bar' }); + }); +}); + +describe('sorting change', () => { + it('replaces sort and order and resets the page', async() => { + routerStandIn.reset({ + pathname: '/blocks', + query: { page: '2', next_page_params: encodeCursor(PAGE_1_CURSOR), sort: 'value', order: 'asc', filter: 'from' }, + }); + const { result } = renderActions(undefined); + + await act(async() => { + result.current.onSortingChange({ sort: 'fee', order: 'desc' }); + }); + + expect(routerStandIn.query).toEqual({ sort: 'fee', order: 'desc', filter: 'from' }); + expect(mockScrollToTop).toHaveBeenCalledTimes(1); + }); + + it('removes sorting when called without a value', async() => { + routerStandIn.reset({ pathname: '/blocks', query: { sort: 'value', order: 'asc', filter: 'from' } }); + const { result } = renderActions(undefined); + + await act(async() => { + result.current.onSortingChange(undefined); + }); + + expect(routerStandIn.query).toEqual({ filter: 'from' }); + }); +}); + +describe('scrolling', () => { + it('scrolls the given element into view instead of the window', async() => { + const scrollRef = { current: { scrollIntoView: vi.fn() } }; + const { result } = renderActions(PAGE_1_CURSOR, { scrollRef: scrollRef as unknown as React.RefObject<HTMLDivElement> }); + + await act(async() => { + result.current.onNextPageClick(); + }); + + expect(scrollRef.current.scrollIntoView).toHaveBeenCalledWith(true); + expect(mockScrollToTop).not.toHaveBeenCalled(); + }); + + it('does not scroll when disabled', async() => { + const { result } = renderActions(PAGE_1_CURSOR, { noScroll: true }); + + await act(async() => { + result.current.onNextPageClick(); + }); + + expect(mockScrollToTop).not.toHaveBeenCalled(); + }); +}); + +describe('stability', () => { + it('keeps the same callbacks across re-renders and navigation', async() => { + const { result, rerender } = renderActions(PAGE_1_CURSOR); + const before = result.current; + + rerender({ nextPageParams: PAGE_2_CURSOR }); + await act(async() => { + result.current.onNextPageClick(); + }); + + expect(result.current.onNextPageClick).toBe(before.onNextPageClick); + expect(result.current.onPrevPageClick).toBe(before.onPrevPageClick); + expect(result.current.resetPage).toBe(before.resetPage); + expect(result.current.onFilterChange).toBe(before.onFilterChange); + expect(result.current.onSortingChange).toBe(before.onSortingChange); + }); + + it('keeps the same object when nothing relevant changed', () => { + const { result, rerender } = renderActions(PAGE_1_CURSOR); + const before = result.current; + + rerender({ nextPageParams: PAGE_1_CURSOR }); + + expect(result.current).toBe(before); + }); +}); diff --git a/src/shared/pagination/usePaginationActions.ts b/src/shared/pagination/usePaginationActions.ts new file mode 100644 index 00000000000..6224695ba73 --- /dev/null +++ b/src/shared/pagination/usePaginationActions.ts @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { omit } from 'es-toolkit'; +import React from 'react'; +import { animateScroll } from 'react-scroll'; + +import type { NextPageParams } from './types'; + +import type { PaginatedResourceName, PaginationFilters, PaginationSorting } from 'src/api/resources'; +import { SORTING_FIELDS } from 'src/api/resources'; + +import { useRouter } from 'src/shared/router/useRouter'; +import type { Router } from 'src/shared/router/useRouter'; + +import { getFilterFields, PAGE_FIELDS } from './usePaginationParams'; + +type Query = Router['query']; + +export interface PaginationActionsParams<Resource extends PaginatedResourceName> { + readonly resourceName: Resource; + readonly page: number; + readonly cursor: NextPageParams; + readonly nextPageParams: NextPageParams | undefined; + readonly scrollRef: React.RefObject<HTMLDivElement | null> | undefined; + readonly noScroll: boolean | undefined; +} + +export interface PaginationActions<Resource extends PaginatedResourceName> { + readonly onNextPageClick: () => void; + readonly onPrevPageClick: () => void; + readonly resetPage: () => void; + readonly onFilterChange: <R extends PaginatedResourceName = Resource>(filters: PaginationFilters<R> | undefined) => void; + readonly onSortingChange: (sorting?: PaginationSorting<Resource>) => void; + readonly canGoBackwards: boolean; +} + +interface LatestInputs<Resource extends PaginatedResourceName> extends PaginationActionsParams<Resource> { + readonly router: Router; +} + +type PageCursors = Record<number, NextPageParams>; + +export function encodeCursor(cursor: NextPageParams): string { + return encodeURIComponent(JSON.stringify(cursor)); +} + +export function scrollListToTop(scrollRef: React.RefObject<HTMLDivElement | null> | undefined, noScroll: boolean | undefined): void { + if (noScroll) { + return; + } + scrollRef?.current ? scrollRef.current.scrollIntoView(true) : animateScroll.scrollToTop({ duration: 0 }); +} + +function isMeaningfulFilterValue(value: unknown): boolean { + return typeof value === 'boolean' || (typeof value === 'string' && value.length > 0) || (Array.isArray(value) && value.length > 0); +} + +function toQueryValue(value: unknown): string { + return Array.isArray(value) ? value.join(',') : String(value); +} + +export function usePaginationActions<Resource extends PaginatedResourceName>(params: PaginationActionsParams<Resource>): PaginationActions<Resource> { + const router = useRouter(); + + const latest = React.useRef<LatestInputs<Resource>>({ ...params, router }); + latest.current = { ...params, router }; + + const cursorsRef = React.useRef<PageCursors | null>(null); + if (cursorsRef.current === null) { + cursorsRef.current = { [params.page]: params.cursor }; + } + + const navigate = React.useCallback((query: Query) => { + const { router, scrollRef, noScroll } = latest.current; + scrollListToTop(scrollRef, noScroll); + router.push({ pathname: router.pathname, query }, { shallow: true }); + }, []); + + const goToFirstPage = React.useCallback((query: Query) => { + cursorsRef.current = {}; + navigate(omit(query, PAGE_FIELDS)); + }, [ navigate ]); + + const onNextPageClick = React.useCallback(() => { + const { router, page, cursor, nextPageParams } = latest.current; + if (!nextPageParams) { + return; + } + + const cursors = cursorsRef.current ?? {}; + cursors[page] = cursor; + cursors[page + 1] = nextPageParams; + cursorsRef.current = cursors; + + navigate({ ...router.query, page: String(page + 1), next_page_params: encodeCursor(nextPageParams) }); + }, [ navigate ]); + + const onPrevPageClick = React.useCallback(() => { + const { router, page } = latest.current; + const previousPage = page - 1; + const previousCursor = cursorsRef.current?.[previousPage]; + + if (previousPage <= 1 || !previousCursor) { + goToFirstPage(router.query); + return; + } + + navigate({ ...router.query, page: String(previousPage), next_page_params: encodeCursor(previousCursor) }); + }, [ goToFirstPage, navigate ]); + + const resetPage = React.useCallback(() => { + goToFirstPage(latest.current.router.query); + }, [ goToFirstPage ]); + + const onFilterChange = React.useCallback(<R extends PaginatedResourceName = Resource>(filters: PaginationFilters<R> | undefined) => { + const { router, resourceName } = latest.current; + const query: Query = omit(router.query, getFilterFields(resourceName)); + + Object.entries(filters ?? {}).forEach(([ key, value ]) => { + if (isMeaningfulFilterValue(value)) { + query[key] = toQueryValue(value); + } + }); + + goToFirstPage(query); + }, [ goToFirstPage ]); + + const onSortingChange = React.useCallback((sorting?: PaginationSorting<Resource>) => { + const { router } = latest.current; + goToFirstPage({ ...omit(router.query, SORTING_FIELDS), ...sorting }); + }, [ goToFirstPage ]); + + return React.useMemo(() => ({ + onNextPageClick, + onPrevPageClick, + resetPage, + onFilterChange, + onSortingChange, + canGoBackwards: Boolean(cursorsRef.current?.[params.page - 1]), + }), [ onNextPageClick, onPrevPageClick, resetPage, onFilterChange, onSortingChange, params.page ]); +} diff --git a/src/shared/pagination/usePaginationParams.spec.ts b/src/shared/pagination/usePaginationParams.spec.ts new file mode 100644 index 00000000000..258da09aa81 --- /dev/null +++ b/src/shared/pagination/usePaginationParams.spec.ts @@ -0,0 +1,92 @@ +// @vitest-environment jsdom + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { renderHook, act, cleanup } from 'vitest/lib'; +import { routerStandIn } from 'vitest/utils/routerStandIn'; + +import { usePaginationParams } from './usePaginationParams'; + +const CURSOR = { block_number: 11, index: 12, items_count: 13 }; +const ENCODED_CURSOR = encodeURIComponent(JSON.stringify(CURSOR)); + +beforeEach(() => { + routerStandIn.reset({ pathname: '/blocks' }); +}); + +afterEach(cleanup); + +describe('usePaginationParams', () => { + it('defaults to the first page with no cursor, filters or sorting', () => { + const { result } = renderHook(() => usePaginationParams('core:address_txs'), { wrapper: routerStandIn.wrapper }); + + expect(result.current).toEqual({ page: 1, cursor: {}, filters: {}, sorting: {} }); + }); + + it('reads page and cursor from the URL', () => { + routerStandIn.reset({ pathname: '/blocks', query: { page: '3', next_page_params: ENCODED_CURSOR } }); + + const { result } = renderHook(() => usePaginationParams('core:address_txs'), { wrapper: routerStandIn.wrapper }); + + expect(result.current.page).toBe(3); + expect(result.current.cursor).toEqual(CURSOR); + }); + + it('ignores a cursor that is not valid JSON', () => { + routerStandIn.reset({ pathname: '/blocks', query: { page: '2', next_page_params: 'not-json' } }); + + const { result } = renderHook(() => usePaginationParams('core:address_txs'), { wrapper: routerStandIn.wrapper }); + + expect(result.current.cursor).toEqual({}); + }); + + it('falls back to page 1 when the page param is repeated', () => { + routerStandIn.reset({ pathname: '/blocks', query: { page: [ '2', '3' ] } }); + + const { result } = renderHook(() => usePaginationParams('core:address_txs'), { wrapper: routerStandIn.wrapper }); + + expect(result.current.page).toBe(1); + }); + + it('picks only the filter fields declared by the resource', () => { + routerStandIn.reset({ pathname: '/blocks', query: { filter: 'from', type: 'coin_transfer', foo: 'bar' } }); + + const { result: addressTxs } = renderHook(() => usePaginationParams('core:address_txs'), { wrapper: routerStandIn.wrapper }); + const { result: txs } = renderHook(() => usePaginationParams('core:txs'), { wrapper: routerStandIn.wrapper }); + + expect(addressTxs.current.filters).toEqual({ filter: 'from' }); + expect(txs.current.filters).toEqual({ filter: 'from', type: 'coin_transfer' }); + }); + + it('reads sorting from the sort and order params', () => { + routerStandIn.reset({ pathname: '/blocks', query: { sort: 'value', order: 'desc', foo: 'bar' } }); + + const { result } = renderHook(() => usePaginationParams('core:address_txs'), { wrapper: routerStandIn.wrapper }); + + expect(result.current.sorting).toEqual({ sort: 'value', order: 'desc' }); + }); + + it('keeps the same object across an unrelated URL change', () => { + routerStandIn.reset({ pathname: '/blocks', query: { page: '2', next_page_params: ENCODED_CURSOR, filter: 'to' } }); + const { result } = renderHook(() => usePaginationParams('core:address_txs'), { wrapper: routerStandIn.wrapper }); + const before = result.current; + + act(() => { + routerStandIn.setQuery({ ...routerStandIn.query, tab: 'txs' }); + }); + + expect(result.current).toBe(before); + }); + + it('returns a new object when a list param changes', () => { + routerStandIn.reset({ pathname: '/blocks', query: { filter: 'to' } }); + const { result } = renderHook(() => usePaginationParams('core:address_txs'), { wrapper: routerStandIn.wrapper }); + const before = result.current; + + act(() => { + routerStandIn.setQuery({ filter: 'from' }); + }); + + expect(result.current).not.toBe(before); + expect(result.current.filters).toEqual({ filter: 'from' }); + }); +}); diff --git a/src/shared/pagination/usePaginationParams.ts b/src/shared/pagination/usePaginationParams.ts new file mode 100644 index 00000000000..c12c52b7021 --- /dev/null +++ b/src/shared/pagination/usePaginationParams.ts @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { NextPageParams } from './types'; + +import type { PaginatedResourceName, PaginationFilters, PaginationSorting } from 'src/api/resources'; +import { SORTING_FIELDS } from 'src/api/resources'; +import { getResource } from 'src/api/utils/get-resource'; + +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; +import type { Router } from 'src/shared/router/useRouter'; + +type Query = Router['query']; +type QueryValue = string | Array<string>; + +export interface PaginationUrlParams<Resource extends PaginatedResourceName> { + readonly page: number; + readonly cursor: NextPageParams; + readonly filters: PaginationFilters<Resource>; + readonly sorting: PaginationSorting<Resource>; +} + +export const PAGE_FIELDS = [ 'page', 'next_page_params' ]; + +const NO_FILTER_FIELDS: Array<string> = []; + +export function getFilterFields(resourceName: PaginatedResourceName): Array<string> { + return getResource(resourceName).filterFields ?? NO_FILTER_FIELDS; +} + +export function getPageFromQuery(query: Query): number { + return query.page && !Array.isArray(query.page) ? Number(query.page) : 1; +} + +export function getCursorFromQuery(query: Query): NextPageParams { + if (!query.next_page_params) { + return {}; + } + + try { + return JSON.parse(decodeURIComponent(getQueryParamString(query.next_page_params))) as NextPageParams; + } catch (error) { + return {}; + } +} + +function pickPresentFields<T = Record<string, QueryValue>>(query: Query, fields: Array<string>): T { + const result: Record<string, QueryValue> = {}; + for (const field of fields) { + const value = query[field]; + if (value !== undefined) { + result[field] = value; + } + } + return result as T; +} + +function deriveParams<Resource extends PaginatedResourceName>(query: Query, filterFields: Array<string>): PaginationUrlParams<Resource> { + return { + page: getPageFromQuery(query), + cursor: getCursorFromQuery(query), + filters: pickPresentFields<PaginationFilters<Resource>>(query, filterFields), + sorting: pickPresentFields<PaginationSorting<Resource>>(query, SORTING_FIELDS), + }; +} + +export function usePaginationParams<Resource extends PaginatedResourceName>(resourceName: Resource): PaginationUrlParams<Resource> { + const router = useRouter(); + const filterFields = getFilterFields(resourceName); + const relevantQuery = JSON.stringify(pickPresentFields(router.query, [ ...PAGE_FIELDS, ...filterFields, ...SORTING_FIELDS ])); + + return React.useMemo( + () => deriveParams<Resource>(JSON.parse(relevantQuery) as Query, filterFields), + [ relevantQuery, filterFields ], + ); +} diff --git a/src/shared/pagination/useQueryWithPages.spec.tsx b/src/shared/pagination/useQueryWithPages.spec.tsx deleted file mode 100644 index 3f6be8e8f19..00000000000 --- a/src/shared/pagination/useQueryWithPages.spec.tsx +++ /dev/null @@ -1,687 +0,0 @@ -// @vitest-environment jsdom - -import { useRouter } from 'next/router'; -import type React from 'react'; - -import * as addressParamMock from 'src/slices/address/mocks/address-param'; - -import type { Mock } from 'vitest'; -import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { renderHook, wrapper, act } from 'vitest/lib'; -import flushPromises from 'vitest/utils/flushPromises'; - -const { mockScrollToTop, mockRouterPush } = vi.hoisted(() => ({ - mockScrollToTop: vi.fn(), - mockRouterPush: vi.fn(() => Promise.resolve(true)), -})); - -vi.mock('next/router', () => ({ - useRouter: vi.fn(() => ({ - query: {}, - push: mockRouterPush, - })), -})); -vi.mock('react-scroll', () => ({ animateScroll: { scrollToTop: mockScrollToTop } })); - -import type { Params, QueryWithPagesResult } from './useQueryWithPages'; -import useQueryWithPages from './useQueryWithPages'; - -const mockUseRouter = useRouter as Mock<typeof useRouter>; - -export const router = { - query: {}, - push: mockRouterPush, - pathname: '/' as const, -} as unknown as ReturnType<typeof useRouter>; - -const responses = { - page_empty: { - items: [], - next_page_params: null, - }, - page_1: { - items: [ { hash: '11' }, { hash: '12' } ], - next_page_params: { - block_number: 11, - index: 12, - items_count: 13, - }, - }, - page_2: { - items: [ { hash: '21' }, { hash: '22' } ], - next_page_params: { - block_number: 21, - index: 22, - items_count: 23, - }, - }, - page_3: { - items: [ { hash: '31' }, { hash: '32' } ], - next_page_params: null, - }, - page_filtered: { - items: [ { hash: '41' }, { hash: '42' } ], - next_page_params: { - block_number: 41, - index: 42, - items_count: 43, - }, - }, - page_sorted: { - items: [ { hash: '61' }, { hash: '62' } ], - next_page_params: null, - }, -}; - -beforeEach(() => { - fetchMock.resetMocks(); - mockScrollToTop.mockClear(); - mockRouterPush.mockClear(); -}); - -const responseInit = { - headers: { - 'Content-Type': 'application/json', - }, -}; - -it('returns correct data if there is only one page', async() => { - const params: Params<'core:address_txs'> = { - resourceName: 'core:address_txs', - pathParams: { hash: addressParamMock.hash }, - }; - fetchMock.mockResponse(JSON.stringify(responses.page_empty), responseInit); - mockUseRouter.mockReturnValue(router); - - const { result } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_empty); - expect(result.current.pagination).toMatchObject({ - page: 1, - canGoBackwards: false, - hasNextPage: false, - isLoading: false, - isVisible: false, - hasPages: false, - }); -}); - -describe('if there are multiple pages', () => { - const params: Params<'core:address_txs'> = { - resourceName: 'core:address_txs', - pathParams: { hash: addressParamMock.hash }, - }; - - it('return correct data for the first page', async() => { - fetchMock.mockResponse(JSON.stringify(responses.page_1), responseInit); - mockUseRouter.mockReturnValue(router); - - const { result } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_1); - expect(result.current.pagination).toMatchObject({ - page: 1, - canGoBackwards: false, - hasNextPage: true, - isLoading: false, - isVisible: true, - }); - }); - - describe('correctly navigates forward and backward', () => { - let result: { - current: QueryWithPagesResult<'core:address_txs'>; - }; - - beforeEach(async() => { - mockUseRouter.mockReturnValue({ ...router, pathname: '/blocks' }); - - fetchMock.once(JSON.stringify(responses.page_1), responseInit); - fetchMock.once(JSON.stringify(responses.page_2), responseInit); - fetchMock.once(JSON.stringify(responses.page_3), responseInit); - fetchMock.once(JSON.stringify(responses.page_1), responseInit); - - // INITIAL LOAD - const { result: r } = renderHook(() => useQueryWithPages(params), { wrapper }); - result = r; - await waitForApiResponse(); - }); - - it('from page 1 to page 2', async() => { - await act(() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_2); - expect(result.current.pagination).toMatchObject({ - page: 2, - canGoBackwards: true, - hasNextPage: true, - isLoading: false, - isVisible: true, - hasPages: true, - }); - - expect(mockRouterPush).toHaveBeenCalledTimes(1); - expect(mockRouterPush).toHaveBeenLastCalledWith( - { - pathname: '/blocks', - query: { - next_page_params: encodeURIComponent(JSON.stringify(responses.page_1.next_page_params)), - page: '2', - }, - }, - undefined, - { shallow: true }, - ); - - expect(mockScrollToTop).toHaveBeenCalledTimes(1); - expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); - }); - - it('from page 2 to page 3', async() => { - await act(async() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - await act(async() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_3); - expect(result.current.pagination).toMatchObject({ - page: 3, - canGoBackwards: true, - hasNextPage: false, - isLoading: false, - isVisible: true, - hasPages: true, - }); - - expect(mockRouterPush).toHaveBeenCalledTimes(2); - expect(mockRouterPush).toHaveBeenLastCalledWith( - { - pathname: '/blocks', - query: { - next_page_params: encodeURIComponent(JSON.stringify(responses.page_2.next_page_params)), - page: '3', - }, - }, - undefined, - { shallow: true }, - ); - - expect(mockScrollToTop).toHaveBeenCalledTimes(2); - expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); - }); - - it('from page 3 to page 2', async() => { - - await act(() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - await act(() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - await act(() => { - result.current.pagination.onPrevPageClick(); - }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_2); - expect(result.current.pagination).toMatchObject({ - page: 2, - canGoBackwards: true, - hasNextPage: true, - isLoading: false, - isVisible: true, - hasPages: true, - }); - - expect(mockRouterPush).toHaveBeenCalledTimes(3); - expect(mockRouterPush).toHaveBeenLastCalledWith( - { - pathname: '/blocks', - query: { - next_page_params: encodeURIComponent(JSON.stringify(responses.page_1.next_page_params)), - page: '2', - }, - }, - undefined, - { shallow: true }, - ); - - expect(mockScrollToTop).toHaveBeenCalledTimes(3); - expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); - }); - - it('from page 2 to page 1', async() => { - await act(() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - await act(() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - await act(() => { - result.current.pagination.onPrevPageClick(); - }); - await waitForApiResponse(); - - await act(() => { - result.current.pagination.onPrevPageClick(); - }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_1); - expect(result.current.pagination).toMatchObject({ - page: 1, - canGoBackwards: false, - hasNextPage: true, - isLoading: false, - isVisible: true, - hasPages: true, - }); - - expect(mockRouterPush).toHaveBeenCalledTimes(4); - expect(mockRouterPush).toHaveBeenLastCalledWith( - { - pathname: '/blocks', - query: {}, - }, - undefined, - { shallow: true }, - ); - - expect(mockScrollToTop).toHaveBeenCalledTimes(4); - expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); - }); - }); - - it('correctly resets the page', async() => { - mockUseRouter.mockReturnValue({ ...router, pathname: '/blocks' }); - - fetchMock.once(JSON.stringify(responses.page_1), responseInit); - fetchMock.once(JSON.stringify(responses.page_2), responseInit); - fetchMock.once(JSON.stringify(responses.page_3), responseInit); - fetchMock.once(JSON.stringify(responses.page_1), responseInit); - - const { result } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - await act(async() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - await act(async() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - await act(async() => { - result.current.pagination.resetPage(); - }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_1); - expect(result.current.pagination).toMatchObject({ - page: 1, - canGoBackwards: false, - hasNextPage: true, - isLoading: false, - isVisible: true, - hasPages: true, - }); - - expect(mockRouterPush).toHaveBeenCalledTimes(3); - expect(mockRouterPush).toHaveBeenLastCalledWith( - { - pathname: '/blocks', - query: {}, - }, - undefined, - { shallow: true }, - ); - - expect(mockScrollToTop).toHaveBeenCalledTimes(3); - expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); - }); - - it('when navigates between pages can scroll to custom element', async() => { - const scrollRef = { - current: { - scrollIntoView: vi.fn(), - }, - }; - const params: Params<'core:address_txs'> = { - resourceName: 'core:address_txs', - pathParams: { hash: addressParamMock.hash }, - scrollRef: scrollRef as unknown as React.RefObject<HTMLDivElement>, - }; - fetchMock.once(JSON.stringify(responses.page_1), responseInit); - fetchMock.once(JSON.stringify(responses.page_2), responseInit); - mockUseRouter.mockReturnValue(router); - - const { result } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - await act(async() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - expect(scrollRef.current.scrollIntoView).toHaveBeenCalledTimes(1); - expect(scrollRef.current.scrollIntoView).toHaveBeenCalledWith(true); - }); -}); - -describe('if there is page query param in URL', () => { - it('sets this param as the page number', async() => { - mockUseRouter.mockReturnValue({ ...router, query: { page: '3' } } as unknown as ReturnType<typeof useRouter>); - - const params: Params<'core:address_txs'> = { - resourceName: 'core:address_txs', - pathParams: { hash: addressParamMock.hash }, - }; - fetchMock.mockResponse(JSON.stringify(responses.page_empty), responseInit); - - const { result } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_empty); - expect(result.current.pagination).toMatchObject({ - page: 3, - canGoBackwards: false, - hasNextPage: false, - isLoading: false, - isVisible: true, - hasPages: true, - }); - }); - - it('correctly navigates to the following pages', async() => { - mockUseRouter.mockReturnValue({ ...router, pathname: '/blocks', query: { page: '2' } }); - - const params: Params<'core:address_txs'> = { - resourceName: 'core:address_txs', - pathParams: { hash: addressParamMock.hash }, - }; - fetchMock.once(JSON.stringify(responses.page_2), responseInit); - fetchMock.once(JSON.stringify(responses.page_3), responseInit); - - const { result } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - await act(async() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_3); - expect(result.current.pagination).toMatchObject({ - page: 3, - canGoBackwards: true, - hasNextPage: false, - isLoading: false, - isVisible: true, - hasPages: true, - }); - - expect(mockRouterPush).toHaveBeenCalledTimes(1); - expect(mockRouterPush).toHaveBeenLastCalledWith( - { - pathname: '/blocks', - query: { - next_page_params: encodeURIComponent(JSON.stringify(responses.page_2.next_page_params)), - page: '3', - }, - }, - undefined, - { shallow: true }, - ); - }); -}); - -describe('queries with filters', () => { - it('reset page, keep sorting when filter is changed', async() => { - mockUseRouter.mockReturnValue({ ...router, pathname: '/blocks', query: { foo: 'bar', sort: 'val-desc' } }); - - const params: Params<'core:address_txs'> = { - resourceName: 'core:address_txs', - pathParams: { hash: addressParamMock.hash }, - - // @ts-ignore: - sorting: { sort: 'val-desc' }, - }; - fetchMock.once(JSON.stringify(responses.page_1), responseInit); - fetchMock.once(JSON.stringify(responses.page_2), responseInit); - fetchMock.once(JSON.stringify(responses.page_filtered), responseInit); - - const { result } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - await act(async() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - await act(async() => { - result.current.onFilterChange({ filter: 'from' }); - }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_filtered); - expect(result.current.pagination).toMatchObject({ - page: 1, - canGoBackwards: false, - hasNextPage: true, - isLoading: false, - isVisible: true, - hasPages: false, - }); - - expect(mockRouterPush).toHaveBeenCalledTimes(2); - expect(mockRouterPush).toHaveBeenLastCalledWith( - { - pathname: '/blocks', - query: { filter: 'from', foo: 'bar', sort: 'val-desc' }, - }, - undefined, - { shallow: true }, - ); - - expect(mockScrollToTop).toHaveBeenCalledTimes(2); - expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); - }); - - it('saves filter params in query when navigating between pages', async() => { - mockUseRouter.mockReturnValue({ ...router, pathname: '/blocks', query: { filter: 'from', foo: 'bar' } }); - - const params: Params<'core:address_txs'> = { - resourceName: 'core:address_txs', - pathParams: { hash: addressParamMock.hash }, - }; - fetchMock.once(JSON.stringify(responses.page_1), responseInit); - fetchMock.once(JSON.stringify(responses.page_2), responseInit); - - const { result } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - await act(async() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - expect(mockRouterPush).toHaveBeenCalledTimes(1); - expect(mockRouterPush).toHaveBeenLastCalledWith( - { - pathname: '/blocks', - query: { - filter: 'from', - foo: 'bar', - next_page_params: encodeURIComponent(JSON.stringify(responses.page_1.next_page_params)), - page: '2', - }, - }, - undefined, - { shallow: true }, - ); - }); -}); - -describe('queries with sorting', () => { - it('reset page, save filter when sorting is changed', async() => { - mockUseRouter.mockReturnValue({ ...router, pathname: '/blocks', query: { foo: 'bar', filter: 'from' } }); - - const params: Params<'core:address_txs'> = { - resourceName: 'core:address_txs', - pathParams: { hash: addressParamMock.hash }, - filters: { filter: 'from' }, - }; - fetchMock.once(JSON.stringify(responses.page_1), responseInit); - fetchMock.once(JSON.stringify(responses.page_2), responseInit); - fetchMock.once(JSON.stringify(responses.page_sorted), responseInit); - - const { result } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - await act(async() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - await act(async() => { - - // @ts-ignore: - result.current.onSortingChange({ sort: 'val-desc' }); - }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_sorted); - expect(result.current.pagination).toMatchObject({ - page: 1, - canGoBackwards: false, - hasNextPage: false, - isLoading: false, - isVisible: false, - hasPages: false, - }); - - expect(mockRouterPush).toHaveBeenCalledTimes(2); - expect(mockRouterPush).toHaveBeenLastCalledWith( - { - pathname: '/blocks', - query: { filter: 'from', foo: 'bar', sort: 'val-desc' }, - }, - undefined, - { shallow: true }, - ); - - expect(mockScrollToTop).toHaveBeenCalledTimes(2); - expect(mockScrollToTop).toHaveBeenLastCalledWith({ duration: 0 }); - }); - - it('saves sorting params in query when navigating between pages', async() => { - mockUseRouter.mockReturnValue({ ...router, pathname: '/blocks', query: { foo: 'bar', sort: 'val-desc' } }); - - const params: Params<'core:address_txs'> = { - resourceName: 'core:address_txs', - pathParams: { hash: addressParamMock.hash }, - - // @ts-ignore: - sorting: { sort: 'val-desc' }, - }; - fetchMock.once(JSON.stringify(responses.page_1), responseInit); - fetchMock.once(JSON.stringify(responses.page_2), responseInit); - - const { result } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - await act(async() => { - result.current.pagination.onNextPageClick(); - }); - await waitForApiResponse(); - - expect(mockRouterPush).toHaveBeenCalledTimes(1); - expect(mockRouterPush).toHaveBeenLastCalledWith( - { - pathname: '/blocks', - query: { - sort: 'val-desc', - foo: 'bar', - next_page_params: encodeURIComponent(JSON.stringify(responses.page_1.next_page_params)), - page: '2', - }, - }, - undefined, - { shallow: true }, - ); - }); -}); - -describe('router query changes', () => { - it('refetches correct page when page number changes in URL', async() => { - const router = { - pathname: '/blocks' as const, - push: mockRouterPush, - query: { - page: '3', - next_page_params: encodeURIComponent(JSON.stringify(responses.page_2.next_page_params)), - }, - } as unknown as ReturnType<typeof useRouter>; - mockUseRouter.mockReturnValue(router); - - const params: Params<'core:address_txs'> = { - resourceName: 'core:address_txs', - pathParams: { hash: addressParamMock.hash }, - }; - - fetchMock.once(JSON.stringify(responses.page_3), responseInit); - fetchMock.once(JSON.stringify(responses.page_2), responseInit); - - const { result, rerender } = renderHook(() => useQueryWithPages(params), { wrapper }); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_3); - expect(result.current.pagination.page).toBe(3); - - // Simulate URL change to page 2 - mockUseRouter.mockReturnValue({ - ...router, - query: { - page: '2', - next_page_params: encodeURIComponent(JSON.stringify(responses.page_1.next_page_params)), - } as never, - }); - - rerender(); - await waitForApiResponse(); - - expect(result.current.data).toEqual(responses.page_2); - expect(result.current.pagination).toMatchObject({ - page: 2, - canGoBackwards: false, - hasNextPage: true, - isLoading: false, - isVisible: true, - }); - }); -}); - -async function waitForApiResponse() { - await flushPromises(); - await act(flushPromises); -} diff --git a/src/shared/pagination/useQueryWithPages.ts b/src/shared/pagination/useQueryWithPages.ts deleted file mode 100644 index 668b0e7302e..00000000000 --- a/src/shared/pagination/useQueryWithPages.ts +++ /dev/null @@ -1,341 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { UseQueryResult } from '@tanstack/react-query'; -import { hashKey, useQueryClient } from '@tanstack/react-query'; -import { clamp, omit } from 'es-toolkit'; -import { useRouter } from 'next/router'; -import type { Route } from 'nextjs-routes'; -import React, { useCallback } from 'react'; -import { animateScroll } from 'react-scroll'; - -import type { PaginationParams } from './types'; - -import type { Params as UseApiQueryParams } from 'src/api/hooks/useApiQuery'; -import useApiQuery, { getResourceKey } from 'src/api/hooks/useApiQuery'; -import type { PaginatedResourceName, PaginationFilters, PaginationSorting, ResourceError, ResourcePayload } from 'src/api/resources'; -import { SORTING_FIELDS } from 'src/api/resources'; -import getResourceParams from 'src/api/utils/get-resource-params'; - -import multichainConfig from 'src/features/multichain/chains-config'; -import { useMultichainContext } from 'src/features/multichain/context'; -import getChainValueFromQuery from 'src/features/multichain/utils/get-chain-value-from-query'; - -import getQueryParamString from 'src/shared/router/get-query-param-string'; - -type NextPageParams = Record<string, unknown>; - -export interface Params<Resource extends PaginatedResourceName> { - resourceName: Resource; - options?: UseApiQueryParams<Resource>['queryOptions']; - queryParams?: UseApiQueryParams<Resource>['queryParams']; - pathParams?: UseApiQueryParams<Resource>['pathParams']; - filters?: PaginationFilters<Resource>; - sorting?: PaginationSorting<Resource>; - scrollRef?: React.RefObject<HTMLDivElement | null>; - hasNextPageFn?: (nextPageParams: NextPageParams) => boolean; - isMultichain?: boolean; - chainIds?: Array<string>; - noScroll?: boolean; -} - -const INITIAL_PAGE_PARAMS = { '1': {} }; - -function getPageFromQuery(query: Route['query']) { - return query?.page && !Array.isArray(query.page) ? Number(query.page) : 1; -} - -function getPaginationParamsFromQuery(queryString: string | Array<string> | undefined) { - if (queryString) { - try { - return JSON.parse(decodeURIComponent(getQueryParamString(queryString))) as NextPageParams; - } catch (error) {} - } - - return {}; -} - -function getNextPageParams<R extends PaginatedResourceName>(data: ResourcePayload<R> | undefined) { - if (!data || typeof data !== 'object' || !('next_page_params' in data)) { - return; - } - - return data.next_page_params; -} - -export type QueryWithPagesResult<Resource extends PaginatedResourceName> = -UseQueryResult<ResourcePayload<Resource>, ResourceError<unknown>> & -{ - onFilterChange: <R extends PaginatedResourceName = Resource>(filters: PaginationFilters<R>) => void; - onSortingChange: (sorting?: PaginationSorting<Resource>) => void; - pagination: PaginationParams; - chainValue: Array<string> | undefined; - onChainValueChange: ({ value }: { value: Array<string> }) => void; - queryHash: string; -}; - -export default function useQueryWithPages<Resource extends PaginatedResourceName>({ - resourceName, - filters, - sorting, - options, - pathParams, - queryParams: queryParamsFromProps, - scrollRef, - noScroll, - hasNextPageFn, - isMultichain, - chainIds, -}: Params<Resource>): QueryWithPagesResult<Resource> { - const queryClient = useQueryClient(); - const router = useRouter(); - const multichainContext = useMultichainContext(); - - const hasChainValue = Boolean(isMultichain ?? multichainContext?.chain); - - const [ page, setPage ] = React.useState<number>(getPageFromQuery(router.query)); - const [ pageParams, setPageParams ] = React.useState<Record<number, NextPageParams>>({ - [page]: getPaginationParamsFromQuery(router.query.next_page_params), - }); - const [ hasPages, setHasPages ] = React.useState(page > 1); - const [ chainValue, setChainValue ] = React.useState<Array<string> | undefined>( - hasChainValue ? [ getChainValueFromQuery(router.query, chainIds) ].filter(Boolean) : undefined, - ); - - const selectedChain = React.useMemo(() => { - if (!hasChainValue) { - return; - } - - if (multichainContext?.chain) { - return multichainContext.chain.id === chainValue?.[0] ? multichainContext.chain : undefined; - } - - const config = multichainConfig(); - if (config) { - return config.chains.find((chain) => chain.id === chainValue?.[0]); - } - }, [ chainValue, hasChainValue, multichainContext?.chain ]); - - const isMounted = React.useRef(false); - const queryParams = { ...pageParams[page], ...filters, ...sorting, ...queryParamsFromProps }; - const resolvedQueryParams = Object.keys(queryParams).length ? queryParams : undefined; - - // Stable hash of the query identity (resource + path/query params + chain), mirroring the key - // useApiQuery builds below. Exposed as `queryHash` so list components can use it as the - // `resetKey` for useLazyRenderedList: it changes on filter/pagination/chain changes but is - // stable across in-place cache updates (socket prepends via setQueryData), which is exactly - // when the render window should / shouldn't reset. - const queryHash = hashKey(getResourceKey(resourceName, { - pathParams, - queryParams: resolvedQueryParams, - chainId: (selectedChain || multichainContext?.chain)?.id, - })); - - const scrollToTop = useCallback(() => { - if (noScroll) { - return; - } - scrollRef?.current ? scrollRef.current.scrollIntoView(true) : animateScroll.scrollToTop({ duration: 0 }); - }, [ scrollRef, noScroll ]); - - const queryResult = useApiQuery(resourceName, { - pathParams, - queryParams: resolvedQueryParams, - queryOptions: { - staleTime: page === 1 ? 0 : Infinity, - ...options, - }, - chain: selectedChain, - }); - const { data } = queryResult; - const nextPageParams = getNextPageParams(data); - - React.useEffect(() => { - if (hasChainValue) { - setChainValue([ getChainValueFromQuery(router.query, chainIds) ].filter(Boolean)); - } - // don't trigger the hook on query change - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ chainIds, hasChainValue ]); - - const onNextPageClick = useCallback(() => { - if (!nextPageParams) { - // we hide next page button if no next_page_params - return; - } - - setPageParams((prev) => ({ - ...prev, - [page + 1]: nextPageParams as NextPageParams, - })); - setPage(prev => prev + 1); - - const nextPageQuery = { - ...router.query, - page: String(page + 1), - next_page_params: encodeURIComponent(JSON.stringify(nextPageParams)), - }; - - setHasPages(true); - scrollToTop(); - router.push({ pathname: router.pathname, query: nextPageQuery }, undefined, { shallow: true }); - }, [ nextPageParams, page, router, scrollToTop ]); - - const onPrevPageClick = useCallback(() => { - // returning to the first page - // we don't have pagination params for the first page - let nextPageQuery: typeof router.query = { ...router.query }; - if (page === 2) { - nextPageQuery = omit(router.query, [ 'next_page_params', 'page' ]); - } else { - nextPageQuery.next_page_params = encodeURIComponent(JSON.stringify(pageParams[page - 1])); - nextPageQuery.page = String(page - 1); - } - - scrollToTop(); - setPage(prev => clamp(prev - 1, 1, Infinity)); - page === 2 && queryClient.removeQueries({ queryKey: [ resourceName ] }); - router.push({ pathname: router.pathname, query: nextPageQuery }, undefined, { shallow: true }); - }, [ router, page, pageParams, scrollToTop, queryClient, resourceName ]); - - const resetPage = useCallback(({ chainValue }: { chainValue?: Array<string> } = {}) => { - queryClient.removeQueries({ queryKey: [ resourceName ] }); - - scrollToTop(); - const nextRouterQuery = omit(router.query, [ 'next_page_params', 'page' ]); - if (chainValue) { - nextRouterQuery.chain_id = chainValue[0]; - } - router.push({ pathname: router.pathname, query: nextRouterQuery }, undefined, { shallow: true }).then(() => { - queryClient.removeQueries({ queryKey: [ resourceName ] }); - setPage(1); - setPageParams(INITIAL_PAGE_PARAMS); - chainValue && setChainValue(chainValue); - window.setTimeout(() => { - // FIXME after router is updated we still have inactive queries for previously visited page (e.g third), where we came from - // so have to remove it but with some delay :) - queryClient.removeQueries({ queryKey: [ resourceName ], type: 'inactive' }); - }, 100); - }); - }, [ queryClient, resourceName, router, scrollToTop ]); - - const onFilterChange = useCallback(<R extends PaginatedResourceName = Resource>(newFilters: PaginationFilters<R> | undefined) => { - const { resource } = getResourceParams(resourceName, selectedChain); - const newQuery: typeof router.query = omit( - router.query, - [ - 'next_page_params', - 'page', - ...(resource.filterFields || []), - ], - ); - if (newFilters) { - Object.entries(newFilters).forEach(([ key, value ]) => { - const isValidValue = typeof value === 'boolean' || (value && value.length); - if (isValidValue) { - newQuery[key] = Array.isArray(value) ? value.join(',') : (String(value) || ''); - } - }); - } - scrollToTop(); - router.push( - { - pathname: router.pathname, - query: newQuery, - }, - undefined, - { shallow: true }, - ).then(() => { - setHasPages(false); - setPage(1); - setPageParams(INITIAL_PAGE_PARAMS); - }); - }, [ resourceName, selectedChain, router, scrollToTop ]); - - const onSortingChange = useCallback((newSorting: PaginationSorting<Resource> | undefined) => { - const newQuery: typeof router.query = { - ...omit(router.query, [ 'next_page_params', 'page', ...SORTING_FIELDS ]), - ...newSorting, - }; - scrollToTop(); - router.push( - { - pathname: router.pathname, - query: newQuery, - }, - undefined, - { shallow: true }, - ).then(() => { - setHasPages(false); - setPage(1); - setPageParams(INITIAL_PAGE_PARAMS); - }); - }, [ router, scrollToTop ]); - - const onChainValueChange = useCallback(({ value }: { value: Array<string> }) => { - - if (options?.enabled === false) { - setChainValue(value); - return; - } - - if (page !== 1) { - resetPage({ chainValue: value }); - } else { - const nextPageQuery = { - ...router.query, - chain_id: value[0], - }; - - setChainValue(value); - router.push({ pathname: router.pathname, query: nextPageQuery }, undefined, { shallow: true }); - } - }, [ page, resetPage, router, options?.enabled ]); - - let hasNextPage = false; - if (nextPageParams) { - - hasNextPage = hasNextPageFn ? hasNextPageFn(nextPageParams as NextPageParams) : Object.keys(nextPageParams).length > 0; - } - - const pagination = { - page, - onNextPageClick, - onPrevPageClick, - resetPage, - hasPages, - hasNextPage, - canGoBackwards: Boolean(pageParams[page - 1]), - isLoading: queryResult.isPlaceholderData, - isVisible: hasPages || hasNextPage, - }; - - React.useEffect(() => { - if (page !== 1 && isMounted.current) { - queryClient.cancelQueries({ queryKey: [ resourceName ] }); - setPage(1); - } - // hook should run only when queryName has changed - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ resourceName ]); - - React.useEffect(() => { - window.setTimeout(() => { - isMounted.current = true; - }, 0); - }, []); - - React.useEffect(() => { - const pageFromQuery = getPageFromQuery(router.query); - const nextPageParamsFromQuery = getPaginationParamsFromQuery(router.query.next_page_params); - - setPage(pageFromQuery); - setPageParams(prev => ({ - ...prev, - [pageFromQuery]: nextPageParamsFromQuery, - })); - setHasPages(pageFromQuery > 1); - }, [ router.query, hasChainValue ]); - - return { ...queryResult, pagination, onFilterChange, onSortingChange, chainValue, onChainValueChange, queryHash }; -} diff --git a/src/shared/router/NextRouterProvider.spec.tsx b/src/shared/router/NextRouterProvider.spec.tsx new file mode 100644 index 00000000000..3fa98b6496e --- /dev/null +++ b/src/shared/router/NextRouterProvider.spec.tsx @@ -0,0 +1,60 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, renderHook } from 'vitest/lib'; + +import NextRouterProvider from './NextRouterProvider'; +import { usePathname } from './usePathname'; +import { useRouter } from './useRouter'; + +const { nextRouter } = vi.hoisted(() => ({ + nextRouter: { + query: { hash: '0xabc' }, + pathname: '/tx/[hash]', + asPath: '/tx/0xabc', + push: vi.fn(() => Promise.resolve(true)), + replace: vi.fn(() => Promise.resolve(true)), + }, +})); + +vi.mock('next/router', () => ({ useRouter: () => nextRouter })); +vi.mock('next/navigation', () => ({ usePathname: () => '/tx/0xabc' })); + +const wrapper = ({ children }: { children: React.ReactNode }) => <NextRouterProvider>{ children }</NextRouterProvider>; + +describe('NextRouterProvider', () => { + afterEach(() => { + cleanup(); + nextRouter.push.mockClear(); + nextRouter.replace.mockClear(); + }); + + it('exposes the Next.js router members through the facade', () => { + const { result } = renderHook(() => ({ router: useRouter(), pathname: usePathname() }), { wrapper }); + + expect(result.current.router.query).toEqual({ hash: '0xabc' }); + expect(result.current.router.pathname).toBe('/tx/[hash]'); + expect(result.current.router.asPath).toBe('/tx/0xabc'); + expect(result.current.pathname).toBe('/tx/0xabc'); + }); + + it('maps push(url, options) onto the Next.js (url, as, options) signature', async() => { + const { result } = renderHook(() => useRouter(), { wrapper }); + + await expect(result.current.push({ pathname: '/blocks' }, { shallow: true })).resolves.toBe(true); + await expect(result.current.push('/txs')).resolves.toBe(true); + + expect(nextRouter.push).toHaveBeenNthCalledWith(1, { pathname: '/blocks' }, undefined, { shallow: true }); + expect(nextRouter.push).toHaveBeenNthCalledWith(2, '/txs', undefined, undefined); + }); + + it('maps replace(url, options) the same way', async() => { + const { result } = renderHook(() => useRouter(), { wrapper }); + + await expect(result.current.replace({ pathname: '/stats' }, { scroll: false, shallow: true })).resolves.toBe(true); + + expect(nextRouter.replace).toHaveBeenCalledWith({ pathname: '/stats' }, undefined, { scroll: false, shallow: true }); + }); +}); diff --git a/src/shared/router/NextRouterProvider.tsx b/src/shared/router/NextRouterProvider.tsx new file mode 100644 index 00000000000..a795bca91c2 --- /dev/null +++ b/src/shared/router/NextRouterProvider.tsx @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import NextJsLink from 'next/link'; +import type { LinkProps as NextJsLinkProps } from 'next/link'; +import { usePathname } from 'next/navigation'; +import { useRouter as useNextJsRouter } from 'next/router'; +import React from 'react'; + +import type { Router, RouterContextValue, RouterLinkProps, Url } from 'src/toolkit/router/types'; + +import { RouterProvider } from 'src/toolkit/router/context'; + +// `nextjs-routes` narrows the Next `href` / `url` arguments to the generated route union; the toolkit contract +// is framework-neutral and carries no route map, so the value is handed back to Next as it came in. +const toNextJsUrl = (url: Url): NextJsLinkProps['href'] => url as NextJsLinkProps['href']; + +export const NextLink = React.forwardRef<HTMLAnchorElement, RouterLinkProps>( + function NextLink({ href, scroll, shallow, prefetch, children, ...rest }, ref) { + return ( + <NextJsLink ref={ ref } href={ toNextJsUrl(href) } scroll={ scroll } shallow={ shallow } prefetch={ prefetch } { ...rest }> + { children } + </NextJsLink> + ); + }, +); + +export const useNextRouter = (): Router => { + const nextRouter = useNextJsRouter(); + + return React.useMemo(() => ({ + query: nextRouter.query, + pathname: nextRouter.pathname, + asPath: nextRouter.asPath, + push: (url, options) => nextRouter.push(toNextJsUrl(url), undefined, options), + replace: (url, options) => nextRouter.replace(toNextJsUrl(url), undefined, options), + }), [ nextRouter ]); +}; + +interface Props { + children: React.ReactNode; +} + +const NextRouterProvider = ({ children }: Props) => { + const router = useNextRouter(); + const pathname = usePathname(); + + const value = React.useMemo((): RouterContextValue => ({ Link: NextLink, router, pathname }), [ router, pathname ]); + + return <RouterProvider value={ value }>{ children }</RouterProvider>; +}; + +export default NextRouterProvider; diff --git a/src/shared/router/nextjs-routes.d.ts b/src/shared/router/nextjs-routes.d.ts index 4637e8bd959..f15b6b58fad 100644 --- a/src/shared/router/nextjs-routes.d.ts +++ b/src/shared/router/nextjs-routes.d.ts @@ -45,6 +45,7 @@ declare module "nextjs-routes" { | StaticRoute<"/block/countdown"> | DynamicRoute<"/block/countdown/[height]", { "height": string }> | StaticRoute<"/blocks"> + | DynamicRoute<"/bridge/[bridgeId]/cross-chain-tx/[id]", { "bridgeId": string; "id": string }> | DynamicRoute<"/cc/tx/[hash]", { "hash": string }> | DynamicRoute<"/chain/[chain_slug_or_id]/accounts/label/[slug]", { "chain_slug_or_id": string; "slug": string }> | DynamicRoute<"/chain/[chain_slug_or_id]/advanced-filter", { "chain_slug_or_id": string }> @@ -58,7 +59,6 @@ declare module "nextjs-routes" { | DynamicRoute<"/chain/[chain_slug_or_id]/visualize/sol2uml", { "chain_slug_or_id": string }> | StaticRoute<"/chakra"> | StaticRoute<"/contract-verification"> - | DynamicRoute<"/cross-chain-tx/[id]", { "id": string }> | StaticRoute<"/deposits"> | StaticRoute<"/dispute-games"> | StaticRoute<"/ecosystems"> diff --git a/src/shared/router/remove-query-param.ts b/src/shared/router/remove-query-param.ts index 10a83bb14a5..c68347749d2 100644 --- a/src/shared/router/remove-query-param.ts +++ b/src/shared/router/remove-query-param.ts @@ -1,8 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { NextRouter } from 'next/router'; +import type { Router } from 'src/shared/router/useRouter'; -export default function removeQueryParam(router: NextRouter, param: string) { +export default function removeQueryParam(router: Router, param: string) { const { pathname, query, asPath } = router; const newQuery = { ...query }; delete newQuery[param]; @@ -10,5 +10,5 @@ export default function removeQueryParam(router: NextRouter, param: string) { const hashIndex = asPath.indexOf('#'); const hash = hashIndex !== -1 ? asPath.substring(hashIndex) : ''; - router.replace({ pathname, query: newQuery, hash }, undefined, { shallow: true }); + router.replace({ pathname, query: newQuery, hash }, { shallow: true }); } diff --git a/src/shared/router/routes.ts b/src/shared/router/routes.ts index 52bf08a0dd1..bbb88d96afd 100644 --- a/src/shared/router/routes.ts +++ b/src/shared/router/routes.ts @@ -9,6 +9,8 @@ import config from 'src/config'; import { stripTrailingSlash } from 'src/toolkit/utils/url'; +export type { Route, Query, DynamicRoute } from 'nextjs-routes'; + export interface RouteParams { external?: boolean; chain?: ExternalChain & { slug?: string }; diff --git a/src/shared/router/update-query-param.ts b/src/shared/router/update-query-param.ts index f4d3c7cac30..2feeaa50b2a 100644 --- a/src/shared/router/update-query-param.ts +++ b/src/shared/router/update-query-param.ts @@ -1,8 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { NextRouter } from 'next/router'; +import type { Router } from 'src/shared/router/useRouter'; -export default function updateQueryParam(router: NextRouter, param: string, newValue: string) { +export default function updateQueryParam(router: Router, param: string, newValue: string) { const { pathname, query, asPath } = router; const newQuery = { ...query }; newQuery[param] = newValue; @@ -10,5 +10,5 @@ export default function updateQueryParam(router: NextRouter, param: string, newV const hashIndex = asPath.indexOf('#'); const hash = hashIndex !== -1 ? asPath.substring(hashIndex) : ''; - router.replace({ pathname, query: newQuery, hash }, undefined, { shallow: true }); + router.replace({ pathname, query: newQuery, hash }, { shallow: true }); } diff --git a/src/shared/router/useEtherscanRedirects.spec.ts b/src/shared/router/useEtherscanRedirects.spec.ts new file mode 100644 index 00000000000..d6f902584b6 --- /dev/null +++ b/src/shared/router/useEtherscanRedirects.spec.ts @@ -0,0 +1,63 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, renderHook } from 'vitest/lib'; +import { routerStandIn } from 'vitest/utils/routerStandIn'; + +import useEtherscanRedirects from './useEtherscanRedirects'; + +const HASH = '0xd789a607CEac2f0E14867de4EB15b15C9FFB5859'; + +function mountAt(pathname: string, segmentHash: string, query: Record<string, string> = { hash: HASH }) { + window.location.hash = segmentHash; + routerStandIn.reset({ pathname, query }); + renderHook(() => useEtherscanRedirects(), { wrapper: routerStandIn.wrapper }); +} + +describe('useEtherscanRedirects', () => { + afterEach(() => { + cleanup(); + window.history.replaceState(null, '', '/'); + }); + + it('turns an etherscan tx anchor into the matching tab', () => { + mountAt('/tx/[hash]', '#eventlog'); + + expect(routerStandIn.replace).toHaveBeenCalledTimes(1); + expect(routerStandIn.replace).toHaveBeenCalledWith({ pathname: '/tx/[hash]', query: { hash: HASH, tab: 'logs' } }); + }); + + it('turns an etherscan address anchor into the matching tab', () => { + mountAt('/address/[hash]', '#writeContract'); + + expect(routerStandIn.replace).toHaveBeenCalledWith({ pathname: '/address/[hash]', query: { hash: HASH, tab: 'write_contract' } }); + }); + + it('turns the etherscan token balances anchor into the holders tab', () => { + mountAt('/token/[hash]', '#balances'); + + expect(routerStandIn.replace).toHaveBeenCalledWith({ pathname: '/token/[hash]', query: { hash: HASH, tab: 'holders' } }); + }); + + it('turns the etherscan contracts stats anchor into the contracts section', () => { + mountAt('/stats', '#section-contracts-data', {}); + + expect(routerStandIn.replace).toHaveBeenCalledWith({ pathname: '/stats', hash: 'contracts' }); + }); + + it.each([ + [ '/tx/[hash]', '#something-else', { hash: HASH } ], + [ '/stats', '#eventlog', {} ], + [ '/blocks', '#eventlog', {} ], + ])('leaves an anchor it does not know alone (%s %s)', (pathname, segmentHash, query) => { + mountAt(pathname, segmentHash, query); + + expect(routerStandIn.replace).not.toHaveBeenCalled(); + }); + + it('does nothing without an anchor', () => { + mountAt('/tx/[hash]', ''); + + expect(routerStandIn.replace).not.toHaveBeenCalled(); + }); +}); diff --git a/src/shared/router/useEtherscanRedirects.ts b/src/shared/router/useEtherscanRedirects.ts index f1273b57517..a2ea5a888e5 100644 --- a/src/shared/router/useEtherscanRedirects.ts +++ b/src/shared/router/useEtherscanRedirects.ts @@ -1,137 +1,65 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import getQueryParamString from './get-query-param-string'; +import type { Route } from './routes'; +import type { Router } from './useRouter'; +import { useRouter } from './useRouter'; -export default function useEtherscanRedirects() { - const router = useRouter(); +type TabRedirectPathname = '/tx/[hash]' | '/address/[hash]' | '/token/[hash]'; - // The browser does not send the segment hash (or anchor) to the server, - // so we have to handle such redirects for the etherscan-like links on the client side. - React.useEffect(() => { - const segmentHash = window.location.hash; +const TAB_REDIRECTS: Record<TabRedirectPathname, Record<string, string | undefined>> = { + '/tx/[hash]': { + '#statechange': 'state', + '#eventlog': 'logs', + '#aa': 'user_ops', + '#internal': 'internal', + }, + '/address/[hash]': { + '#internaltx': 'internal_txns', + '#tokentxns': 'token_transfers', + '#asset-tokens': 'tokens', + '#asset-nfts': 'tokens_nfts', + '#aatx': 'user_ops', + '#code': 'contract', + '#readContract': 'read_contract', + '#writeContract': 'write_contract', + }, + '/token/[hash]': { + '#balances': 'holders', + }, +}; - if (segmentHash) { - switch (router.route) { - case '/tx/[hash]': { - const hash = getQueryParamString(router.query.hash); +const isTabRedirectPathname = (pathname: Route['pathname']): pathname is TabRedirectPathname => pathname in TAB_REDIRECTS; - switch (segmentHash) { - case '#statechange': - router.replace({ - pathname: '/tx/[hash]', - query: { hash, tab: 'state' }, - }); - break; - case '#eventlog': - router.replace({ - pathname: '/tx/[hash]', - query: { hash, tab: 'logs' }, - }); - break; - case '#aa': - router.replace({ - pathname: '/tx/[hash]', - query: { hash, tab: 'user_ops' }, - }); - break; - case '#internal': - router.replace({ - pathname: '/tx/[hash]', - query: { hash, tab: 'internal' }, - }); - break; - } - break; - } +export function getEtherscanRedirect(router: Router, segmentHash: string): Route | undefined { + if (router.pathname === '/stats') { + return segmentHash === '#section-contracts-data' ? { pathname: '/stats', hash: 'contracts' } : undefined; + } - case '/address/[hash]': { - const hash = getQueryParamString(router.query.hash); + if (!isTabRedirectPathname(router.pathname)) { + return undefined; + } - switch (segmentHash) { - case '#internaltx': - router.replace({ - pathname: '/address/[hash]', - query: { hash, tab: 'internal_txns' }, - }); - break; - case '#tokentxns': - router.replace({ - pathname: '/address/[hash]', - query: { hash, tab: 'token_transfers' }, - }); - break; - case '#asset-tokens': - router.replace({ - pathname: '/address/[hash]', - query: { hash, tab: 'tokens' }, - }); - break; - case '#asset-nfts': - router.replace({ - pathname: '/address/[hash]', - query: { hash, tab: 'tokens_nfts' }, - }); - break; - case '#aatx': - router.replace({ - pathname: '/address/[hash]', - query: { hash, tab: 'user_ops' }, - }); - break; - case '#code': - router.replace({ - pathname: '/address/[hash]', - query: { hash, tab: 'contract' }, - }); - break; - case '#readContract': - router.replace({ - pathname: '/address/[hash]', - query: { hash, tab: 'read_contract' }, - }); - break; - case '#writeContract': - router.replace({ - pathname: '/address/[hash]', - query: { hash, tab: 'write_contract' }, - }); - break; - } - break; - } + const tab = TAB_REDIRECTS[router.pathname][segmentHash]; + if (!tab) { + return undefined; + } - case '/token/[hash]': { - const hash = getQueryParamString(router.query.hash); + return { pathname: router.pathname, query: { hash: getQueryParamString(router.query.hash), tab } }; +} - switch (segmentHash) { - case '#balances': - router.replace({ - pathname: '/token/[hash]', - query: { hash, tab: 'holders' }, - }); - break; - } - break; - } +export default function useEtherscanRedirects() { + const router = useRouter(); - case '/stats': { - switch (segmentHash) { - case '#section-contracts-data': - router.replace({ - pathname: '/stats', - hash: 'contracts', - }); - break; - } - break; - } + // The browser does not send the segment hash (or anchor) to the server, + // so we have to handle such redirects for the etherscan-like links on the client side. + React.useEffect(() => { + const target = window.location.hash ? getEtherscanRedirect(router, window.location.hash) : undefined; - default: - break; - } + if (target) { + router.replace(target); } // run only on mount // eslint-disable-next-line react-hooks/exhaustive-deps diff --git a/src/shared/router/usePathname.ts b/src/shared/router/usePathname.ts new file mode 100644 index 00000000000..449807f4ef6 --- /dev/null +++ b/src/shared/router/usePathname.ts @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { useRouterContext } from 'src/toolkit/router/context'; + +export function usePathname(): string | null { + return useRouterContext().pathname; +} diff --git a/src/shared/router/useQueryParams.ts b/src/shared/router/useQueryParams.ts index 22ef42fc725..90e64432ecc 100644 --- a/src/shared/router/useQueryParams.ts +++ b/src/shared/router/useQueryParams.ts @@ -1,8 +1,9 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import { useCallback } from 'react'; +import { useRouter } from 'src/shared/router/useRouter'; + export function useQueryParams() { const router = useRouter(); @@ -18,7 +19,7 @@ export function useQueryParams() { }); const routerFn = replace ? router.replace : router.push; - routerFn({ pathname: router.pathname, query: newQuery }, undefined, { shallow: true }); + routerFn({ pathname: router.pathname, query: newQuery }, { shallow: true }); }, [ router ]); return { updateQuery }; diff --git a/src/shared/router/useRouter.spec.tsx b/src/shared/router/useRouter.spec.tsx new file mode 100644 index 00000000000..34889e71b8f --- /dev/null +++ b/src/shared/router/useRouter.spec.tsx @@ -0,0 +1,81 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import type { RouterContextValue } from 'src/toolkit/router/types'; + +import { RouterProvider } from 'src/toolkit/router/context'; +import { DefaultLink } from 'src/toolkit/router/defaults'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, renderHook } from 'vitest/lib'; + +import { usePathname } from './usePathname'; +import { useRouter } from './useRouter'; + +const buildWrapper = (value: RouterContextValue) => ({ children }: { children: React.ReactNode }) => ( + <RouterProvider value={ value }>{ children }</RouterProvider> +); + +const contextValue: RouterContextValue = { + Link: DefaultLink, + router: { + query: { hash: '0xabc', tab: [ 'txs', 'logs' ], missing: undefined }, + pathname: '/tx/[hash]', + asPath: '/tx/0xabc?tab=txs&tab=logs', + push: vi.fn(() => Promise.resolve(true)), + replace: vi.fn(() => Promise.resolve(true)), + }, + pathname: '/tx/0xabc', +}; + +describe('useRouter', () => { + afterEach(cleanup); + + it('reads the string, array and absent query params the provider carries', () => { + const { result } = renderHook(() => useRouter(), { wrapper: buildWrapper(contextValue) }); + + expect(result.current.query.hash).toBe('0xabc'); + expect(result.current.query.tab).toEqual([ 'txs', 'logs' ]); + expect(result.current.query.missing).toBeUndefined(); + expect(result.current.query.unknown).toBeUndefined(); + expect(result.current.pathname).toBe('/tx/[hash]'); + expect(result.current.asPath).toBe('/tx/0xabc?tab=txs&tab=logs'); + }); + + it('hands push and replace to the provided router with the url and options as given', async() => { + const { result } = renderHook(() => useRouter(), { wrapper: buildWrapper(contextValue) }); + + await expect(result.current.push({ pathname: '/blocks' }, { shallow: true })).resolves.toBe(true); + await expect(result.current.replace('/txs?page=2', { scroll: false })).resolves.toBe(true); + + expect(contextValue.router.push).toHaveBeenCalledWith({ pathname: '/blocks' }, { shallow: true }); + expect(contextValue.router.replace).toHaveBeenCalledWith('/txs?page=2', { scroll: false }); + }); + + it('falls back to an empty, no-op router without a provider', async() => { + const { result } = renderHook(() => useRouter()); + + expect(result.current.query).toEqual({}); + expect(result.current.pathname).toBe(''); + expect(result.current.asPath).toBe(''); + await expect(result.current.push({ pathname: '/blocks' })).resolves.toBe(false); + await expect(result.current.replace({ pathname: '/blocks' })).resolves.toBe(false); + }); +}); + +describe('usePathname', () => { + afterEach(cleanup); + + it('returns the browser pathname the provider carries', () => { + const { result } = renderHook(() => usePathname(), { wrapper: buildWrapper(contextValue) }); + + expect(result.current).toBe('/tx/0xabc'); + }); + + it('is null without a provider', () => { + const { result } = renderHook(() => usePathname()); + + expect(result.current).toBeNull(); + }); +}); diff --git a/src/shared/router/useRouter.ts b/src/shared/router/useRouter.ts new file mode 100644 index 00000000000..1766b6b8b77 --- /dev/null +++ b/src/shared/router/useRouter.ts @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { NavigateOptions, Router as ToolkitRouter } from 'src/toolkit/router/types'; + +import { useRouter as useToolkitRouter } from 'src/toolkit/router/context'; + +import type { Route } from './routes'; + +export type { NavigateOptions }; + +// Mirrors the `next/router` augmentation in `nextjs-routes.d.ts`: a typed route, a route-less `{ query }` +// patch on the current page, or a plain href. +export type RouteUrl = Route | Omit<Route, 'pathname'> | string; + +export interface Router extends Omit<ToolkitRouter, 'push' | 'replace'> { + readonly pathname: Route['pathname']; + push(url: RouteUrl, options?: NavigateOptions): Promise<boolean>; + replace(url: RouteUrl, options?: NavigateOptions): Promise<boolean>; +} + +export function useRouter(): Router { + // the toolkit router is framework-neutral and carries no route map; the app narrows it to the generated routes + return useToolkitRouter() as Router; +} diff --git a/src/shared/sort/get-sort-params-from-query.ts b/src/shared/sort/get-sort-params-from-query.ts index 7124422e0b6..3e237ac006f 100644 --- a/src/shared/sort/get-sort-params-from-query.ts +++ b/src/shared/sort/get-sort-params-from-query.ts @@ -1,8 +1,7 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { Query } from 'nextjs-routes'; - import getQueryParamString from 'src/shared/router/get-query-param-string'; +import type { Query } from 'src/shared/router/routes'; export default function getSortParamsFromQuery<T>(query: Query, sortOptions: Record<string, Array<string | undefined>>) { if (!query.sort || !query.order) { diff --git a/src/shared/sort/get-sort-value-from-query.ts b/src/shared/sort/get-sort-value-from-query.ts index d2fa4666487..7f8451eb77a 100644 --- a/src/shared/sort/get-sort-value-from-query.ts +++ b/src/shared/sort/get-sort-value-from-query.ts @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { Query } from 'nextjs-routes'; +import type { Query } from 'src/shared/router/routes'; import type { SelectOption } from 'src/toolkit/chakra/select'; diff --git a/src/shared/stats/StatsContainer.tsx b/src/shared/stats/StatsContainer.tsx new file mode 100644 index 00000000000..74fb03a2c40 --- /dev/null +++ b/src/shared/stats/StatsContainer.tsx @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { GridProps } from '@chakra-ui/react'; +import { Grid } from '@chakra-ui/react'; +import { clamp } from 'es-toolkit'; +import React from 'react'; + +const MAX_COLUMNS_NUM = { + desktop: 5, + mobile: 2, +}; + +const GAPS = { + desktop: 2 * 4, + mobile: 1 * 4, +}; + +interface Props extends Omit<GridProps, 'columns'> { + columnsNum?: { + desktop: number; + mobile: number; + }; +} + +const StatsContainer = ({ columnsNum: columnsNumProp, ...rest }: Props) => { + + const columnNum = (() => { + if (columnsNumProp) { + return columnsNumProp; + } + + const childrenNum = React.Children.toArray(rest.children).length; + return { + desktop: clamp(childrenNum, 1, MAX_COLUMNS_NUM.desktop), + mobile: clamp(childrenNum, 1, MAX_COLUMNS_NUM.mobile), + }; + })(); + + const desktopColumnSize = `calc(${ 100 / columnNum.desktop }% - ${ (columnNum.desktop - 1) * GAPS.desktop }px / ${ columnNum.desktop })`; + const mobileColumnSize = `calc(${ 100 / columnNum.mobile }% - ${ (columnNum.mobile - 1) * GAPS.mobile }px / ${ columnNum.mobile })`; + + return ( + <Grid + gridTemplateColumns={{ + base: `repeat(${ columnNum.mobile }, ${ mobileColumnSize })`, + lg: `repeat(${ columnNum.desktop }, ${ desktopColumnSize })`, + }} + gap={{ base: `${ GAPS.mobile }px`, lg: `${ GAPS.desktop }px` }} + { ...rest } + /> + ); +}; + +export default React.memo(StatsContainer); diff --git a/src/shared/stats/StatsWidget.tsx b/src/shared/stats/StatsWidget.tsx index 440225d1348..c320bcfe505 100644 --- a/src/shared/stats/StatsWidget.tsx +++ b/src/shared/stats/StatsWidget.tsx @@ -2,17 +2,17 @@ import type { BoxProps } from '@chakra-ui/react'; import { Box, Flex, Text, chakra } from '@chakra-ui/react'; -import type { Route } from 'nextjs-routes'; -import { route } from 'nextjs-routes'; import React from 'react'; +import type { Route } from 'src/shared/router/routes'; +import { route } from 'src/shared/router/routes'; import type { IconName } from 'src/sprite/SpriteIcon'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { Hint } from 'src/toolkit/components/Hint/Hint'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface ContainerProps extends BoxProps { href?: Route; @@ -112,12 +112,12 @@ const StatsWidget = React.forwardRef<HTMLDivElement, Props>(({ > { valuePrefix && <chakra.span whiteSpace="pre">{ valuePrefix }</chakra.span> } { typeof value === 'string' ? ( - <TruncatedText text={ value } loading={ isLoading }/> + <Truncate value={ value } type="end" loading={ isLoading }/> ) : ( value ) } { valuePostfix && <chakra.span whiteSpace="pre">{ valuePostfix }</chakra.span> } - { diff && Number(diff) > 0 && ( + { Number(diff) > 0 && ( <> <Text ml={ 2 } mr={ 1 } color="green.500"> +{ diffFormatted || Number(diff).toLocaleString() } diff --git a/src/shared/stats/__screenshots__/LineChartWidget.pw.tsx_default_error-1.png b/src/shared/stats/__screenshots__/LineChartWidget.pw.tsx_default_error-1.png index cf410bd462d..9236e20bce2 100644 Binary files a/src/shared/stats/__screenshots__/LineChartWidget.pw.tsx_default_error-1.png and b/src/shared/stats/__screenshots__/LineChartWidget.pw.tsx_default_error-1.png differ diff --git a/src/shared/stats/__screenshots__/LineChartWidget.pw.tsx_default_loading-1.png b/src/shared/stats/__screenshots__/LineChartWidget.pw.tsx_default_loading-1.png index d49fb6be4d9..4289e0b1652 100644 Binary files a/src/shared/stats/__screenshots__/LineChartWidget.pw.tsx_default_loading-1.png and b/src/shared/stats/__screenshots__/LineChartWidget.pw.tsx_default_loading-1.png differ diff --git a/src/shared/stats/__screenshots__/StatsWidget.pw.tsx_default_loading-state-1.png b/src/shared/stats/__screenshots__/StatsWidget.pw.tsx_default_loading-state-1.png index 5ff55ac3c9a..639c97f9109 100644 Binary files a/src/shared/stats/__screenshots__/StatsWidget.pw.tsx_default_loading-state-1.png and b/src/shared/stats/__screenshots__/StatsWidget.pw.tsx_default_loading-state-1.png differ diff --git a/src/shared/storage/cookies.ts b/src/shared/storage/cookies.ts index a5644748168..9af462f4800 100644 --- a/src/shared/storage/cookies.ts +++ b/src/shared/storage/cookies.ts @@ -22,14 +22,15 @@ export enum NAMES { LOCAL_TIME = 'local_time', INDEXING_ALERT = 'indexing_alert', ADBLOCK_DETECTED = 'adblock_detected', - MIXPANEL_DEBUG = '_mixpanel_debug', + ANALYTICS_DEBUG = '_analytics_debug', ADDRESS_NFT_DISPLAY_TYPE = 'address_nft_display_type', HIDE_ADD_TO_WALLET_BUTTON = 'hide_add_to_wallet_button', UUID = 'uuid', SHOW_SCAM_TOKENS = 'show_scam_tokens', SHOW_POOR_REPUTATION_TOKENS = 'show_poor_reputation_tokens', APP_PROFILE = 'app_profile', - TABLE_VIEW_ON_MOBILE = 'table_view_on_mobile', + CUSTOM_RPC_URL = 'custom_rpc_url', + CUSTOM_RPC_IN_USE = 'custom_rpc_in_use', } /** @@ -39,7 +40,7 @@ export enum NAMES { export const PRIVATE_MODE_DISALLOWED: ReadonlyArray<NAMES> = [ NAMES.UUID, NAMES.ADBLOCK_DETECTED, - NAMES.MIXPANEL_DEBUG, + NAMES.ANALYTICS_DEBUG, ]; export const getDefaultAttributes = () => ({ diff --git a/src/shared/tags/select/__screenshots__/TagGroupSelect.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/shared/tags/select/__screenshots__/TagGroupSelect.pw.tsx_dark-color-mode_base-view-dark-mode-1.png index f482db23073..5288e0bf33c 100644 Binary files a/src/shared/tags/select/__screenshots__/TagGroupSelect.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and b/src/shared/tags/select/__screenshots__/TagGroupSelect.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/shared/tags/select/__screenshots__/TagGroupSelect.pw.tsx_default_base-view-dark-mode-1.png b/src/shared/tags/select/__screenshots__/TagGroupSelect.pw.tsx_default_base-view-dark-mode-1.png index a139a2986aa..45a0fa30a10 100644 Binary files a/src/shared/tags/select/__screenshots__/TagGroupSelect.pw.tsx_default_base-view-dark-mode-1.png and b/src/shared/tags/select/__screenshots__/TagGroupSelect.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/shared/texts/HashStringShorten.tsx b/src/shared/texts/HashStringShorten.tsx deleted file mode 100644 index 96360189b41..00000000000 --- a/src/shared/texts/HashStringShorten.tsx +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { chakra } from '@chakra-ui/react'; -import React from 'react'; - -import shortenString from 'src/shared/texts/shorten-string'; - -import { Tooltip } from 'src/toolkit/chakra/tooltip'; - -interface Props { - hash: string; - noTooltip?: boolean; - tooltipInteractive?: boolean; - tooltipContent?: React.ReactNode; - type?: 'long' | 'short'; - maxSymbols?: number; - as?: React.ElementType; -} - -const HashStringShorten = ({ hash, noTooltip, as = 'span', type, tooltipInteractive, tooltipContent, maxSymbols }: Props) => { - const charNumber = maxSymbols ?? (type === 'long' ? 16 : 8); - if (hash.length <= charNumber) { - return <chakra.span as={ as }>{ hash }</chakra.span>; - } - - const content = <chakra.span as={ as }>{ shortenString(hash, charNumber) }</chakra.span>; - - if (noTooltip) { - return content; - } - - return ( - <Tooltip - contentProps={{ maxW: { base: 'calc(100vw - 8px)', lg: '400px' } }} - content={ tooltipContent ?? hash } - interactive={ tooltipInteractive } - > - { content } - </Tooltip> - ); -}; - -export default HashStringShorten; diff --git a/src/shared/texts/HashStringShortenDynamic.tsx b/src/shared/texts/HashStringShortenDynamic.tsx deleted file mode 100644 index 27c3d149284..00000000000 --- a/src/shared/texts/HashStringShortenDynamic.tsx +++ /dev/null @@ -1,129 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -// this component trims hash string like 0x123...4567 (always 4 chars after dots) -// or shows full hash string, if fits - -// i can't do this with pure css. if you can, feel free to replace it - -// if i use <span text-overflow=ellipsis>some chars</span><span>last 4 chars</span> -// i have an unremovable gap between dots and second span - -// so i did it with js - -import type { BoxProps } from '@chakra-ui/react'; -import { chakra } from '@chakra-ui/react'; -import { debounce } from 'es-toolkit'; -import React, { useCallback, useEffect, useRef } from 'react'; -import type { FontFace } from 'use-font-face-observer'; -import useFontFaceObserver from 'use-font-face-observer'; - -import { Tooltip } from 'src/toolkit/chakra/tooltip'; -import { BODY_TYPEFACE, HEADING_TYPEFACE } from 'src/toolkit/theme/foundations/typography'; - -const TAIL_LENGTH = 4; -const HEAD_MIN_LENGTH = 4; - -interface Props extends BoxProps { - hash: string; - fontWeight?: string | number; - noTooltip?: boolean; - tooltipInteractive?: boolean; - tooltipContent?: React.ReactNode; - tailLength?: number; - as?: React.ElementType; -} - -const HashStringShortenDynamic = ({ - hash, - fontWeight = '400', - noTooltip, - tailLength = TAIL_LENGTH, - as = 'span', - tooltipInteractive, - tooltipContent, - ...props -}: Props) => { - const elementRef = useRef<HTMLSpanElement>(null); - const [ displayedString, setDisplayedString ] = React.useState(hash); - - const isFontFaceLoaded = useFontFaceObserver([ - { family: BODY_TYPEFACE, weight: String(fontWeight) as FontFace['weight'] }, - { family: HEADING_TYPEFACE, weight: String(fontWeight) as FontFace['weight'] }, - ]); - - const calculateString = useCallback(() => { - const parent = elementRef?.current?.parentNode as HTMLElement; - if (!parent) { - return; - } - - const shadowEl = document.createElement('span'); - shadowEl.style.opacity = '0'; - parent.appendChild(shadowEl); - shadowEl.textContent = hash; - - const parentWidth = getWidth(parent); - - if (getWidth(shadowEl) > parentWidth) { - const tail = hash.slice(-tailLength); - let leftI = HEAD_MIN_LENGTH; - let rightI = hash.length - tailLength; - - while (rightI - leftI > 1) { - const medI = ((rightI - leftI) % 2) ? leftI + (rightI - leftI + 1) / 2 : leftI + (rightI - leftI) / 2; - const res = hash.slice(0, medI) + '...' + tail; - shadowEl.textContent = res; - if (getWidth(shadowEl) < parentWidth) { - leftI = medI; - } else { - rightI = medI; - } - } - setDisplayedString(hash.slice(0, rightI - 1) + '...' + tail); - } else { - setDisplayedString(hash); - } - - parent.removeChild(shadowEl); - }, [ hash, tailLength ]); - - // we want to do recalculation when isFontFaceLoaded flag is changed - // but we don't want to create more resize event listeners - // that's why there are separate useEffect hooks - useEffect(() => { - calculateString(); - }, [ calculateString, isFontFaceLoaded ]); - - useEffect(() => { - const resizeHandler = debounce(calculateString, 100); - const resizeObserver = new ResizeObserver(resizeHandler); - - resizeObserver.observe(document.body); - return function cleanup() { - resizeObserver.unobserve(document.body); - }; - }, [ calculateString ]); - - const content = <chakra.span ref={ elementRef } as={ as } { ...props }>{ displayedString }</chakra.span>; - const isTruncated = hash.length !== displayedString.length; - - if (!noTooltip && (isTruncated || tooltipContent)) { - return ( - <Tooltip - content={ tooltipContent ?? hash } - contentProps={{ maxW: { base: 'calc(100vw - 8px)', lg: '400px' } }} - interactive={ tooltipInteractive } - > - { content } - </Tooltip> - ); - } - - return content; -}; - -function getWidth(el: HTMLElement) { - return el.getBoundingClientRect().width; -} - -export default React.memo(HashStringShortenDynamic); diff --git a/src/shared/texts/sanitize-html.spec.ts b/src/shared/texts/sanitize-html.spec.ts new file mode 100644 index 00000000000..9dbd555d819 --- /dev/null +++ b/src/shared/texts/sanitize-html.spec.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest'; + +import { findDisallowedHtml, sanitizeHtml } from './sanitize-html'; + +const BANNER = [ + '<p>Example <a href="https://example.com" target="_blank" rel="noopener"><b>Learn more</b></a>', + '<br /><img src="https://example.com/i.png" alt="i"></p>', +].join(''); +const SRCDOC_FRAME = `Hello <iframe srcdoc="<script src='/assets/configs/network_logo.js'></script>"></iframe> world`; +const OVERLAY = [ + '<div style="position:fixed;inset:0;z-index:2147483647">Wallet verification required ', + '<a href="https://evil.example" onclick="x()">Connect Wallet</a></div>', +].join(''); + +describe('sanitizeHtml', () => { + it('keeps text formatting, links and images', () => { + expect(sanitizeHtml(BANNER)).toBe(BANNER); + }); + + it('removes a frame with its content', () => { + expect(sanitizeHtml(SRCDOC_FRAME)).toBe('Hello world'); + expect(sanitizeHtml('<IFRAME/src=https://evil.example></IFRAME>after')).toBe('after'); + }); + + it('removes scripts and vector graphics with their content', () => { + expect(sanitizeHtml('<script>alert(1)</script>tail')).toBe('tail'); + expect(sanitizeHtml('<svg onload="alert(1)"><circle/></svg>after')).toBe('after'); + }); + + it('drops inline styles and event handlers but keeps the text', () => { + expect(sanitizeHtml(OVERLAY)).toBe('<div>Wallet verification required <a href="https://evil.example">Connect Wallet</a></div>'); + }); + + it('drops a form but keeps its text', () => { + expect(sanitizeHtml('<form action="https://evil.example"><input name="pw"><button>Go</button></form>')).toBe('Go'); + }); + + it('blanks a javascript: link target', () => { + expect(sanitizeHtml('<a href="javascript:alert(1)">x</a>')).toBe('<a href>x</a>'); + }); +}); + +describe('findDisallowedHtml', () => { + it('reports nothing for allowed markup', () => { + expect(findDisallowedHtml(BANNER)).toEqual([]); + expect(findDisallowedHtml('plain text')).toEqual([]); + }); + + it('names disallowed tags once, whatever the casing', () => { + expect(findDisallowedHtml(SRCDOC_FRAME)).toEqual([ '<iframe>' ]); + expect(findDisallowedHtml('<IFRAME/src=https://evil.example></IFRAME><iframe></iframe>')).toEqual([ '<iframe>' ]); + }); + + it('names an unclosed disallowed tag and ignores a stray closing one', () => { + expect(findDisallowedHtml('<iframe src="https://evil.example">')).toEqual([ '<iframe>' ]); + expect(findDisallowedHtml('Hello</iframe>')).toEqual([]); + }); + + it('names disallowed attributes with their tag', () => { + expect(findDisallowedHtml(OVERLAY)).toEqual([ 'style attribute on <div>', 'onclick attribute on <a>' ]); + }); + + it('names an attribute whose value is rejected', () => { + expect(findDisallowedHtml('<a href="javascript:alert(1)">x</a>')).toEqual([ 'href attribute value on <a>' ]); + }); + + it('reports nothing for an attribute that is already empty', () => { + expect(findDisallowedHtml('<a href="">x</a><img src=" " alt="">')).toEqual([]); + }); +}); diff --git a/src/shared/texts/sanitize-html.ts b/src/shared/texts/sanitize-html.ts new file mode 100644 index 00000000000..56ab83aa924 --- /dev/null +++ b/src/shared/texts/sanitize-html.ts @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { FilterXSS, getDefaultWhiteList, safeAttrValue } from 'xss'; +import type { IWhiteList } from 'xss'; + +// Operator-supplied HTML (e.g. NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE) is rendered via innerHTML on the app's +// own origin. Markup is limited to text formatting, links and images; no scripts, frames, forms or inline styles. +// A frame is the only way such markup runs JS under the app's CSP (a same-origin `srcdoc` frame loading a script +// from `'self'`), and an inline style lets a banner cover the page with a phishing overlay. +const ALLOWED_TAGS: IWhiteList = { + ...getDefaultWhiteList(), + a: [ 'href', 'target', 'title', 'rel' ], +}; + +const TAGS_STRIPPED_WITH_CONTENT = [ 'script', 'style', 'iframe', 'object', 'embed', 'noscript', 'template', 'svg', 'math' ]; + +const sanitizer = new FilterXSS({ + whiteList: ALLOWED_TAGS, + // Stryker disable next-line BooleanLiteral: evaluated at module load, before runtime mutant activation, so the frame and form assertions cannot see it + stripIgnoreTag: true, + stripIgnoreTagBody: TAGS_STRIPPED_WITH_CONTENT, +}); + +export function sanitizeHtml(html: string): string { + return sanitizer.process(html); +} + +export function findDisallowedHtml(html: string): Array<string> { + const found = new Set<string>(); + + new FilterXSS({ + whiteList: ALLOWED_TAGS, + onIgnoreTag: (tag, _html, options) => { + if (!options.isClosing) { + found.add(`<${ tag.split('/')[0] }>`); + } + return ''; + }, + onIgnoreTagAttr: (tag, name) => { + found.add(`${ name } attribute on <${ tag }>`); + return ''; + }, + safeAttrValue: (tag, name, value, cssFilter) => { + const safeValue = safeAttrValue(tag, name, value, cssFilter); + if (safeValue === '' && value.trim() !== '') { + found.add(`${ name } attribute value on <${ tag }>`); + } + return safeValue; + }, + }).process(html); + + return Array.from(found); +} diff --git a/src/shared/texts/shorten-string.ts b/src/shared/texts/shorten-string.ts deleted file mode 100644 index 9da82937f67..00000000000 --- a/src/shared/texts/shorten-string.ts +++ /dev/null @@ -1,15 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -export default function shortenString(string: string | null, charNumber: number | undefined = 8) { - if (!string) { - return ''; - } - - if (string.length <= charNumber) { - return string; - } - - const tailLength = charNumber < 8 ? 2 : 4; - - return string.slice(0, charNumber - tailLength) + '...' + string.slice(-tailLength); -} diff --git a/src/shared/types/utils.ts b/src/shared/types/utils.ts index ac0432b089b..05697806c85 100644 --- a/src/shared/types/utils.ts +++ b/src/shared/types/utils.ts @@ -6,6 +6,9 @@ export type ExcludeUndefined<T> = T extends undefined ? never : T; export type KeysOfObjectOrNull<T> = keyof ExcludeNull<T>; +export type NonEmptyArray<T> = [T, ...Array<T>]; +export type Pairs<T> = Array<[T, T]>; + /** Combines members of an intersection into a readable type. */ // https://twitter.com/mattpocockuk/status/1622730173446557697?s=20&t=NdpAcmEFXY01xkqU3KO0Mg export type Evaluate<Type> = { [key in keyof Type]: Type[key] } & unknown; @@ -19,6 +22,9 @@ export type PickByType<T, X> = Record< // Make some properties of an object optional export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; +// Omit applied to each member of a union separately, so keys present in only some members survive +export type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never; + // Make all properties of an object optional export type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K]; diff --git a/src/shared/utils/fallback-provider.tsx b/src/shared/utils/fallback-provider.ts similarity index 100% rename from src/shared/utils/fallback-provider.tsx rename to src/shared/utils/fallback-provider.ts diff --git a/src/shared/values/entity/AssetValue.tsx b/src/shared/values/entity/AssetValue.tsx index 93beecc92c9..0d822f223db 100644 --- a/src/shared/values/entity/AssetValue.tsx +++ b/src/shared/values/entity/AssetValue.tsx @@ -42,6 +42,7 @@ const AssetValue = ({ hasExchangeRateToggle, layout = 'horizontal', tooltipContent, + multiplier, ...rest }: Props) => { const hasHistorical = Boolean(historicalExchangeRate); @@ -66,12 +67,14 @@ const AssetValue = ({ return <chakra.span { ...rest }>-</chakra.span>; } - const { valueBn, usdBn } = calculateUsdValue({ amount, decimals, accuracy, accuracyUsd, exchangeRate: activeExchangeRate }); + const { valueBn, rawValueBn, usdBn } = calculateUsdValue({ amount, decimals, accuracy, accuracyUsd, exchangeRate: activeExchangeRate, multiplier }); if (!activeExchangeRate) { return ( <SimpleValue value={ valueBn } + rawValue={ rawValueBn } + multiplier={ multiplier } accuracy={ accuracy } startElement={ startElement } endElement={ endElement ?? (typeof asset === 'string' ? `${ thinsp }${ asset }` : asset) } @@ -86,6 +89,8 @@ const AssetValue = ({ const nativeValue = ( <SimpleValue value={ valueBn } + rawValue={ rawValueBn } + multiplier={ multiplier } accuracy={ accuracy } startElement={ startElement } endElement={ endElement ?? (typeof asset === 'string' ? `${ thinsp }${ asset }` : asset) } diff --git a/src/shared/values/entity/SimpleValue.tsx b/src/shared/values/entity/SimpleValue.tsx index 2b2f0a96d8d..9fa143b2a41 100644 --- a/src/shared/values/entity/SimpleValue.tsx +++ b/src/shared/values/entity/SimpleValue.tsx @@ -5,6 +5,8 @@ import { Box, chakra } from '@chakra-ui/react'; import type BigNumber from 'bignumber.js'; import React from 'react'; +import { formatUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; + import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; @@ -26,6 +28,8 @@ export interface Props extends Omit<BoxProps, 'prefix' | 'postfix'> { loading?: boolean; overflowed?: boolean; tooltipContentBefore?: React.ReactNode; + multiplier?: BigNumber | null; + rawValue?: BigNumber; } const SimpleValue = ({ @@ -40,6 +44,8 @@ const SimpleValue = ({ noTooltip, loading, overflowed, + multiplier, + rawValue, ...rest }: Props) => { @@ -51,9 +57,14 @@ const SimpleValue = ({ { prefix ?? '' }{ value.toFormat() }{ postfix ?? '' } <CopyToClipboard text={ value.toFixed() } verticalAlign="bottom" noTooltip/> </Box> + { multiplier && rawValue && ( + <Box whiteSpace="wrap" wordBreak="break-all"> + (Raw: { prefix ?? '' }{ rawValue.toFormat() }{ postfix ?? '' } * Multiplier: { formatUiMultiplier(multiplier, '') }) + </Box> + ) } </> ); - }, [ postfix, prefix, value, tooltipContentBefore ]); + }, [ postfix, prefix, value, tooltipContentBefore, multiplier, rawValue ]); return ( <Skeleton loading={ loading } display="inline-flex" alignItems="center" whiteSpace="pre" maxW="100%" overflow="hidden" { ...rest }> diff --git a/src/shared/values/entity/TokenValueInterchain.tsx b/src/shared/values/entity/TokenValueInterchain.tsx index e02c3b992c9..12a6ed22a06 100644 --- a/src/shared/values/entity/TokenValueInterchain.tsx +++ b/src/shared/values/entity/TokenValueInterchain.tsx @@ -9,6 +9,8 @@ import type { ExternalChain } from 'src/shared/external-chains/types'; import type { EntityProps as TokenEntityProps } from 'src/slices/token/components/entity/TokenEntity'; import TokenEntityInterchain from 'src/slices/token/components/entity/TokenEntityInterchain'; +import { isNativeToken, toCoreTokenType } from 'src/features/cross-chain-txs/utils/token-type'; + import type { Props as AssetValueProps } from './AssetValue'; import AssetValue from './AssetValue'; @@ -23,13 +25,13 @@ const TokenValueInterchain = ({ token, tokenEntityProps, chain, ...rest }: Props const tokenInfo = React.useMemo(() => { return { symbol: token.symbol ?? null, - address_hash: token.address_hash, + address_hash: token.address_hash ?? '', icon_url: token.icon_url ?? null, name: token.name ?? null, - type: 'ERC-20', + type: toCoreTokenType(token.type), reputation: null, }; - }, [ token.address_hash, token.icon_url, token.name, token.symbol ]); + }, [ token.address_hash, token.icon_url, token.name, token.symbol, token.type ]); const asset = ( <TokenEntityInterchain @@ -37,6 +39,7 @@ const TokenValueInterchain = ({ token, tokenEntityProps, chain, ...rest }: Props chain={ chain } noCopy onlySymbol + noLink={ isNativeToken(token.type) } w="fit-content" ml={ 2 } icon={{ marginRight: 1, marginRightShield: '14px' }} diff --git a/src/shared/values/entity/calculateUsdValue.spec.ts b/src/shared/values/entity/calculateUsdValue.spec.ts new file mode 100644 index 00000000000..dde7733ffb6 --- /dev/null +++ b/src/shared/values/entity/calculateUsdValue.spec.ts @@ -0,0 +1,41 @@ +import BigNumber from 'bignumber.js'; + +import { describe, expect, it } from 'vitest'; + +import calculateUsdValue from './calculateUsdValue'; + +const ONE_THOUSAND_TOKENS = '1000000000000000000000'; +const DECIMALS = '18'; +const EXCHANGE_RATE = '2'; +const MULTIPLIER = new BigNumber('1.69'); + +describe('calculateUsdValue', () => { + describe('with a multiplier', () => { + const result = calculateUsdValue({ amount: ONE_THOUSAND_TOKENS, decimals: DECIMALS, exchangeRate: EXCHANGE_RATE, multiplier: MULTIPLIER }); + + it('scales the displayed value', () => { + expect(result.valueBn.toFixed()).toBe('1690'); + expect(result.valueStr).toBe('1,690'); + }); + + it('keeps the raw value reachable', () => { + expect(result.rawValueBn.toFixed()).toBe('1000'); + }); + + it('computes USD from the scaled value', () => { + expect(result.usdBn.toFixed()).toBe('3380'); + expect(result.usdStr).toBe('3,380'); + }); + }); + + describe('without a multiplier', () => { + it.each([ undefined, null ])('renders the raw value as is (multiplier: %s)', (multiplier) => { + const result = calculateUsdValue({ amount: ONE_THOUSAND_TOKENS, decimals: DECIMALS, exchangeRate: EXCHANGE_RATE, multiplier }); + + expect(result.valueBn.toFixed()).toBe('1000'); + expect(result.valueStr).toBe('1,000'); + expect(result.rawValueBn.isEqualTo(result.valueBn)).toBe(true); + expect(result.usdStr).toBe('2,000'); + }); + }); +}); diff --git a/src/shared/values/entity/calculateUsdValue.ts b/src/shared/values/entity/calculateUsdValue.ts new file mode 100644 index 00000000000..7290bb1d133 --- /dev/null +++ b/src/shared/values/entity/calculateUsdValue.ts @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import BigNumber from 'bignumber.js'; + +import { ZERO } from 'src/toolkit/utils/consts'; + +import { DEFAULT_ACCURACY, DEFAULT_ACCURACY_USD } from './utils'; + +export interface Params { + amount: string | null; + decimals?: string | number | null; + exchangeRate?: string | null; + accuracy?: number; + accuracyUsd?: number; + multiplier?: BigNumber | null; +} + +export default function calculateUsdValue({ + amount, + accuracy = DEFAULT_ACCURACY, + accuracyUsd = DEFAULT_ACCURACY_USD, + decimals, + exchangeRate, + multiplier, +}: Params) { + const rawValueBn = BigNumber(amount ?? '0').div(BigNumber(10 ** Number(decimals || '0'))); + const valueBn = multiplier ? rawValueBn.times(multiplier) : rawValueBn; + + const valueStr = (() => { + if (!accuracy) { + return valueBn.toFormat(); + } + const formattedValue = valueBn.dp(accuracy).toFormat(); + return formattedValue === '0' && !valueBn.isEqualTo(ZERO) ? `< 0.${ '0'.repeat(accuracy - 1) }1` : formattedValue; + })(); + + const usdBn = (() => { + if (!exchangeRate) { + return ZERO; + } + const exchangeRateBn = new BigNumber(exchangeRate); + return valueBn.times(exchangeRateBn); + })(); + + const usdStr = (() => { + if (!exchangeRate) { + return undefined; + } + + if (accuracyUsd && !usdBn.isEqualTo(0)) { + const usdBnDp = usdBn.dp(accuracyUsd); + return usdBnDp.isEqualTo(0) ? usdBn.precision(accuracyUsd).toFormat() : usdBnDp.toFormat(); + } + return usdBn.toFormat(); + })(); + + return { + valueBn, + rawValueBn, + valueStr, + usdBn, + usdStr, + }; +} diff --git a/src/shared/values/entity/calculateUsdValue.tsx b/src/shared/values/entity/calculateUsdValue.tsx deleted file mode 100644 index 435f3e95866..00000000000 --- a/src/shared/values/entity/calculateUsdValue.tsx +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import BigNumber from 'bignumber.js'; - -import { ZERO } from 'src/toolkit/utils/consts'; - -import { DEFAULT_ACCURACY, DEFAULT_ACCURACY_USD } from './utils'; - -export interface Params { - amount: string | null; - decimals?: string | number | null; - exchangeRate?: string | null; - accuracy?: number; - accuracyUsd?: number; -} - -export default function calculateUsdValue({ amount, accuracy = DEFAULT_ACCURACY, accuracyUsd = DEFAULT_ACCURACY_USD, decimals, exchangeRate }: Params) { - const valueBn = BigNumber(amount ?? '0').div(BigNumber(10 ** Number(decimals || '0'))); - - const valueStr = (() => { - if (!accuracy) { - return valueBn.toFormat(); - } - const formattedValue = valueBn.dp(accuracy).toFormat(); - return formattedValue === '0' && !valueBn.isEqualTo(ZERO) ? `< 0.${ '0'.repeat(accuracy - 1) }1` : formattedValue; - })(); - - const usdBn = (() => { - if (!exchangeRate) { - return ZERO; - } - const exchangeRateBn = new BigNumber(exchangeRate); - return valueBn.times(exchangeRateBn); - })(); - - const usdStr = (() => { - if (!exchangeRate) { - return undefined; - } - - if (accuracyUsd && !usdBn.isEqualTo(0)) { - const usdBnDp = usdBn.dp(accuracyUsd); - return usdBnDp.isEqualTo(0) ? usdBn.precision(accuracyUsd).toFormat() : usdBnDp.toFormat(); - } - return usdBn.toFormat(); - })(); - - return { - valueBn, - valueStr, - usdBn, - usdStr, - }; -} diff --git a/src/shell/app/context.tsx b/src/shell/app/context.tsx index 930288542fd..df4275f7637 100644 --- a/src/shell/app/context.tsx +++ b/src/shell/app/context.tsx @@ -1,10 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { Route } from 'nextjs-routes'; import React, { createContext, useContext } from 'react'; import type { Props as PageProps } from 'src/server/getServerSideProps/handlers'; +import type { Route } from 'src/shared/router/routes'; + type Props = { children: React.ReactNode; pageProps: PageProps; diff --git a/src/shell/footer/Footer.pw.tsx b/src/shell/footer/Footer.pw.tsx index e761186de2a..cc512ac4ef7 100644 --- a/src/shell/footer/Footer.pw.tsx +++ b/src/shell/footer/Footer.pw.tsx @@ -1,5 +1,8 @@ import React from 'react'; +import * as indexingStatusMock from 'src/slices/chain/indexing-status/mocks'; +import * as chainMock from 'src/slices/chain/mocks'; + import { test, expect } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; @@ -15,12 +18,8 @@ test.describe('with custom links, max cols', () => { ]); await mockConfigResponse('NEXT_PUBLIC_FOOTER_LINKS', FOOTER_LINKS_URL, FOOTER_LINKS); await injectMetaMaskProvider(); - await mockApiResponse('core:homepage_indexing_status', { - finished_indexing: false, - finished_indexing_blocks: false, - indexed_internal_transactions_ratio: 0.1, - indexed_blocks_ratio: 0.1, - }); + await mockApiResponse('core:homepage_indexing_status', indexingStatusMock.inProgress); + await mockApiResponse('core:config_backend_version', chainMock.backendVersion); await mockAssetResponse(FOOTER_LINKS[3].links[0].iconUrl?.[0]!, './playwright/mocks/image_s.jpg'); await mockAssetResponse(FOOTER_LINKS[3].links[0].iconUrl?.[1]!, './playwright/mocks/image_svg.svg'); @@ -41,11 +40,13 @@ test.describe('with custom links, max cols', () => { }); test.describe('with custom links, min cols', () => { - test('base view +@dark-mode +@mobile', async({ render, page, mockConfigResponse, mockEnvs }) => { + test('base view +@dark-mode +@mobile', async({ render, page, mockConfigResponse, mockEnvs, mockApiResponse }) => { await mockEnvs([ [ 'NEXT_PUBLIC_FOOTER_LINKS', FOOTER_LINKS_URL ], ]); await mockConfigResponse('NEXT_PUBLIC_FOOTER_LINKS', FOOTER_LINKS_URL, [ FOOTER_LINKS[0] ]); + await mockApiResponse('core:homepage_indexing_status', indexingStatusMock.finished); + await mockApiResponse('core:config_backend_version', chainMock.backendVersion); await render(<Footer/>); await expect(page).toHaveScreenshot(); }); @@ -54,19 +55,16 @@ test.describe('with custom links, min cols', () => { test.describe('without custom links', () => { test('base view +@dark-mode +@mobile', async({ render, page, injectMetaMaskProvider, mockApiResponse }) => { await injectMetaMaskProvider(); - await mockApiResponse('core:config_backend_version', { backend_version: 'v5.2.0-beta.+commit.1ce1a355' }); + await mockApiResponse('core:homepage_indexing_status', indexingStatusMock.finished); + await mockApiResponse('core:config_backend_version', chainMock.backendVersion); await render(<Footer/>); await expect(page).toHaveScreenshot(); }); test('with indexing alert +@dark-mode +@mobile', async({ render, injectMetaMaskProvider, mockApiResponse }) => { await injectMetaMaskProvider(); - await mockApiResponse('core:homepage_indexing_status', { - finished_indexing: false, - finished_indexing_blocks: false, - indexed_internal_transactions_ratio: 0.1, - indexed_blocks_ratio: 0.1, - }); + await mockApiResponse('core:homepage_indexing_status', indexingStatusMock.inProgress); + await mockApiResponse('core:config_backend_version', chainMock.backendVersion); const component = await render(<Footer/>); await expect(component).toHaveScreenshot(); @@ -74,16 +72,11 @@ test.describe('without custom links', () => { test('with full info +@mobile', async({ render, page, injectMetaMaskProvider, mockApiResponse, mockEnvs }) => { await injectMetaMaskProvider(); - await mockApiResponse('core:homepage_indexing_status', { - finished_indexing: false, - finished_indexing_blocks: false, - indexed_internal_transactions_ratio: 0.1, - indexed_blocks_ratio: 0.1, - }); - await mockApiResponse('core:config_backend_version', { backend_version: 'v5.2.0-beta.+commit.1ce1a355' }); await mockEnvs([ [ 'NEXT_PUBLIC_USERCENTRICS_CONFIG', JSON.stringify({ settingsId: '123' }) ], ]); + await mockApiResponse('core:homepage_indexing_status', indexingStatusMock.inProgress); + await mockApiResponse('core:config_backend_version', chainMock.backendVersion); await render(<Footer/>, undefined, { appContext: { diff --git a/src/shell/footer/Footer.tsx b/src/shell/footer/Footer.tsx index 1b7b76545d6..134925449e0 100644 --- a/src/shell/footer/Footer.tsx +++ b/src/shell/footer/Footer.tsx @@ -68,8 +68,8 @@ const Footer = () => { { icon: 'brands/pro_api' as const, iconSize: '20px', - text: 'PRO API', - url: 'https://dev.blockscout.com', + text: 'Blockscout API', + url: 'https://dev.blockscout.com/?utm_source=blockscout&utm_medium=footer', }, { icon: 'brands/autoscout' as const, @@ -93,7 +93,7 @@ const Footer = () => { icon: 'social/discord' as const, iconSize: '24px', text: 'Discord', - url: 'https://discord.gg/blockscout', + url: 'https://discord.gg/3yAWj8TXV2', }, { icon: 'brands/blockscout' as const, diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_with-custom-links-max-cols-mobile-dark-mode-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_with-custom-links-max-cols-mobile-dark-mode-1.png index 2b74a459547..eab4247a1c1 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_with-custom-links-max-cols-mobile-dark-mode-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_with-custom-links-max-cols-mobile-dark-mode-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png index c436476184d..71f8d59849b 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_without-custom-links-base-view-dark-mode-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_without-custom-links-base-view-dark-mode-mobile-1.png index 74ea9bf9735..5584cbd3288 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_without-custom-links-base-view-dark-mode-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_without-custom-links-base-view-dark-mode-mobile-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png index 51ea588c1e9..e005dfbb5ed 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_dark-color-mode_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-max-cols-mobile-dark-mode-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-max-cols-mobile-dark-mode-1.png index dfc4987e154..3eb103dd1a4 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-max-cols-mobile-dark-mode-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-max-cols-mobile-dark-mode-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-max-cols-screen-xl-base-view-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-max-cols-screen-xl-base-view-1.png index 29fc538a6ba..87404a850e6 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-max-cols-screen-xl-base-view-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-max-cols-screen-xl-base-view-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png index e66adbfaf95..05857d5e911 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-base-view-dark-mode-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-base-view-dark-mode-mobile-1.png index ca6d5e2deb9..5a993531c33 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-base-view-dark-mode-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-base-view-dark-mode-mobile-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-with-full-info-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-with-full-info-mobile-1.png index 30e318afd85..eaca114cfac 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-with-full-info-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-with-full-info-mobile-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png index eba00108683..437ef85c566 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_default_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_with-custom-links-max-cols-mobile-dark-mode-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_with-custom-links-max-cols-mobile-dark-mode-1.png index aabf612c440..cc3c03f4a91 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_with-custom-links-max-cols-mobile-dark-mode-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_with-custom-links-max-cols-mobile-dark-mode-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png index 5a823b8e670..5bed93525a2 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_with-custom-links-min-cols-base-view-dark-mode-mobile-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-base-view-dark-mode-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-base-view-dark-mode-mobile-1.png index 0ad702cc33b..2100744edb6 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-base-view-dark-mode-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-base-view-dark-mode-mobile-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-with-full-info-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-with-full-info-mobile-1.png index d47790a7fd1..3d540765a48 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-with-full-info-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-with-full-info-mobile-1.png differ diff --git a/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png b/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png index d014fd7f2be..c6b924516fe 100644 Binary files a/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png and b/src/shell/footer/__screenshots__/Footer.pw.tsx_mobile_without-custom-links-with-indexing-alert-dark-mode-mobile-1.png differ diff --git a/src/shell/footer/get-api-version-url.tsx b/src/shell/footer/get-api-version-url.ts similarity index 100% rename from src/shell/footer/get-api-version-url.tsx rename to src/shell/footer/get-api-version-url.ts diff --git a/src/shell/header/Burger.pw.tsx b/src/shell/header/Burger.pw.tsx index e02d26279f4..dd042745e2d 100644 --- a/src/shell/header/Burger.pw.tsx +++ b/src/shell/header/Burger.pw.tsx @@ -1,6 +1,8 @@ import type { BrowserContext } from '@playwright/test'; import React from 'react'; +import * as profileMock from 'src/features/account/mocks/user-profile'; + import { contextWithAuth } from 'playwright/fixtures/auth'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; import { test, expect, devices } from 'playwright/lib'; @@ -50,7 +52,8 @@ const authTest = test.extend<{ context: BrowserContext }>({ authTest.describe('auth', () => { authTest.use({ viewport: { width: devices['iPhone 13 Pro'].viewport.width, height: 800 } }); - authTest('base view', async({ render, page }) => { + authTest('base view', async({ render, page, mockApiResponse }) => { + await mockApiResponse('core:user_info', profileMock.base); const component = await render(<Burger/>, { hooksConfig }); await component.getByRole('button', { name: 'Menu button' }).click(); diff --git a/src/shell/header/HeaderAlert.spec.tsx b/src/shell/header/HeaderAlert.spec.tsx new file mode 100644 index 00000000000..0508031a1eb --- /dev/null +++ b/src/shell/header/HeaderAlert.spec.tsx @@ -0,0 +1,138 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import { describe, expect, it, vi } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const sdk = vi.hoisted(() => ({ + init: vi.fn(), + track: vi.fn(), + register: vi.fn(), + identify: vi.fn(), + people: { set: vi.fn(), set_once: vi.fn() }, +})); +vi.mock('mixpanel-browser', () => ({ 'default': sdk })); + +const LINK = 'https://example.com/campaign?utm_source=blockscout#details'; +const HTML = [ + '<p>Example campaign ', + `<a href="${ LINK }" target="_blank"><span>Learn more</span></a>`, + '<a href="/apps" target="_blank">Open apps</a>', + '<a>More info</a>', + '</p>', +].join(''); + +type Target = 'link' | 'span' | 'relativeLink' | 'text' | 'anchor'; + +interface Click { + readonly target: Target; + readonly type: 'click' | 'auxclick'; + readonly button: number; + readonly isInsideOuterLink: boolean; +} + +const clickInBanner = async({ target, type, button, isInsideOuterLink }: Click): Promise<MouseEvent> => { + const event = new MouseEvent(type, { bubbles: true, cancelable: true, button }); + + await withEnvs([ + [ 'NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE', HTML ], + [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', 'test-token' ], + [ 'NEXT_PUBLIC_HIDE_INDEXING_ALERT_BLOCKS', 'true' ], + ], async() => { + const { render, screen, fireEvent } = await import('vitest/lib'); + const { 'default': HeaderAlert } = await import('./HeaderAlert'); + const analytics = await import('src/shared/analytics'); + + const Harness = () => { + const isInitialized = analytics.useInit(); + return ( + <> + <span>{ isInitialized ? 'analytics ready' : 'analytics pending' }</span> + { isInsideOuterLink ? <a href="https://example.com/outer"><HeaderAlert/></a> : <HeaderAlert/> } + </> + ); + }; + + const view = render(<Harness/>); + try { + await screen.findByText('analytics ready'); + sdk.track.mockClear(); + + const elements: Record<Target, HTMLElement> = { + link: screen.getByRole('link', { name: 'Learn more' }), + span: screen.getByText('Learn more'), + relativeLink: screen.getByRole('link', { name: 'Open apps' }), + text: screen.getByText('Example campaign'), + anchor: screen.getByText('More info'), + }; + fireEvent(elements[target], event); + } finally { + view.unmount(); + } + }); + + return event; +}; + +describe('header banner link tracking', () => { + it.each([ + { target: 'link', type: 'click', button: 0, loggedLink: LINK }, + { target: 'span', type: 'click', button: 0, loggedLink: LINK }, + { target: 'span', type: 'auxclick', button: 1, loggedLink: LINK }, + { target: 'relativeLink', type: 'click', button: 0, loggedLink: 'http://localhost:3000/apps' }, + ] as const)('tracks $type with button $button on $target as $loggedLink', async({ loggedLink, ...click }) => { + const event = await clickInBanner({ ...click, isInsideOuterLink: false }); + + expect(event.defaultPrevented).toBe(false); + expect(sdk.track).toHaveBeenCalledTimes(1); + expect(sdk.track.mock.calls[0].slice(0, 2)).toEqual([ 'Promo banner', { Source: 'Header', Link: loggedLink } ]); + }); + + it.each([ + { target: 'span', type: 'auxclick', button: 2 }, + { target: 'text', type: 'click', button: 0 }, + { target: 'anchor', type: 'click', button: 0 }, + ] as const)('ignores $type with button $button on $target', async(click) => { + const event = await clickInBanner({ ...click, isInsideOuterLink: false }); + + expect(event.defaultPrevented).toBe(false); + expect(sdk.track).not.toHaveBeenCalled(); + }); + + it('ignores a click on banner text when the link is outside the banner', async() => { + const event = await clickInBanner({ target: 'text', type: 'click', button: 0, isInsideOuterLink: true }); + + expect(event.defaultPrevented).toBe(false); + expect(sdk.track).not.toHaveBeenCalled(); + }); +}); + +describe('header banner markup', () => { + it('renders the banner text and links without frames, inline styles or event handlers', async() => { + await withEnvs([ + [ 'NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE', [ + '<div style="position:fixed;inset:0">Wallet verification required ', + '<a href="https://example.com" onclick="steal()">Connect</a>', + '<iframe srcdoc="<script src=/assets/configs/network_logo.js></script>"></iframe></div>', + ].join('') ], + [ 'NEXT_PUBLIC_HIDE_INDEXING_ALERT_BLOCKS', 'true' ], + ], async() => { + const { render, screen } = await import('vitest/lib'); + const { 'default': HeaderAlert } = await import('./HeaderAlert'); + + const view = render(<HeaderAlert/>); + try { + const link = screen.getByRole('link', { name: 'Connect' }); + const text = screen.getByText('Wallet verification required'); + + expect(link.getAttribute('href')).toBe('https://example.com'); + expect(link.hasAttribute('onclick')).toBe(false); + expect(text.hasAttribute('style')).toBe(false); + expect(view.container.querySelector('iframe')).toBeNull(); + } finally { + view.unmount(); + } + }); + }); +}); diff --git a/src/shell/header/HeaderAlert.tsx b/src/shell/header/HeaderAlert.tsx index d5e36c2efc2..7c7d3644518 100644 --- a/src/shell/header/HeaderAlert.tsx +++ b/src/shell/header/HeaderAlert.tsx @@ -7,16 +7,35 @@ import React from 'react'; import IndexingStatusBlocks from 'src/slices/chain/indexing-status/IndexingStatusBlocks'; import config from 'src/config'; +import * as analytics from 'src/shared/analytics'; +import { sanitizeHtml } from 'src/shared/texts/sanitize-html'; import { Alert } from 'src/toolkit/chakra/alert'; import { BoxHtml } from 'src/toolkit/chakra/box'; -const maintenanceAlertHtml = config.shell.header.maintenanceAlert.message || ''; +const maintenanceAlertHtml = sanitizeHtml(config.shell.header.maintenanceAlert.message || ''); + +const handleLinkClick = (event: React.MouseEvent<HTMLDivElement>): void => { + if (event.button > 1 || !(event.target instanceof Element)) { + return; + } + + const link = event.target.closest('a[href]'); + if (!(link instanceof HTMLAnchorElement) || !event.currentTarget.contains(link)) { + return; + } + + analytics.logEvent(analytics.EventTypes.PROMO_BANNER, { Source: 'Header', Link: link.href }); +}; const HeaderAlert = (props: FlexProps) => { return ( <Flex flexDir="column" rowGap={ 1 } mb={{ base: 6, lg: 3 }} _empty={{ display: 'none' }} { ...props }> - { maintenanceAlertHtml && <Alert status="info" showIcon><BoxHtml html={ maintenanceAlertHtml }/></Alert> } + { maintenanceAlertHtml && ( + <Alert status="info" showIcon> + <BoxHtml html={ maintenanceAlertHtml } onClick={ handleLinkClick } onAuxClick={ handleLinkClick }/> + </Alert> + ) } <IndexingStatusBlocks/> </Flex> ); diff --git a/src/shell/header/HeaderDesktop.pw.tsx b/src/shell/header/HeaderDesktop.pw.tsx index 4cd6f0eef72..86dcacfea72 100644 --- a/src/shell/header/HeaderDesktop.pw.tsx +++ b/src/shell/header/HeaderDesktop.pw.tsx @@ -1,14 +1,17 @@ import React from 'react'; +import * as rewardsConfigMock from 'src/features/rewards/mocks/rewards-config'; + import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; import { test, expect } from 'playwright/lib'; import HeaderDesktop from './HeaderDesktop'; -test.beforeEach(async({ mockEnvs }) => { +test.beforeEach(async({ mockEnvs, mockApiResponse }) => { await mockEnvs([ ...ENVS_MAP.rewardsService, ]); + await mockApiResponse('rewards:config', rewardsConfigMock.base); }); test('default view +@dark-mode', async({ render }) => { diff --git a/src/shell/header/HeaderMobile.pw.tsx b/src/shell/header/HeaderMobile.pw.tsx index 4757dc1e58b..7cb81c5c7d1 100644 --- a/src/shell/header/HeaderMobile.pw.tsx +++ b/src/shell/header/HeaderMobile.pw.tsx @@ -1,5 +1,7 @@ import React from 'react'; +import * as rewardsConfigMock from 'src/features/rewards/mocks/rewards-config'; + import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; import { test, expect, devices } from 'playwright/lib'; @@ -7,10 +9,11 @@ import HeaderMobile from './HeaderMobile'; test.use({ viewport: devices['iPhone 13 Pro'].viewport }); -test.beforeEach(async({ mockEnvs }) => { +test.beforeEach(async({ mockEnvs, mockApiResponse }) => { await mockEnvs([ ...ENVS_MAP.rewardsService, ]); + await mockApiResponse('rewards:config', rewardsConfigMock.base); }); test('default view +@dark-mode', async({ render, page }) => { diff --git a/src/shell/header/__screenshots__/Burger.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png b/src/shell/header/__screenshots__/Burger.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png index 47a71c5af87..5e11e3fc7a4 100644 Binary files a/src/shell/header/__screenshots__/Burger.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png and b/src/shell/header/__screenshots__/Burger.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png differ diff --git a/src/shell/header/__screenshots__/Burger.pw.tsx_default_auth-base-view-1.png b/src/shell/header/__screenshots__/Burger.pw.tsx_default_auth-base-view-1.png index 5e0c46c8277..1fbe7d18ca7 100644 Binary files a/src/shell/header/__screenshots__/Burger.pw.tsx_default_auth-base-view-1.png and b/src/shell/header/__screenshots__/Burger.pw.tsx_default_auth-base-view-1.png differ diff --git a/src/shell/header/__screenshots__/Burger.pw.tsx_default_base-view-1.png b/src/shell/header/__screenshots__/Burger.pw.tsx_default_base-view-1.png index 722f1cee468..c25a001e343 100644 Binary files a/src/shell/header/__screenshots__/Burger.pw.tsx_default_base-view-1.png and b/src/shell/header/__screenshots__/Burger.pw.tsx_default_base-view-1.png differ diff --git a/src/shell/header/__screenshots__/Burger.pw.tsx_default_submenu-1.png b/src/shell/header/__screenshots__/Burger.pw.tsx_default_submenu-1.png index 43f8233a171..4bd04bffac4 100644 Binary files a/src/shell/header/__screenshots__/Burger.pw.tsx_default_submenu-1.png and b/src/shell/header/__screenshots__/Burger.pw.tsx_default_submenu-1.png differ diff --git a/src/shell/header/__screenshots__/Burger.pw.tsx_default_with-promo-banner-text-dark-mode-1.png b/src/shell/header/__screenshots__/Burger.pw.tsx_default_with-promo-banner-text-dark-mode-1.png index 3a94b9e0c30..5faca8b7328 100644 Binary files a/src/shell/header/__screenshots__/Burger.pw.tsx_default_with-promo-banner-text-dark-mode-1.png and b/src/shell/header/__screenshots__/Burger.pw.tsx_default_with-promo-banner-text-dark-mode-1.png differ diff --git a/src/shell/header/config.spec.ts b/src/shell/header/config.spec.ts new file mode 100644 index 00000000000..8d56d071ded --- /dev/null +++ b/src/shell/header/config.spec.ts @@ -0,0 +1,81 @@ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const NAME = 'NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE'; +const LINK = 'https://keeperwallet.com/download?utm_source=blockscout#mobile'; +const MAKE_ENVS_SCRIPT = path.resolve('deploy/scripts/make_envs_script.sh'); + +const buildBrowserEnvs = (value: string): Record<string, string> => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'envs-js-')); + const file = path.join(dir, 'envs.js'); + try { + // eslint-disable-next-line no-restricted-properties -- the script runs in a child shell that needs the parent's environment + execFileSync('bash', [ MAKE_ENVS_SCRIPT, file ], { cwd: dir, env: { ...process.env, [NAME]: value } }); + const browserGlobal: { __envs?: Record<string, string> } = {}; + new Function('window', fs.readFileSync(file, 'utf8'))(browserGlobal); + return browserGlobal.__envs ?? {}; + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}; + +const resolveMessage = async(value: string, side: 'server' | 'browser'): Promise<string> => { + return withEnvs([ [ NAME, value ] ], async() => { + if (side === 'browser') { + vi.stubGlobal('window', { __envs: buildBrowserEnvs(value) }); + } + const { 'default': config } = await import('./config'); + return config.maintenanceAlert.message; + }); +}; + +const SIDES = [ 'server', 'browser' ] as const; + +const ITEMS_DOUBLE_QUOTED_HREF = [ + `Keeper on Ethereum. <a href="${ LINK }">Download now</a>`, + `Keeper on Base. <a href="${ LINK }">Download now</a>`, +]; +const ITEMS_SINGLE_QUOTED_HREF = [ + `Keeper on Ethereum. <a href='${ LINK }'>Download now</a>`, + `Keeper's on Base. <a href='${ LINK }'>Download now</a>`, +]; + +describe('maintenance alert', () => { + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + it('shows the item Math.random lands on', async() => { + vi.spyOn(Math, 'random').mockReturnValue(0.99); + expect(await resolveMessage(JSON.stringify(ITEMS_SINGLE_QUOTED_HREF), 'server')).toBe(ITEMS_SINGLE_QUOTED_HREF[1]); + + vi.spyOn(Math, 'random').mockReturnValue(0); + expect(await resolveMessage(JSON.stringify(ITEMS_SINGLE_QUOTED_HREF), 'server')).toBe(ITEMS_SINGLE_QUOTED_HREF[0]); + }); + + it('shows nothing when the variable is unset', async() => { + expect(await resolveMessage('', 'server')).toBe(''); + }); + + it.each(SIDES)('shows a single HTML message as set on the %s', async(side) => { + expect(await resolveMessage(`Keeper. <a href="${ LINK }">Download now</a>`, side)).toBe(`Keeper. <a href="${ LINK }">Download now</a>`); + }); + + it.each(SIDES)('rotates single-quoted plain-text items on the %s', async(side) => { + expect([ 'Hello', 'Duck me' ]).toContain(await resolveMessage('[\'Hello\',\'Duck me\']', side)); + }); + + it.each(SIDES)('rotates JSON items whose HTML has escaped double-quoted attributes on the %s', async(side) => { + expect(ITEMS_DOUBLE_QUOTED_HREF).toContain(await resolveMessage(JSON.stringify(ITEMS_DOUBLE_QUOTED_HREF), side)); + }); + + it.each(SIDES)('rotates JSON items whose HTML has single-quoted attributes on the %s', async(side) => { + expect(ITEMS_SINGLE_QUOTED_HREF).toContain(await resolveMessage(JSON.stringify(ITEMS_SINGLE_QUOTED_HREF), side)); + }); +}); diff --git a/src/shell/header/config.ts b/src/shell/header/config.ts index 9ff5b32aaff..0b8adcac5d8 100644 --- a/src/shell/header/config.ts +++ b/src/shell/header/config.ts @@ -1,27 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { getEnvValue, parseEnvJson } from 'src/config/utils/envs'; +import { getRawEnvValue, parseEnvHtmlList } from 'src/config/utils/envs'; -const maintenanceAlertMessage = (() => { - const envValue = getEnvValue('NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE'); - const parsedValue = envValue ? parseEnvJson<Array<string>>(envValue) : undefined; - - if (!parsedValue || !Array.isArray(parsedValue)) { - return envValue; - } - - if (parsedValue.length < 2) { - return parsedValue[0]; - } - - const index = Math.floor(Math.random() * parsedValue.length); - - return parsedValue[index]; -})(); +const messages = parseEnvHtmlList(getRawEnvValue('NEXT_PUBLIC_MAINTENANCE_ALERT_MESSAGE')); const config = Object.freeze({ maintenanceAlert: { - message: maintenanceAlertMessage || '', + message: messages.length > 0 ? messages[Math.floor(Math.random() * messages.length)] : '', }, }); diff --git a/src/shell/layout/Layout.pw.tsx b/src/shell/layout/Layout.pw.tsx index 039f352ee56..12a3719a2bc 100644 --- a/src/shell/layout/Layout.pw.tsx +++ b/src/shell/layout/Layout.pw.tsx @@ -1,6 +1,6 @@ import React from 'react'; -import { indexingStatus } from 'src/slices/home/mocks/indexing-status'; +import * as indexingStatusMock from 'src/slices/chain/indexing-status/mocks'; import { test, expect } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; @@ -16,7 +16,7 @@ test.skip('base view +@mobile', async({ render, mockEnvs, mockApiResponse }) => 'We are currently lacking pictures of <i>ducks</i>. Please <a href="mailto:duck@blockscout.com">send</a> us one.', ], ]); - await mockApiResponse('core:homepage_indexing_status', indexingStatus); + await mockApiResponse('core:homepage_indexing_status', indexingStatusMock.blocksInProgress); const component = await render(<Layout>Page Content</Layout>); await expect(component).toHaveScreenshot(); }); diff --git a/src/shell/layout/LayoutError.pw.tsx b/src/shell/layout/LayoutError.pw.tsx index 01790f3c358..46409cdc02d 100644 --- a/src/shell/layout/LayoutError.pw.tsx +++ b/src/shell/layout/LayoutError.pw.tsx @@ -1,7 +1,7 @@ import { Box } from '@chakra-ui/react'; import React from 'react'; -import { indexingStatus } from 'src/slices/home/mocks/indexing-status'; +import * as indexingStatusMock from 'src/slices/chain/indexing-status/mocks'; import { test, expect } from 'playwright/lib'; @@ -10,7 +10,7 @@ import LayoutHome from './LayoutHome'; // FIXME: at the moment, in the docker container playwright make screenshot before the page is completely loaded // I cannot figure out the reason, so I skip this test for now test.skip('base view +@mobile', async({ render, mockApiResponse }) => { - await mockApiResponse('core:homepage_indexing_status', indexingStatus); + await mockApiResponse('core:homepage_indexing_status', indexingStatusMock.blocksInProgress); const component = await render( <LayoutHome> <Box pt={ 10 }>Error</Box> diff --git a/src/shell/layout/LayoutHome.pw.tsx b/src/shell/layout/LayoutHome.pw.tsx index fa124afecdc..fc485cdda52 100644 --- a/src/shell/layout/LayoutHome.pw.tsx +++ b/src/shell/layout/LayoutHome.pw.tsx @@ -1,6 +1,6 @@ import React from 'react'; -import { indexingStatus } from 'src/slices/home/mocks/indexing-status'; +import * as indexingStatusMock from 'src/slices/chain/indexing-status/mocks'; import { test, expect } from 'playwright/lib'; @@ -9,7 +9,7 @@ import LayoutHome from './LayoutHome'; // FIXME: at the moment, in the docker container playwright make screenshot before the page is completely loaded // I cannot figure out the reason, so I skip this test for now test.skip('base view +@mobile', async({ render, mockApiResponse }) => { - await mockApiResponse('core:homepage_indexing_status', indexingStatus); + await mockApiResponse('core:homepage_indexing_status', indexingStatusMock.blocksInProgress); const component = await render(<LayoutHome>Page Content</LayoutHome>); await expect(component).toHaveScreenshot(); }); diff --git a/src/shell/layout/components/NavBar.tsx b/src/shell/layout/components/NavBar.ts similarity index 100% rename from src/shell/layout/components/NavBar.tsx rename to src/shell/layout/components/NavBar.ts diff --git a/src/shell/layout/components/Root.tsx b/src/shell/layout/components/Root.ts similarity index 100% rename from src/shell/layout/components/Root.tsx rename to src/shell/layout/components/Root.ts diff --git a/src/shell/layout/components/SideBar.tsx b/src/shell/layout/components/SideBar.ts similarity index 100% rename from src/shell/layout/components/SideBar.tsx rename to src/shell/layout/components/SideBar.ts diff --git a/src/shell/layout/components/index.tsx b/src/shell/layout/components/index.ts similarity index 100% rename from src/shell/layout/components/index.tsx rename to src/shell/layout/components/index.ts diff --git a/src/shell/metadata/generate.ts b/src/shell/metadata/generate.ts index 287d2c31de4..25f8c22f677 100644 --- a/src/shell/metadata/generate.ts +++ b/src/shell/metadata/generate.ts @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { kebabCase, upperFirst } from 'es-toolkit'; -import type { Route } from 'nextjs-routes'; import type { ApiData, Metadata, OgTemplateValue, TemplateValue } from './types'; import type { RouteParams } from 'src/server/types'; @@ -9,9 +8,10 @@ import type { RouteParams } from 'src/server/types'; import { currencyUnits } from 'src/slices/chain/units'; import config from 'src/config'; -import shortenString from 'src/shared/texts/shorten-string'; +import type { Route } from 'src/shared/router/routes'; import { castToString } from 'src/toolkit/utils/guards'; +import { shortenString } from 'src/toolkit/utils/texts'; import compileValue from './compile-value'; import getCanonicalUrl from './get-canonical-url'; diff --git a/src/shell/metadata/get-canonical-url.ts b/src/shell/metadata/get-canonical-url.ts index 752e20e43f4..878cd4ad800 100644 --- a/src/shell/metadata/get-canonical-url.ts +++ b/src/shell/metadata/get-canonical-url.ts @@ -1,8 +1,7 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { Route } from 'nextjs-routes'; - import config from 'src/config'; +import type { Route } from 'src/shared/router/routes'; const CANONICAL_ROUTES: Array<Route['pathname']> = [ '/', diff --git a/src/shell/metadata/structured-data/index.ts b/src/shell/metadata/structured-data/index.ts index 393a495bb2c..837be723ff7 100644 --- a/src/shell/metadata/structured-data/index.ts +++ b/src/shell/metadata/structured-data/index.ts @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout // https://schema.org -import type { Route } from 'nextjs-routes'; import type { StructuredData, ApiData } from '../types'; import type { RouteParams } from 'src/server/types'; @@ -10,6 +9,8 @@ import generateTokenProductSchema from 'src/slices/token/structured-data/token'; import generateDappInfoSchema from 'src/features/marketplace/structured-data/dapp-info'; +import type { Route } from 'src/shared/router/routes'; + interface Params<Pathname extends Route['pathname']> { route: RouteParams<Pathname>; apiData: ApiData<Pathname>; diff --git a/src/shell/metadata/templates/index.ts b/src/shell/metadata/templates/index.ts index 7db193a61d1..f08fa90db71 100644 --- a/src/shell/metadata/templates/index.ts +++ b/src/shell/metadata/templates/index.ts @@ -2,14 +2,13 @@ /* eslint-disable max-len */ -import type { Route } from 'nextjs-routes'; - import type { OgTemplateValue, TemplateValue } from '../types'; import { layerLabels } from 'src/features/rollup/common/utils/layer'; import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; +import type { Route } from 'src/shared/router/routes'; const dappEntityName = (getFeaturePayload(config.features.marketplace)?.titles.entity_name ?? '').toLowerCase(); @@ -662,7 +661,7 @@ export const TEMPLATE_MAP: Record<Route['pathname'], RouteTemplateRecord> = { }, }, }, - '/cross-chain-tx/[id]': { + '/bridge/[bridgeId]/cross-chain-tx/[id]': { metadata: { title: { 'default': '%chain_name% cross-chain transaction %id% details', diff --git a/src/shell/metadata/types.ts b/src/shell/metadata/types.ts index e021dfb5827..4279d8b7190 100644 --- a/src/shell/metadata/types.ts +++ b/src/shell/metadata/types.ts @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { Route } from 'nextjs-routes'; import type { Product, WebApplication, WithContext } from 'schema-dts'; import type { MarketplaceDapp } from '@blockscout/admin-rs-types'; @@ -8,6 +7,8 @@ import type { schemas } from '@blockscout/api-types'; import type { LineChart } from '@blockscout/stats-types'; import type { TxOgDescriptionParams } from 'src/slices/tx/types/api'; +import type { Route } from 'src/shared/router/routes'; + /* eslint-disable @stylistic/indent */ export type ApiData<Pathname extends Route['pathname']> = ( diff --git a/src/shell/metadata/update.ts b/src/shell/metadata/update.ts index 6a9234fb587..4ab96a7e148 100644 --- a/src/shell/metadata/update.ts +++ b/src/shell/metadata/update.ts @@ -1,10 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { Route } from 'nextjs-routes'; - import type { ApiData } from './types'; import type { RouteParams } from 'src/server/types'; +import type { Route } from 'src/shared/router/routes'; + import generate from './generate'; const JSON_LD_SCRIPT_ID = 'blockscout-structured-data'; diff --git a/src/shell/navigation/horizontal/NavLink.tsx b/src/shell/navigation/horizontal/NavLink.tsx index 9feb3121969..bc7e4952f21 100644 --- a/src/shell/navigation/horizontal/NavLink.tsx +++ b/src/shell/navigation/horizontal/NavLink.tsx @@ -1,11 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { NavItem } from '../types'; +import { route } from 'src/shared/router/routes'; + import { Link } from 'src/toolkit/chakra/link'; import LightningLabel from '../LightningLabel'; diff --git a/src/shell/navigation/horizontal/NavigationDesktop.pw.tsx b/src/shell/navigation/horizontal/NavigationDesktop.pw.tsx index e4411c92ea2..8b8032970e9 100644 --- a/src/shell/navigation/horizontal/NavigationDesktop.pw.tsx +++ b/src/shell/navigation/horizontal/NavigationDesktop.pw.tsx @@ -4,6 +4,8 @@ import React from 'react'; import * as profileMock from 'src/features/account/mocks/user-profile'; import * as rewardsBalanceMock from 'src/features/rewards/mocks/balance'; import * as dailyRewardMock from 'src/features/rewards/mocks/daily-reward'; +import * as referralsMock from 'src/features/rewards/mocks/referrals'; +import * as rewardsConfigMock from 'src/features/rewards/mocks/rewards-config'; import { contextWithAuth } from 'playwright/fixtures/auth'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; @@ -26,15 +28,17 @@ testWithAuth('base view +@dark-mode', async({ render, mockApiResponse, mockEnvs, }, }; - await mockApiResponse('core:user_info', profileMock.withEmailAndWallet); - await mockApiResponse('rewards:user_balances', rewardsBalanceMock.base); - await mockApiResponse('rewards:user_daily_check', dailyRewardMock.base); await mockEnvs([ ...ENVS_MAP.userOps, ...ENVS_MAP.nameService, ...ENVS_MAP.rewardsService, [ 'NEXT_PUBLIC_NAVIGATION_HIGHLIGHTED_ROUTES', '["/blocks","/apps"]' ], ]); + await mockApiResponse('core:user_info', profileMock.withEmailAndWallet); + await mockApiResponse('rewards:user_balances', rewardsBalanceMock.base); + await mockApiResponse('rewards:user_daily_check', dailyRewardMock.base); + await mockApiResponse('rewards:user_referrals', referralsMock.base); + await mockApiResponse('rewards:config', rewardsConfigMock.base); const component = await render(<NavigationDesktop/>, { hooksConfig }); await component.getByText('Blockchain').hover(); diff --git a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png index fa8a0ebc92f..8064c89d40c 100644 Binary files a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png and b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png differ diff --git a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_base-view-dark-mode-1.png b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_base-view-dark-mode-1.png index eca1b9496a0..99c3fd337f6 100644 Binary files a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_base-view-dark-mode-1.png and b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-groped-items-1.png b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-groped-items-1.png index f466dd958a7..c83b9bd0be9 100644 Binary files a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-groped-items-1.png and b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-groped-items-1.png differ diff --git a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-1.png b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-1.png index 4a7db29b9f0..a83059de1a0 100644 Binary files a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-1.png and b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-1.png differ diff --git a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-with-tooltip-1.png b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-with-tooltip-1.png index 8ac8e855fd0..8f2d3f7405f 100644 Binary files a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-with-tooltip-1.png and b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-with-tooltip-1.png differ diff --git a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-dark-mode-1.png b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-dark-mode-1.png index fe53cd3ad39..202a11f5b12 100644 Binary files a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-dark-mode-1.png and b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-dark-mode-1.png differ diff --git a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-with-tooltip-1.png b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-with-tooltip-1.png index f869ef24986..a05c7987ffb 100644 Binary files a/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-with-tooltip-1.png and b/src/shell/navigation/horizontal/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-with-tooltip-1.png differ diff --git a/src/shell/navigation/types.ts b/src/shell/navigation/types.ts index d7d02fe5af1..369781cd95f 100644 --- a/src/shell/navigation/types.ts +++ b/src/shell/navigation/types.ts @@ -1,8 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { Route } from 'nextjs-routes'; import type React from 'react'; +import type { Route } from 'src/shared/router/routes'; import type { IconName } from 'src/sprite/SpriteIcon'; type NavIconOrComponent = { diff --git a/src/shell/navigation/useNavItems.ts b/src/shell/navigation/useNavItems.ts new file mode 100644 index 00000000000..d9e08ef74cd --- /dev/null +++ b/src/shell/navigation/useNavItems.ts @@ -0,0 +1,426 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { NavItemInternal, NavItem, NavGroupItem } from './types'; + +import { layerLabels } from 'src/features/rollup/common/utils/layer'; + +import config from 'src/config'; +import { getFeaturePayload } from 'src/config/utils/features'; +import { useRouter } from 'src/shared/router/useRouter'; + +import { rightLineArrow } from 'src/toolkit/utils/htmlEntities'; + +const marketplaceFeature = config.features.marketplace; +const beaconChainFeature = config.features.beaconChain; + +interface ReturnType { + mainNavItems: Array<NavItem | NavGroupItem>; + accountNavItems: Array<NavItem>; +} + +export function isGroupItem(item: NavItem | NavGroupItem): item is NavGroupItem { + return 'subItems' in item; +} + +export function isInternalItem(item: NavItem): item is NavItemInternal { + return 'nextRoute' in item; +} + +export default function useNavItems(): ReturnType { + const router = useRouter(); + const pathname = router.pathname; + const query = router.query; + const tab = query.tab; + + return React.useMemo(() => { + let blockchainNavItems: Array<NavItem> | Array<Array<NavItem>> = []; + + const topAccounts: NavItem | null = !config.slices.address.hiddenViews?.top_accounts ? { + text: 'Top accounts', + nextRoute: { pathname: '/accounts' as const }, + icon: 'navigation/top_accounts', + isActive: pathname === '/accounts', + } : null; + const blocks: NavItem | null = { + text: 'Blocks', + nextRoute: { pathname: '/blocks' as const }, + icon: 'navigation/block', + isActive: pathname === '/blocks' || pathname === '/block/[height_or_hash]' || pathname === '/chain/[chain_slug_or_id]/block/[height_or_hash]', + }; + const txs: NavItem | null = { + text: 'Transactions', + nextRoute: { pathname: '/txs' as const }, + icon: 'navigation/transactions', + isActive: + // sorry, but this is how it was designed + (pathname === '/txs' && (!config.features.zetachain.isEnabled || !tab || !tab.includes('cctx'))) || + pathname === '/tx/[hash]' || + pathname === '/chain/[chain_slug_or_id]/tx/[hash]', + }; + const cctxs: NavItem | null = config.features.zetachain.isEnabled ? { + text: 'Cross-chain transactions', + nextRoute: { pathname: '/txs' as const, query: { tab: 'cctx' } }, + icon: 'navigation/cross_chain_txs', + isActive: pathname === '/cc/tx/[hash]' || (pathname === '/txs' && tab?.includes('cctx')), + } : null; + const operations: NavItem | null = config.features.tac.isEnabled ? { + text: 'Operations', + nextRoute: { pathname: '/operations' as const }, + icon: 'navigation/operation', + isActive: pathname === '/operations' || pathname === '/operation/[id]', + } : null; + const internalTxs: NavItem | null = config.slices.internalTx.isEnabled ? { + text: 'Internal transactions', + nextRoute: { pathname: '/internal-txs' as const }, + icon: 'navigation/internal_txns', + isActive: pathname === '/internal-txs', + } : null; + const userOps: NavItem | null = config.features.userOps.isEnabled ? { + text: 'User operations', + nextRoute: { pathname: '/ops' as const }, + icon: 'navigation/user_op', + isActive: pathname === '/ops' || pathname === '/op/[hash]' || pathname === '/chain/[chain_slug_or_id]/op/[hash]', + } : null; + + const verifiedContracts: NavItem | null = + { + text: 'Verified contracts', + nextRoute: { pathname: '/verified-contracts' as const }, + icon: 'navigation/verified_contracts', + isActive: pathname === '/verified-contracts', + }; + const nameLookup = config.features.nameServices.isEnabled ? { + text: 'Name services lookup', + nextRoute: { pathname: '/name-services' as const }, + icon: 'navigation/name_services', + isActive: pathname.startsWith('/name-services'), + } : null; + const validators = config.features.validators.isEnabled ? { + text: 'Validators', + nextRoute: { pathname: '/validators' as const }, + icon: 'navigation/validator', + isActive: pathname === '/validators' || pathname === '/validators/[id]', + } : null; + const rollupDeposits = { + text: `Deposits (${ layerLabels.parent }${ rightLineArrow }${ layerLabels.current })`, + nextRoute: { pathname: '/deposits' as const }, + icon: 'navigation/deposits', + isActive: pathname === '/deposits', + }; + const rollupWithdrawals = { + text: `Withdrawals (${ layerLabels.current }${ rightLineArrow }${ layerLabels.parent })`, + nextRoute: { pathname: '/withdrawals' as const }, + icon: 'navigation/withdrawals', + isActive: pathname === '/withdrawals', + }; + const rollupTxnBatches = { + text: 'Txn batches', + nextRoute: { pathname: '/batches' as const }, + icon: 'navigation/txn_batches', + isActive: pathname === '/batches', + }; + const rollupOutputRoots = { + text: 'Output roots', + nextRoute: { pathname: '/output-roots' as const }, + icon: 'navigation/output_roots', + isActive: pathname === '/output-roots', + }; + const rollupDisputeGames = getFeaturePayload(config.features.rollup)?.faultProofSystemEnabled ? { + text: 'Dispute games', + nextRoute: { pathname: '/dispute-games' as const }, + icon: 'navigation/games', + isActive: pathname === '/dispute-games', + } : null; + const epochs = config.features.celo.isEnabled ? { + text: 'Epochs', + nextRoute: { pathname: '/epochs' as const }, + icon: 'navigation/hourglass', + isActive: pathname.startsWith('/epochs'), + } : null; + + const rollupFeature = config.features.rollup; + + const rollupInteropMessages = rollupFeature.isEnabled && rollupFeature.interopEnabled ? { + text: 'Interop messages', + nextRoute: { pathname: '/interop-messages' as const }, + icon: 'navigation/cross_chain_txs', + isActive: pathname === '/interop-messages', + } : null; + + if (rollupFeature.isEnabled && ( + rollupFeature.type === 'optimistic' || + rollupFeature.type === 'arbitrum' || + rollupFeature.type === 'scroll' + )) { + blockchainNavItems = [ + [ + txs, + internalTxs, + rollupDeposits, + rollupWithdrawals, + rollupInteropMessages, + ].filter(Boolean), + [ + blocks, + epochs, + // currently, transaction batches are not implemented for Celo + !config.features.celo.isEnabled ? rollupTxnBatches : undefined, + rollupDisputeGames, + rollupFeature.outputRootsEnabled ? rollupOutputRoots : undefined, + ].filter(Boolean), + [ + userOps, + topAccounts, + validators, + verifiedContracts, + nameLookup, + ].filter(Boolean), + ]; + } else if (rollupFeature.isEnabled && rollupFeature.type === 'shibarium') { + blockchainNavItems = [ + [ + txs, + internalTxs, + rollupDeposits, + rollupWithdrawals, + ].filter(Boolean), + [ + blocks, + userOps, + topAccounts, + verifiedContracts, + nameLookup, + ].filter(Boolean), + ]; + } else if (rollupFeature.isEnabled && rollupFeature.type === 'zkSync') { + blockchainNavItems = [ + [ + txs, + internalTxs, + userOps, + blocks, + rollupTxnBatches, + ].filter(Boolean), + [ + topAccounts, + validators, + verifiedContracts, + nameLookup, + ].filter(Boolean), + ]; + } else { + blockchainNavItems = [ + txs, + operations, + internalTxs, + cctxs, + userOps, + blocks, + epochs, + topAccounts, + validators, + verifiedContracts, + nameLookup, + beaconChainFeature.isEnabled && !beaconChainFeature.withdrawalsOnly && { + text: 'Deposits', + nextRoute: { pathname: '/deposits' as const }, + icon: 'navigation/deposits', + isActive: pathname === '/deposits', + }, + config.features.beaconChain.isEnabled && { + text: 'Withdrawals', + nextRoute: { pathname: '/withdrawals' as const }, + icon: 'navigation/withdrawals', + isActive: pathname === '/withdrawals', + }, + ].filter(Boolean); + } + + const tokensNavItems = [ + { + text: 'Tokens', + nextRoute: { pathname: '/tokens' as const }, + icon: 'navigation/tokens', + isActive: pathname === '/tokens' || pathname.startsWith('/token/'), + }, + { + text: 'Token transfers', + nextRoute: { pathname: '/token-transfers' as const }, + icon: 'navigation/token_transfers', + isActive: pathname === '/token-transfers', + }, + config.features.dexPools.isEnabled && { + text: 'DEX tracker', + nextRoute: { pathname: '/pools' as const }, + icon: 'navigation/dex_tracker', + isActive: pathname === '/pools' || pathname.startsWith('/pool/'), + }, + ].filter(Boolean); + + const statsNavItem: NavGroupItem | null = (() => { + const megaEthFeature = config.features.megaEth; + + const items = [ + config.features.stats.isEnabled && { + text: 'Chain stats', + nextRoute: { pathname: '/stats' as const }, + icon: 'navigation/chain_stats', + isActive: pathname.startsWith('/stats'), + }, + config.features.multichain.isEnabled && { + text: 'Ecosystems', + nextRoute: { pathname: '/ecosystems' as const }, + icon: 'navigation/ecosystems', + isActive: pathname.startsWith('/ecosystems'), + }, + megaEthFeature.isEnabled && megaEthFeature.socketUrl.metrics && { + text: 'Uptime', + nextRoute: { pathname: '/uptime' as const }, + icon: 'navigation/uptime', + isActive: pathname.startsWith('/uptime'), + }, + config.features.hotContracts.isEnabled && { + text: 'Hot contracts', + nextRoute: { pathname: '/hot-contracts' as const }, + icon: 'navigation/hot_contracts', + isActive: pathname.startsWith('/hot-contracts'), + }, + config.features.gasTracker.isEnabled && { + text: 'Gas tracker', + nextRoute: { pathname: '/gas-tracker' as const }, + icon: 'navigation/gas_tracker', + isActive: pathname.startsWith('/gas-tracker'), + }, + config.features.crossChainTxs.isEnabled && !config.features.multichain.isEnabled && { + text: 'ICTT users', + nextRoute: { pathname: '/ictt-users' as const }, + icon: 'navigation/ictt_users', + isActive: pathname.startsWith('/ictt-users'), + }, + ].filter(Boolean); + + if (items.length === 0) { + return null; + } + + return { + text: 'Charts & stats', + nextRoute: { pathname: '/stats' as const }, + icon: 'navigation/stats', + isActive: items.some(item => isInternalItem(item) && item.isActive), + subItems: items, + }; + })(); + + const apiNavItem: NavItem | null = (() => { + const feature = getFeaturePayload(config.features.apiDocs); + + if (!feature) { + return null; + } + + if (feature.mode === 'external') { + return { + text: 'API', + url: feature.url, + icon: 'navigation/api_docs', + }; + } + + return { + text: 'API', + nextRoute: { pathname: '/api-docs' as const }, + icon: 'navigation/api_docs', + isActive: pathname.startsWith('/api-docs'), + }; + })(); + + const otherNavItems: Array<NavItem> | Array<Array<NavItem>> = [ + config.features.multichain.isEnabled ? { + text: 'Verify contract', + url: 'https://vera.blockscout.com', + } : { + text: 'Verify contract', + nextRoute: { pathname: '/contract-verification' as const }, + isActive: pathname.startsWith('/contract-verification'), + }, + getFeaturePayload(config.features.addressMetadata)?.isTagSubmitionEnabled && { + text: 'Submit public tag', + nextRoute: { pathname: '/public-tags/submit' as const }, + isActive: pathname.startsWith('/public-tags/submit'), + }, + rollupFeature.isEnabled && rollupFeature.type === 'arbitrum' && { + text: 'Txn withdrawals', + nextRoute: { pathname: '/txn-withdrawals' as const }, + isActive: pathname.startsWith('/txn-withdrawals'), + }, + ...config.shell.navigation.otherLinks, + ].filter(Boolean); + + const mainNavItems: ReturnType['mainNavItems'] = [ + { + text: 'Blockchain', + icon: 'navigation/blockchain', + isActive: blockchainNavItems.flat().some(item => isInternalItem(item) && item.isActive), + subItems: blockchainNavItems, + }, + { + text: 'Tokens', + icon: 'navigation/tokens', + isActive: tokensNavItems.flat().some(item => isInternalItem(item) && item.isActive), + subItems: tokensNavItems, + }, + marketplaceFeature.isEnabled ? { + text: marketplaceFeature.titles.menu_item, + nextRoute: { pathname: '/apps' as const }, + icon: 'navigation/apps', + isActive: pathname.startsWith('/app') || pathname.startsWith('/essential-dapps'), + } : null, + statsNavItem, + apiNavItem, + { + text: 'Other', + icon: 'navigation/other', + isActive: otherNavItems.flat().some(item => isInternalItem(item) && item.isActive), + subItems: otherNavItems, + }, + ].filter(Boolean); + + const accountNavItems: ReturnType['accountNavItems'] = [ + { + text: 'Watch list', + nextRoute: { pathname: '/account/watchlist' as const }, + icon: 'navigation/watchlist', + isActive: pathname === '/account/watchlist', + }, + { + text: 'Private tags', + nextRoute: { pathname: '/account/tag-address' as const }, + icon: 'navigation/private_tags', + isActive: pathname === '/account/tag-address', + }, + { + text: 'API keys', + nextRoute: { pathname: '/account/api-key' as const }, + icon: 'navigation/api_keys', + isActive: pathname === '/account/api-key', + }, + { + text: 'Custom ABI', + nextRoute: { pathname: '/account/custom-abi' as const }, + icon: 'navigation/custom_abi', + isActive: pathname === '/account/custom-abi', + }, + getFeaturePayload(config.features.account)?.verifiedAddresses?.isEnabled && { + text: 'Verified addrs', + nextRoute: { pathname: '/account/verified-addresses' as const }, + icon: 'navigation/verified_contracts', + isActive: pathname === '/account/verified-addresses', + }, + ].filter(Boolean); + + return { mainNavItems, accountNavItems }; + }, [ pathname, tab ]); +} diff --git a/src/shell/navigation/useNavItems.tsx b/src/shell/navigation/useNavItems.tsx deleted file mode 100644 index 825af72d648..00000000000 --- a/src/shell/navigation/useNavItems.tsx +++ /dev/null @@ -1,426 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useRouter } from 'next/router'; -import React from 'react'; - -import type { NavItemInternal, NavItem, NavGroupItem } from './types'; - -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import { getFeaturePayload } from 'src/config/utils/features'; - -import { rightLineArrow } from 'src/toolkit/utils/htmlEntities'; - -const marketplaceFeature = config.features.marketplace; -const beaconChainFeature = config.features.beaconChain; - -interface ReturnType { - mainNavItems: Array<NavItem | NavGroupItem>; - accountNavItems: Array<NavItem>; -} - -export function isGroupItem(item: NavItem | NavGroupItem): item is NavGroupItem { - return 'subItems' in item; -} - -export function isInternalItem(item: NavItem): item is NavItemInternal { - return 'nextRoute' in item; -} - -export default function useNavItems(): ReturnType { - const router = useRouter(); - const pathname = router.pathname; - const query = router.query; - const tab = query.tab; - - return React.useMemo(() => { - let blockchainNavItems: Array<NavItem> | Array<Array<NavItem>> = []; - - const topAccounts: NavItem | null = !config.slices.address.hiddenViews?.top_accounts ? { - text: 'Top accounts', - nextRoute: { pathname: '/accounts' as const }, - icon: 'navigation/top_accounts', - isActive: pathname === '/accounts', - } : null; - const blocks: NavItem | null = { - text: 'Blocks', - nextRoute: { pathname: '/blocks' as const }, - icon: 'navigation/block', - isActive: pathname === '/blocks' || pathname === '/block/[height_or_hash]' || pathname === '/chain/[chain_slug_or_id]/block/[height_or_hash]', - }; - const txs: NavItem | null = { - text: 'Transactions', - nextRoute: { pathname: '/txs' as const }, - icon: 'navigation/transactions', - isActive: - // sorry, but this is how it was designed - (pathname === '/txs' && (!config.features.zetachain.isEnabled || !tab || !tab.includes('cctx'))) || - pathname === '/tx/[hash]' || - pathname === '/chain/[chain_slug_or_id]/tx/[hash]', - }; - const cctxs: NavItem | null = config.features.zetachain.isEnabled ? { - text: 'Cross-chain transactions', - nextRoute: { pathname: '/txs' as const, query: { tab: 'cctx' } }, - icon: 'navigation/cross_chain_txs', - isActive: pathname === '/cc/tx/[hash]' || (pathname === '/txs' && tab?.includes('cctx')), - } : null; - const operations: NavItem | null = config.features.tac.isEnabled ? { - text: 'Operations', - nextRoute: { pathname: '/operations' as const }, - icon: 'navigation/operation', - isActive: pathname === '/operations' || pathname === '/operation/[id]', - } : null; - const internalTxs: NavItem | null = config.slices.internalTx.isEnabled ? { - text: 'Internal transactions', - nextRoute: { pathname: '/internal-txs' as const }, - icon: 'navigation/internal_txns', - isActive: pathname === '/internal-txs', - } : null; - const userOps: NavItem | null = config.features.userOps.isEnabled ? { - text: 'User operations', - nextRoute: { pathname: '/ops' as const }, - icon: 'navigation/user_op', - isActive: pathname === '/ops' || pathname === '/op/[hash]' || pathname === '/chain/[chain_slug_or_id]/op/[hash]', - } : null; - - const verifiedContracts: NavItem | null = - { - text: 'Verified contracts', - nextRoute: { pathname: '/verified-contracts' as const }, - icon: 'navigation/verified_contracts', - isActive: pathname === '/verified-contracts', - }; - const nameLookup = config.features.nameServices.isEnabled ? { - text: 'Name services lookup', - nextRoute: { pathname: '/name-services' as const }, - icon: 'navigation/name_services', - isActive: pathname.startsWith('/name-services'), - } : null; - const validators = config.features.validators.isEnabled ? { - text: 'Validators', - nextRoute: { pathname: '/validators' as const }, - icon: 'navigation/validator', - isActive: pathname === '/validators' || pathname === '/validators/[id]', - } : null; - const rollupDeposits = { - text: `Deposits (${ layerLabels.parent }${ rightLineArrow }${ layerLabels.current })`, - nextRoute: { pathname: '/deposits' as const }, - icon: 'navigation/deposits', - isActive: pathname === '/deposits', - }; - const rollupWithdrawals = { - text: `Withdrawals (${ layerLabels.current }${ rightLineArrow }${ layerLabels.parent })`, - nextRoute: { pathname: '/withdrawals' as const }, - icon: 'navigation/withdrawals', - isActive: pathname === '/withdrawals', - }; - const rollupTxnBatches = { - text: 'Txn batches', - nextRoute: { pathname: '/batches' as const }, - icon: 'navigation/txn_batches', - isActive: pathname === '/batches', - }; - const rollupOutputRoots = { - text: 'Output roots', - nextRoute: { pathname: '/output-roots' as const }, - icon: 'navigation/output_roots', - isActive: pathname === '/output-roots', - }; - const rollupDisputeGames = getFeaturePayload(config.features.rollup)?.faultProofSystemEnabled ? { - text: 'Dispute games', - nextRoute: { pathname: '/dispute-games' as const }, - icon: 'navigation/games', - isActive: pathname === '/dispute-games', - } : null; - const epochs = config.features.celo.isEnabled ? { - text: 'Epochs', - nextRoute: { pathname: '/epochs' as const }, - icon: 'navigation/hourglass', - isActive: pathname.startsWith('/epochs'), - } : null; - - const rollupFeature = config.features.rollup; - - const rollupInteropMessages = rollupFeature.isEnabled && rollupFeature.interopEnabled ? { - text: 'Interop messages', - nextRoute: { pathname: '/interop-messages' as const }, - icon: 'navigation/cross_chain_txs', - isActive: pathname === '/interop-messages', - } : null; - - if (rollupFeature.isEnabled && ( - rollupFeature.type === 'optimistic' || - rollupFeature.type === 'arbitrum' || - rollupFeature.type === 'scroll' - )) { - blockchainNavItems = [ - [ - txs, - internalTxs, - rollupDeposits, - rollupWithdrawals, - rollupInteropMessages, - ].filter(Boolean), - [ - blocks, - epochs, - // currently, transaction batches are not implemented for Celo - !config.features.celo.isEnabled ? rollupTxnBatches : undefined, - rollupDisputeGames, - rollupFeature.outputRootsEnabled ? rollupOutputRoots : undefined, - ].filter(Boolean), - [ - userOps, - topAccounts, - validators, - verifiedContracts, - nameLookup, - ].filter(Boolean), - ]; - } else if (rollupFeature.isEnabled && rollupFeature.type === 'shibarium') { - blockchainNavItems = [ - [ - txs, - internalTxs, - rollupDeposits, - rollupWithdrawals, - ].filter(Boolean), - [ - blocks, - userOps, - topAccounts, - verifiedContracts, - nameLookup, - ].filter(Boolean), - ]; - } else if (rollupFeature.isEnabled && rollupFeature.type === 'zkSync') { - blockchainNavItems = [ - [ - txs, - internalTxs, - userOps, - blocks, - rollupTxnBatches, - ].filter(Boolean), - [ - topAccounts, - validators, - verifiedContracts, - nameLookup, - ].filter(Boolean), - ]; - } else { - blockchainNavItems = [ - txs, - operations, - internalTxs, - cctxs, - userOps, - blocks, - epochs, - topAccounts, - validators, - verifiedContracts, - nameLookup, - beaconChainFeature.isEnabled && !beaconChainFeature.withdrawalsOnly && { - text: 'Deposits', - nextRoute: { pathname: '/deposits' as const }, - icon: 'navigation/deposits', - isActive: pathname === '/deposits', - }, - config.features.beaconChain.isEnabled && { - text: 'Withdrawals', - nextRoute: { pathname: '/withdrawals' as const }, - icon: 'navigation/withdrawals', - isActive: pathname === '/withdrawals', - }, - ].filter(Boolean); - } - - const tokensNavItems = [ - { - text: 'Tokens', - nextRoute: { pathname: '/tokens' as const }, - icon: 'navigation/tokens', - isActive: pathname === '/tokens' || pathname.startsWith('/token/'), - }, - { - text: 'Token transfers', - nextRoute: { pathname: '/token-transfers' as const }, - icon: 'navigation/token_transfers', - isActive: pathname === '/token-transfers', - }, - config.features.dexPools.isEnabled && { - text: 'DEX tracker', - nextRoute: { pathname: '/pools' as const }, - icon: 'navigation/dex_tracker', - isActive: pathname === '/pools' || pathname.startsWith('/pool/'), - }, - ].filter(Boolean); - - const statsNavItem: NavGroupItem | null = (() => { - const megaEthFeature = config.features.megaEth; - - const items = [ - config.features.stats.isEnabled && { - text: 'Chain stats', - nextRoute: { pathname: '/stats' as const }, - icon: 'navigation/chain_stats', - isActive: pathname.startsWith('/stats'), - }, - config.features.multichain.isEnabled && { - text: 'Ecosystems', - nextRoute: { pathname: '/ecosystems' as const }, - icon: 'navigation/ecosystems', - isActive: pathname.startsWith('/ecosystems'), - }, - megaEthFeature.isEnabled && megaEthFeature.socketUrl.metrics && { - text: 'Uptime', - nextRoute: { pathname: '/uptime' as const }, - icon: 'navigation/uptime', - isActive: pathname.startsWith('/uptime'), - }, - config.features.hotContracts.isEnabled && { - text: 'Hot contracts', - nextRoute: { pathname: '/hot-contracts' as const }, - icon: 'navigation/hot_contracts', - isActive: pathname.startsWith('/hot-contracts'), - }, - config.features.gasTracker.isEnabled && { - text: 'Gas tracker', - nextRoute: { pathname: '/gas-tracker' as const }, - icon: 'navigation/gas_tracker', - isActive: pathname.startsWith('/gas-tracker'), - }, - config.features.crossChainTxs.isEnabled && !config.features.multichain.isEnabled && { - text: 'ICTT users', - nextRoute: { pathname: '/ictt-users' as const }, - icon: 'navigation/ictt_users', - isActive: pathname.startsWith('/ictt-users'), - }, - ].filter(Boolean); - - if (items.length === 0) { - return null; - } - - return { - text: 'Charts & stats', - nextRoute: { pathname: '/stats' as const }, - icon: 'navigation/stats', - isActive: items.some(item => isInternalItem(item) && item.isActive), - subItems: items, - }; - })(); - - const apiNavItem: NavItem | null = (() => { - const feature = getFeaturePayload(config.features.apiDocs); - - if (!feature) { - return null; - } - - if (feature.mode === 'external') { - return { - text: 'API', - url: feature.url, - icon: 'navigation/api_docs', - }; - } - - return { - text: 'API', - nextRoute: { pathname: '/api-docs' as const }, - icon: 'navigation/api_docs', - isActive: pathname.startsWith('/api-docs'), - }; - })(); - - const otherNavItems: Array<NavItem> | Array<Array<NavItem>> = [ - config.features.multichain.isEnabled ? { - text: 'Verify contract', - url: 'https://vera.blockscout.com', - } : { - text: 'Verify contract', - nextRoute: { pathname: '/contract-verification' as const }, - isActive: pathname.startsWith('/contract-verification'), - }, - getFeaturePayload(config.features.addressMetadata)?.isTagSubmitionEnabled && { - text: 'Submit public tag', - nextRoute: { pathname: '/public-tags/submit' as const }, - isActive: pathname.startsWith('/public-tags/submit'), - }, - rollupFeature.isEnabled && rollupFeature.type === 'arbitrum' && { - text: 'Txn withdrawals', - nextRoute: { pathname: '/txn-withdrawals' as const }, - isActive: pathname.startsWith('/txn-withdrawals'), - }, - ...config.shell.navigation.otherLinks, - ].filter(Boolean); - - const mainNavItems: ReturnType['mainNavItems'] = [ - { - text: 'Blockchain', - icon: 'navigation/blockchain', - isActive: blockchainNavItems.flat().some(item => isInternalItem(item) && item.isActive), - subItems: blockchainNavItems, - }, - { - text: 'Tokens', - icon: 'navigation/tokens', - isActive: tokensNavItems.flat().some(item => isInternalItem(item) && item.isActive), - subItems: tokensNavItems, - }, - marketplaceFeature.isEnabled ? { - text: marketplaceFeature.titles.menu_item, - nextRoute: { pathname: '/apps' as const }, - icon: 'navigation/apps', - isActive: pathname.startsWith('/app') || pathname.startsWith('/essential-dapps'), - } : null, - statsNavItem, - apiNavItem, - { - text: 'Other', - icon: 'navigation/other', - isActive: otherNavItems.flat().some(item => isInternalItem(item) && item.isActive), - subItems: otherNavItems, - }, - ].filter(Boolean); - - const accountNavItems: ReturnType['accountNavItems'] = [ - { - text: 'Watch list', - nextRoute: { pathname: '/account/watchlist' as const }, - icon: 'navigation/watchlist', - isActive: pathname === '/account/watchlist', - }, - { - text: 'Private tags', - nextRoute: { pathname: '/account/tag-address' as const }, - icon: 'navigation/private_tags', - isActive: pathname === '/account/tag-address', - }, - { - text: 'API keys', - nextRoute: { pathname: '/account/api-key' as const }, - icon: 'navigation/api_keys', - isActive: pathname === '/account/api-key', - }, - { - text: 'Custom ABI', - nextRoute: { pathname: '/account/custom-abi' as const }, - icon: 'navigation/custom_abi', - isActive: pathname === '/account/custom-abi', - }, - getFeaturePayload(config.features.account)?.verifiedAddresses?.isEnabled && { - text: 'Verified addrs', - nextRoute: { pathname: '/account/verified-addresses' as const }, - icon: 'navigation/verified_contracts', - isActive: pathname === '/account/verified-addresses', - }, - ].filter(Boolean); - - return { mainNavItems, accountNavItems }; - }, [ pathname, tab ]); -} diff --git a/src/shell/navigation/useNavLinkStyleProps.tsx b/src/shell/navigation/useNavLinkStyleProps.ts similarity index 100% rename from src/shell/navigation/useNavLinkStyleProps.tsx rename to src/shell/navigation/useNavLinkStyleProps.ts diff --git a/src/shell/navigation/vertical/NavLink.tsx b/src/shell/navigation/vertical/NavLink.tsx index 8170ba378b9..8767f593a47 100644 --- a/src/shell/navigation/vertical/NavLink.tsx +++ b/src/shell/navigation/vertical/NavLink.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { HStack, Box, useBreakpointValue, chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { NavItem } from '../types'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; import { Link, LinkExternalIcon } from 'src/toolkit/chakra/link'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_hover-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_hover-dark-mode-1.png index 1aec9cf9a44..2d55b4123e8 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_hover-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_hover-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_no-auth-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_no-auth-dark-mode-1.png index 1aec9cf9a44..2d55b4123e8 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_no-auth-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_no-auth-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-highlighted-routes-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-highlighted-routes-dark-mode-1.png index 48fe80b354e..a9b7d743176 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-highlighted-routes-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-highlighted-routes-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png index c9e69f3e231..0d249c746e8 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_dark-color-mode_with-promo-banner-text-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_hover-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_hover-dark-mode-1.png index 25487a52ff7..403dea30677 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_hover-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_hover-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_hover-xl-screen-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_hover-xl-screen-dark-mode-1.png index 63710fcd44b..0727deae621 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_hover-xl-screen-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_hover-xl-screen-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_no-auth-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_no-auth-dark-mode-1.png index c6074004fd3..403dea30677 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_no-auth-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_no-auth-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_no-auth-xl-screen-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_no-auth-xl-screen-dark-mode-1.png index 63710fcd44b..0727deae621 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_no-auth-xl-screen-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_no-auth-xl-screen-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-dark-mode-1.png index d7996adb2ee..78eca4ccac8 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-with-submenu-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-with-submenu-1.png index 1b49e0c0086..4d3fe2c8e83 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-with-submenu-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-with-submenu-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-xl-screen-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-xl-screen-dark-mode-1.png index ca70401dbdb..07a5874a206 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-xl-screen-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-highlighted-routes-xl-screen-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-1.png index f13a43d114f..0825aeebb49 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-with-tooltip-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-with-tooltip-1.png index 256ef8fadab..6a241f982fc 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-with-tooltip-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-with-tooltip-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-xl-screen-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-xl-screen-1.png index e19c8d4f75b..0caea9ced87 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-xl-screen-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-image-xl-screen-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-dark-mode-1.png index 018ce37a1ed..1adb2c84c3a 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-with-tooltip-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-with-tooltip-1.png index 20c2f8f66e5..3dce8060676 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-with-tooltip-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-with-tooltip-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-xl-screen-dark-mode-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-xl-screen-dark-mode-1.png index cd480582bdf..038d81e497f 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-xl-screen-dark-mode-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-promo-banner-text-xl-screen-dark-mode-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-submenu-base-view-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-submenu-base-view-1.png index e3b0eb3a5fe..6b5df29d4e7 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-submenu-base-view-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-submenu-base-view-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-submenu-xl-screen-base-view-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-submenu-xl-screen-base-view-1.png index fa13f10cfe5..b94cb75bb94 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-submenu-xl-screen-base-view-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-submenu-xl-screen-base-view-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-tooltips-base-view-1.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-tooltips-base-view-1.png index 3b87f08fa3e..98ced87c9ec 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-tooltips-base-view-1.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-tooltips-base-view-1.png differ diff --git a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-tooltips-base-view-2.png b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-tooltips-base-view-2.png index eb5f0df5665..cc39ebf37a2 100644 Binary files a/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-tooltips-base-view-2.png and b/src/shell/navigation/vertical/__screenshots__/NavigationDesktop.pw.tsx_default_with-tooltips-base-view-2.png differ diff --git a/src/shell/page/actions-menu/ActionsMenu.pw.tsx b/src/shell/page/actions-menu/ActionsMenu.pw.tsx index cbaa980aa2b..3bb3a8e552f 100644 --- a/src/shell/page/actions-menu/ActionsMenu.pw.tsx +++ b/src/shell/page/actions-menu/ActionsMenu.pw.tsx @@ -2,27 +2,49 @@ import type { BrowserContext } from '@playwright/test'; import React from 'react'; import * as profileMock from 'src/features/account/mocks/user-profile'; +import * as verifiedAddressesMock from 'src/features/account/mocks/verified-addresses'; + +import config from 'src/config'; import { contextWithAuth } from 'playwright/fixtures/auth'; import { test as base, expect } from 'playwright/lib'; import ActionsMenu from './ActionsMenu'; +const HASH = '<hash>'; + const test = base.extend<{ context: BrowserContext }>({ context: contextWithAuth, }); +test.beforeEach(async({ mockApiResponse }) => { + await mockApiResponse('core:user_info', profileMock.base); +}); + test.describe('with multiple items', () => { const hooksConfig = { router: { - query: { hash: '<hash>' }, + query: { hash: HASH }, pathname: '/token/[hash]', - isReady: true, }, }; test.beforeEach(async({ mockApiResponse }) => { - mockApiResponse('core:user_info', profileMock.base); + await mockApiResponse( + 'contractInfo:verified_addresses', + verifiedAddressesMock.VERIFIED_ADDRESS_RESPONSE.DEFAULT, + { pathParams: { instanceId: config.apis.contractInfo?.instanceId } }, + ); + await mockApiResponse( + 'admin:token_info_applications', + verifiedAddressesMock.TOKEN_INFO_APPLICATIONS_RESPONSE.DEFAULT, + { pathParams: { instanceId: config.apis.admin?.instanceId, id: undefined } }, + ); + await mockApiResponse( + 'contractInfo:token_verified_info', + verifiedAddressesMock.TOKEN_INFO, + { pathParams: { instanceId: config.apis.contractInfo?.instanceId, hash: HASH } }, + ); }); test('base view', async({ render, page }) => { @@ -55,9 +77,8 @@ test.describe('with multiple items', () => { test.describe('with one item', () => { const hooksConfig = { router: { - query: { hash: '<hash>' }, + query: { hash: HASH }, pathname: '/tx/[hash]', - isReady: true, }, }; diff --git a/src/shell/page/actions-menu/ActionsMenu.tsx b/src/shell/page/actions-menu/ActionsMenu.tsx index 46c32759df4..772455cc782 100644 --- a/src/shell/page/actions-menu/ActionsMenu.tsx +++ b/src/shell/page/actions-menu/ActionsMenu.tsx @@ -1,15 +1,15 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, chakra } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { ItemProps } from './types'; import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { IconButton } from 'src/toolkit/chakra/icon-button'; @@ -36,7 +36,7 @@ const AccountActionsMenu = ({ isLoading, className, showUpdateMetadataItem }: Pr const isTxPage = router.pathname === '/tx/[hash]'; const handleButtonClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { Type: 'Address actions (more button)' }); + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Address actions (more button)' }); }, []); const items = [ diff --git a/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-base-view-1.png b/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-base-view-1.png index be51242c10d..0368fbc9d2d 100644 Binary files a/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-base-view-1.png and b/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-base-view-1.png differ diff --git a/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-base-view-with-styles-1.png b/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-base-view-with-styles-1.png index 5ab4cff8dfe..87a126417c8 100644 Binary files a/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-base-view-with-styles-1.png and b/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-base-view-with-styles-1.png differ diff --git a/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-loading-with-styles-1.png b/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-loading-with-styles-1.png index d2572c191cd..38949b6818e 100644 Binary files a/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-loading-with-styles-1.png and b/src/shell/page/actions-menu/__screenshots__/ActionsMenu.pw.tsx_default_with-multiple-items-loading-with-styles-1.png differ diff --git a/src/shell/page/actions-menu/items/PrivateTagMenuItem.tsx b/src/shell/page/actions-menu/items/PrivateTagMenuItem.tsx index a81dd176285..c81a6de1ed0 100644 --- a/src/shell/page/actions-menu/items/PrivateTagMenuItem.tsx +++ b/src/shell/page/actions-menu/items/PrivateTagMenuItem.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React from 'react'; import type { ItemProps } from '../types'; @@ -13,7 +12,8 @@ import AuthGuard from 'src/features/account/components/auth-modal/guard/AuthGuar import AddressModal from 'src/features/account/pages/private-tags/AddressModal/AddressModal'; import TransactionModal from 'src/features/account/pages/private-tags/TransactionModal/TransactionModal'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { MenuItem } from 'src/toolkit/chakra/menu'; @@ -48,7 +48,7 @@ const PrivateTagMenuItem = ({ hash, entityType = 'address', type }: Props) => { return null; } - const pageType = mixpanel.getPageType(router.pathname); + const pageType = analytics.getPageType(router.pathname); const modalProps = { open: modal.open, onOpenChange: modal.onOpenChange, diff --git a/src/shell/page/actions-menu/items/PublicTagMenuItem.tsx b/src/shell/page/actions-menu/items/PublicTagMenuItem.tsx index 7ba93a398e8..cbf8fe2cc5d 100644 --- a/src/shell/page/actions-menu/items/PublicTagMenuItem.tsx +++ b/src/shell/page/actions-menu/items/PublicTagMenuItem.tsx @@ -1,10 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { ItemProps } from '../types'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { MenuItem } from 'src/toolkit/chakra/menu'; diff --git a/src/shell/page/actions-menu/items/TokenInfoMenuItem.tsx b/src/shell/page/actions-menu/items/TokenInfoMenuItem.tsx index de2e64db90b..f7baefbb094 100644 --- a/src/shell/page/actions-menu/items/TokenInfoMenuItem.tsx +++ b/src/shell/page/actions-menu/items/TokenInfoMenuItem.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { ItemProps } from '../types'; @@ -13,7 +12,8 @@ import useIsAuth from 'src/features/account/hooks/useIsAuth'; import AddressVerificationModal from 'src/features/account/pages/verified-addresses/address-verification/AddressVerificationModal'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { MenuItem } from 'src/toolkit/chakra/menu'; @@ -106,7 +106,7 @@ const TokenInfoMenuItem = ({ hash, type }: ItemProps) => { { element } <AddressVerificationModal defaultAddress={ hash } - pageType={ mixpanel.getPageType('/token/[hash]') } + pageType={ analytics.getPageType('/token/[hash]') } open={ modal.open } onOpenChange={ modal.onOpenChange } onSubmit={ handleVerifiedAddressSubmit } diff --git a/src/shell/page/title/PageTitle.tsx b/src/shell/page/title/PageTitle.tsx index 2d9d5d3322a..15190703661 100644 --- a/src/shell/page/title/PageTitle.tsx +++ b/src/shell/page/title/PageTitle.tsx @@ -123,7 +123,7 @@ const PageTitle = ({ title, contentAfter, withTextAd, className, isLoading = fal { contentAfter } { withTextAd && <TextAd order={{ base: -1, lg: 100 }} mb={{ base: 6, lg: 0 }} ml="auto" w={{ base: '100%', lg: 'auto' }}/> } </Flex> - { secondRow && ( + { Boolean(secondRow) && ( <Skeleton loading={ isLoading } alignItems="center" minH={ 10 } overflow="hidden" display="flex" _empty={{ display: 'none' }} { ...secondRowProps }> { secondRow } </Skeleton> diff --git a/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_default-view-mobile-1.png b/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_default-view-mobile-1.png index 0bcfecc8fdc..50b3f7aa038 100644 Binary files a/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_default-view-mobile-1.png and b/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_default-view-mobile-1.png differ diff --git a/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_with-long-name-and-many-tags-mobile-1.png b/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_with-long-name-and-many-tags-mobile-1.png index 0ef2f10cbe7..b94f12e39a8 100644 Binary files a/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_with-long-name-and-many-tags-mobile-1.png and b/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_with-long-name-and-many-tags-mobile-1.png differ diff --git a/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_with-text-ad-mobile-1.png b/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_with-text-ad-mobile-1.png index ac26b8ad855..b48854b9760 100644 Binary files a/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_with-text-ad-mobile-1.png and b/src/shell/page/title/__screenshots__/PageTitle.pw.tsx_mobile_with-text-ad-mobile-1.png differ diff --git a/src/shell/top-bar/TopBar.pw.tsx b/src/shell/top-bar/TopBar.pw.tsx index 31d2732dbae..a4eab889f2d 100644 --- a/src/shell/top-bar/TopBar.pw.tsx +++ b/src/shell/top-bar/TopBar.pw.tsx @@ -6,6 +6,8 @@ import * as csvExportStorageMock from 'src/features/csv-export/mocks/storage'; import type { StorageItem } from 'src/features/csv-export/utils/storage'; import { STORAGE_KEY } from 'src/features/csv-export/utils/storage'; +import { SECOND } from 'src/toolkit/utils/consts'; + import { test, expect } from 'playwright/lib'; import TopBar from './TopBar'; @@ -31,15 +33,30 @@ test('default view +@dark-mode', async({ render, mockApiResponse, page, injectMe await component.getByLabel('User settings').click(); await expect(page).toHaveScreenshot({ clip: { x: 0, y: 0, width: 1500, height: 450 } }); + + await page.getByText('Advanced settings').click(); + await expect(page.getByRole('dialog')).toBeVisible(); + await expect(page).toHaveScreenshot(); + + await page.getByRole('tab', { name: 'Custom RPC' }).click(); + await expect(page).toHaveScreenshot(); }); test('default view +@mobile -@default', async({ render, mockApiResponse, page, injectMetaMaskProvider }) => { + test.slow(); await mockApiResponse('core:stats', statsMock.base); await injectMetaMaskProvider(); const component = await render(<TopBar/>); await component.getByLabel('User settings').click(); - await expect(page).toHaveScreenshot({ clip: { x: 0, y: 0, width: 1500, height: 450 } }); + await expect(page).toHaveScreenshot({ clip: { x: 0, y: 0, width: 1500, height: 450 }, timeout: 10 * SECOND }); + + await page.getByText('Advanced settings').click(); + await expect(page.getByRole('dialog')).toBeVisible(); + await expect(page).toHaveScreenshot({ timeout: 10 * SECOND }); + + await page.getByRole('tab', { name: 'Custom RPC' }).click(); + await expect(page).toHaveScreenshot({ timeout: 10 * SECOND }); }); test('with secondary coin price +@mobile', async({ render, mockApiResponse }) => { diff --git a/src/shell/top-bar/TopBar.tsx b/src/shell/top-bar/TopBar.tsx index 8f016edd12f..50357893039 100644 --- a/src/shell/top-bar/TopBar.tsx +++ b/src/shell/top-bar/TopBar.tsx @@ -17,6 +17,7 @@ import * as cookies from 'src/shared/storage/cookies'; import NetworkMenu from './chain-menu/ChainMenu'; import Settings from './settings/Settings'; +import TopBarCustomRpc from './TopBarCustomRpc'; import TopBarStats from './TopBarStats'; const TopBar = () => { @@ -68,6 +69,7 @@ const TopBar = () => { </HStack> ) } <HStack gap={ 0 }> + <TopBarCustomRpc/> <CsvExportDownloads/> <Settings/> </HStack> diff --git a/src/shell/top-bar/TopBarCustomRpc.tsx b/src/shell/top-bar/TopBarCustomRpc.tsx new file mode 100644 index 00000000000..7b216a7fa2a --- /dev/null +++ b/src/shell/top-bar/TopBarCustomRpc.tsx @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Flex, Separator } from '@chakra-ui/react'; +import React from 'react'; + +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { IconButton } from 'src/toolkit/chakra/icon-button'; +import { Tooltip } from 'src/toolkit/chakra/tooltip'; + +import { useCustomRpcNodeStatus } from './settings/fields/rpc-node/useCustomRpcNodeStatus'; +import { useSettingsModalContext } from './settings/modal/context'; + +const TopBarCustomRpc = () => { + const customRpc = useCustomRpcNodeStatus(); + const settingsModal = useSettingsModalContext(); + + const handleClick = React.useCallback(() => { + settingsModal?.open('rpc-node'); + }, [ settingsModal ]); + + if (!customRpc) { + return null; + } + + const { status, isPending } = customRpc; + const tooltipContent = ( + <> + <div>Custom RPC: { status.tag.label }</div> + { status.alert?.text && <div>{ status.alert?.text }</div> } + </> + ); + + return ( + <Flex alignItems="center"> + <Tooltip content={ tooltipContent } disabled={ isPending }> + <IconButton + aria-label="Custom RPC node" + variant="link" + size="2xs" + borderRadius="none" + color={ isPending ? 'icon.secondary' : status.plug.color } + _hover={{ color: isPending ? 'icon.secondary' : status.plug.color, opacity: 0.8 }} + onClick={ handleClick } + > + <SpriteIcon name={ status.plug.icon }/> + </IconButton> + </Tooltip> + <Separator orientation="vertical" mx={ 2 } h={ 4 }/> + </Flex> + ); +}; + +export default React.memo(TopBarCustomRpc); diff --git a/src/shell/top-bar/TopBarStats.tsx b/src/shell/top-bar/TopBarStats.tsx index 726a1167549..edb1b8ac315 100644 --- a/src/shell/top-bar/TopBarStats.tsx +++ b/src/shell/top-bar/TopBarStats.tsx @@ -66,7 +66,7 @@ const TopBarStats = () => { <chakra.span color="text.secondary">{ config.chain.currency.symbol } </chakra.span> <span>${ Number(data.coin_price).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 6 }) }</span> </Skeleton> - { data.coin_price_change_percentage && !(isMobile && Boolean(config.shell.topBar.chainMenu.items)) && ( + { data.coin_price_change_percentage !== null && !(isMobile && Boolean(config.shell.topBar.chainMenu.items)) && ( <Skeleton loading={ isPlaceholderData }> <chakra.span color={ Number(data.coin_price_change_percentage) >= 0 ? 'green.500' : 'red.500' }> { Number(data.coin_price_change_percentage).toFixed(2) }% diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_dark-color-mode_default-view-dark-mode-2.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_dark-color-mode_default-view-dark-mode-2.png index f8622ba8a0c..81ec32c69f7 100644 Binary files a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_dark-color-mode_default-view-dark-mode-2.png and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_dark-color-mode_default-view-dark-mode-2.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_dark-color-mode_default-view-dark-mode-3.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_dark-color-mode_default-view-dark-mode-3.png new file mode 100644 index 00000000000..edd227e70e4 Binary files /dev/null and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_dark-color-mode_default-view-dark-mode-3.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_dark-color-mode_default-view-dark-mode-4.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_dark-color-mode_default-view-dark-mode-4.png new file mode 100644 index 00000000000..8b7c3fe57d3 Binary files /dev/null and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_dark-color-mode_default-view-dark-mode-4.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-1.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-1.png index 5ed32e64b3f..77f364f4b31 100644 Binary files a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-1.png and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-1.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-2.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-2.png index 851ede0db7e..c4d2bdb6c0e 100644 Binary files a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-2.png and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-2.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-3.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-3.png new file mode 100644 index 00000000000..3853eb1c678 Binary files /dev/null and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-3.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-4.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-4.png new file mode 100644 index 00000000000..563dc55b58c Binary files /dev/null and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_default-view-dark-mode-4.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-DeFi-dropdown-dark-mode-mobile-1.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-DeFi-dropdown-dark-mode-mobile-1.png index 02651329bdc..b1159c3e428 100644 Binary files a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-DeFi-dropdown-dark-mode-mobile-1.png and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-DeFi-dropdown-dark-mode-mobile-1.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-Get-gas-button-1.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-Get-gas-button-1.png index 9cd58b91e8b..cefb7d639dd 100644 Binary files a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-Get-gas-button-1.png and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-Get-gas-button-1.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-csv-downloads-1.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-csv-downloads-1.png index 821d859d5d9..30709d256e3 100644 Binary files a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-csv-downloads-1.png and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-csv-downloads-1.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-secondary-coin-price-mobile-1.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-secondary-coin-price-mobile-1.png index c17f5d9c8dd..30842d7b709 100644 Binary files a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-secondary-coin-price-mobile-1.png and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_default_with-secondary-coin-price-mobile-1.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_default-view-mobile---default-1.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_default-view-mobile---default-1.png index 4b9d6914041..59344bb6f74 100644 Binary files a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_default-view-mobile---default-1.png and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_default-view-mobile---default-1.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_default-view-mobile---default-2.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_default-view-mobile---default-2.png new file mode 100644 index 00000000000..6af014e65ad Binary files /dev/null and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_default-view-mobile---default-2.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_default-view-mobile---default-3.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_default-view-mobile---default-3.png new file mode 100644 index 00000000000..58fd05899cc Binary files /dev/null and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_default-view-mobile---default-3.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_with-DeFi-dropdown-dark-mode-mobile-1.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_with-DeFi-dropdown-dark-mode-mobile-1.png index 3bc0f355af7..6891638b44d 100644 Binary files a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_with-DeFi-dropdown-dark-mode-mobile-1.png and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_with-DeFi-dropdown-dark-mode-mobile-1.png differ diff --git a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_with-secondary-coin-price-mobile-1.png b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_with-secondary-coin-price-mobile-1.png index 1863a8c66c3..52f82cb86ef 100644 Binary files a/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_with-secondary-coin-price-mobile-1.png and b/src/shell/top-bar/__screenshots__/TopBar.pw.tsx_mobile_with-secondary-coin-price-mobile-1.png differ diff --git a/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_dark-color-mode_tabs-dark-mode-1.png b/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_dark-color-mode_tabs-dark-mode-1.png index 653ef3e6303..fcb248c9ccc 100644 Binary files a/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_dark-color-mode_tabs-dark-mode-1.png and b/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_dark-color-mode_tabs-dark-mode-1.png differ diff --git a/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_dark-color-mode_tabs-dark-mode-2.png b/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_dark-color-mode_tabs-dark-mode-2.png index f2b67867e14..444c9f695ae 100644 Binary files a/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_dark-color-mode_tabs-dark-mode-2.png and b/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_dark-color-mode_tabs-dark-mode-2.png differ diff --git a/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_default_tabs-dark-mode-1.png b/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_default_tabs-dark-mode-1.png index b45c64a7b74..0862d5e43be 100644 Binary files a/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_default_tabs-dark-mode-1.png and b/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_default_tabs-dark-mode-1.png differ diff --git a/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_default_tabs-dark-mode-2.png b/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_default_tabs-dark-mode-2.png index 108cd501176..8ca6a6672ce 100644 Binary files a/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_default_tabs-dark-mode-2.png and b/src/shell/top-bar/chain-menu/__screenshots__/ChainMenu.pw.tsx_default_tabs-dark-mode-2.png differ diff --git a/src/shell/top-bar/chain-menu/useChainMenu.ts b/src/shell/top-bar/chain-menu/useChainMenu.ts new file mode 100644 index 00000000000..0461636c4bc --- /dev/null +++ b/src/shell/top-bar/chain-menu/useChainMenu.ts @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { useQuery } from '@tanstack/react-query'; +import React from 'react'; + +import type { FeaturedNetwork } from './types'; +import { NETWORK_GROUPS } from './types'; + +import useFetch from 'src/api/hooks/useFetch'; +import type { ResourceError } from 'src/api/resources'; + +import multichainConfig from 'src/features/multichain/chains-config'; + +import config from 'src/config'; +import * as analytics from 'src/shared/analytics'; + +import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; + +export default function useChainMenu() { + const { open, onClose, onOpen, onOpenChange, onToggle } = useDisclosure(); + + const fetch = useFetch(); + const { isPending, data } = useQuery<unknown, ResourceError<unknown>, Array<FeaturedNetwork>>({ + queryKey: [ 'featured-network' ], + queryFn: async() => { + const configData: Array<FeaturedNetwork> = await (async() => { + try { + if (config.shell.topBar.chainMenu.items) { + const data = await fetch<Array<FeaturedNetwork>, unknown>(config.shell.topBar.chainMenu.items, undefined, { resource: 'featured-network' }); + if (Array.isArray(data)) { + return data; + } + } + } catch (error) {} + return []; + })(); + + const multichainData: Array<FeaturedNetwork> = (() => { + if (config.features.multichain.isEnabled) { + return multichainConfig()?.chains + .filter((chain) => chain?.explorer_url) + .filter((chain) => !configData.some((configNetwork) => configNetwork.url.includes(chain.explorer_url ?? ''))) + .map((chain) => ({ + title: chain.name, + url: chain.explorer_url ?? '', + group: chain.app_config.chain.isTestnet ? 'Testnets' : 'Mainnets', + icon: chain.logo, + invertIconInDarkMode: false, + })) ?? []; + } + return []; + })(); + + return [ ...configData, ...multichainData ]; + }, + enabled: Boolean(config.shell.topBar.chainMenu.items || config.features.multichain.isEnabled) && open, + staleTime: Infinity, + }); + + const handleOpenChange = React.useCallback((details: { open: boolean }) => { + if (details.open) { + analytics.logEvent(analytics.EventTypes.BUTTON_CLICK, { Content: 'Network menu', Source: 'Header' }); + } + onOpenChange(details); + }, [ onOpenChange ]); + + return React.useMemo(() => ({ + open, + onClose, + onOpen, + onToggle, + onOpenChange: handleOpenChange, + isPending, + data, + availableTabs: NETWORK_GROUPS.filter((tab) => data?.some(({ group }) => group === tab)), + }), [ open, onClose, onOpen, onToggle, handleOpenChange, data, isPending ]); +} diff --git a/src/shell/top-bar/chain-menu/useChainMenu.tsx b/src/shell/top-bar/chain-menu/useChainMenu.tsx deleted file mode 100644 index 7cc0c689671..00000000000 --- a/src/shell/top-bar/chain-menu/useChainMenu.tsx +++ /dev/null @@ -1,77 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useQuery } from '@tanstack/react-query'; -import React from 'react'; - -import type { FeaturedNetwork } from './types'; -import { NETWORK_GROUPS } from './types'; - -import useFetch from 'src/api/hooks/useFetch'; -import type { ResourceError } from 'src/api/resources'; - -import multichainConfig from 'src/features/multichain/chains-config'; - -import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; - -import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; - -export default function useChainMenu() { - const { open, onClose, onOpen, onOpenChange, onToggle } = useDisclosure(); - - const fetch = useFetch(); - const { isPending, data } = useQuery<unknown, ResourceError<unknown>, Array<FeaturedNetwork>>({ - queryKey: [ 'featured-network' ], - queryFn: async() => { - const configData: Array<FeaturedNetwork> = await (async() => { - try { - if (config.shell.topBar.chainMenu.items) { - const data = await fetch<Array<FeaturedNetwork>, unknown>(config.shell.topBar.chainMenu.items, undefined, { resource: 'featured-network' }); - if (Array.isArray(data)) { - return data; - } - } - } catch (error) {} - return []; - })(); - - const multichainData: Array<FeaturedNetwork> = (() => { - if (config.features.multichain.isEnabled) { - return multichainConfig()?.chains - .filter((chain) => chain?.explorer_url) - .filter((chain) => !configData.some((configNetwork) => configNetwork.url.includes(chain.explorer_url ?? ''))) - .map((chain) => ({ - title: chain.name, - url: chain.explorer_url ?? '', - group: chain.app_config.chain.isTestnet ? 'Testnets' : 'Mainnets', - icon: chain.logo, - invertIconInDarkMode: false, - })) ?? []; - } - return []; - })(); - - return [ ...configData, ...multichainData ]; - }, - enabled: Boolean(config.shell.topBar.chainMenu.items || config.features.multichain.isEnabled) && open, - staleTime: Infinity, - }); - - const handleOpenChange = React.useCallback((details: { open: boolean }) => { - if (details.open) { - mixpanel.logEvent(mixpanel.EventTypes.BUTTON_CLICK, { Content: 'Network menu', Source: 'Header' }); - } - onOpenChange(details); - }, [ onOpenChange ]); - - return React.useMemo(() => ({ - open, - onClose, - onOpen, - onToggle, - onOpenChange: handleOpenChange, - isPending, - data, - availableTabs: NETWORK_GROUPS.filter((tab) => data?.some(({ group }) => group === tab)), - }), [ open, onClose, onOpen, onToggle, handleOpenChange, data, isPending ]); -} diff --git a/src/shell/top-bar/config.spec.ts b/src/shell/top-bar/config.spec.ts index 6c5fc64f94e..54b468c30b7 100644 --- a/src/shell/top-bar/config.spec.ts +++ b/src/shell/top-bar/config.spec.ts @@ -4,7 +4,11 @@ import { describe, expect, it } from 'vitest'; import withEnvs from 'vitest/utils/mockEnvs'; import type topBarConfig from './config'; +<<<<<<< HEAD import { COLOR_THEMES } from './settings/color-theme/config'; +======= +import { COLOR_THEMES } from './settings/fields/color-theme/config'; +>>>>>>> v2.13.0 async function loadConfig(envs: Array<[ string, string ]>): Promise<typeof topBarConfig> { return withEnvs(envs, async() => (await import('./config')).default); @@ -17,11 +21,37 @@ function getThemeIds(config: typeof topBarConfig): Array<string> { const ALL_THEME_IDS = COLOR_THEMES.map((theme) => theme.id); describe('color themes', () => { +<<<<<<< HEAD it('offers every theme when NEXT_PUBLIC_COLOR_THEMES is not set', async() => { const config = await loadConfig([]); expect(getThemeIds(config)).toEqual(ALL_THEME_IDS); expect(config.colorTheme.default).toBeUndefined(); +======= + it('offers every theme, the system one included, when NEXT_PUBLIC_COLOR_THEMES is not set', async() => { + const config = await loadConfig([]); + + expect(getThemeIds(config)).toEqual(ALL_THEME_IDS); + expect(config.colorTheme.default?.id).toBe('system'); + }); + + it('offers the system theme only when it is listed next to a light and a dark theme', async() => { + const config = await loadConfig([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","dark","system"]' ] ]); + + expect(getThemeIds(config)).toEqual([ 'light', 'dark', 'system' ]); + }); + + it('hides the system theme when the listed themes are all of one color mode', async() => { + const config = await loadConfig([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["dim","dark","system"]' ] ]); + + expect(getThemeIds(config)).toEqual([ 'dim', 'dark' ]); + }); + + it('offers every theme when the system theme is the only one listed', async() => { + const config = await loadConfig([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["system"]' ] ]); + + expect(getThemeIds(config)).toEqual(ALL_THEME_IDS); +>>>>>>> v2.13.0 }); it('offers only the configured themes', async() => { @@ -46,7 +76,11 @@ describe('color themes', () => { const config = await loadConfig([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["sepia"]' ] ]); expect(getThemeIds(config)).toEqual(ALL_THEME_IDS); +<<<<<<< HEAD expect(config.colorTheme.default).toBeUndefined(); +======= + expect(config.colorTheme.default?.id).toBe('system'); +>>>>>>> v2.13.0 }); }); @@ -87,16 +121,42 @@ describe('default color theme', () => { expect(config.colorTheme.default?.id).toBe('midnight'); }); +<<<<<<< HEAD it('stays undefined when the available themes cover both color modes', async() => { +======= + it('is the system theme when the configured default is system', async() => { + const config = await loadConfig([ + [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","dark","system"]' ], + [ 'NEXT_PUBLIC_COLOR_THEME_DEFAULT', 'system' ], + ]); + + expect(config.colorTheme.default?.id).toBe('system'); + }); + + it('is the system theme when the available themes cover both color modes and no default is configured', async() => { + const config = await loadConfig([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","dark","system"]' ] ]); + + expect(config.colorTheme.default?.id).toBe('system'); + }); + + it('stays undefined when the available themes cover both color modes but leave the system theme out', async() => { +>>>>>>> v2.13.0 const config = await loadConfig([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","dark"]' ] ]); expect(config.colorTheme.default).toBeUndefined(); }); +<<<<<<< HEAD it('stays undefined when every theme is listed explicitly', async() => { const config = await loadConfig([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","dim","midnight","dark"]' ] ]); expect(getThemeIds(config)).toEqual(ALL_THEME_IDS); +======= + it('stays undefined when every concrete theme is listed explicitly', async() => { + const config = await loadConfig([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","dim","midnight","dark"]' ] ]); + + expect(getThemeIds(config)).toEqual([ 'light', 'dim', 'midnight', 'dark' ]); +>>>>>>> v2.13.0 expect(config.colorTheme.default).toBeUndefined(); }); }); diff --git a/src/shell/top-bar/config.ts b/src/shell/top-bar/config.ts index beb1b6e3263..e7e55dcc250 100644 --- a/src/shell/top-bar/config.ts +++ b/src/shell/top-bar/config.ts @@ -1,28 +1,53 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { COLOR_THEMES, type ColorTheme, type ColorThemeId } from 'src/shell/top-bar/settings/color-theme/config'; +import { + COLOR_THEMES, + coversBothColorModes, + isConcreteColorTheme, + isSystemColorTheme, + type ColorThemeId, +} from 'src/shell/top-bar/settings/fields/color-theme/config'; import { getExternalAssetFilePath, getEnvValue, parseEnvJson } from 'src/config/utils/envs'; const availableColorThemes = (() => { const envValue = parseEnvJson<Array<ColorThemeId>>(getEnvValue('NEXT_PUBLIC_COLOR_THEMES')); +<<<<<<< HEAD const themes = Array.isArray(envValue) ? COLOR_THEMES.filter((theme) => envValue.includes(theme.id)) : []; return themes.length > 0 ? themes : COLOR_THEMES; +======= + const listedThemes = Array.isArray(envValue) ? COLOR_THEMES.filter((theme) => envValue.includes(theme.id)) : []; + const themes = listedThemes.some(isConcreteColorTheme) ? listedThemes : COLOR_THEMES; + + return coversBothColorModes(themes) ? themes : themes.filter(isConcreteColorTheme); +>>>>>>> v2.13.0 })(); const defaultColorTheme = (() => { const envValue = getEnvValue('NEXT_PUBLIC_COLOR_THEME_DEFAULT') as ColorThemeId | undefined; +<<<<<<< HEAD const theme = availableColorThemes.find((theme) => theme.id === envValue) as ColorTheme | undefined; +======= + const theme = availableColorThemes.find((theme) => theme.id === envValue); +>>>>>>> v2.13.0 if (theme) { return theme; } +<<<<<<< HEAD const coversBothColorModes = availableColorThemes.some((theme) => theme.colorMode === 'light') && availableColorThemes.some((theme) => theme.colorMode === 'dark'); return coversBothColorModes ? undefined : availableColorThemes.slice(-1)[0]; +======= + if (coversBothColorModes(availableColorThemes)) { + return availableColorThemes.find(isSystemColorTheme); + } + + return availableColorThemes.slice(-1)[0]; +>>>>>>> v2.13.0 })(); const config = Object.freeze({ diff --git a/src/shell/top-bar/settings/Settings.tsx b/src/shell/top-bar/settings/Settings.tsx index a5ab65f1cf8..c301dc6d834 100644 --- a/src/shell/top-bar/settings/Settings.tsx +++ b/src/shell/top-bar/settings/Settings.tsx @@ -6,20 +6,19 @@ import React from 'react'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { IconButton } from 'src/toolkit/chakra/icon-button'; +import { Link } from 'src/toolkit/chakra/link'; import { PopoverBody, PopoverContent, PopoverRoot, PopoverTrigger } from 'src/toolkit/chakra/popover'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; import { useDisclosure } from 'src/toolkit/hooks/useDisclosure'; -import SettingsColorTheme from './color-theme/SettingsColorTheme'; -import SettingsIdentIcon from './ident-icon/SettingsIdentIcon'; -import SettingsAddressFormat from './SettingsAddressFormat'; -import SettingsPoorReputationTokens from './SettingsPoorReputationTokens'; -import SettingsScamTokens from './SettingsScamTokens'; -import SettingsLocalTime from './time-format/SettingsLocalTime'; +import SettingsColorTheme from './fields/color-theme/SettingsColorTheme'; +import SettingsIdentIcon from './fields/ident-icon/SettingsIdentIcon'; +import { useSettingsModalContext } from './modal/context'; const Settings = () => { const popover = useDisclosure(); const tooltip = useDisclosure(); + const settingsModal = useSettingsModalContext(); const handlePopoverOpenChange = React.useCallback(({ open }: { open: boolean }) => { open && tooltip.onClose(); @@ -32,6 +31,11 @@ const Settings = () => { } }, [ popover, tooltip ]); + const handleAdvancedSettingsClick = React.useCallback(() => { + popover.onClose(); + settingsModal?.open(); + }, [ popover, settingsModal ]); + return ( <PopoverRoot positioning={{ placement: 'bottom-end' }} @@ -66,6 +70,7 @@ const Settings = () => { </Tooltip> <PopoverContent overflowY="hidden" w="auto" fontSize="sm"> <PopoverBody> +<<<<<<< HEAD <SettingsColorTheme onSelect={ popover.onClose }/> <SettingsIdentIcon/> <SettingsAddressFormat/> @@ -74,6 +79,22 @@ const Settings = () => { <SettingsScamTokens/> <SettingsPoorReputationTokens/> <SettingsLocalTime/> +======= + <VStack gap={ 3 } alignItems="stretch" separator={ <Separator my={ 3 }/> }> + <SettingsColorTheme onSelect={ popover.onClose }/> + <SettingsIdentIcon/> + <Link + display="flex" + alignItems="center" + gap={ 2 } + minH="32px" + textStyle="sm" + onClick={ handleAdvancedSettingsClick } + > + <SpriteIcon name="gear" boxSize={ 5 }/> + Advanced settings + </Link> +>>>>>>> v2.13.0 </VStack> </PopoverBody> </PopoverContent> diff --git a/src/shell/top-bar/settings/SettingsAddressFormat.tsx b/src/shell/top-bar/settings/SettingsAddressFormat.tsx deleted file mode 100644 index 97c0d987611..00000000000 --- a/src/shell/top-bar/settings/SettingsAddressFormat.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import { BECH_32_SEPARATOR } from 'src/slices/address/utils/bech32'; - -import config from 'src/config'; - -import { Switch } from 'src/toolkit/chakra/switch'; - -import { useSettingsContext } from './context'; - -const SettingsAddressFormat = () => { - const settingsContext = useSettingsContext(); - - if (!settingsContext || config.slices.address.hashFormat.availableFormats.length < 2) { - return null; - } - - const { addressFormat, toggleAddressFormat } = settingsContext; - - return ( - <Switch - id="address-format" - defaultChecked={ addressFormat === 'bech32' } - onChange={ toggleAddressFormat } - mt={ 4 } - direction="rtl" - justifyContent="space-between" - w="100%" - > - Show { config.slices.address.hashFormat.bech32Prefix }{ BECH_32_SEPARATOR } format - </Switch> - ); -}; - -export default React.memo(SettingsAddressFormat); diff --git a/src/shell/top-bar/settings/color-theme/config.ts b/src/shell/top-bar/settings/color-theme/config.ts deleted file mode 100644 index d53fd990ebb..00000000000 --- a/src/shell/top-bar/settings/color-theme/config.ts +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { ColorMode } from 'src/toolkit/chakra/color-mode'; - -export const COLOR_THEME_IDS = [ 'light', 'dim', 'midnight', 'dark' ] as const; -export type ColorThemeId = typeof COLOR_THEME_IDS[number]; - -export interface ColorTheme { - id: ColorThemeId; - label: string; - colorMode: ColorMode; - hex: string; - sampleBg: string; -} - -export const COLOR_THEMES: Array<ColorTheme> = [ - { - id: 'light', - label: 'Light', - colorMode: 'light', - hex: '#FFFFFF', - sampleBg: 'linear-gradient(154deg, #EFEFEF 50%, rgba(255, 255, 255, 0.00) 330.86%)', - }, - { - id: 'dim', - label: 'Dim', - colorMode: 'dark', - hex: '#232B37', - sampleBg: 'linear-gradient(152deg, #232B37 50%, rgba(255, 255, 255, 0.00) 290.71%)', - }, - { - id: 'midnight', - label: 'Midnight', - colorMode: 'dark', - hex: '#1B2E48', - sampleBg: 'linear-gradient(148deg, #1B3F71 50%, rgba(255, 255, 255, 0.00) 312.35%)', - }, - { - id: 'dark', - label: 'Dark', - colorMode: 'dark', - hex: '#101112', - sampleBg: 'linear-gradient(161deg, #000 9.37%, #383838 92.52%)', - }, -]; diff --git a/src/shell/top-bar/settings/context.tsx b/src/shell/top-bar/settings/context.tsx index 0a5007ec4da..3020b2858ee 100644 --- a/src/shell/top-bar/settings/context.tsx +++ b/src/shell/top-bar/settings/context.tsx @@ -8,7 +8,8 @@ import { useAppContext } from 'src/shell/app/context'; import * as cookies from 'src/shared/storage/cookies'; -import type { TimeFormat } from './time-format/utils'; +import type { ColorThemeId } from './fields/color-theme/config'; +import type { TimeFormat } from './fields/time-format/utils'; interface SettingsProviderProps { children: React.ReactNode; @@ -21,6 +22,8 @@ interface TSettingsContext { toggleTimeFormat: () => void; isLocalTime: boolean; toggleIsLocalTime: () => void; + colorTheme: ColorThemeId | undefined; + setColorTheme: (value: ColorThemeId) => void; } export const SettingsContext = React.createContext<TSettingsContext | null>(null); @@ -41,29 +44,25 @@ export function SettingsContextProvider({ children }: SettingsProviderProps) { (cookies.get(cookies.NAMES.LOCAL_TIME, appCookies) ?? 'true') === 'true', ); + const [ colorTheme, setColorTheme ] = React.useState<ColorThemeId>(); + const toggleAddressFormat = React.useCallback(() => { - setAddressFormat(prev => { - const nextValue = prev === 'base16' ? 'bech32' : 'base16'; - cookies.set(cookies.NAMES.ADDRESS_FORMAT, nextValue); - return nextValue; - }); - }, []); + const nextValue = addressFormat === 'base16' ? 'bech32' : 'base16'; + cookies.set(cookies.NAMES.ADDRESS_FORMAT, nextValue); + setAddressFormat(nextValue); + }, [ addressFormat ]); const toggleTimeFormat = React.useCallback(() => { - setTimeFormat(prev => { - const nextValue = prev === 'relative' ? 'absolute' : 'relative'; - cookies.set(cookies.NAMES.TIME_FORMAT, nextValue); - return nextValue; - }); - }, []); + const nextValue = timeFormat === 'relative' ? 'absolute' : 'relative'; + cookies.set(cookies.NAMES.TIME_FORMAT, nextValue); + setTimeFormat(nextValue); + }, [ timeFormat ]); const toggleIsLocalTime = React.useCallback(() => { - setIsLocalTime(prev => { - const nextValue = !prev; - cookies.set(cookies.NAMES.LOCAL_TIME, nextValue ? 'true' : 'false'); - return nextValue; - }); - }, []); + const nextValue = !isLocalTime; + cookies.set(cookies.NAMES.LOCAL_TIME, nextValue ? 'true' : 'false'); + setIsLocalTime(nextValue); + }, [ isLocalTime ]); const value = React.useMemo(() => { return { @@ -73,8 +72,10 @@ export function SettingsContextProvider({ children }: SettingsProviderProps) { toggleTimeFormat, isLocalTime, toggleIsLocalTime, + colorTheme, + setColorTheme, }; - }, [ addressFormat, toggleAddressFormat, timeFormat, toggleTimeFormat, isLocalTime, toggleIsLocalTime ]); + }, [ addressFormat, toggleAddressFormat, timeFormat, toggleTimeFormat, isLocalTime, toggleIsLocalTime, colorTheme ]); return ( <SettingsContext.Provider value={ value }> diff --git a/src/shell/top-bar/settings/fields/SettingsAddressFormat.tsx b/src/shell/top-bar/settings/fields/SettingsAddressFormat.tsx new file mode 100644 index 00000000000..c128ad74f4f --- /dev/null +++ b/src/shell/top-bar/settings/fields/SettingsAddressFormat.tsx @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { SettingsControlVariant } from '../types'; + +import { BECH_32_SEPARATOR } from 'src/slices/address/utils/bech32'; + +import config from 'src/config'; + +import type { SwitchProps } from 'src/toolkit/chakra/switch'; +import { Switch } from 'src/toolkit/chakra/switch'; + +import { useSettingsContext } from '../context'; +import SettingsSectionTitle from '../parts/SettingsSectionTitle'; + +interface Props extends Omit<SwitchProps, 'variant'> { + variant: SettingsControlVariant; +} + +const SettingsAddressFormat = ({ variant, ...rest }: Props) => { + const settingsContext = useSettingsContext(); + + if (!settingsContext || config.slices.address.hashFormat.availableFormats.length < 2) { + return null; + } + + const { addressFormat, toggleAddressFormat } = settingsContext; + + return ( + <div> + { variant === 'popover' && <SettingsSectionTitle variant={ variant } title="Address format"/> } + <Switch + id="address-format" + defaultChecked={ addressFormat === 'bech32' } + onChange={ toggleAddressFormat } + direction="rtl" + justifyContent="space-between" + w="100%" + minH="32px" + { ...rest } + > + Show { config.slices.address.hashFormat.bech32Prefix }{ BECH_32_SEPARATOR } format + </Switch> + </div> + ); +}; + +export default React.memo(SettingsAddressFormat); diff --git a/src/shell/top-bar/settings/SettingsPoorReputationTokens.tsx b/src/shell/top-bar/settings/fields/SettingsPoorReputationTokens.tsx similarity index 98% rename from src/shell/top-bar/settings/SettingsPoorReputationTokens.tsx rename to src/shell/top-bar/settings/fields/SettingsPoorReputationTokens.tsx index be5caa3ae94..9c0f8d02e54 100644 --- a/src/shell/top-bar/settings/SettingsPoorReputationTokens.tsx +++ b/src/shell/top-bar/settings/fields/SettingsPoorReputationTokens.tsx @@ -35,7 +35,7 @@ const SettingsPoorReputationTokens = () => { direction="rtl" justifyContent="space-between" w="100%" - minH="34px" + minH="32px" > Hide poor reputation tokens </Switch> diff --git a/src/shell/top-bar/settings/SettingsScamTokens.tsx b/src/shell/top-bar/settings/fields/SettingsScamTokens.tsx similarity index 82% rename from src/shell/top-bar/settings/SettingsScamTokens.tsx rename to src/shell/top-bar/settings/fields/SettingsScamTokens.tsx index 242fe97435b..ceb77362f1f 100644 --- a/src/shell/top-bar/settings/SettingsScamTokens.tsx +++ b/src/shell/top-bar/settings/fields/SettingsScamTokens.tsx @@ -17,13 +17,11 @@ const SettingsScamTokens = () => { const [ isChecked, setIsChecked ] = React.useState(initialValue !== 'true'); const handleChange = React.useCallback(() => { - setIsChecked(prev => { - const nextValue = !prev; - cookies.set(cookies.NAMES.SHOW_SCAM_TOKENS, nextValue ? 'false' : 'true'); - return nextValue; - }); + const nextValue = !isChecked; + cookies.set(cookies.NAMES.SHOW_SCAM_TOKENS, nextValue ? 'false' : 'true'); + setIsChecked(nextValue); window.location.reload(); - }, []); + }, [ isChecked ]); if (!config.slices.token.hideScamTokensEnabled) { return null; @@ -37,7 +35,7 @@ const SettingsScamTokens = () => { direction="rtl" justifyContent="space-between" w="100%" - minH="34px" + minH="32px" > Hide scam tokens </Switch> diff --git a/src/shell/top-bar/settings/fields/color-theme/SettingsColorTheme.spec.tsx b/src/shell/top-bar/settings/fields/color-theme/SettingsColorTheme.spec.tsx new file mode 100644 index 00000000000..6d55617f28a --- /dev/null +++ b/src/shell/top-bar/settings/fields/color-theme/SettingsColorTheme.spec.tsx @@ -0,0 +1,188 @@ +// @vitest-environment jsdom + +import Cookies from 'js-cookie'; +import React from 'react'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type * as TestLib from 'vitest/lib'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const COLOR_MODE_COOKIE = 'chakra-ui-color-mode'; +const COLOR_THEME_COOKIE = 'chakra-ui-color-theme'; +const NEXT_THEMES_STORAGE_KEY = 'theme'; + +function getRootCssVar(name: string): string { + return window.document.documentElement.style.getPropertyValue(name); +} + +type ChangeListener = (event: MediaQueryListEvent) => void; + +interface PrefersColorSchemeStub { + readonly switchTo: (nextPrefersDark: boolean) => void; +} + +function stubPrefersColorScheme(prefersDark: boolean): PrefersColorSchemeStub { + const listeners = new Set<ChangeListener>(); + let matches = prefersDark; + + const subscribe = (listener: ChangeListener) => { + listeners.add(listener); + }; + const unsubscribe = (listener: ChangeListener) => { + listeners.delete(listener); + }; + + // jsdom has no matchMedia; the stub is typed loosely because MediaQueryList's overloads are not worth reproducing + window.matchMedia = ((media: string) => ({ + get matches() { + return matches; + }, + media, + onchange: null, + addListener: subscribe, + removeListener: unsubscribe, + addEventListener: (_: string, listener: ChangeListener) => subscribe(listener), + removeEventListener: (_: string, listener: ChangeListener) => unsubscribe(listener), + dispatchEvent: () => false, + })) as unknown as typeof window.matchMedia; + + return { + switchTo(nextPrefersDark: boolean) { + matches = nextPrefersDark; + listeners.forEach((listener) => listener({ matches, media: '' } as MediaQueryListEvent)); + }, + }; +} + +let unmountRendered: (() => void) | undefined; + +interface RenderedSettings { + readonly screen: typeof TestLib.screen; + readonly fireEvent: typeof TestLib.fireEvent; + readonly act: typeof TestLib.act; +} + +async function renderSettings(envs: Array<[ string, string ]> = []): Promise<RenderedSettings> { + return withEnvs(envs, async() => { + const { render, screen, fireEvent, act } = await import('vitest/lib'); + const { 'default': SettingsColorTheme } = await import('./SettingsColorTheme'); + + const { unmount } = render(<SettingsColorTheme/>); + unmountRendered = unmount; + + return { screen, fireEvent, act }; + }); +} + +function getSwatch(themeId: string): HTMLElement { + const swatch = window.document.querySelector<HTMLElement>(`[data-value="${ themeId }"]`); + if (!swatch) { + throw new Error(`No swatch for theme ${ themeId }`); + } + return swatch; +} + +function getSwatchIds(): Array<string | null> { + return Array.from(window.document.querySelectorAll('[data-value]')).map((element) => element.getAttribute('data-value')); +} + +describe('SettingsColorTheme', () => { + beforeEach(() => { + Cookies.remove(COLOR_MODE_COOKIE); + Cookies.remove(COLOR_THEME_COOKIE); + window.localStorage.clear(); + }); + + afterEach(() => { + unmountRendered?.(); + unmountRendered = undefined; + window.document.documentElement.className = ''; + window.document.documentElement.removeAttribute('style'); + }); + + it('offers the Auto (System) swatch after the concrete themes', async() => { + stubPrefersColorScheme(false); + await renderSettings(); + + expect(getSwatchIds()).toEqual([ 'light', 'dim', 'midnight', 'dark', 'system' ]); + }); + + it('hides the Auto (System) swatch when the offered themes leave it out', async() => { + stubPrefersColorScheme(false); + await renderSettings([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","dark"]' ] ]); + + expect(getSwatchIds()).toEqual([ 'light', 'dark' ]); + }); + + it('starts on the system theme on a first visit and paints the OS color mode', async() => { + stubPrefersColorScheme(true); + const { screen } = await renderSettings(); + + expect(screen.getByText('Auto (System)')).toBeTruthy(); + expect(Cookies.get(COLOR_THEME_COOKIE)).toBe('system'); + expect(Cookies.get(COLOR_MODE_COOKIE)).toBe('dark'); + expect(window.localStorage.getItem(NEXT_THEMES_STORAGE_KEY)).toBe('system'); + expect(getRootCssVar('--chakra-colors-black')).toBe('#101112'); + expect(getRootCssVar('--chakra-colors-theme-bg-primary-_dark')).toBe('#101112'); + expect(getRootCssVar('--chakra-colors-white')).toBe(''); + }); + + it('follows the OS color mode live while the system theme is active', async() => { + const os = stubPrefersColorScheme(false); + const { act } = await renderSettings(); + + expect(Cookies.get(COLOR_MODE_COOKIE)).toBe('light'); + expect(getRootCssVar('--chakra-colors-white')).toBe('#FFFFFF'); + expect(getRootCssVar('--chakra-colors-theme-bg-primary-_light')).toBe('#FFFFFF'); + expect(getRootCssVar('--chakra-colors-black')).toBe(''); + + await act(async() => os.switchTo(true)); + + expect(Cookies.get(COLOR_THEME_COOKIE)).toBe('system'); + expect(Cookies.get(COLOR_MODE_COOKIE)).toBe('dark'); + expect(window.document.documentElement.classList.contains('dark')).toBe(true); + expect(getRootCssVar('--chakra-colors-black')).toBe('#101112'); + expect(getRootCssVar('--chakra-colors-theme-bg-primary-_dark')).toBe('#101112'); + }); + + it('stops following the OS once a concrete theme is picked', async() => { + const os = stubPrefersColorScheme(true); + const { screen, fireEvent, act } = await renderSettings(); + + expect(window.document.documentElement.classList.contains('dark')).toBe(true); + + fireEvent.click(getSwatch('light')); + expect(screen.getByText('Light')).toBeTruthy(); + expect(Cookies.get(COLOR_THEME_COOKIE)).toBe('light'); + expect(Cookies.get(COLOR_MODE_COOKIE)).toBe('light'); + expect(window.localStorage.getItem(NEXT_THEMES_STORAGE_KEY)).toBe('light'); + expect(window.document.documentElement.classList.contains('dark')).toBe(false); + + await act(async() => os.switchTo(false)); + await act(async() => os.switchTo(true)); + + expect(Cookies.get(COLOR_THEME_COOKIE)).toBe('light'); + expect(Cookies.get(COLOR_MODE_COOKIE)).toBe('light'); + expect(window.document.documentElement.classList.contains('dark')).toBe(false); + }); + + it('keeps a concrete theme stored in the cookie instead of switching to the system theme', async() => { + stubPrefersColorScheme(true); + Cookies.set(COLOR_THEME_COOKIE, 'light'); + Cookies.set(COLOR_MODE_COOKIE, 'light'); + const { screen } = await renderSettings(); + + expect(screen.getByText('Light')).toBeTruthy(); + expect(Cookies.get(COLOR_THEME_COOKIE)).toBe('light'); + expect(Cookies.get(COLOR_MODE_COOKIE)).toBe('light'); + }); + + it('resolves the system theme to the darkest offered dark theme', async() => { + stubPrefersColorScheme(true); + const { screen } = await renderSettings([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","midnight","system"]' ] ]); + + expect(screen.getByText('Auto (System)')).toBeTruthy(); + expect(Cookies.get(COLOR_MODE_COOKIE)).toBe('dark'); + expect(window.document.documentElement.style.getPropertyValue('--chakra-colors-black')).toBe('#1B2E48'); + }); +}); diff --git a/src/shell/top-bar/settings/fields/color-theme/SettingsColorTheme.tsx b/src/shell/top-bar/settings/fields/color-theme/SettingsColorTheme.tsx new file mode 100644 index 00000000000..846a5b27a6b --- /dev/null +++ b/src/shell/top-bar/settings/fields/color-theme/SettingsColorTheme.tsx @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { SettingsControlVariant } from '../../types'; + +import config from 'src/config'; +import * as cookies from 'src/shared/storage/cookies'; + +import type { ColorMode } from 'src/toolkit/chakra/color-mode'; +import { useColorMode } from 'src/toolkit/chakra/color-mode'; + +import { useSettingsContext } from '../../context'; +import SettingsSample from '../../parts/SettingsSample'; +import SettingsSamplesRow from '../../parts/SettingsSamplesRow'; +import type { ColorThemeId } from './config'; +import { SYSTEM_COLOR_THEME_ID, isConcreteColorTheme } from './config'; +import { getInitialColorTheme, getThemeHexWithOverrides, resolveColorTheme } from './utils'; + +const MIN_THEMES_FOR_SWITCHER = 2; +const PREFERS_DARK_QUERY = '(prefers-color-scheme: dark)'; + +const availableThemes = config.shell.topBar.colorTheme.themes; +const concreteThemes = availableThemes.filter(isConcreteColorTheme); + +interface Props { + onSelect?: () => void; + variant?: SettingsControlVariant; +} + +const SettingsColorTheme = ({ onSelect, variant = 'popover' }: Props) => { + const { setColorMode } = useColorMode(); + const settingsContext = useSettingsContext(); + + const activeThemeId = settingsContext?.colorTheme; + const setActiveThemeId = settingsContext?.setColorTheme; + + const applyTheme = React.useCallback((themeId: ColorThemeId, prefersDark: boolean) => { + const concreteThemeId = resolveColorTheme(themeId, prefersDark); + const concreteTheme = concreteThemes.find((theme) => theme.id === concreteThemeId); + const varValue = getThemeHexWithOverrides(concreteThemeId); + + // Stryker disable next-line ConditionalExpression,LogicalOperator: the id is one of the offered themes, so neither lookup can miss; the guard narrows types + if (!concreteTheme || !varValue) { + return; + } + + setColorMode(themeId === SYSTEM_COLOR_THEME_ID ? SYSTEM_COLOR_THEME_ID : concreteTheme.colorMode); + + const varName = concreteTheme.colorMode === 'light' ? '--chakra-colors-white' : '--chakra-colors-black'; + const varNameBg = concreteTheme.colorMode === 'light' ? '--chakra-colors-theme-bg-primary-_light' : '--chakra-colors-theme-bg-primary-_dark'; + window.document.documentElement.style.setProperty(varName, varValue); + window.document.documentElement.style.setProperty(varNameBg, varValue); + + cookies.set(cookies.NAMES.COLOR_MODE, concreteTheme.colorMode); + cookies.set(cookies.NAMES.COLOR_THEME, themeId); + window.localStorage.setItem(cookies.NAMES.COLOR_MODE, concreteTheme.colorMode); + }, [ setColorMode ]); + + React.useEffect(() => { + const prefersDark = window.matchMedia(PREFERS_DARK_QUERY).matches; + const nextColorTheme = getInitialColorTheme({ + cookieColorMode: cookies.get(cookies.NAMES.COLOR_MODE) as ColorMode | undefined, + cookieColorTheme: cookies.get(cookies.NAMES.COLOR_THEME), + prefersDark, + }); + + applyTheme(nextColorTheme, prefersDark); + setActiveThemeId?.(nextColorTheme); + // should run only on mount + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ ]); + + React.useEffect(() => { + if (activeThemeId !== SYSTEM_COLOR_THEME_ID) { + return; + } + + const mediaQuery = window.matchMedia(PREFERS_DARK_QUERY); + const handleChange = (event: MediaQueryListEvent) => applyTheme(SYSTEM_COLOR_THEME_ID, event.matches); + mediaQuery.addEventListener('change', handleChange); + + return () => mediaQuery.removeEventListener('change', handleChange); + }, [ activeThemeId, applyTheme ]); + + const handleSelect = React.useCallback((event: React.MouseEvent<HTMLDivElement>) => { + event.stopPropagation(); + + const themeId = event.currentTarget.getAttribute('data-value') as ColorThemeId | null; + + // Stryker disable next-line ConditionalExpression: every sample renders its data-value, so the guard only narrows the nullable attribute type + if (!themeId) { + return; + } + + applyTheme(themeId, window.matchMedia(PREFERS_DARK_QUERY).matches); + setActiveThemeId?.(themeId); + onSelect?.(); + }, [ applyTheme, setActiveThemeId, onSelect ]); + + const activeTheme = availableThemes.find((theme) => theme.id === activeThemeId); + + if (concreteThemes.length < MIN_THEMES_FOR_SWITCHER) { + return null; + } + + return ( + <SettingsSamplesRow variant={ variant } title="Color theme" mobileTitle="Theme" value={ activeTheme?.label }> + { availableThemes.map((theme) => { + return ( + <SettingsSample + key={ theme.label } + label={ theme.label } + value={ theme.id } + bg={ theme.sampleBg } + isActive={ theme.id === activeThemeId } + onClick={ handleSelect } + /> + ); + }) } + </SettingsSamplesRow> + ); +}; + +export default React.memo(SettingsColorTheme); diff --git a/src/shell/top-bar/settings/fields/color-theme/config.ts b/src/shell/top-bar/settings/fields/color-theme/config.ts new file mode 100644 index 00000000000..36d482cb8db --- /dev/null +++ b/src/shell/top-bar/settings/fields/color-theme/config.ts @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { ConditionalValue } from '@chakra-ui/react'; + +import type { ColorMode } from 'src/toolkit/chakra/color-mode'; + +export type SampleBg = ConditionalValue<string>; + +export const COLOR_THEME_IDS = [ 'light', 'dim', 'midnight', 'dark', 'system' ] as const; +export type ColorThemeId = typeof COLOR_THEME_IDS[number]; + +export const SYSTEM_COLOR_THEME_ID = 'system' satisfies ColorThemeId; +export type SystemColorThemeId = typeof SYSTEM_COLOR_THEME_ID; + +export type ConcreteColorThemeId = Exclude<ColorThemeId, SystemColorThemeId>; + +export interface ConcreteColorTheme { + readonly id: ConcreteColorThemeId; + readonly label: string; + readonly colorMode: ColorMode; + readonly hex: string; + readonly sampleBg: SampleBg; +} + +export interface SystemColorTheme { + readonly id: SystemColorThemeId; + readonly label: string; + readonly colorMode: SystemColorThemeId; + readonly sampleBg: SampleBg; +} + +export type ColorTheme = ConcreteColorTheme | SystemColorTheme; + +const DARK_SAMPLE_BG = 'linear-gradient(161deg, #000 9.37%, #383838 92.52%)'; + +export const COLOR_THEMES: Array<ColorTheme> = [ + { + id: 'light', + label: 'Light', + colorMode: 'light', + hex: '#FFFFFF', + sampleBg: 'rgba(255, 255, 255, 1)', + }, + { + id: 'dim', + label: 'Dim', + colorMode: 'dark', + hex: '#232B37', + sampleBg: 'linear-gradient(152deg, #232B37 50%, rgba(255, 255, 255, 0.00) 290.71%)', + }, + { + id: 'midnight', + label: 'Midnight', + colorMode: 'dark', + hex: '#1B2E48', + sampleBg: 'linear-gradient(148deg, #1B3F71 50%, rgba(255, 255, 255, 0.00) 312.35%)', + }, + { + id: 'dark', + label: 'Dark', + colorMode: 'dark', + hex: '#101112', + sampleBg: DARK_SAMPLE_BG, + }, + { + id: SYSTEM_COLOR_THEME_ID, + label: 'Auto (System)', + colorMode: SYSTEM_COLOR_THEME_ID, + sampleBg: { + _light: `linear-gradient(90deg, transparent 10.5px, {colors.blackAlpha.50} 10.5px), ${ DARK_SAMPLE_BG } left / 10.5px 100% no-repeat`, + _dark: `linear-gradient(90deg, transparent 10.5px, {colors.whiteAlpha.900} 10.5px), ${ DARK_SAMPLE_BG } left / 10.5px 100% no-repeat`, + }, + }, +]; + +export function isSystemColorTheme(theme: ColorTheme): theme is SystemColorTheme { + return theme.id === SYSTEM_COLOR_THEME_ID; +} + +export function isConcreteColorTheme(theme: ColorTheme): theme is ConcreteColorTheme { + return !isSystemColorTheme(theme); +} + +export function coversBothColorModes(themes: ReadonlyArray<ColorTheme>): boolean { + return themes.some((theme) => theme.colorMode === 'light') && themes.some((theme) => theme.colorMode === 'dark'); +} diff --git a/src/shell/top-bar/settings/fields/color-theme/utils.spec.ts b/src/shell/top-bar/settings/fields/color-theme/utils.spec.ts new file mode 100644 index 00000000000..0a3fe1bbdb9 --- /dev/null +++ b/src/shell/top-bar/settings/fields/color-theme/utils.spec.ts @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import type * as colorThemeUtils from './utils'; + +async function loadUtils(envs: Array<[ string, string ]>): Promise<typeof colorThemeUtils> { + return withEnvs(envs, async() => import('./utils')); +} + +const LIGHT_ONLY = [ 'NEXT_PUBLIC_COLOR_THEMES', '["light"]' ] satisfies [ string, string ]; +const DIM_AND_MIDNIGHT = [ 'NEXT_PUBLIC_COLOR_THEMES', '["dim","midnight"]' ] satisfies [ string, string ]; + +describe('isColorThemeAvailable', () => { + it('accepts every theme when no theme list is configured', async() => { + const { isColorThemeAvailable } = await loadUtils([]); + + expect(isColorThemeAvailable('dim')).toBe(true); + expect(isColorThemeAvailable('midnight')).toBe(true); + }); + + it('rejects a theme left out of the configured list', async() => { + const { isColorThemeAvailable } = await loadUtils([ DIM_AND_MIDNIGHT ]); + + expect(isColorThemeAvailable('dim')).toBe(true); + expect(isColorThemeAvailable('light')).toBe(false); + }); + + it('rejects an unknown theme id', async() => { + const { isColorThemeAvailable } = await loadUtils([]); + + expect(isColorThemeAvailable('sepia')).toBe(false); + }); +}); + +describe('getDefaultColorTheme', () => { + it('picks the darkest theme of the requested color mode', async() => { + const { getDefaultColorTheme } = await loadUtils([]); + + expect(getDefaultColorTheme('light')).toBe('light'); + expect(getDefaultColorTheme('dark')).toBe('dark'); + }); + + it('picks the darkest available theme of the requested color mode', async() => { + const { getDefaultColorTheme } = await loadUtils([ DIM_AND_MIDNIGHT ]); + + expect(getDefaultColorTheme('dark')).toBe('midnight'); + }); + + it('falls back to an available theme when the requested color mode is not available', async() => { + const { getDefaultColorTheme } = await loadUtils([ LIGHT_ONLY ]); + + expect(getDefaultColorTheme('dark')).toBe('light'); + }); +}); + +describe('getInitialColorTheme', () => { + const DEFAULT_LIGHT = [ 'NEXT_PUBLIC_COLOR_THEME_DEFAULT', 'light' ] satisfies [ string, string ]; + + it('keeps an available theme from the cookie', async() => { + const { getInitialColorTheme } = await loadUtils([ DEFAULT_LIGHT ]); + + expect(getInitialColorTheme({ cookieColorMode: 'dark', cookieColorTheme: 'dim', prefersDark: false })).toBe('dim'); + }); + + it('derives the theme from the cookie color mode when the cookie theme is unavailable', async() => { + const { getInitialColorTheme } = await loadUtils([ DEFAULT_LIGHT ]); + + expect(getInitialColorTheme({ cookieColorMode: 'dark', cookieColorTheme: 'sepia', prefersDark: false })).toBe('dark'); + }); + + it('prefers the configured default over the OS preference when there are no cookies', async() => { + const { getInitialColorTheme } = await loadUtils([ DEFAULT_LIGHT ]); + + expect(getInitialColorTheme({ cookieColorMode: undefined, cookieColorTheme: undefined, prefersDark: true })).toBe('light'); + }); + + it('uses the exact configured default theme, not just its color mode', async() => { + const { getInitialColorTheme } = await loadUtils([ [ 'NEXT_PUBLIC_COLOR_THEME_DEFAULT', 'dim' ] ]); + + expect(getInitialColorTheme({ cookieColorMode: undefined, cookieColorTheme: undefined, prefersDark: false })).toBe('dim'); + }); + + it('is the system theme when no default is configured and there are no cookies', async() => { + const { getInitialColorTheme } = await loadUtils([]); + + expect(getInitialColorTheme({ cookieColorMode: undefined, cookieColorTheme: undefined, prefersDark: true })).toBe('system'); + expect(getInitialColorTheme({ cookieColorMode: undefined, cookieColorTheme: undefined, prefersDark: false })).toBe('system'); + }); + + it('keeps the system theme from the cookie', async() => { + const { getInitialColorTheme } = await loadUtils([ DEFAULT_LIGHT ]); + + expect(getInitialColorTheme({ cookieColorMode: 'dark', cookieColorTheme: 'system', prefersDark: false })).toBe('system'); + }); + + it('follows the OS preference when the offered themes leave the system theme out and there are no cookies', async() => { + const { getInitialColorTheme } = await loadUtils([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","dark"]' ] ]); + + expect(getInitialColorTheme({ cookieColorMode: undefined, cookieColorTheme: undefined, prefersDark: true })).toBe('dark'); + expect(getInitialColorTheme({ cookieColorMode: undefined, cookieColorTheme: undefined, prefersDark: false })).toBe('light'); + }); + + it('derives a concrete theme from the cookie color mode when the system theme is no longer offered', async() => { + const { getInitialColorTheme } = await loadUtils([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","dark"]' ] ]); + + expect(getInitialColorTheme({ cookieColorMode: 'dark', cookieColorTheme: 'system', prefersDark: false })).toBe('dark'); + }); +}); + +describe('resolveColorTheme', () => { + it('resolves the system theme to the darkest offered theme of the OS color mode', async() => { + const { resolveColorTheme } = await loadUtils([]); + + expect(resolveColorTheme('system', true)).toBe('dark'); + expect(resolveColorTheme('system', false)).toBe('light'); + }); + + it('resolves the system theme to the darkest available theme of the OS color mode', async() => { + const { resolveColorTheme } = await loadUtils([ [ 'NEXT_PUBLIC_COLOR_THEMES', '["light","midnight","system"]' ] ]); + + expect(resolveColorTheme('system', true)).toBe('midnight'); + }); + + it('leaves a concrete theme alone whatever the OS color mode', async() => { + const { resolveColorTheme } = await loadUtils([]); + + expect(resolveColorTheme('dim', false)).toBe('dim'); + expect(resolveColorTheme('light', true)).toBe('light'); + }); +}); + +describe('getThemeHexWithOverrides', () => { + const OVERRIDES = [ + 'NEXT_PUBLIC_COLOR_THEME_OVERRIDES', + '{"bg":{"primary":{"_light":{"value":"#f0f0f0"},"_dark":{"value":"#101010"}}}}', + ] satisfies [ string, string ]; + + it('returns the theme hex when no overrides are configured', async() => { + const { getThemeHexWithOverrides } = await loadUtils([]); + + expect(getThemeHexWithOverrides('light')).toBe('#FFFFFF'); + expect(getThemeHexWithOverrides('dark')).toBe('#101112'); + }); + + it('takes the overridden background for the light and dark themes', async() => { + const { getThemeHexWithOverrides } = await loadUtils([ OVERRIDES ]); + + expect(getThemeHexWithOverrides('light')).toBe('#f0f0f0'); + expect(getThemeHexWithOverrides('dark')).toBe('#101010'); + }); + + it('leaves the other themes alone even when overrides are configured', async() => { + const { getThemeHexWithOverrides } = await loadUtils([ OVERRIDES ]); + + expect(getThemeHexWithOverrides('dim')).toBe('#232B37'); + expect(getThemeHexWithOverrides('midnight')).toBe('#1B2E48'); + }); + + it('falls back to the theme hex when the override value is missing or not a string', async() => { + const { getThemeHexWithOverrides } = await loadUtils([ + [ 'NEXT_PUBLIC_COLOR_THEME_OVERRIDES', '{"bg":{"primary":{"_light":{"value":1},"_dark":{"color":"#000"}}}}' ], + ]); + + expect(getThemeHexWithOverrides('light')).toBe('#FFFFFF'); + expect(getThemeHexWithOverrides('dark')).toBe('#101112'); + }); + + it('takes a leaf string reached before the end of the override path', async() => { + const { getThemeHexWithOverrides } = await loadUtils([ + [ 'NEXT_PUBLIC_COLOR_THEME_OVERRIDES', '{"bg":{"primary":{"_dark":"#000"}}}' ], + ]); + + expect(getThemeHexWithOverrides('dark')).toBe('#000'); + }); + + it('falls back to the theme hex when an intermediate override node is an array or null', async() => { + const { getThemeHexWithOverrides } = await loadUtils([ + [ 'NEXT_PUBLIC_COLOR_THEME_OVERRIDES', '{"bg":{"primary":{"_light":[],"_dark":null}}}' ], + ]); + + expect(getThemeHexWithOverrides('light')).toBe('#FFFFFF'); + expect(getThemeHexWithOverrides('dark')).toBe('#101112'); + }); +}); diff --git a/src/shell/top-bar/settings/fields/color-theme/utils.ts b/src/shell/top-bar/settings/fields/color-theme/utils.ts new file mode 100644 index 00000000000..7c38947b91c --- /dev/null +++ b/src/shell/top-bar/settings/fields/color-theme/utils.ts @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import config from 'src/config'; + +import type { ColorMode } from 'src/toolkit/chakra/color-mode'; + +import type { ColorThemeId, ConcreteColorThemeId } from './config'; +import { COLOR_THEMES, SYSTEM_COLOR_THEME_ID, isConcreteColorTheme } from './config'; + +const getNestedValue = (obj: Record<string, unknown>, property: string) => { + const keys = property.split('.'); + let current = obj; + for (const key of keys) { + const value = current[key]; + if (typeof value === 'object' && value !== null && !Array.isArray(value)) { + current = value as Record<string, unknown>; + } else { + return value; + } + } +}; + +export function getThemeHexWithOverrides(colorThemeId: ConcreteColorThemeId): string | undefined { + const defaultHex = COLOR_THEMES.filter(isConcreteColorTheme).find((theme) => theme.id === colorThemeId)?.hex; + + // Stryker disable next-line ConditionalExpression: the id is a concrete theme id, so the lookup cannot miss; the guard narrows the type + if (!defaultHex) { + return; + } + + const overrides = config.shell.topBar.colorTheme.overrides; + if (colorThemeId === 'light') { + const value = getNestedValue(overrides, 'bg.primary._light.value'); + return typeof value === 'string' ? value : defaultHex; + } + + if (colorThemeId === 'dark') { + const value = getNestedValue(overrides, 'bg.primary._dark.value'); + return typeof value === 'string' ? value : defaultHex; + } + + return defaultHex; +}; + +export function isColorThemeAvailable(colorThemeId: string): colorThemeId is ColorThemeId { + return config.shell.topBar.colorTheme.themes.some((theme) => theme.id === colorThemeId); +} + +export function getDefaultColorTheme(colorMode: ColorMode): ConcreteColorThemeId { + const themes = config.shell.topBar.colorTheme.themes.filter(isConcreteColorTheme); + const colorTheme = themes.filter((theme) => theme.colorMode === colorMode).slice(-1)[0]; + + return (colorTheme ?? themes[0]).id; +} + +export function resolveColorTheme(colorThemeId: ColorThemeId, prefersDark: boolean): ConcreteColorThemeId { + if (colorThemeId === SYSTEM_COLOR_THEME_ID) { + return getDefaultColorTheme(prefersDark ? 'dark' : 'light'); + } + + return colorThemeId; +} + +interface InitialColorThemeParams { + readonly cookieColorMode: ColorMode | undefined; + readonly cookieColorTheme: string | undefined; + readonly prefersDark: boolean; +} + +export function getInitialColorTheme({ cookieColorMode, cookieColorTheme, prefersDark }: InitialColorThemeParams): ColorThemeId { + if (cookieColorTheme && isColorThemeAvailable(cookieColorTheme)) { + return cookieColorTheme; + } + + if (cookieColorMode) { + return getDefaultColorTheme(cookieColorMode); + } + + const defaultTheme = config.shell.topBar.colorTheme.default; + if (defaultTheme) { + return defaultTheme.id; + } + + return getDefaultColorTheme(prefersDark ? 'dark' : 'light'); +} diff --git a/src/shell/top-bar/settings/fields/ident-icon/SettingsIdentIcon.tsx b/src/shell/top-bar/settings/fields/ident-icon/SettingsIdentIcon.tsx new file mode 100644 index 00000000000..ab5acfd0560 --- /dev/null +++ b/src/shell/top-bar/settings/fields/ident-icon/SettingsIdentIcon.tsx @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { SettingsControlVariant } from '../../types'; + +import config from 'src/config'; +import * as cookies from 'src/shared/storage/cookies'; + +import SettingsSample from '../../parts/SettingsSample'; +import SettingsSamplesRow from '../../parts/SettingsSamplesRow'; +import { IDENTICONS } from './utils'; + +interface Props { + variant?: SettingsControlVariant; +} + +const SettingsIdentIcon = ({ variant = 'popover' }: Props) => { + const [ activeId, setActiveId ] = React.useState<string>(); + + React.useEffect(() => { + const initialId = cookies.get(cookies.NAMES.ADDRESS_IDENTICON_TYPE) || config.slices.address.identiconType; + setActiveId(initialId); + }, []); + + const handleSelect = React.useCallback((event: React.MouseEvent<HTMLDivElement>) => { + event.stopPropagation(); + + const id = event.currentTarget.getAttribute('data-value'); + + if (!id) { + return; + } + + cookies.set(cookies.NAMES.ADDRESS_IDENTICON_TYPE, id); + window.location.reload(); + }, []); + + const activeIdenticon = IDENTICONS.find((identicon) => identicon.id === activeId); + return ( + <SettingsSamplesRow variant={ variant } title="Address identicon" mobileTitle="Identicon" value={ activeIdenticon?.label }> + { IDENTICONS.map((identicon) => ( + <SettingsSample + key={ identicon.id } + label={ identicon.label } + value={ identicon.id } + bg={ identicon.sampleBg } + isActive={ identicon.id === activeId } + onClick={ handleSelect } + /> + )) } + </SettingsSamplesRow> + ); +}; + +export default React.memo(SettingsIdentIcon); diff --git a/src/shell/top-bar/settings/ident-icon/utils.ts b/src/shell/top-bar/settings/fields/ident-icon/utils.ts similarity index 100% rename from src/shell/top-bar/settings/ident-icon/utils.ts rename to src/shell/top-bar/settings/fields/ident-icon/utils.ts diff --git a/src/shell/top-bar/settings/fields/rpc-node/SettingsRpcNode.spec.tsx b/src/shell/top-bar/settings/fields/rpc-node/SettingsRpcNode.spec.tsx new file mode 100644 index 00000000000..b8e008e96a1 --- /dev/null +++ b/src/shell/top-bar/settings/fields/rpc-node/SettingsRpcNode.spec.tsx @@ -0,0 +1,176 @@ +// @vitest-environment jsdom + +import Cookies from 'js-cookie'; +import React from 'react'; + +import * as cookies from 'src/shared/storage/cookies'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from 'vitest/lib'; + +import SettingsRpcNode from './SettingsRpcNode'; + +const analyticsMock = vi.hoisted(() => ({ + logEvent: vi.fn(), + EventTypes: { RPC_NODE: 'RPC node' }, +})); + +vi.mock('src/shared/analytics', () => analyticsMock); + +const CUSTOM_URL = 'https://rpc.example.com/eth'; +const IMMEDIATE = { sendImmediately: true }; + +function typeUrl(value: string): void { + const input = screen.getByRole('textbox'); + fireEvent.change(input, { target: { value } }); + fireEvent.blur(input); +} + +function button(name: string | RegExp): HTMLButtonElement { + return screen.getByRole('button', { name }) as HTMLButtonElement; +} + +function setSavedNode(url: string, isInUse: boolean): void { + Cookies.set(cookies.NAMES.CUSTOM_RPC_URL, url); + if (isInUse) { + Cookies.set(cookies.NAMES.CUSTOM_RPC_IN_USE, 'true'); + } +} + +describe('SettingsRpcNode', () => { + const reload = vi.fn(); + + beforeEach(() => { + vi.stubGlobal('location', { ...window.location, reload }); + fetchMock.resetMocks(); + fetchMock.mockResponse(JSON.stringify({ jsonrpc: '2.0', id: 1, result: '0x1' })); + }); + + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + reload.mockReset(); + analyticsMock.logEvent.mockReset(); + Cookies.remove(cookies.NAMES.CUSTOM_RPC_URL); + Cookies.remove(cookies.NAMES.CUSTOM_RPC_IN_USE); + }); + + it('with no saved URL shows an empty field, no plug and no status', () => { + render(<SettingsRpcNode/>); + + const input = screen.getByRole('textbox') as HTMLInputElement; + expect(input.value).toBe(''); + expect(input.getAttribute('spellcheck')).toBe('false'); + expect(button('Save').disabled).toBe(true); + expect(screen.queryByRole('button', { name: /RPC node$/ })).toBeNull(); + expect(screen.queryByText(/Using/)).toBeNull(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('flags a non-https value as invalid and keeps Save disabled', async() => { + render(<SettingsRpcNode/>); + + typeUrl('http://rpc.example.com'); + + await waitFor(() => expect(screen.getByText('Invalid format')).toBeTruthy()); + await waitFor(() => expect(button('Save').disabled).toBe(true)); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('saves a valid URL as the node in use and reloads', async() => { + render(<SettingsRpcNode/>); + + typeUrl(CUSTOM_URL); + await waitFor(() => expect(button('Save').disabled).toBe(false)); + fireEvent.click(button('Save')); + + await waitFor(() => expect(reload).toHaveBeenCalledTimes(1)); + expect(Cookies.get(cookies.NAMES.CUSTOM_RPC_URL)).toBe(CUSTOM_URL); + expect(Cookies.get(cookies.NAMES.CUSTOM_RPC_IN_USE)).toBe('true'); + expect(analyticsMock.logEvent).toHaveBeenCalledWith('RPC node', { Action: 'Set' }, IMMEDIATE); + }); + + it('clearing the field and saving forgets the node and reloads', async() => { + setSavedNode(CUSTOM_URL, true); + render(<SettingsRpcNode/>); + + expect(button('Save').disabled).toBe(true); + typeUrl(''); + await waitFor(() => expect(button('Save').disabled).toBe(false)); + fireEvent.click(button('Save')); + + await waitFor(() => expect(reload).toHaveBeenCalledTimes(1)); + expect(Cookies.get(cookies.NAMES.CUSTOM_RPC_URL)).toBeUndefined(); + expect(Cookies.get(cookies.NAMES.CUSTOM_RPC_IN_USE)).toBeUndefined(); + expect(analyticsMock.logEvent).toHaveBeenCalledWith('RPC node', { Action: 'Reset' }, IMMEDIATE); + }); + + it('pings the saved node in use and shows the outcome', async() => { + setSavedNode(CUSTOM_URL, true); + render(<SettingsRpcNode/>); + + await waitFor(() => expect(screen.getByText('Connected')).toBeTruthy()); + expect(screen.getByText('Using your custom node')).toBeTruthy(); + expect(fetchMock.mock.calls[0][0]).toBe(CUSTOM_URL); + expect(screen.queryByRole('alert')).toBeNull(); + }); + + it('keeps a dead node in use and reports it as not responding', async() => { + fetchMock.mockReject(new TypeError('Failed to fetch')); + setSavedNode(CUSTOM_URL, true); + render(<SettingsRpcNode/>); + + await waitFor(() => expect(screen.getByText('Not responding')).toBeTruthy()); + expect(screen.getByText('Using your custom node')).toBeTruthy(); + expect(screen.getByText(/isn't responding/)).toBeTruthy(); + expect(Cookies.get(cookies.NAMES.CUSTOM_RPC_IN_USE)).toBe('true'); + }); + + it('warns on a chain mismatch under a connected tag', async() => { + fetchMock.mockResponse(JSON.stringify({ jsonrpc: '2.0', id: 1, result: '0x89' })); + setSavedNode(CUSTOM_URL, true); + render(<SettingsRpcNode/>); + + await waitFor(() => expect(screen.getByText(/different network/)).toBeTruthy()); + expect(screen.getByText('Connected')).toBeTruthy(); + }); + + it('disconnects a node in use without forgetting the URL', async() => { + setSavedNode(CUSTOM_URL, true); + render(<SettingsRpcNode/>); + + await waitFor(() => expect(screen.getByText('Connected')).toBeTruthy()); + fireEvent.click(button('Disconnect custom RPC node')); + + expect(Cookies.get(cookies.NAMES.CUSTOM_RPC_URL)).toBe(CUSTOM_URL); + expect(Cookies.get(cookies.NAMES.CUSTOM_RPC_IN_USE)).toBeUndefined(); + expect(analyticsMock.logEvent).toHaveBeenCalledWith('RPC node', { Action: 'Disconnect' }, IMMEDIATE); + expect(reload).toHaveBeenCalledTimes(1); + }); + + it('shows a saved but unused node as disconnected without pinging it, and reconnects on click', async() => { + setSavedNode(CUSTOM_URL, false); + render(<SettingsRpcNode/>); + + expect(screen.getByText('Disconnected')).toBeTruthy(); + expect(screen.getByText('Using the default node')).toBeTruthy(); + expect((screen.getByRole('textbox') as HTMLInputElement).value).toBe(CUSTOM_URL); + expect(fetchMock).not.toHaveBeenCalled(); + + fireEvent.click(button('Connect custom RPC node')); + + expect(Cookies.get(cookies.NAMES.CUSTOM_RPC_IN_USE)).toBe('true'); + expect(analyticsMock.logEvent).toHaveBeenCalledWith('RPC node', { Action: 'Connect' }, IMMEDIATE); + expect(reload).toHaveBeenCalledTimes(1); + }); + + it('disables the plug while the field holds an unsaved value', async() => { + setSavedNode(CUSTOM_URL, false); + render(<SettingsRpcNode/>); + + typeUrl(`${ CUSTOM_URL }2`); + + await waitFor(() => expect(button('Connect custom RPC node').disabled).toBe(true)); + expect(button('Save').disabled).toBe(false); + }); +}); diff --git a/src/shell/top-bar/settings/fields/rpc-node/SettingsRpcNode.tsx b/src/shell/top-bar/settings/fields/rpc-node/SettingsRpcNode.tsx new file mode 100644 index 00000000000..2e1e8cb8e64 --- /dev/null +++ b/src/shell/top-bar/settings/fields/rpc-node/SettingsRpcNode.tsx @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { chakra, HStack, VStack } from '@chakra-ui/react'; +import React from 'react'; +import type { SubmitHandler } from 'react-hook-form'; +import { FormProvider, useForm } from 'react-hook-form'; + +import { CUSTOM_RPC_IN_USE_VALUE } from 'src/features/connect-wallet/utils/rpc-urls'; + +import * as analytics from 'src/shared/analytics'; +import * as cookies from 'src/shared/storage/cookies'; +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { Alert } from 'src/toolkit/chakra/alert'; +import { Badge } from 'src/toolkit/chakra/badge'; +import { Button } from 'src/toolkit/chakra/button'; +import { IconButton } from 'src/toolkit/chakra/icon-button'; +import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { FormFieldUrl } from 'src/toolkit/components/forms/fields/FormFieldUrl'; + +import { useRpcNodePingQuery } from './useRpcNodePingQuery'; +import type { SavedRpcNode } from './utils'; +import { getRpcNodeStatus, getSavedRpcNode, validateRpcUrl } from './utils'; + +interface FormFields { + url: string; +} + +const URL_RULES = { validate: { https: validateRpcUrl } }; +// Stryker disable next-line BooleanLiteral: evaluated at module load, before runtime mutant activation, so the spellcheck assertion cannot see it +const INPUT_PROPS = { 'aria-label': 'RPC node URL', spellCheck: false, bgColor: 'dialog.bg' }; + +const SettingsRpcNode = () => { + const [ savedNode ] = React.useState<SavedRpcNode>(getSavedRpcNode); + + const formApi = useForm<FormFields>({ + mode: 'onBlur', + defaultValues: { url: savedNode.url ?? '' }, + }); + const { isDirty, errors } = formApi.formState; + + const pingQuery = useRpcNodePingQuery(savedNode.isInUse ? savedNode.url : undefined); + + const handleSubmit: SubmitHandler<FormFields> = React.useCallback(({ url }) => { + const nextUrl = url.trim(); + + if (nextUrl) { + cookies.set(cookies.NAMES.CUSTOM_RPC_URL, nextUrl); + cookies.set(cookies.NAMES.CUSTOM_RPC_IN_USE, CUSTOM_RPC_IN_USE_VALUE); + analytics.logEvent(analytics.EventTypes.RPC_NODE, { Action: 'Set' }, { sendImmediately: true }); + } else { + cookies.remove(cookies.NAMES.CUSTOM_RPC_URL); + cookies.remove(cookies.NAMES.CUSTOM_RPC_IN_USE); + analytics.logEvent(analytics.EventTypes.RPC_NODE, { Action: 'Reset' }, { sendImmediately: true }); + } + + window.location.reload(); + }, []); + + const handleTogglePlug = React.useCallback(() => { + if (savedNode.isInUse) { + cookies.remove(cookies.NAMES.CUSTOM_RPC_IN_USE); + analytics.logEvent(analytics.EventTypes.RPC_NODE, { Action: 'Disconnect' }, { sendImmediately: true }); + } else { + cookies.set(cookies.NAMES.CUSTOM_RPC_IN_USE, CUSTOM_RPC_IN_USE_VALUE); + analytics.logEvent(analytics.EventTypes.RPC_NODE, { Action: 'Connect' }, { sendImmediately: true }); + } + + window.location.reload(); + }, [ savedNode.isInUse ]); + + const status = savedNode.url ? getRpcNodeStatus(savedNode.isInUse ? (pingQuery.data?.outcome ?? 'connected') : 'disconnected') : undefined; + const isStatusPending = savedNode.isInUse && pingQuery.data === undefined; + + return ( + <FormProvider { ...formApi }> + <chakra.form noValidate onSubmit={ formApi.handleSubmit(handleSubmit) }> + <VStack gap={ 3 } alignItems="stretch"> + <HStack gap={ 3 } alignItems="flex-start"> + <FormFieldUrl<FormFields> + name="url" + placeholder="RPC node URL" + rules={ URL_RULES } + size="sm" + floating={ false } + flexGrow={ 1 } + inputProps={ INPUT_PROPS } + /> + <Button type="submit" variant="outline" size="sm" disabled={ !isDirty || Boolean(errors.url) } loading={ formApi.formState.isSubmitting }> + Save + </Button> + { status && ( + <Tooltip content={ savedNode.isInUse ? 'Disconnect custom RPC node' : 'Connect custom RPC node' }> + <IconButton + variant="icon_background" + size="md" + aria-label={ savedNode.isInUse ? 'Disconnect custom RPC node' : 'Connect custom RPC node' } + disabled={ isDirty } + loadingSkeleton={ isStatusPending } + onClick={ handleTogglePlug } + color={ status.plug.color } + > + <SpriteIcon name={ status.plug.icon }/> + </IconButton> + </Tooltip> + ) } + </HStack> + { status && ( + <VStack gap={ 2 } alignItems="stretch"> + <HStack gap={ 1 }> + <Badge colorPalette={ status.tag.colorPalette } loading={ isStatusPending }>{ status.tag.label }</Badge> + <Skeleton loading={ isStatusPending } textStyle="sm" color="text.secondary">{ status.nodeText }</Skeleton> + </HStack> + { !isStatusPending && status.alert && ( + <Alert status={ status.alert.status } textStyle="sm">{ status.alert.text }</Alert> + ) } + </VStack> + ) } + </VStack> + </chakra.form> + </FormProvider> + ); +}; + +export default React.memo(SettingsRpcNode); diff --git a/src/shell/top-bar/settings/fields/rpc-node/useCustomRpcNodeStatus.ts b/src/shell/top-bar/settings/fields/rpc-node/useCustomRpcNodeStatus.ts new file mode 100644 index 00000000000..40a7b8774b2 --- /dev/null +++ b/src/shell/top-bar/settings/fields/rpc-node/useCustomRpcNodeStatus.ts @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { useAppContext } from 'src/shell/app/context'; + +import { useRpcNodePingQuery } from './useRpcNodePingQuery'; +import type { RpcNodeStatus } from './utils'; +import { getRpcNodeStatus, getSavedRpcNode, isRpcNodeSettingAvailable } from './utils'; + +export interface CustomRpcNodeStatus { + readonly status: RpcNodeStatus; + readonly isPending: boolean; +} + +export function useCustomRpcNodeStatus(): CustomRpcNodeStatus | undefined { + const { cookies } = useAppContext(); + const [ savedNode ] = React.useState(() => getSavedRpcNode(cookies)); + const url = isRpcNodeSettingAvailable() && savedNode.isInUse ? savedNode.url : undefined; + + const pingQuery = useRpcNodePingQuery(url); + + if (!url) { + return; + } + + return { + status: getRpcNodeStatus(pingQuery.data?.outcome ?? 'connected'), + isPending: pingQuery.data === undefined, + }; +} diff --git a/src/shell/top-bar/settings/fields/rpc-node/useRpcNodePingQuery.ts b/src/shell/top-bar/settings/fields/rpc-node/useRpcNodePingQuery.ts new file mode 100644 index 00000000000..c4662c9b20f --- /dev/null +++ b/src/shell/top-bar/settings/fields/rpc-node/useRpcNodePingQuery.ts @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { UseQueryResult } from '@tanstack/react-query'; +import { useQuery } from '@tanstack/react-query'; + +import type { RpcPingResult } from './utils'; +import { pingRpcNode } from './utils'; + +export function useRpcNodePingQuery(url: string | undefined): UseQueryResult<RpcPingResult> { + return useQuery({ + queryKey: [ 'RPC', 'custom-node-ping', { url } ], + queryFn: () => pingRpcNode(url ?? ''), + enabled: Boolean(url), + refetchOnMount: 'always', + retry: false, + }); +} diff --git a/src/shell/top-bar/settings/fields/rpc-node/utils.spec.ts b/src/shell/top-bar/settings/fields/rpc-node/utils.spec.ts new file mode 100644 index 00000000000..0dff9a01f3a --- /dev/null +++ b/src/shell/top-bar/settings/fields/rpc-node/utils.spec.ts @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import { getRpcNodeStatus, pingRpcNode, validateRpcUrl } from './utils'; + +describe('validateRpcUrl', () => { + it('accepts an https URL and an empty value', () => { + expect(validateRpcUrl('https://rpc.example.com/eth')).toBe(true); + expect(validateRpcUrl('')).toBe(true); + }); + + it('rejects other schemes and malformed values', () => { + expect(validateRpcUrl('http://rpc.example.com')).toBe('Invalid format'); + expect(validateRpcUrl('wss://rpc.example.com')).toBe('Invalid format'); + expect(validateRpcUrl('rpc.example.com')).toBe('Invalid format'); + expect(validateRpcUrl('https://')).toBe('Invalid format'); + }); +}); + +describe('pingRpcNode', () => { + const url = 'https://rpc.example.com'; + + beforeEach(() => { + fetchMock.resetMocks(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('posts eth_chainId with a 5s timeout and reports connected when the chain id matches', async() => { + const timeoutSpy = vi.spyOn(AbortSignal, 'timeout'); + fetchMock.mockResponseOnce(JSON.stringify({ jsonrpc: '2.0', id: 1, result: '0x1' })); + + expect(await pingRpcNode(url)).toEqual({ outcome: 'connected', chainId: '0x1' }); + + const [ requestUrl, init ] = fetchMock.mock.calls[0]; + expect(requestUrl).toBe(url); + expect(init?.method).toBe('POST'); + expect(JSON.parse(String(init?.body))).toMatchObject({ method: 'eth_chainId' }); + expect(timeoutSpy).toHaveBeenCalledWith(5_000); + expect(init?.signal).toBe(timeoutSpy.mock.results[0].value); + }); + + it('reports wrong-chain with the reported id when another chain answers', async() => { + fetchMock.mockResponseOnce(JSON.stringify({ jsonrpc: '2.0', id: 1, result: '0x89' })); + + expect(await pingRpcNode(url)).toEqual({ outcome: 'wrong-chain', chainId: '0x89' }); + }); + + it('reports unknown-chain for a 2xx answer without a hex chain id', async() => { + fetchMock.mockResponseOnce(JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: -32601, message: 'nope' } })); + expect(await pingRpcNode(url)).toEqual({ outcome: 'unknown-chain', chainId: undefined }); + + fetchMock.mockResponseOnce(JSON.stringify({ result: 'mainnet' })); + expect(await pingRpcNode(url)).toEqual({ outcome: 'unknown-chain', chainId: undefined }); + + fetchMock.mockResponseOnce(JSON.stringify({ result: [ '0x1' ] })); + expect(await pingRpcNode(url)).toEqual({ outcome: 'unknown-chain', chainId: undefined }); + + fetchMock.mockResponseOnce(JSON.stringify('0x1')); + expect(await pingRpcNode(url)).toEqual({ outcome: 'unknown-chain', chainId: undefined }); + + fetchMock.mockResponseOnce(JSON.stringify(null)); + expect(await pingRpcNode(url)).toEqual({ outcome: 'unknown-chain', chainId: undefined }); + + fetchMock.mockResponseOnce('<html/>'); + expect(await pingRpcNode(url)).toEqual({ outcome: 'unreachable', chainId: undefined }); + }); + + it('reports unreachable on an HTTP error or a network failure', async() => { + fetchMock.mockResponseOnce('', { status: 503 }); + expect(await pingRpcNode(url)).toEqual({ outcome: 'unreachable', chainId: undefined }); + + fetchMock.mockResponseOnce(JSON.stringify({ jsonrpc: '2.0', id: 1, result: '0x1' }), { status: 500 }); + expect(await pingRpcNode(url)).toEqual({ outcome: 'unreachable', chainId: undefined }); + + fetchMock.mockRejectOnce(new TypeError('Failed to fetch')); + expect(await pingRpcNode(url)).toEqual({ outcome: 'unreachable', chainId: undefined }); + }); +}); + +describe('getRpcNodeStatus', () => { + it('reports a healthy custom node as connected with a green plug and no alert', () => { + const status = getRpcNodeStatus('connected'); + expect(status.tag).toEqual({ label: 'Connected', colorPalette: 'green' }); + expect(status.nodeText).toBe('Using your custom node'); + expect(status.plug).toEqual({ icon: 'integration/full', color: 'green.500' }); + expect(status.alert).toBeUndefined(); + }); + + it('keeps the connected tag but warns with an orange plug on a chain mismatch', () => { + const status = getRpcNodeStatus('wrong-chain'); + expect(status.tag.label).toBe('Connected'); + expect(status.plug).toEqual({ icon: 'integration/full', color: 'orange.500' }); + expect(status.alert?.status).toBe('warning'); + expect(status.alert?.text).toMatch(/different network/); + }); + + it('informs with an orange plug when the chain cannot be identified', () => { + const status = getRpcNodeStatus('unknown-chain'); + expect(status.tag.label).toBe('Connected'); + expect(status.plug.color).toBe('orange.500'); + expect(status.alert?.status).toBe('info'); + expect(status.alert?.text).toMatch(/couldn't identify the network/); + }); + + it('reports a dead custom node as not responding with the connected plug in red', () => { + const status = getRpcNodeStatus('unreachable'); + expect(status.tag).toEqual({ label: 'Not responding', colorPalette: 'red' }); + expect(status.nodeText).toBe('Using your custom node'); + expect(status.plug).toEqual({ icon: 'integration/full', color: 'red.500' }); + expect(status.alert?.status).toBe('error'); + expect(status.alert?.text).toMatch(/isn't responding/); + }); + + it('shows a saved but unused node as disconnected on the default node', () => { + const status = getRpcNodeStatus('disconnected'); + expect(status.tag).toEqual({ label: 'Disconnected', colorPalette: 'gray' }); + expect(status.nodeText).toBe('Using the default node'); + expect(status.plug).toEqual({ icon: 'integration/partial', color: 'icon.secondary' }); + expect(status.alert).toBeUndefined(); + }); +}); + +describe('isRpcNodeSettingAvailable', () => { + async function isAvailable(envs: Array<[ string, string ]>): Promise<boolean> { + return withEnvs(envs, async() => { + const { isRpcNodeSettingAvailable } = await import('./utils'); + return isRpcNodeSettingAvailable(); + }); + } + + it('is available on a single-chain instance with a configured RPC URL', async() => { + expect(await isAvailable([])).toBe(true); + }); + + it('is hidden on multichain instances', async() => { + expect(await isAvailable(ENVS_MAP.multichain)).toBe(false); + }); + + it('is hidden when no RPC URL is configured', async() => { + expect(await isAvailable([ [ 'NEXT_PUBLIC_NETWORK_RPC_URL', '' ] ])).toBe(false); + }); +}); diff --git a/src/shell/top-bar/settings/fields/rpc-node/utils.ts b/src/shell/top-bar/settings/fields/rpc-node/utils.ts new file mode 100644 index 00000000000..1e4311cc14a --- /dev/null +++ b/src/shell/top-bar/settings/fields/rpc-node/utils.ts @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { CUSTOM_RPC_IN_USE_VALUE } from 'src/features/connect-wallet/utils/rpc-urls'; + +import config from 'src/config'; +import * as cookies from 'src/shared/storage/cookies'; +import type { IconName } from 'src/sprite/SpriteIcon'; + +import type { AlertProps } from 'src/toolkit/chakra/alert'; +import type { BadgeProps } from 'src/toolkit/chakra/badge'; +import { SECOND } from 'src/toolkit/utils/consts'; + +export type RpcPingOutcome = 'connected' | 'wrong-chain' | 'unknown-chain' | 'unreachable'; + +export interface RpcPingResult { + readonly outcome: RpcPingOutcome; + readonly chainId: string | undefined; +} + +export type RpcNodeState = RpcPingOutcome | 'disconnected'; + +export interface RpcNodeStatus { + readonly tag: { readonly label: string; readonly colorPalette: BadgeProps['colorPalette'] }; + readonly nodeText: string; + readonly plug: { readonly icon: IconName; readonly color: string }; + readonly alert: { readonly status: AlertProps['status']; readonly text: string } | undefined; +} + +// Stryker disable next-line ArithmeticOperator: evaluated at module load, before runtime mutant activation, so the timeout assertion cannot see it +const PING_TIMEOUT = 5 * SECOND; + +const HEX_CHAIN_ID_REGEXP = /^0x[0-9a-f]+$/i; + +export const RPC_URL_INVALID_MESSAGE = 'Invalid format'; + +export function validateRpcUrl(value: string): true | string { + if (value === '') { + return true; + } + + try { + return new URL(value).protocol === 'https:' || RPC_URL_INVALID_MESSAGE; + } catch { + return RPC_URL_INVALID_MESSAGE; + } +} + +export interface SavedRpcNode { + readonly url: string | undefined; + readonly isInUse: boolean; +} + +export function getSavedRpcNode(serverCookies?: string): SavedRpcNode { + const url = cookies.get(cookies.NAMES.CUSTOM_RPC_URL, serverCookies); + return { + url: url || undefined, + isInUse: Boolean(url) && cookies.get(cookies.NAMES.CUSTOM_RPC_IN_USE, serverCookies) === CUSTOM_RPC_IN_USE_VALUE, + }; +} + +export function isRpcNodeSettingAvailable(): boolean { + return !config.features.multichain.isEnabled && config.chain.rpcUrls.length > 0; +} + +function readChainId(body: unknown): string | undefined { + if (typeof body !== 'object' || body === null || !('result' in body)) { + return; + } + + const result = body.result; + + return typeof result === 'string' && HEX_CHAIN_ID_REGEXP.test(result) ? result : undefined; +} + +export async function pingRpcNode(url: string): Promise<RpcPingResult> { + try { + const response = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_chainId', params: [] }), + signal: AbortSignal.timeout(PING_TIMEOUT), + }); + + if (!response.ok) { + return { outcome: 'unreachable', chainId: undefined }; + } + + const chainId = readChainId(await response.json()); + + if (chainId === undefined) { + return { outcome: 'unknown-chain', chainId: undefined }; + } + + const outcome = String(parseInt(chainId, 16)) === config.chain.id ? 'connected' : 'wrong-chain'; + + return { outcome, chainId }; + } catch { + return { outcome: 'unreachable', chainId: undefined }; + } +} + +const WRONG_CHAIN_TEXT = 'This RPC belongs to a different network. Make sure you\'re using the correct RPC URL to avoid displaying incorrect data.'; +const UNKNOWN_CHAIN_TEXT = 'We couldn\'t identify the network for this RPC. Please verify the RPC URL and make sure it matches your selected network.'; +const UNREACHABLE_TEXT = 'This RPC node isn\'t responding. Check the URL and try again.'; + +const CUSTOM_NODE_TEXT = 'Using your custom node'; + +export function getRpcNodeStatus(state: RpcNodeState): RpcNodeStatus { + switch (state) { + case 'connected': + return { + tag: { label: 'Connected', colorPalette: 'green' }, + nodeText: CUSTOM_NODE_TEXT, + plug: { icon: 'integration/full', color: 'green.500' }, + alert: undefined, + }; + case 'wrong-chain': + return { + tag: { label: 'Connected', colorPalette: 'green' }, + nodeText: CUSTOM_NODE_TEXT, + plug: { icon: 'integration/full', color: 'orange.500' }, + alert: { status: 'warning', text: WRONG_CHAIN_TEXT }, + }; + case 'unknown-chain': + return { + tag: { label: 'Connected', colorPalette: 'green' }, + nodeText: CUSTOM_NODE_TEXT, + plug: { icon: 'integration/full', color: 'orange.500' }, + alert: { status: 'info', text: UNKNOWN_CHAIN_TEXT }, + }; + case 'unreachable': + return { + tag: { label: 'Not responding', colorPalette: 'red' }, + nodeText: CUSTOM_NODE_TEXT, + plug: { icon: 'integration/full', color: 'red.500' }, + alert: { status: 'error', text: UNREACHABLE_TEXT }, + }; + case 'disconnected': + return { + tag: { label: 'Disconnected', colorPalette: 'gray' }, + nodeText: 'Using the default node', + plug: { icon: 'integration/partial', color: 'icon.secondary' }, + alert: undefined, + }; + } +} diff --git a/src/shell/top-bar/settings/time-format/SettingsLocalTime.tsx b/src/shell/top-bar/settings/fields/time-format/SettingsLocalTime.tsx similarity index 91% rename from src/shell/top-bar/settings/time-format/SettingsLocalTime.tsx rename to src/shell/top-bar/settings/fields/time-format/SettingsLocalTime.tsx index 4fafd5a305f..c001cbdb47b 100644 --- a/src/shell/top-bar/settings/time-format/SettingsLocalTime.tsx +++ b/src/shell/top-bar/settings/fields/time-format/SettingsLocalTime.tsx @@ -5,7 +5,7 @@ import React from 'react'; import type { SwitchProps } from 'src/toolkit/chakra/switch'; import { Switch } from 'src/toolkit/chakra/switch'; -import { useSettingsContext } from '../context'; +import { useSettingsContext } from '../../context'; const SettingsLocalTime = (props: SwitchProps) => { const settingsContext = useSettingsContext(); @@ -24,7 +24,7 @@ const SettingsLocalTime = (props: SwitchProps) => { direction="rtl" justifyContent="space-between" w="100%" - minH="34px" + minH="32px" { ...props } > Local time format diff --git a/src/shell/top-bar/settings/time-format/utils.ts b/src/shell/top-bar/settings/fields/time-format/utils.ts similarity index 100% rename from src/shell/top-bar/settings/time-format/utils.ts rename to src/shell/top-bar/settings/fields/time-format/utils.ts diff --git a/src/shell/top-bar/settings/ident-icon/SettingsIdentIcon.tsx b/src/shell/top-bar/settings/ident-icon/SettingsIdentIcon.tsx deleted file mode 100644 index 6e3cd7852f0..00000000000 --- a/src/shell/top-bar/settings/ident-icon/SettingsIdentIcon.tsx +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box, Flex } from '@chakra-ui/react'; -import React from 'react'; - -import config from 'src/config'; -import * as cookies from 'src/shared/storage/cookies'; - -import SettingsSample from '../SettingsSample'; -import { IDENTICONS } from './utils'; - -const SettingsIdentIcon = () => { - const [ activeId, setActiveId ] = React.useState<string>(); - - React.useEffect(() => { - const initialId = cookies.get(cookies.NAMES.ADDRESS_IDENTICON_TYPE) || config.slices.address.identiconType; - setActiveId(initialId); - }, []); - - const handleSelect = React.useCallback((event: React.MouseEvent<HTMLDivElement>) => { - event.stopPropagation(); - - const id = event.currentTarget.getAttribute('data-value'); - - if (!id) { - return; - } - - cookies.set(cookies.NAMES.ADDRESS_IDENTICON_TYPE, id); - window.location.reload(); - }, []); - - const activeIdenticon = IDENTICONS.find((identicon) => identicon.id === activeId); - - return ( - <div> - <Box fontWeight={ 600 }>Address settings</Box> - <Box color="text.secondary" mt={ 1 } mb={ 2 }>{ activeIdenticon?.label }</Box> - <Flex> - { IDENTICONS.map((identicon) => ( - <SettingsSample - key={ identicon.id } - label={ identicon.label } - value={ identicon.id } - bg={ identicon.sampleBg } - isActive={ identicon.id === activeId } - onClick={ handleSelect } - /> - )) } - </Flex> - </div> - ); -}; - -export default React.memo(SettingsIdentIcon); diff --git a/src/shell/top-bar/settings/modal/SettingsModal.tsx b/src/shell/top-bar/settings/modal/SettingsModal.tsx new file mode 100644 index 00000000000..e1c2f6fef1b --- /dev/null +++ b/src/shell/top-bar/settings/modal/SettingsModal.tsx @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { DialogBody, DialogContent, DialogHeader, DialogRoot } from 'src/toolkit/chakra/dialog'; + +import type { SettingsModalTabId } from './registry'; +import { getVisibleSettingsModalTabs } from './registry'; +import SettingsModalTabs from './SettingsModalTabs'; + +interface Props { + targetTab: SettingsModalTabId | undefined; + onClose: () => void; +} + +const SettingsModal = ({ targetTab, onClose }: Props) => { + const tabs = React.useMemo(() => getVisibleSettingsModalTabs(), []); + + const handleOpenChange = React.useCallback(({ open }: { open: boolean }) => { + if (!open) { + onClose(); + } + }, [ onClose ]); + + return ( + <DialogRoot open onOpenChange={ handleOpenChange } size={{ lgDown: 'full', lg: 'md' }}> + <DialogContent h={{ lg: '560px' }}> + <DialogHeader mb={{ base: 3, lg: 6 }}>Advanced site settings</DialogHeader> + <DialogBody> + <SettingsModalTabs tabs={ tabs } targetTab={ targetTab }/> + </DialogBody> + </DialogContent> + </DialogRoot> + ); +}; + +export default React.memo(SettingsModal); diff --git a/src/shell/top-bar/settings/modal/SettingsModalTabs.tsx b/src/shell/top-bar/settings/modal/SettingsModalTabs.tsx new file mode 100644 index 00000000000..019b72b73d9 --- /dev/null +++ b/src/shell/top-bar/settings/modal/SettingsModalTabs.tsx @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import useIsMobile from 'src/shared/hooks/useIsMobile'; +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { TabsContent, TabsList, TabsRoot, TabsTrigger } from 'src/toolkit/chakra/tabs'; + +import type { SettingsModalTab, SettingsModalTabId } from './registry'; + +interface Props { + tabs: Array<SettingsModalTab>; + targetTab: SettingsModalTabId | undefined; +} + +const SettingsModalTabs = ({ tabs, targetTab }: Props) => { + const isMobile = useIsMobile(); + const defaultTab = tabs.find((tab) => tab.id === targetTab) ?? tabs[0]; + + if (tabs.length === 1 && defaultTab) { + return <defaultTab.Content/>; + } + + const contents = tabs.map((tab) => ( + <TabsContent key={ tab.id } value={ tab.id } ps={ 0 } pt={{ base: 6, lg: 2 }} flexGrow={ 1 } minW={ 0 } overflowY="auto" overflowX="hidden"> + <tab.Content/> + </TabsContent> + )); + + if (isMobile) { + return ( + <TabsRoot defaultValue={ defaultTab?.id } orientation="horizontal" variant="secondary" size="sm"> + <TabsList> + { tabs.map((tab) => ( + <TabsTrigger key={ tab.id } value={ tab.id }>{ tab.title }</TabsTrigger> + )) } + </TabsList> + { contents } + </TabsRoot> + ); + } + + return ( + <TabsRoot defaultValue={ defaultTab?.id } orientation="vertical" variant="solid" size="md" gap={ 8 } h="100%"> + <TabsList w="180px" gap={ 1 } flexShrink={ 0 }> + { tabs.map((tab) => ( + <TabsTrigger key={ tab.id } value={ tab.id } justifyContent="flex-start" fontWeight="medium" px={ 3 } textStyle="sm" gap={ 2 }> + <SpriteIcon name={ tab.icon } boxSize={ 5 }/> + { tab.title } + </TabsTrigger> + )) } + </TabsList> + { contents } + </TabsRoot> + ); +}; + +export default React.memo(SettingsModalTabs); diff --git a/src/shell/top-bar/settings/modal/context.tsx b/src/shell/top-bar/settings/modal/context.tsx new file mode 100644 index 00000000000..964bbe2848e --- /dev/null +++ b/src/shell/top-bar/settings/modal/context.tsx @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import dynamic from 'next/dynamic'; +import React from 'react'; + +import type { SettingsModalTabId } from './registry'; + +const SettingsModal = dynamic(() => import('./SettingsModal'), { ssr: false }); + +type SettingsModalState = + | { isOpen: false } | + { isOpen: true; targetTab: SettingsModalTabId | undefined }; + +interface TSettingsModalContext { + state: SettingsModalState; + open: (targetTab?: SettingsModalTabId) => void; + close: () => void; +} + +const CLOSED: SettingsModalState = { isOpen: false }; + +const SettingsModalContext = React.createContext<TSettingsModalContext | null>(null); + +interface Props { + children: React.ReactNode; +} + +export function SettingsModalContextProvider({ children }: Props) { + const [ state, setState ] = React.useState<SettingsModalState>(CLOSED); + + const open = React.useCallback((targetTab?: SettingsModalTabId) => { + setState({ isOpen: true, targetTab }); + }, []); + + const close = React.useCallback(() => { + setState(CLOSED); + }, []); + + const value = React.useMemo(() => ({ state, open, close }), [ state, open, close ]); + + return ( + <SettingsModalContext.Provider value={ value }> + { children } + { state.isOpen && <SettingsModal targetTab={ state.targetTab } onClose={ close }/> } + </SettingsModalContext.Provider> + ); +} + +export function useSettingsModalContext(): TSettingsModalContext | null { + return React.useContext(SettingsModalContext); +} diff --git a/src/shell/top-bar/settings/modal/registry.spec.ts b/src/shell/top-bar/settings/modal/registry.spec.ts new file mode 100644 index 00000000000..8ab4fc69bf6 --- /dev/null +++ b/src/shell/top-bar/settings/modal/registry.spec.ts @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import type * as registryModule from './registry'; + +async function loadRegistry(envs: Array<[ string, string ]>): Promise<typeof registryModule> { + return withEnvs(envs, async() => import('./registry')); +} + +async function visibleTabIds(envs: Array<[ string, string ]>): Promise<Array<string>> { + const { getVisibleSettingsModalTabs } = await loadRegistry(envs); + return getVisibleSettingsModalTabs().map((tab) => tab.id); +} + +describe('SETTINGS_MODAL_TABS', () => { + it('holds exactly the General and Custom RPC tabs', async() => { + const { SETTINGS_MODAL_TABS } = await loadRegistry([]); + expect(SETTINGS_MODAL_TABS.map((tab) => [ tab.id, tab.title, tab.icon ])).toEqual([ + [ 'general', 'General', 'gear' ], + [ 'rpc-node', 'Custom RPC', 'link' ], + ]); + }); +}); + +describe('getVisibleSettingsModalTabs', () => { + it('lists General first and Custom RPC second when an RPC URL is configured', async() => { + expect(await visibleTabIds([])).toEqual([ 'general', 'rpc-node' ]); + }); + + it('keeps General and hides Custom RPC on multichain instances', async() => { + expect(await visibleTabIds(ENVS_MAP.multichain)).toEqual([ 'general' ]); + }); + + it('keeps General and hides Custom RPC when no RPC URL is configured', async() => { + expect(await visibleTabIds([ [ 'NEXT_PUBLIC_NETWORK_RPC_URL', '' ] ])).toEqual([ 'general' ]); + }); +}); diff --git a/src/shell/top-bar/settings/modal/registry.ts b/src/shell/top-bar/settings/modal/registry.ts new file mode 100644 index 00000000000..db8bdf0b6e2 --- /dev/null +++ b/src/shell/top-bar/settings/modal/registry.ts @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type React from 'react'; + +import type { IconName } from 'src/sprite/SpriteIcon'; + +import { isRpcNodeSettingAvailable } from '../fields/rpc-node/utils'; +import SettingsModalGeneralTab from './tabs/SettingsModalGeneralTab'; +import SettingsModalRpcNodeTab from './tabs/SettingsModalRpcNodeTab'; + +export type SettingsModalTabId = 'general' | 'rpc-node'; + +export interface SettingsModalTab { + readonly id: SettingsModalTabId; + readonly title: string; + readonly icon: IconName; + readonly Content: React.ComponentType; + readonly isVisible: () => boolean; +} + +export const SETTINGS_MODAL_TABS: ReadonlyArray<SettingsModalTab> = [ + { + id: 'general', + title: 'General', + icon: 'gear', + Content: SettingsModalGeneralTab, + isVisible: () => true, + }, + { + id: 'rpc-node', + title: 'Custom RPC', + icon: 'link', + Content: SettingsModalRpcNodeTab, + isVisible: isRpcNodeSettingAvailable, + }, +]; + +export function getVisibleSettingsModalTabs(): Array<SettingsModalTab> { + return SETTINGS_MODAL_TABS.filter((tab) => tab.isVisible()); +} diff --git a/src/shell/top-bar/settings/modal/tabs/SettingsModalGeneralTab.tsx b/src/shell/top-bar/settings/modal/tabs/SettingsModalGeneralTab.tsx new file mode 100644 index 00000000000..dc49ef3d5ec --- /dev/null +++ b/src/shell/top-bar/settings/modal/tabs/SettingsModalGeneralTab.tsx @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { VStack } from '@chakra-ui/react'; +import React from 'react'; + +import useIsMobile from 'src/shared/hooks/useIsMobile'; + +import SettingsColorTheme from '../../fields/color-theme/SettingsColorTheme'; +import SettingsIdentIcon from '../../fields/ident-icon/SettingsIdentIcon'; +import SettingsAddressFormat from '../../fields/SettingsAddressFormat'; +import SettingsPoorReputationTokens from '../../fields/SettingsPoorReputationTokens'; +import SettingsScamTokens from '../../fields/SettingsScamTokens'; +import SettingsLocalTime from '../../fields/time-format/SettingsLocalTime'; +import SettingsSectionTitle from '../../parts/SettingsSectionTitle'; + +const SettingsModalGeneralTab = () => { + const isMobile = useIsMobile(); + + return ( + <> + { !isMobile && <SettingsSectionTitle title="General site settings" variant="modal"/> } + <VStack gap={ 6 } alignItems="stretch"> + <SettingsColorTheme variant="modal"/> + <SettingsIdentIcon variant="modal"/> + <SettingsAddressFormat variant="modal"/> + <SettingsScamTokens/> + <SettingsPoorReputationTokens/> + <SettingsLocalTime/> + </VStack> + </> + ); +}; + +export default React.memo(SettingsModalGeneralTab); diff --git a/src/shell/top-bar/settings/modal/tabs/SettingsModalRpcNodeTab.tsx b/src/shell/top-bar/settings/modal/tabs/SettingsModalRpcNodeTab.tsx new file mode 100644 index 00000000000..cfe9eb34425 --- /dev/null +++ b/src/shell/top-bar/settings/modal/tabs/SettingsModalRpcNodeTab.tsx @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Text } from '@chakra-ui/react'; +import React from 'react'; + +import useIsMobile from 'src/shared/hooks/useIsMobile'; + +import SettingsRpcNode from '../../fields/rpc-node/SettingsRpcNode'; +import SettingsSectionTitle from '../../parts/SettingsSectionTitle'; + +// eslint-disable-next-line max-len +const DESCRIPTION = 'Contract reads and writes made from your browser go through a default public RPC node. Add your own node url if the default is slow, rate-limited, or you want more privacy. Blocks, transactions, balances, and other indexed data still come from the Blockscout API. HTTPS only. To go back to the default, clear the field and save.'; + +const SettingsModalRpcNodeTab = () => { + const isMobile = useIsMobile(); + return ( + <> + { isMobile ? + <Text textStyle="sm" mb={ 3 }>{ DESCRIPTION }</Text> : + <SettingsSectionTitle title="RPC node" description={ DESCRIPTION } variant="modal"/> } + <SettingsRpcNode/> + </> + ); +}; + +export default React.memo(SettingsModalRpcNodeTab); diff --git a/src/shell/top-bar/settings/SettingsSample.tsx b/src/shell/top-bar/settings/parts/SettingsSample.tsx similarity index 86% rename from src/shell/top-bar/settings/SettingsSample.tsx rename to src/shell/top-bar/settings/parts/SettingsSample.tsx index f44bd617b2c..8d6ff3bf9dd 100644 --- a/src/shell/top-bar/settings/SettingsSample.tsx +++ b/src/shell/top-bar/settings/parts/SettingsSample.tsx @@ -5,28 +5,29 @@ import React from 'react'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import type { SampleBg } from '../fields/color-theme/config'; + interface Props { onClick?: (event: React.MouseEvent<HTMLDivElement>) => void; isActive: boolean; - bg: string; + bg: SampleBg; value: string; label: string; } const SettingsSample = ({ label, value, bg, onClick, isActive }: Props) => { const bgColor = { base: 'white', _dark: 'gray.900' }; - const activeBgColor = { base: 'blue.50', _dark: 'whiteAlpha.100' }; const activeBorderColor = { base: 'blackAlpha.800', _dark: 'gray.50' }; return ( - <Box p="9px" bgColor={ isActive ? activeBgColor : 'transparent' } borderRadius="base"> + <Box p="9px" bgColor={ isActive ? 'selected.control.bg' : 'transparent' } borderRadius="base"> <Tooltip content={ label }> <Box bg={ bg } boxSize="22px" borderRadius="full" borderWidth="1px" - borderColor={ isActive ? activeBgColor : bgColor } + borderColor={ bgColor } position="relative" cursor="pointer" _before={{ diff --git a/src/shell/top-bar/settings/parts/SettingsSamplesRow.tsx b/src/shell/top-bar/settings/parts/SettingsSamplesRow.tsx new file mode 100644 index 00000000000..5bb1c8e9951 --- /dev/null +++ b/src/shell/top-bar/settings/parts/SettingsSamplesRow.tsx @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Box, Flex } from '@chakra-ui/react'; +import React from 'react'; + +import type { SettingsControlVariant } from '../types'; + +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; + +import SettingsSectionTitle from './SettingsSectionTitle'; + +interface Props { + variant: SettingsControlVariant; + title: string; + mobileTitle: string; + value: string | undefined; + children: React.ReactNode; +} + +const SettingsSamplesRow = ({ variant, title, mobileTitle, value, children }: Props) => { + if (variant === 'modal') { + return ( + <Flex alignItems="center" justifyContent="space-between" gap={{ base: 2, lg: 3 }} minH="48px"> + <Box minW={ 0 } textStyle="sm"> + <Box fontWeight="medium" hideBelow="lg">{ title }</Box> + <Box fontWeight="medium" hideFrom="lg">{ mobileTitle }</Box> + { value && <Truncate value={ value } color="text.secondary" type="end" maxW="100%" mt={ 1 }/> } + </Box> + <Flex gap={{ base: 1, lg: 2 }} flexShrink={ 0 }>{ children }</Flex> + </Flex> + ); + } + + return ( + <div> + <SettingsSectionTitle variant={ variant } title={ title }/> + <Box color="text.secondary" mt={ 1 } mb={ 2 }>{ value }</Box> + <Flex>{ children }</Flex> + </div> + ); +}; + +export default React.memo(SettingsSamplesRow); diff --git a/src/shell/top-bar/settings/parts/SettingsSectionTitle.tsx b/src/shell/top-bar/settings/parts/SettingsSectionTitle.tsx new file mode 100644 index 00000000000..c9942712299 --- /dev/null +++ b/src/shell/top-bar/settings/parts/SettingsSectionTitle.tsx @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Box, Text, VStack } from '@chakra-ui/react'; +import React from 'react'; + +import type { SettingsControlVariant } from '../types'; + +import { Heading } from 'src/toolkit/chakra/heading'; + +interface Props { + variant: SettingsControlVariant; + title: string; + description?: string; +} + +const SettingsSectionTitle = ({ variant, title, description }: Props) => { + return variant === 'modal' ? ( + <VStack alignItems="stretch" mb={{ base: 3, lg: 6 }}> + <Heading level="3">{ title }</Heading> + { description && <Text textStyle="sm">{ description }</Text> } + </VStack> + ) : ( + <Box fontWeight="semibold">{ title }</Box> + ); +}; + +export default React.memo(SettingsSectionTitle); diff --git a/src/shell/top-bar/settings/types.ts b/src/shell/top-bar/settings/types.ts new file mode 100644 index 00000000000..a01d85fbb3d --- /dev/null +++ b/src/shell/top-bar/settings/types.ts @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +export type SettingsControlVariant = 'popover' | 'modal'; diff --git a/src/slices/address/components/entity/AddressEntity.pw.tsx b/src/slices/address/components/entity/AddressEntity.pw.tsx index d3db89aefa4..11ecc20b128 100644 --- a/src/slices/address/components/entity/AddressEntity.pw.tsx +++ b/src/slices/address/components/entity/AddressEntity.pw.tsx @@ -290,8 +290,17 @@ test('hover', async({ page, render }) => { </AddressHighlightProvider>, ); - await component.getByText(addressParamMock.hash.slice(0, 4)).hover(); + const entityText = component.getByText(addressParamMock.hash.slice(0, 4)); + await entityText.hover(); await page.getByText(addressParamMock.hash).waitFor({ state: 'visible' }); + + // In this tiny viewport the tooltip's first, not yet positioned frame at the page's top-left covers the cursor. + // If the highlight delay expires during that frame, the entity is not ':hover' and the highlight is skipped, + // so the pointer re-enters the entity once the tooltip is positioned (it stays open, see closeDelay in pw). + await page.mouse.move(0, 0); + await entityText.hover(); + await expect(component.locator(`[data-hash="${ addressParamMock.hash }"]`)).toHaveClass(/address-entity_highlighted/); + await expect(page).toHaveScreenshot(); }); diff --git a/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_loading-with-alias-1.png b/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_loading-with-alias-1.png index 8eaea70e138..58cbc50195e 100644 Binary files a/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_loading-with-alias-1.png and b/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_loading-with-alias-1.png differ diff --git a/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_loading-without-alias-1.png b/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_loading-without-alias-1.png index 085369deae3..5b6a4a92650 100644 Binary files a/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_loading-without-alias-1.png and b/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_loading-without-alias-1.png differ diff --git a/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-with-multiple-implementations-1.png b/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-with-multiple-implementations-1.png index 7796eb0f638..45138edfed0 100644 Binary files a/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-with-multiple-implementations-1.png and b/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-with-multiple-implementations-1.png differ diff --git a/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-without-any-name-1.png b/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-without-any-name-1.png index 83054ac5c31..f09a47c0aec 100644 Binary files a/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-without-any-name-1.png and b/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-without-any-name-1.png differ diff --git a/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-without-implementation-name-1.png b/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-without-implementation-name-1.png index 68befbba522..22cc696549c 100644 Binary files a/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-without-implementation-name-1.png and b/src/slices/address/components/entity/__screenshots__/AddressEntity.pw.tsx_default_proxy-contract-without-implementation-name-1.png differ diff --git a/src/slices/address/components/from-to/AddressFromTo.tsx b/src/slices/address/components/from-to/AddressFromTo.tsx index 7cdc807ee23..b9faef5d70d 100644 --- a/src/slices/address/components/from-to/AddressFromTo.tsx +++ b/src/slices/address/components/from-to/AddressFromTo.tsx @@ -26,6 +26,7 @@ interface Props { tokenSymbol?: string; truncation?: EntityProps['truncation']; noIcon?: boolean; + plainArrow?: boolean; } const AddressFromTo = ({ @@ -33,7 +34,13 @@ const AddressFromTo = ({ to, current, mode: modeProp, - className, isLoading, tokenHash = '', tokenSymbol = '', noIcon }: Props) => { + className, + isLoading, + tokenHash = '', + tokenSymbol = '', + noIcon, + plainArrow, +}: Props) => { const mode = useBreakpointValue( { base: (typeof modeProp === 'object' && 'base' in modeProp ? modeProp.base : modeProp), @@ -74,7 +81,7 @@ const AddressFromTo = ({ <Flex alignItems="center" columnGap={ 2 }> <AddressFromToIcon isLoading={ isLoading } - type={ getTxCourseType(from.hash, to?.hash, current) } + type={ plainArrow ? 'unspecified' : getTxCourseType(from.hash, to?.hash, current) } transform="rotate(90deg)" /> <EntityFrom @@ -130,7 +137,7 @@ const AddressFromTo = ({ /> <AddressFromToIcon isLoading={ isLoading } - type={ getTxCourseType(from.hash, to?.hash, current) } + type={ plainArrow ? 'unspecified' : getTxCourseType(from.hash, to?.hash, current) } /> { to && ( <EntityTo diff --git a/src/slices/address/components/from-to/AddressFromToIcon.tsx b/src/slices/address/components/from-to/AddressFromToIcon.tsx index b48ba91a875..64f440b7f5d 100644 --- a/src/slices/address/components/from-to/AddressFromToIcon.tsx +++ b/src/slices/address/components/from-to/AddressFromToIcon.tsx @@ -18,16 +18,16 @@ interface Props { const AddressFromToIcon = ({ isLoading, type, className }: Props) => { const styles = { 'in': { - color: { _light: 'green.500', _dark: 'green.200' }, - bgColor: { _light: 'green.50', _dark: 'green.800' }, + color: 'badge.teal.fg', + bgColor: 'badge.teal.bg', }, out: { - color: { _light: 'yellow.600', _dark: 'yellow.500' }, - bgColor: { _light: 'orange.50', _dark: 'yellow.900' }, + color: 'badge.yellow.fg', + bgColor: 'badge.yellow.bg', }, self: { - color: { _light: 'blackAlpha.400', _dark: 'whiteAlpha.400' }, - bgColor: { _light: 'blackAlpha.50', _dark: 'whiteAlpha.50' }, + color: 'badge.gray.fg', + bgColor: 'badge.gray.bg', }, unspecified: { color: 'icon.primary', diff --git a/src/slices/address/components/from-to/AddressFromToTag.tsx b/src/slices/address/components/from-to/AddressFromToTag.tsx new file mode 100644 index 00000000000..c33cbeb2409 --- /dev/null +++ b/src/slices/address/components/from-to/AddressFromToTag.tsx @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { TxCourseType } from 'src/slices/address/utils/tx'; + +import { Badge, type BadgeProps } from 'src/toolkit/chakra/badge'; + +const TAGS = { + 'in': { text: 'In', colorPalette: 'teal' as const }, + out: { text: 'Out', colorPalette: 'yellow' as const }, + self: { text: 'Self', colorPalette: 'gray' as const }, +}; + +interface Props extends BadgeProps { + readonly type: Exclude<TxCourseType, 'unspecified'>; + readonly isLoading?: boolean; +} + +const AddressFromToTag = ({ type, isLoading, ...rest }: Props) => { + const { text, colorPalette } = TAGS[type]; + + return ( + <Badge + loading={ isLoading } + colorPalette={ colorPalette } + minW={ 10 } + justifyContent="center" + { ...rest } + > + { text } + </Badge> + ); +}; + +export default React.memo(AddressFromToTag); diff --git a/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_incoming-txn-1.png b/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_incoming-txn-1.png index 525f5e92a2a..dd6bad37aac 100644 Binary files a/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_incoming-txn-1.png and b/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_incoming-txn-1.png differ diff --git a/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_loading-state-1.png b/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_loading-state-1.png index a6a799e8543..d874b138386 100644 Binary files a/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_loading-state-1.png and b/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_loading-state-1.png differ diff --git a/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_outgoing-txn-1.png b/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_outgoing-txn-1.png index 3bb1b3ab8b4..b9148231ec7 100644 Binary files a/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_outgoing-txn-1.png and b/src/slices/address/components/from-to/__screenshots__/AddressFromTo.pw.tsx_default_outgoing-txn-1.png differ diff --git a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_in-txn-type-dark-mode-1.png b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_in-txn-type-dark-mode-1.png index 3281fd2758f..c2720ace036 100644 Binary files a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_in-txn-type-dark-mode-1.png and b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_in-txn-type-dark-mode-1.png differ diff --git a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_out-txn-type-dark-mode-1.png b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_out-txn-type-dark-mode-1.png index 284e76fecc6..42b1c3f00d5 100644 Binary files a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_out-txn-type-dark-mode-1.png and b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_out-txn-type-dark-mode-1.png differ diff --git a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_self-txn-type-dark-mode-1.png b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_self-txn-type-dark-mode-1.png index 75893d1870f..0d3daf733eb 100644 Binary files a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_self-txn-type-dark-mode-1.png and b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_self-txn-type-dark-mode-1.png differ diff --git a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_unspecified-txn-type-dark-mode-1.png b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_unspecified-txn-type-dark-mode-1.png index fc9325bfc38..c12328375d5 100644 Binary files a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_unspecified-txn-type-dark-mode-1.png and b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_dark-color-mode_unspecified-txn-type-dark-mode-1.png differ diff --git a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_in-txn-type-dark-mode-1.png b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_in-txn-type-dark-mode-1.png index 13ce62772e0..8c17d7fd297 100644 Binary files a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_in-txn-type-dark-mode-1.png and b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_in-txn-type-dark-mode-1.png differ diff --git a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_out-txn-type-dark-mode-1.png b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_out-txn-type-dark-mode-1.png index cb3e2ba1403..8033971d1d4 100644 Binary files a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_out-txn-type-dark-mode-1.png and b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_out-txn-type-dark-mode-1.png differ diff --git a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_self-txn-type-dark-mode-1.png b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_self-txn-type-dark-mode-1.png index a0ff9b65a48..bd829d6ea14 100644 Binary files a/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_self-txn-type-dark-mode-1.png and b/src/slices/address/components/from-to/__screenshots__/AddressFromToIcon.pw.tsx_default_self-txn-type-dark-mode-1.png differ diff --git a/src/slices/address/contexts/address-highlight.tsx b/src/slices/address/contexts/address-highlight.tsx index a533a034821..250b33cd6d1 100644 --- a/src/slices/address/contexts/address-highlight.tsx +++ b/src/slices/address/contexts/address-highlight.tsx @@ -11,36 +11,44 @@ interface TAddressHighlightContext { onMouseLeave: (event: React.MouseEvent) => void; } +const HIGHLIGHTED_CLASS = 'address-entity_highlighted'; + export const AddressHighlightContext = React.createContext<TAddressHighlightContext | null>(null); export function AddressHighlightProvider({ children }: AddressHighlightProviderProps) { const timeoutId = React.useRef<number | null>(null); - const hashRef = React.useRef<string | null>(null); + + const clearHighlightTimeout = React.useCallback(() => { + typeof timeoutId.current === 'number' && window.clearTimeout(timeoutId.current); + }, []); const onMouseEnter = React.useCallback((event: React.MouseEvent) => { - const hash = event.currentTarget.getAttribute('data-hash'); + const target = event.currentTarget; + const hash = target.getAttribute('data-hash'); if (hash) { - hashRef.current = hash; + clearHighlightTimeout(); timeoutId.current = window.setTimeout(() => { + // A lazily mounted tooltip swaps the DOM node under the cursor right after the first hover, + // and the browser may never dispatch 'mouseleave' if the pointer exits before it re-targets. + if (!target.matches(':hover')) { + return; + } // for better performance we update DOM-nodes directly bypassing React reconciliation - const nodes = window.document.querySelectorAll(`[data-hash="${ hashRef.current }"]`); + const nodes = window.document.querySelectorAll(`[data-hash="${ hash }"]`); for (const node of nodes) { - node.classList.add('address-entity_highlighted'); + node.classList.add(HIGHLIGHTED_CLASS); } }, 100); } - }, []); + }, [ clearHighlightTimeout ]); const onMouseLeave = React.useCallback(() => { - if (hashRef.current) { - const nodes = window.document.querySelectorAll(`[data-hash="${ hashRef.current }"]`); - for (const node of nodes) { - node.classList.remove('address-entity_highlighted'); - } - hashRef.current = null; + const nodes = window.document.querySelectorAll(`.${ HIGHLIGHTED_CLASS }`); + for (const node of nodes) { + node.classList.remove(HIGHLIGHTED_CLASS); } - typeof timeoutId.current === 'number' && window.clearTimeout(timeoutId.current); - }, []); + clearHighlightTimeout(); + }, [ clearHighlightTimeout ]); const value = React.useMemo(() => { return { @@ -50,10 +58,8 @@ export function AddressHighlightProvider({ children }: AddressHighlightProviderP }, [ onMouseEnter, onMouseLeave ]); React.useEffect(() => { - return () => { - typeof timeoutId.current === 'number' && window.clearTimeout(timeoutId.current); - }; - }, []); + return clearHighlightTimeout; + }, [ clearHighlightTimeout ]); return ( <AddressHighlightContext.Provider value={ value }> diff --git a/src/slices/address/hooks/useCheckAddressFormat.ts b/src/slices/address/hooks/useCheckAddressFormat.ts index 628660d85b9..49c68a16f8a 100644 --- a/src/slices/address/hooks/useCheckAddressFormat.ts +++ b/src/slices/address/hooks/useCheckAddressFormat.ts @@ -1,29 +1,23 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import { fromBech32Address, isBech32Address } from 'src/slices/address/utils/bech32'; import config from 'src/config'; +import { useRouter } from 'src/shared/router/useRouter'; export default function useCheckAddressFormat(hash: string) { const router = useRouter(); const hasBech32Format = config.slices.address.hashFormat.availableFormats.includes('bech32') && isBech32Address(hash); - const [ isLoading, setIsLoading ] = React.useState(hasBech32Format); + const base16Hash = hasBech32Format ? fromBech32Address(hash) : hash; + const needsRedirect = base16Hash !== hash; React.useEffect(() => { - if (!isLoading) { - return; - } - - const base16Hash = fromBech32Address(hash); - if (base16Hash !== hash) { + if (needsRedirect) { router.replace({ pathname: '/address/[hash]', query: { ...router.query, hash: base16Hash } }); - } else { - setIsLoading(false); } - }, [ hash, isLoading, router ]); + }, [ base16Hash, needsRedirect, router ]); - return isLoading; + return needsRedirect; } diff --git a/src/slices/address/pages/details/Address.pw.tsx b/src/slices/address/pages/details/Address.pw.tsx index bb4deddd1d2..940626be5d3 100644 --- a/src/slices/address/pages/details/Address.pw.tsx +++ b/src/slices/address/pages/details/Address.pw.tsx @@ -5,6 +5,9 @@ import * as addressMock from 'src/slices/address/mocks/address'; import * as addressParamMock from 'src/slices/address/mocks/address-param'; import * as addressCountersMock from 'src/slices/address/mocks/counters'; import * as addressTabCountersMock from 'src/slices/address/mocks/tab-counters'; +import * as statsMock from 'src/slices/chain/stats/mocks'; + +import { generateAddressMetadataInfo, nameTag } from 'src/features/address-metadata/mocks/tags'; import { USER_OPS_ACCOUNT, USER_OPS_ITEM } from 'src/features/user-ops/stubs'; @@ -23,6 +26,21 @@ const hooksConfig = { }, }; +const addressMetadataQueryParams = { + addresses: [ addressParamMock.hash ], + chainId: config.chain.id, + tagsLimit: '20', +}; + +const ensLookupQueryParams = { + address: addressParamMock.hash, + protocols: [ 'ens' ], + resolved_to: true, + owned_by: true, + only_active: true, + order: 'ASC', +}; + test.beforeEach(async({ mockTextAd }) => { await mockTextAd(); }); @@ -33,6 +51,10 @@ test.describe('fetched bytecode', () => { await mockApiResponse('core:address_counters', addressCountersMock.forValidator, { pathParams: { hash: addressParamMock.hash } }); await mockApiResponse('core:address_tabs_counters', addressTabCountersMock.base, { pathParams: { hash: addressParamMock.hash } }); await mockApiResponse('core:address_txs', { items: [], next_page_params: null }, { pathParams: { hash: addressParamMock.hash } }); + await mockApiResponse('core:stats', statsMock.base); + await mockApiResponse('metadata:info', generateAddressMetadataInfo(addressParamMock.hash, nameTag), { queryParams: addressMetadataQueryParams }); + await mockApiResponse('metadata:address_submit', null as never); + await mockApiResponse('bens:addresses_lookup', { items: [], next_page_params: undefined }, { queryParams: ensLookupQueryParams }); await render(<Address/>, { hooksConfig }, { withSocket: true }); const socket = await createSocket(); @@ -50,11 +72,23 @@ test('degradation view', async({ render, page, mockRpcResponse, mockApiResponse await mockApiResponse('core:address_counters', addressCountersMock.forValidator, { pathParams: { hash: addressParamMock.hash } }); await mockApiResponse('core:address_tabs_counters', null as never, { pathParams: { hash: addressParamMock.hash }, status: 500 }); await mockApiResponse('core:address_txs', null as never, { pathParams: { hash: addressParamMock.hash }, status: 500 }); - await mockRpcResponse([ { - Method: 'eth_getBalance', - Parameters: [ addressParamMock.hash, 'latest' ], - ReturnType: numberToHex(1234567890123456), - } ]); + await mockApiResponse('core:stats', null as never, { status: 500 }); + await mockApiResponse('metadata:info', null as never, { queryParams: addressMetadataQueryParams, status: 500 }); + await mockApiResponse('bens:addresses_lookup', null as never, { queryParams: ensLookupQueryParams, status: 500 }); + await mockRpcResponse([ + { + Method: 'eth_getBalance', + Parameters: [ addressParamMock.hash, 'latest' ], + ReturnType: numberToHex(1234567890123456), + }, + // the node is down for the tx count too, which keeps the row in its loading state like the balance-only run + { + Method: 'eth_getTransactionCount', + Parameters: [ addressParamMock.hash, 'latest' ], + ReturnType: numberToHex(0), + status: 500, + }, + ]); const component = await render(<Address/>, { hooksConfig }); await page.waitForResponse(config.chain.rpcUrls[0]); diff --git a/src/slices/address/pages/details/Address.spec.tsx b/src/slices/address/pages/details/Address.spec.tsx new file mode 100644 index 00000000000..ce9e23617ef --- /dev/null +++ b/src/slices/address/pages/details/Address.spec.tsx @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import React from 'react'; + +import type { schemas } from '@blockscout/api-types'; + +import * as addressMock from 'src/slices/address/mocks/address'; +import * as addressParamMock from 'src/slices/address/mocks/address-param'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { cleanup, screen } from 'vitest/lib'; +import withEnvs from 'vitest/utils/mockEnvs'; +import { buildRouterMock } from 'vitest/utils/mockRouter'; + +const SCAM_ALERT_TEXT = 'This address has been flagged as a potential scam.'; +const ADDRESS_PATH = `/api/v2/addresses/${ addressParamMock.hash }`; + +// every test re-imports the whole address page (withEnvs resets modules), which took >5s on a CI runner +const TEST_TIMEOUT = 20_000; + +const scamAddress: schemas['AddressResponse'] = { ...addressMock.eoa, is_scam: true }; + +const metadataEnvs: Array<[ string, string ]> = [ + [ 'NEXT_PUBLIC_METADATA_SERVICE_API_HOST', 'https://localhost:3007' ], +]; + +function jsonResponse(body: unknown): { headers: Record<string, string>; body: string } { + return { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }; +} + +function mockAddress(address: schemas['AddressResponse']): void { + fetchMock.mockResponse((request) => { + const { pathname } = new URL(request.url); + + if (pathname === ADDRESS_PATH) { + return jsonResponse(address); + } + + if (pathname.endsWith('/metadata')) { + return jsonResponse({ addresses: {} }); + } + + if (pathname.endsWith('/addresses:submit')) { + return jsonResponse({}); + } + + return { status: 404, body: '{}' }; + }); +} + +async function renderAddressPage(): Promise<void> { + const { render, wrapper: TestApp } = await import('vitest/lib'); + const { 'default': Address } = await import('./Address'); + const router = buildRouterMock('/address/[hash]', `/address/${ addressParamMock.hash }`); + render(<TestApp router={ router }><Address/></TestApp>); +} + +beforeEach(() => { + fetchMock.resetMocks(); +}); + +afterEach(() => { + cleanup(); +}); + +describe('address scam flag', () => { + it('warns that the address is flagged as a scam', { timeout: TEST_TIMEOUT }, async() => { + await withEnvs([], async() => { + mockAddress(scamAddress); + await renderAddressPage(); + + expect(await screen.findByText(SCAM_ALERT_TEXT)).toBeTruthy(); + }); + }); + + it('warns that the address is flagged as a scam when the metadata service is on', { timeout: TEST_TIMEOUT }, async() => { + await withEnvs(metadataEnvs, async() => { + mockAddress(scamAddress); + await renderAddressPage(); + + expect(await screen.findByText(SCAM_ALERT_TEXT)).toBeTruthy(); + }); + }); + + it('shows no scam warning for an address that is not flagged', { timeout: TEST_TIMEOUT }, async() => { + await withEnvs([], async() => { + mockAddress(addressMock.eoa); + await renderAddressPage(); + + // the hash is on screen from the first render (inside the loading skeleton), so it does not + // prove the address query settled; the title does — the placeholder is a contract, + // so the page reads "Contract details" until the EOA response replaces it + expect(await screen.findByText('Address details')).toBeTruthy(); + expect(screen.queryByText(SCAM_ALERT_TEXT)).toBeNull(); + }); + }); +}); diff --git a/src/slices/address/pages/details/Address.tsx b/src/slices/address/pages/details/Address.tsx index df1c41f8cd6..8721e719be4 100644 --- a/src/slices/address/pages/details/Address.tsx +++ b/src/slices/address/pages/details/Address.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex, HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { MetadataTag } from 'src/features/address-metadata/components/tag/types'; @@ -48,7 +47,6 @@ import AlternativeExplorers from 'src/features/alternative-explorers/components/ import AddressDeposits from 'src/features/chain-variants/beacon-chain/pages/address/AddressDeposits'; import AddressWithdrawals from 'src/features/chain-variants/beacon-chain/pages/address/AddressWithdrawals'; import AddressEpochRewards from 'src/features/chain-variants/celo/pages/address/AddressEpochRewards'; -import AddressMultichainInfoButton from 'src/features/multichain-button/pages/address/AddressMultichainInfoButton'; import { useAddressClusters } from 'src/features/name-services/clusters/hooks/useAddressClusters'; import AddressClusters from 'src/features/name-services/clusters/pages/address/AddressClusters'; import EnsEntity from 'src/features/name-services/domains/components/EnsEntity'; @@ -65,6 +63,7 @@ import useFetchXStarScore from 'src/features/x-star-score/hooks/useFetchXStarSco import config from 'src/config'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import useEtherscanRedirects from 'src/shared/router/useEtherscanRedirects'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -475,7 +474,6 @@ const AddressPageContent = () => { <AddressQrCode hash={ addressQuery.data?.filecoin?.robust ?? checkSummedHash } isLoading={ isLoading }/> <ActionsMenu isLoading={ isLoading }/> <HStack ml="auto" gap={ 2 }/> - <AddressMultichainInfoButton loading={ isLoading } addressData={ addressQuery.data }/> { !isLoading && addressQuery.data?.is_contract && addressQuery.data?.is_verified && config.slices.contract.solidityscanEnabled && <SolidityscanReport hash={ hash }/> } { !isLoading && nameServicesFeature.isEnabled && nameServicesFeature.ens.isEnabled && @@ -495,8 +493,10 @@ const AddressPageContent = () => { secondRow={ titleSecondRow } isLoading={ isLoading } /> - { !addressMetadataQuery.isPending && - <AddressAlerts tags={ addressMetadataQuery.data?.addresses?.[hash.toLowerCase()]?.tags }/> } + <AddressAlerts + tags={ addressMetadataQuery.data?.addresses?.[hash.toLowerCase()]?.tags } + isScamAddress={ addressQuery.data?.is_scam } + /> { config.features.metasuites.isEnabled && <Box display="none" id="meta-suites__address" data-ready={ !isLoading }/> } <RoutedTabs tabs={ tabs } isLoading={ isTabsLoading }/> </> diff --git a/src/slices/address/pages/details/AddressPageMock.tsx b/src/slices/address/pages/details/AddressPageMock.tsx index 45cb9f12883..fcac3be79b4 100644 --- a/src/slices/address/pages/details/AddressPageMock.tsx +++ b/src/slices/address/pages/details/AddressPageMock.tsx @@ -1,10 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; +import { useRouter } from 'src/shared/router/useRouter'; + const MockAddressPage = ({ children }: { children: React.JSX.Element }): React.JSX.Element => { const router = useRouter(); diff --git a/src/slices/address/pages/details/__screenshots__/Address.pw.tsx_default_degradation-view-1.png b/src/slices/address/pages/details/__screenshots__/Address.pw.tsx_default_degradation-view-1.png index d48e795674b..b36bbb9194c 100644 Binary files a/src/slices/address/pages/details/__screenshots__/Address.pw.tsx_default_degradation-view-1.png and b/src/slices/address/pages/details/__screenshots__/Address.pw.tsx_default_degradation-view-1.png differ diff --git a/src/slices/address/pages/details/blocks-validated/AddressBlocksValidated.tsx b/src/slices/address/pages/details/blocks-validated/AddressBlocksValidated.tsx index c58c03dc8cc..55266052463 100644 --- a/src/slices/address/pages/details/blocks-validated/AddressBlocksValidated.tsx +++ b/src/slices/address/pages/details/blocks-validated/AddressBlocksValidated.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React from 'react'; import type { operations } from '@blockscout/api-types'; @@ -23,8 +22,9 @@ import useIsMounted from 'src/shared/hooks/useIsMounted'; import DataList from 'src/shared/lists/DataList'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; +import { useRouter } from 'src/shared/router/useRouter'; import { TableBody, TableColumnHeader, TableContainerScrollable, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -46,7 +46,7 @@ const AddressBlocksValidated = ({ shouldRender = true, isQueryEnabled = true }: const isMounted = useIsMounted(); const addressHash = String(router.query.hash); - const query = useQueryWithPages({ + const query = useApiPaginatedQuery({ resourceName: 'core:address_blocks_validated', pathParams: { hash: addressHash }, options: { @@ -95,7 +95,7 @@ const AddressBlocksValidated = ({ shouldRender = true, isQueryEnabled = true }: topic: `blocks:${ addressHash.toLowerCase() }`, onSocketClose: handleSocketError, onSocketError: handleSocketError, - isDisabled: !addressHash || query.isPlaceholderData || query.pagination.page !== 1, + isDisabled: !addressHash || query.isInitialLoading || query.pagination.page !== 1, }); useSocketMessage({ channel, @@ -105,7 +105,7 @@ const AddressBlocksValidated = ({ shouldRender = true, isQueryEnabled = true }: const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: query.data?.items, - isEnabled: !query.isPlaceholderData, + isEnabled: !query.isInitialLoading, resetKey: query.queryHash, }); @@ -134,14 +134,14 @@ const AddressBlocksValidated = ({ shouldRender = true, isQueryEnabled = true }: num={ newItemsCount } showErrorAlert={ showSocketAlert } type="block" - isLoading={ query.isPlaceholderData } + isLoading={ query.isInitialLoading } /> { query.data.items.slice(0, renderedItemsNum).map((item, index) => ( <AddressBlocksValidatedTableItem - key={ item.height + (query.isPlaceholderData ? String(index) : '') } + key={ item.height + (query.isInitialLoading ? String(index) : '') } data={ item } page={ query.pagination.page } - isLoading={ query.isPlaceholderData } + isLoading={ query.isInitialLoading } /> )) } </TableBody> @@ -162,6 +162,7 @@ const AddressBlocksValidated = ({ shouldRender = true, isQueryEnabled = true }: itemsNum={ query.data?.items.length } emptyText="There are no validated blocks for this address." actionBar={ actionBar } + isTransitioning={ query.isTransitioning } > { content } </DataList> diff --git a/src/slices/address/pages/details/blocks-validated/AddressBlocksValidatedListItem.tsx b/src/slices/address/pages/details/blocks-validated/AddressBlocksValidatedListItem.tsx deleted file mode 100644 index 8fa0b34782d..00000000000 --- a/src/slices/address/pages/details/blocks-validated/AddressBlocksValidatedListItem.tsx +++ /dev/null @@ -1,78 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Text, Flex } from '@chakra-ui/react'; -import BigNumber from 'bignumber.js'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import getBlockTotalReward from 'src/slices/block/utils/get-block-total-reward'; -import { currencyUnits } from 'src/slices/chain/units'; -import GasUsed from 'src/slices/gas/components/GasUsed'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import SimpleValue from 'src/shared/values/entity/SimpleValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -type Props = schemas['Block'] & { - page: number; - isLoading: boolean; -}; - -const AddressBlocksValidatedListItem = (props: Props) => { - const totalReward = getBlockTotalReward(props); - - return ( - <ListItemMobile rowGap={ 2 }> - <Flex justifyContent="space-between" w="100%"> - <BlockEntity - isLoading={ props.isLoading } - number={ props.height } - noIcon - fontWeight={ 700 } - /> - <TimeWithTooltip - timestamp={ props.timestamp } - enableIncrement={ props.page === 1 } - isLoading={ props.isLoading } - color="text.secondary" - display="inline-block" - /> - </Flex> - <Flex columnGap={ 2 } w="100%"> - <Skeleton loading={ props.isLoading } fontWeight={ 500 } flexShrink={ 0 }>Txn</Skeleton> - <Skeleton loading={ props.isLoading } display="inline-block" color="Skeleton_secondary"> - <span>{ props.transactions_count }</span> - </Skeleton> - </Flex> - <Flex columnGap={ 2 } w="100%"> - <Skeleton loading={ props.isLoading } fontWeight={ 500 } flexShrink={ 0 }>Gas used</Skeleton> - <Skeleton loading={ props.isLoading }> - <Text color="text.secondary">{ BigNumber(props.gas_used || 0).toFormat() }</Text> - </Skeleton> - <GasUsed - gasUsed={ props.gas_used || undefined } - gasLimit={ props.gas_limit } - isLoading={ props.isLoading } - /> - </Flex> - { !config.slices.block.hiddenFields?.total_reward && !config.features.rollup.isEnabled && ( - <Flex columnGap={ 2 } w="100%"> - <Skeleton loading={ props.isLoading } fontWeight={ 500 } flexShrink={ 0 }>Reward { currencyUnits.ether }</Skeleton> - <SimpleValue - value={ totalReward } - accuracy={ 0 } - loading={ props.isLoading } - color="text.secondary" - /> - </Flex> - ) } - </ListItemMobile> - ); -}; - -export default React.memo(AddressBlocksValidatedListItem); diff --git a/src/slices/address/pages/details/coin-balance/AddressCoinBalance.tsx b/src/slices/address/pages/details/coin-balance/AddressCoinBalance.tsx index 93e1c5b0ad3..b4867a73e7f 100644 --- a/src/slices/address/pages/details/coin-balance/AddressCoinBalance.tsx +++ b/src/slices/address/pages/details/coin-balance/AddressCoinBalance.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React from 'react'; import type { operations } from '@blockscout/api-types'; @@ -15,9 +14,10 @@ import useSocketMessage from 'src/api/socket/useSocketMessage'; import { ADDRESS_COIN_BALANCE } from 'src/slices/address/stubs/address'; import useIsMounted from 'src/shared/hooks/useIsMounted'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import AddressCoinBalanceChart from './AddressCoinBalanceChart'; import AddressCoinBalanceHistory from './AddressCoinBalanceHistory'; @@ -36,7 +36,7 @@ const AddressCoinBalance = ({ shouldRender = true, isQueryEnabled = true }: Prop const scrollRef = React.useRef<HTMLDivElement>(null); const addressHash = getQueryParamString(router.query.hash); - const coinBalanceQuery = useQueryWithPages({ + const coinBalanceQuery = useApiPaginatedQuery({ resourceName: 'core:address_coin_balance', pathParams: { hash: addressHash }, scrollRef, @@ -84,7 +84,7 @@ const AddressCoinBalance = ({ shouldRender = true, isQueryEnabled = true }: Prop topic: `addresses:${ addressHash.toLowerCase() }`, onSocketClose: handleSocketError, onSocketError: handleSocketError, - isDisabled: !addressHash || coinBalanceQuery.isPlaceholderData || coinBalanceQuery.pagination.page !== 1, + isDisabled: !addressHash || coinBalanceQuery.isInitialLoading || coinBalanceQuery.pagination.page !== 1, }); useSocketMessage({ channel, diff --git a/src/slices/address/pages/details/coin-balance/AddressCoinBalanceHistory.tsx b/src/slices/address/pages/details/coin-balance/AddressCoinBalanceHistory.tsx index 497ddf4c180..d4c212c7b92 100644 --- a/src/slices/address/pages/details/coin-balance/AddressCoinBalanceHistory.tsx +++ b/src/slices/address/pages/details/coin-balance/AddressCoinBalanceHistory.tsx @@ -1,14 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box } from '@chakra-ui/react'; -import type { UseQueryResult } from '@tanstack/react-query'; import React from 'react'; -import type { paths } from '@blockscout/api-types'; -import type { PaginationParams } from 'src/shared/pagination/types'; - -import type { ResourceError } from 'src/api/resources'; - import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import { currencyUnits } from 'src/slices/chain/units'; @@ -19,18 +13,14 @@ import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; import DataList from 'src/shared/lists/DataList'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import Pagination from 'src/shared/pagination/Pagination'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; import { TableBody, TableColumnHeader, TableContainerScrollable, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; import AddressCoinBalanceTableItem from './AddressCoinBalanceTableItem'; interface Props { - query: UseQueryResult< - paths['/api/v2/addresses/{address_hash_param}/coin-balance-history']['get'], - ResourceError<unknown> - > & { - pagination: PaginationParams; - }; + query: ApiPaginatedQueryResult<'core:address_coin_balance'>; resetKey?: string; } @@ -40,7 +30,7 @@ const AddressCoinBalanceHistory = ({ query, resetKey }: Props) => { const items = query.data?.items ?? []; const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, - isEnabled: !query.isPlaceholderData, + isEnabled: !query.isInitialLoading, resetKey, }); @@ -64,10 +54,10 @@ const AddressCoinBalanceHistory = ({ query, resetKey }: Props) => { <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( <AddressCoinBalanceTableItem - key={ item.block_number + (query.isPlaceholderData ? String(index) : '') } + key={ item.block_number + (query.isInitialLoading ? String(index) : '') } data={ item } page={ query.pagination.page } - isLoading={ query.isPlaceholderData } + isLoading={ query.isInitialLoading } chainData={ chainData } /> )) } @@ -91,6 +81,7 @@ const AddressCoinBalanceHistory = ({ query, resetKey }: Props) => { itemsNum={ query.data?.items.length } emptyText="There is no coin balance history for this address." actionBar={ actionBar } + isTransitioning={ query.isTransitioning } > { content } </DataList> diff --git a/src/slices/address/pages/details/coin-balance/AddressCoinBalanceListItem.tsx b/src/slices/address/pages/details/coin-balance/AddressCoinBalanceListItem.tsx deleted file mode 100644 index 7e60568de5c..00000000000 --- a/src/slices/address/pages/details/coin-balance/AddressCoinBalanceListItem.tsx +++ /dev/null @@ -1,88 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Stat, Flex } from '@chakra-ui/react'; -import BigNumber from 'bignumber.js'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; - -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; -import SimpleValue from 'src/shared/values/entity/SimpleValue'; -import { WEI } from 'src/shared/values/entity/utils'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { ZERO } from 'src/toolkit/utils/consts'; - -interface Props { - data: schemas['CoinBalance']; - page: number; - isLoading: boolean; - chainData?: ClusterChainConfig; -}; - -const AddressCoinBalanceListItem = ({ data, page, isLoading, chainData }: Props) => { - const deltaBn = BigNumber(data.delta).div(WEI); - const isPositiveDelta = deltaBn.gte(ZERO); - - return ( - <ListItemMobile rowGap={ 2 }> - <Flex justifyContent="space-between" w="100%"> - <NativeCoinValue - amount={ data.value } - loading={ isLoading } - fontWeight={ 600 } - /> - <Skeleton loading={ isLoading }> - <Stat.Root flexGrow="0" positive={ isPositiveDelta } size="sm"> - <Stat.ValueText fontWeight={ 600 }> - <SimpleValue - value={ deltaBn } - loading={ isLoading } - /> - </Stat.ValueText> - { isPositiveDelta ? <Stat.UpIndicator/> : <Stat.DownIndicator/> } - </Stat.Root> - </Skeleton> - </Flex> - <Flex columnGap={ 2 } w="100%"> - <Skeleton loading={ isLoading } fontWeight={ 500 } flexShrink={ 0 }>Block</Skeleton> - <BlockEntity - isLoading={ isLoading } - number={ data.block_number } - noIcon={ !chainData } - fontWeight={ 700 } - chain={ chainData } - /> - </Flex> - { data.transaction_hash && ( - <Flex columnGap={ 2 } w="100%"> - <Skeleton loading={ isLoading } fontWeight={ 500 } flexShrink={ 0 }>Txs</Skeleton> - <TxEntity - hash={ data.transaction_hash } - isLoading={ isLoading } - noIcon - fontWeight={ 700 } - maxW="150px" - /> - </Flex> - ) } - <Flex columnGap={ 2 } w="100%"> - <Skeleton loading={ isLoading } fontWeight={ 500 } flexShrink={ 0 }>Age</Skeleton> - <TimeWithTooltip - timestamp={ data.block_timestamp } - enableIncrement={ page === 1 } - isLoading={ isLoading } - color="text.secondary" - /> - </Flex> - </ListItemMobile> - ); -}; - -export default React.memo(AddressCoinBalanceListItem); diff --git a/src/slices/address/pages/details/coin-balance/__screenshots__/AddressCoinBalance.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/slices/address/pages/details/coin-balance/__screenshots__/AddressCoinBalance.pw.tsx_dark-color-mode_base-view-dark-mode-1.png index 38c3e261728..94b3a75fb5f 100644 Binary files a/src/slices/address/pages/details/coin-balance/__screenshots__/AddressCoinBalance.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and b/src/slices/address/pages/details/coin-balance/__screenshots__/AddressCoinBalance.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/coin-balance/__screenshots__/AddressCoinBalance.pw.tsx_default_base-view-dark-mode-1.png b/src/slices/address/pages/details/coin-balance/__screenshots__/AddressCoinBalance.pw.tsx_default_base-view-dark-mode-1.png index 44ec45474b6..1db532ef085 100644 Binary files a/src/slices/address/pages/details/coin-balance/__screenshots__/AddressCoinBalance.pw.tsx_default_base-view-dark-mode-1.png and b/src/slices/address/pages/details/coin-balance/__screenshots__/AddressCoinBalance.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/info/AddressAlerts.tsx b/src/slices/address/pages/details/info/AddressAlerts.tsx index 0c5fd943afd..31c52465bcf 100644 --- a/src/slices/address/pages/details/info/AddressAlerts.tsx +++ b/src/slices/address/pages/details/info/AddressAlerts.tsx @@ -11,13 +11,14 @@ import { Alert } from 'src/toolkit/chakra/alert'; interface Props { tags: Array<AddressMetadataTagFormatted> | undefined; isScamToken?: boolean; + isScamAddress?: boolean; className?: string; } -const AddressAlerts = ({ tags, isScamToken, className }: Props) => { +const AddressAlerts = ({ tags, isScamToken, isScamAddress, className }: Props) => { const noteTags = tags?.filter(({ tagType }) => tagType === 'note').filter(({ meta }) => meta?.data); - if (!noteTags?.length && !isScamToken) { + if (!noteTags?.length && !isScamToken && !isScamAddress) { return null; } @@ -28,6 +29,11 @@ const AddressAlerts = ({ tags, isScamToken, className }: Props) => { This token has been flagged as a potential scam. </Alert> ) } + { isScamAddress && ( + <Alert status="error"> + This address has been flagged as a potential scam. + </Alert> + ) } { noteTags?.map((noteTag) => ( <Alert key={ noteTag.name } diff --git a/src/slices/address/pages/details/info/AddressDetails.pw.tsx b/src/slices/address/pages/details/info/AddressDetails.pw.tsx index 3d8b69696eb..0a648638c48 100644 --- a/src/slices/address/pages/details/info/AddressDetails.pw.tsx +++ b/src/slices/address/pages/details/info/AddressDetails.pw.tsx @@ -5,6 +5,7 @@ import type { AddressQuery } from 'src/slices/address/hooks/useAddressQuery'; import * as addressMock from 'src/slices/address/mocks/address'; import * as addressParamMock from 'src/slices/address/mocks/address-param'; import * as countersMock from 'src/slices/address/mocks/counters'; +import * as statsMock from 'src/slices/chain/stats/mocks'; import * as tokensMock from 'src/slices/token/mocks/address-tokens'; import * as widgetsMock from 'src/features/address-3rd-party-widgets/mocks'; @@ -32,6 +33,8 @@ const testWidgetsFn = (isMobile: boolean) => async({ render, mockConfigResponse, await mockConfigResponse('NEXT_PUBLIC_ADDRESS_3RD_PARTY_WIDGETS_CONFIG_URL', WIDGETS_CONFIG_URL, widgetsMock.config); await mockApiResponse('core:address', addressMock.contract, { pathParams: { hash: ADDRESS_HASH } }); + + await mockApiResponse('core:stats', statsMock.base); await mockApiResponse('core:address_counters', countersMock.forContract, { pathParams: { hash: ADDRESS_HASH } }); await Promise.all(widgetsMock.widgets.map((widget, i) => mockApiResponse( @@ -65,6 +68,7 @@ test.describe('mobile', () => { test('contract', async({ render, mockApiResponse, page }) => { await mockApiResponse('core:address', addressMock.contract, { pathParams: { hash: ADDRESS_HASH } }); + await mockApiResponse('core:stats', statsMock.base); const component = await render( <AddressDetails @@ -82,6 +86,7 @@ test.describe('mobile', () => { test('validator', async({ render, page, mockApiResponse }) => { await mockApiResponse('core:address', addressMock.validator, { pathParams: { hash: ADDRESS_HASH } }); + await mockApiResponse('core:stats', statsMock.base); const component = await render( <AddressDetails @@ -99,6 +104,7 @@ test.describe('mobile', () => { test('filecoin', async({ render, mockApiResponse, page }) => { await mockApiResponse('core:address', addressMock.filecoin, { pathParams: { hash: ADDRESS_HASH } }); + await mockApiResponse('core:stats', statsMock.base); const component = await render( <AddressDetails @@ -119,6 +125,7 @@ test.describe('mobile', () => { test('contract', async({ render, page, mockApiResponse }) => { await mockApiResponse('core:address', addressMock.contract, { pathParams: { hash: ADDRESS_HASH } }); + await mockApiResponse('core:stats', statsMock.base); const component = await render( <AddressDetails @@ -137,6 +144,7 @@ test('contract', async({ render, page, mockApiResponse }) => { // there's an unexpected timeout occurred in this test test.fixme('token', async({ render, mockApiResponse, injectMetaMaskProvider, page }) => { await mockApiResponse('core:address', addressMock.token, { pathParams: { hash: ADDRESS_HASH } }); + await mockApiResponse('core:stats', statsMock.base); await mockApiResponse('core:address_tokens', tokensMock.erc20List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-20' }, times: 1 }); await mockApiResponse('core:address_tokens', tokensMock.erc721List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-721' }, times: 1 }); await mockApiResponse('core:address_tokens', tokensMock.erc1155List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-1155' }, times: 1 }); @@ -158,6 +166,7 @@ test.fixme('token', async({ render, mockApiResponse, injectMetaMaskProvider, pag test('validator', async({ render, mockApiResponse, page }) => { await mockApiResponse('core:address', addressMock.validator, { pathParams: { hash: ADDRESS_HASH } }); + await mockApiResponse('core:stats', statsMock.base); const component = await render( <AddressDetails @@ -175,6 +184,7 @@ test('validator', async({ render, mockApiResponse, page }) => { test('filecoin', async({ render, mockApiResponse, page }) => { await mockApiResponse('core:address', addressMock.filecoin, { pathParams: { hash: ADDRESS_HASH } }); + await mockApiResponse('core:stats', statsMock.base); const component = await render( <AddressDetails diff --git a/src/slices/address/pages/details/info/AddressDetails.tsx b/src/slices/address/pages/details/info/AddressDetails.tsx index 2cf6b5663f1..0c864e59344 100644 --- a/src/slices/address/pages/details/info/AddressDetails.tsx +++ b/src/slices/address/pages/details/info/AddressDetails.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Text } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; @@ -26,6 +25,7 @@ import DetailedInfoSponsoredItem from 'src/shared/detailed-info/DetailedInfoSpon import isCustomAppError from 'src/shared/errors/is-custom-app-error'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import AddressAlternativeFormat from './AddressAlternativeFormat'; @@ -296,7 +296,7 @@ const AddressDetails = ({ addressQuery, countersQuery, isLoading }: Props) => { </> ) } - { data.block_number_balance_updated_at && ( + { data.block_number_balance_updated_at !== null && ( <> <DetailedInfo.ItemLabel hint="Block number in which the address was updated" diff --git a/src/slices/address/pages/details/info/AddressNetWorth.pw.tsx b/src/slices/address/pages/details/info/AddressNetWorth.pw.tsx index 5575b695a6f..60e4215f86b 100644 --- a/src/slices/address/pages/details/info/AddressNetWorth.pw.tsx +++ b/src/slices/address/pages/details/info/AddressNetWorth.pw.tsx @@ -1,6 +1,7 @@ -import { Box } from '@chakra-ui/react'; import React from 'react'; +import type { MultichainProviderConfig } from 'src/features/multichain-button/types/client'; + import * as addressMock from 'src/slices/address/mocks/address'; import * as addressParamMock from 'src/slices/address/mocks/address-param'; import * as tokensMock from 'src/slices/token/mocks/address-tokens'; @@ -11,72 +12,25 @@ import AddressNetWorth from './AddressNetWorth'; const ADDRESS_HASH = addressParamMock.hash; const ICON_URL = 'https://localhost:3000/my-icon.png'; -const ICON_URL_PROMO = 'https://localhost:3000/my-icon-promo.png'; +const ICON_URL_2 = 'https://localhost:3000/my-icon-2.png'; -test.beforeEach(async({ mockApiResponse }) => { +test('with multichain buttons +@dark-mode', async({ render, mockEnvs, mockApiResponse, mockAssetResponse }) => { + await mockEnvs([ + [ 'NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG', JSON.stringify([ + { name: 'Duck portfolio', dapp_id: 'duck', url_template: 'https://duck.url/{address}', logo: ICON_URL }, + { name: 'duck3', dapp_id: 'duck', url_template: 'https://duck.url/{address}', logo: ICON_URL, view: 'icon' }, + { name: 'Goose tracker', url_template: 'https://duck.url/{address}', logo: ICON_URL_2, view: 'full' }, + { name: 'goose', url_template: 'https://duck.url/{address}', logo: ICON_URL_2, view: 'icon' }, + ] satisfies Array<MultichainProviderConfig>) ], + ]); await mockApiResponse('core:address_tokens', tokensMock.erc20List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-20' } }); await mockApiResponse('core:address_tokens', tokensMock.erc721List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-721' } }); await mockApiResponse('core:address_tokens', tokensMock.erc1155List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-1155' } }); await mockApiResponse('core:address_tokens', tokensMock.erc404List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-404' } }); -}); - -test('base view', async({ render }) => { - const component = await render(<AddressNetWorth addressData={ addressMock.eoa } addressHash={ ADDRESS_HASH }/>); - - await expect(component).toHaveScreenshot(); -}); - -test('with single multichain button internal +@dark-mode', async({ render, mockEnvs, mockAssetResponse }) => { - await mockEnvs([ - [ - 'NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG', - `[{"name": "duck", "dapp_id": "duck", "url_template": "https://duck.url/{address}", "logo": "${ ICON_URL }"}]` ], - ]); - await mockAssetResponse(ICON_URL, './playwright/mocks/image_svg.svg'); + await mockAssetResponse(ICON_URL, './playwright/mocks/duck.png'); + await mockAssetResponse(ICON_URL_2, './playwright/mocks/goose.png'); const component = await render(<AddressNetWorth addressData={ addressMock.eoa } addressHash={ ADDRESS_HASH }/>); await expect(component).toHaveScreenshot(); }); - -test('with single multichain button external', async({ render, mockEnvs, mockAssetResponse }) => { - await mockEnvs([ - [ 'NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG', `[{"name": "duck", "url_template": "https://duck.url/{address}", "logo": "${ ICON_URL }"}]` ], - ]); - await mockAssetResponse(ICON_URL, './playwright/mocks/image_svg.svg'); - - const component = await render(<AddressNetWorth addressData={ addressMock.eoa } addressHash={ ADDRESS_HASH }/>); - - await expect(component).toHaveScreenshot(); -}); - -test('with two multichain button and promo', async({ render, mockEnvs, mockAssetResponse }) => { - await mockEnvs([ - [ 'NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG', `[ - {"name": "duck", "url_template": "https://duck.url/{address}", "logo": "${ ICON_URL }"}, - {"name": "duck2", "url_template": "https://duck.url/{address}", "logo": "${ ICON_URL }"}, - {"name": "duck3", "url_template": "https://duck.url/{address}", "logo": "${ ICON_URL_PROMO }", "promo": true} - ]` ], - ]); - await mockAssetResponse(ICON_URL, './playwright/mocks/image_svg.svg'); - await mockAssetResponse(ICON_URL_PROMO, './playwright/mocks/image_s.jpg'); - - const component = await render(<AddressNetWorth addressData={ addressMock.eoa } addressHash={ ADDRESS_HASH }/>); - - await expect(component).toHaveScreenshot(); -}); - -test('with multichain button internal small screen', async({ render, mockEnvs, mockAssetResponse }) => { - await mockEnvs([ - [ - 'NEXT_PUBLIC_MULTICHAIN_BALANCE_PROVIDER_CONFIG', - `[{"name": "duck", "dapp_id": "duck", "url_template": "https://duck.url/{address}", "logo": "${ ICON_URL }"}]` ], - ]); - await mockAssetResponse(ICON_URL, './playwright/mocks/image_svg.svg'); - - const component = await render( - <Box w="300px"><AddressNetWorth addressData={ addressMock.eoa } addressHash={ ADDRESS_HASH }/></Box>, - ); - - await expect(component).toHaveScreenshot(); -}); diff --git a/src/slices/address/pages/details/info/AddressNetWorth.tsx b/src/slices/address/pages/details/info/AddressNetWorth.tsx index 0c25b56bca0..9f6a15fb219 100644 --- a/src/slices/address/pages/details/info/AddressNetWorth.tsx +++ b/src/slices/address/pages/details/info/AddressNetWorth.tsx @@ -11,7 +11,7 @@ import { getTokensTotalInfo } from 'src/slices/token/pages/address/utils'; import AddressMultichainButton from 'src/features/multichain-button/pages/address/AddressMultichainButton'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import TextSeparator from 'src/shared/texts/TextSeparator'; import calculateUsdValue from 'src/shared/values/entity/calculateUsdValue'; import SimpleValue from 'src/shared/values/entity/SimpleValue'; @@ -41,7 +41,7 @@ const AddressNetWorth = ({ addressData, isLoading, addressHash }: Props) => { const totalUsd = nativeUsd.plus(usd); const onMultichainClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.BUTTON_CLICK, { Content: 'Multichain', Source: 'address' }); + analytics.logEvent(analytics.EventTypes.BUTTON_CLICK, { Content: 'Multichain', Source: 'address' }); }, []); let multichainItems = null; @@ -54,20 +54,17 @@ const AddressNetWorth = ({ addressData, isLoading, addressHash }: Props) => { multichainItems = ( <> <TextSeparator/> - <HStack columnGap={ 2 }> - <Text>Multichain</Text> - <HStack gap={{ base: 2, lg: 3 }}> - { providers.map((item, index) => ( + <HStack columnGap={ 2 } alignItems="flex-start"> + <Text lineHeight="32px">Multichain</Text> + <HStack gap={ 1 } flexWrap="wrap"> + { providers.map((item) => ( <AddressMultichainButton key={ item.name } item={ item } addressHash={ addressHash } onClick={ onMultichainClick } - isFirst={ index === 0 } - isLast={ index === providers.length - 1 } /> - )) - } + )) } </HStack> </HStack> </> diff --git a/src/slices/address/pages/details/info/AddressQrCode.tsx b/src/slices/address/pages/details/info/AddressQrCode.tsx index 7b66ce65a13..719009c803b 100644 --- a/src/slices/address/pages/details/info/AddressQrCode.tsx +++ b/src/slices/address/pages/details/info/AddressQrCode.tsx @@ -1,14 +1,14 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, Box } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import QRCode from 'qrcode'; import React from 'react'; import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import * as mixpanel from 'src/services/mixpanel'; import { useRollbar } from 'src/services/rollbar'; +import * as analytics from 'src/shared/analytics'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Alert } from 'src/toolkit/chakra/alert'; @@ -37,7 +37,7 @@ const AddressQrCode = ({ hash, className, isLoading }: Props) => { const [ qr, setQr ] = React.useState(''); const [ error, setError ] = React.useState(''); - const pageType = mixpanel.getPageType(router.pathname); + const pageType = analytics.getPageType(router.pathname); React.useEffect(() => { if (open) { @@ -50,7 +50,7 @@ const AddressQrCode = ({ hash, className, isLoading }: Props) => { setError(''); setQr(svg); - mixpanel.logEvent(mixpanel.EventTypes.QR_CODE, { 'Page type': pageType }); + analytics.logEvent(analytics.EventTypes.QR_CODE, { 'Page type': pageType }); }); } }, [ hash, open, pageType, rollbar ]); diff --git a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_dark-color-mode_with-multichain-buttons-dark-mode-1.png b/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_dark-color-mode_with-multichain-buttons-dark-mode-1.png new file mode 100644 index 00000000000..00ca9577a85 Binary files /dev/null and b/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_dark-color-mode_with-multichain-buttons-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_dark-color-mode_with-single-multichain-button-internal-dark-mode-1.png b/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_dark-color-mode_with-single-multichain-button-internal-dark-mode-1.png deleted file mode 100644 index 366ded04130..00000000000 Binary files a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_dark-color-mode_with-single-multichain-button-internal-dark-mode-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_base-view-1.png b/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_base-view-1.png deleted file mode 100644 index 85f29e9c0da..00000000000 Binary files a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_base-view-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-multichain-button-internal-small-screen-1.png b/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-multichain-button-internal-small-screen-1.png deleted file mode 100644 index a2a862695ff..00000000000 Binary files a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-multichain-button-internal-small-screen-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-multichain-buttons-dark-mode-1.png b/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-multichain-buttons-dark-mode-1.png new file mode 100644 index 00000000000..9612bdabd60 Binary files /dev/null and b/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-multichain-buttons-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-single-multichain-button-external-1.png b/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-single-multichain-button-external-1.png deleted file mode 100644 index 5ea109667ee..00000000000 Binary files a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-single-multichain-button-external-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-single-multichain-button-internal-dark-mode-1.png b/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-single-multichain-button-internal-dark-mode-1.png deleted file mode 100644 index 11b9a1b1851..00000000000 Binary files a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-single-multichain-button-internal-dark-mode-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-two-multichain-button-and-promo-1.png b/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-two-multichain-button-and-promo-1.png deleted file mode 100644 index eb96c9d25cd..00000000000 Binary files a/src/slices/address/pages/details/info/__screenshots__/AddressNetWorth.pw.tsx_default_with-two-multichain-button-and-promo-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/info/__screenshots__/AddressQrCode.pw.tsx_mobile_default-view-mobile-dark-mode-1.png b/src/slices/address/pages/details/info/__screenshots__/AddressQrCode.pw.tsx_mobile_default-view-mobile-dark-mode-1.png index df3ec46443e..4521081a055 100644 Binary files a/src/slices/address/pages/details/info/__screenshots__/AddressQrCode.pw.tsx_mobile_default-view-mobile-dark-mode-1.png and b/src/slices/address/pages/details/info/__screenshots__/AddressQrCode.pw.tsx_mobile_default-view-mobile-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/info/token-select/TokenSelect.pw.tsx b/src/slices/address/pages/details/info/token-select/TokenSelect.pw.tsx index 4a16fc82894..6de79da257a 100644 --- a/src/slices/address/pages/details/info/token-select/TokenSelect.pw.tsx +++ b/src/slices/address/pages/details/info/token-select/TokenSelect.pw.tsx @@ -1,13 +1,15 @@ import { Flex } from '@chakra-ui/react'; -import React from 'react'; import * as addressMock from 'src/slices/address/mocks/address'; import * as addressParamMock from 'src/slices/address/mocks/address-param'; import MockAddressPage from 'src/slices/address/pages/details/AddressPageMock'; import * as tokensMock from 'src/slices/token/mocks/address-tokens'; -import { tokenInfoERC20c, tokenInfoERC20a } from 'src/slices/token/mocks/info'; +import { tokenInfoERC20a, tokenInfoERC20c } from 'src/slices/token/mocks/info'; -import { test, expect, devices } from 'playwright/lib'; +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import type { TestFnArgs } from 'playwright/lib'; +import { devices, expect, test } from 'playwright/lib'; import TokenSelect from './TokenSelect'; @@ -20,16 +22,25 @@ const hooksConfig = { }; const CLIPPING_AREA = { x: 0, y: 0, width: 360, height: 500 }; -test.beforeEach(async({ mockApiResponse, mockAssetResponse }) => { +const mockTokenSelectData = async({ mockApiResponse, mockAssetResponse }: Pick<TestFnArgs, 'mockApiResponse' | 'mockAssetResponse'>) => { await mockAssetResponse(ASSET_URL, './playwright/mocks/image_s.jpg'); await mockApiResponse('core:address', addressMock.validator, { pathParams: { hash: ADDRESS_HASH }, times: 1 }); await mockApiResponse('core:address_tokens', tokensMock.erc20List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-20' }, times: 1 }); await mockApiResponse('core:address_tokens', tokensMock.erc721List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-721' }, times: 1 }); await mockApiResponse('core:address_tokens', tokensMock.erc1155List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-1155' }, times: 1 }); await mockApiResponse('core:address_tokens', tokensMock.erc404List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-404' }, times: 1 }); -}); + await mockApiResponse( + 'core:address_tokens', + { items: [], next_page_params: null }, + { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-7984' }, times: 1 }, + ); + await mockApiResponse('core:address_tokens', tokensMock.erc8056List, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-8056' }, times: 1 }); +}; + +test('base view +@dark-mode', async({ render, page, mockEnvs, mockApiResponse, mockAssetResponse }) => { + await mockEnvs(ENVS_MAP.additionalTokenTypes); + await mockTokenSelectData({ mockApiResponse, mockAssetResponse }); -test('base view +@dark-mode', async({ render, page }) => { await render( <MockAddressPage> <Flex> @@ -51,7 +62,8 @@ test('base view +@dark-mode', async({ render, page }) => { test.describe('mobile', () => { test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - test('base view', async({ render, page }) => { + test('base view', async({ render, page, mockApiResponse, mockAssetResponse }) => { + await mockTokenSelectData({ mockApiResponse, mockAssetResponse }); await render( <MockAddressPage> <Flex> @@ -67,7 +79,8 @@ test.describe('mobile', () => { }); }); -test('sort', async({ render, page }) => { +test('sort', async({ render, page, mockApiResponse, mockAssetResponse }) => { + await mockTokenSelectData({ mockApiResponse, mockAssetResponse }); await render( <MockAddressPage> <Flex> @@ -89,7 +102,8 @@ test('sort', async({ render, page }) => { await expect(page).toHaveScreenshot({ clip: CLIPPING_AREA }); }); -test('filter', async({ render, page }) => { +test('filter', async({ render, page, mockApiResponse, mockAssetResponse }) => { + await mockTokenSelectData({ mockApiResponse, mockAssetResponse }); await render( <MockAddressPage> <Flex> @@ -104,7 +118,8 @@ test('filter', async({ render, page }) => { await expect(page).toHaveScreenshot({ clip: CLIPPING_AREA }); }); -test('long values', async({ render, page, mockApiResponse }) => { +test('long values', async({ render, page, mockApiResponse, mockAssetResponse }) => { + await mockTokenSelectData({ mockApiResponse, mockAssetResponse }); await mockApiResponse('core:address_tokens', { items: [ tokensMock.erc20LongSymbol, tokensMock.erc20BigAmount ], next_page_params: null, }, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-20' }, times: 1 }); @@ -129,10 +144,11 @@ test('long values', async({ render, page, mockApiResponse }) => { await expect(page).toHaveScreenshot({ clip: CLIPPING_AREA }); }); -test('native token', async({ render, mockEnvs, page }) => { +test('native token', async({ render, mockEnvs, page, mockApiResponse, mockAssetResponse }) => { await mockEnvs([ [ 'NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS', tokenInfoERC20c.address_hash ], ]); + await mockTokenSelectData({ mockApiResponse, mockAssetResponse }); await render( <MockAddressPage> diff --git a/src/slices/address/pages/details/info/token-select/TokenSelect.tsx b/src/slices/address/pages/details/info/token-select/TokenSelect.tsx index 54153985818..833f0a422db 100644 --- a/src/slices/address/pages/details/info/token-select/TokenSelect.tsx +++ b/src/slices/address/pages/details/info/token-select/TokenSelect.tsx @@ -3,7 +3,6 @@ import { Box, Flex } from '@chakra-ui/react'; import { useQueryClient, useIsFetching } from '@tanstack/react-query'; import { sumBy } from 'es-toolkit'; -import { useRouter } from 'next/router'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -14,10 +13,11 @@ import useFetchTokens from 'src/slices/token/pages/address/useFetchTokens'; import { useMultichainContext } from 'src/features/multichain/context'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { IconButton } from 'src/toolkit/chakra/icon-button'; @@ -48,7 +48,7 @@ const TokenSelect = () => { const tokensIsFetching = useIsFetching({ queryKey: tokensResourceKey }); const handleIconButtonClick = React.useCallback(() => { - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { Type: 'Tokens show all (icon)' }); + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Tokens show all (icon)' }); window.scrollTo({ top: 0, behavior: 'smooth' }); }, [ ]); diff --git a/src/slices/address/pages/details/info/token-select/TokenSelectButton.tsx b/src/slices/address/pages/details/info/token-select/TokenSelectButton.tsx index c94e1675552..e54da6a866f 100644 --- a/src/slices/address/pages/details/info/token-select/TokenSelectButton.tsx +++ b/src/slices/address/pages/details/info/token-select/TokenSelectButton.tsx @@ -7,7 +7,7 @@ import type { FormattedData } from './types'; import { getTokensTotalInfo } from 'src/slices/token/pages/address/utils'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; @@ -29,7 +29,7 @@ const TokenSelectButton = ({ isOpen, isLoading, data, ...rest }: Props, ref: Rea return; } - mixpanel.logEvent(mixpanel.EventTypes.PAGE_WIDGET, { Type: 'Tokens dropdown' }); + analytics.logEvent(analytics.EventTypes.PAGE_WIDGET, { Type: 'Tokens dropdown' }); }, [ isLoading, isOpen ]); return ( diff --git a/src/slices/address/pages/details/info/token-select/TokenSelectItem.tsx b/src/slices/address/pages/details/info/token-select/TokenSelectItem.tsx index af07dbc6f92..946ada1044c 100644 --- a/src/slices/address/pages/details/info/token-select/TokenSelectItem.tsx +++ b/src/slices/address/pages/details/info/token-select/TokenSelectItem.tsx @@ -8,7 +8,9 @@ import { isConfidentialTokenType, isFungibleTokenType } from 'src/slices/token/u import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; import NativeTokenTag from 'src/slices/token/components/NativeTokenTag'; +import TokenMultiplierTag from 'src/slices/token/components/ui-multiplier/TokenMultiplierTag'; import type { TokenEnhancedData } from 'src/slices/token/pages/address/utils'; +import { getUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; import multichainConfig from 'src/features/multichain/chains-config'; @@ -17,7 +19,10 @@ import { route } from 'src/shared/router/routes'; import calculateUsdValue from 'src/shared/values/entity/calculateUsdValue'; import { Link } from 'src/toolkit/chakra/link'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; + +const DEFAULT_FUNGIBLE_DECIMALS = 18; +const FULL_PRECISION = 0; interface Props { data: TokenEnhancedData; @@ -48,7 +53,7 @@ const TokenSelectItem = ({ data }: Props) => { return ( <> - <TruncatedText text={ text }/> + <Truncate value={ text } type="end"/> { data.token.exchange_rate && <chakra.span ml={ 2 }>@{ Number(data.token.exchange_rate).toLocaleString() }</chakra.span> } </> ); @@ -57,13 +62,23 @@ const TokenSelectItem = ({ data }: Props) => { const isFungibleToken = isFungibleTokenType(data.token.type, chain?.app_config); if (isFungibleToken) { - const tokenDecimals = Number(data.token.decimals ?? 18); - const text = `${ BigNumber(data.value ?? '0').dividedBy(10 ** tokenDecimals).toFormat() } ${ data.token.symbol || '' }`; + const multiplier = getUiMultiplier(data.token, chain?.app_config); + const { valueStr } = calculateUsdValue({ + amount: data.value, + decimals: data.token.decimals ?? DEFAULT_FUNGIBLE_DECIMALS, + multiplier, + accuracy: FULL_PRECISION, + }); + const text = `${ valueStr } ${ data.token.symbol || '' }`; + const exchangeRate = data.token.exchange_rate ? `@${ Number(data.token.exchange_rate).toLocaleString() }` : undefined; return ( <> - <TruncatedText text={ text }/> - { data.token.exchange_rate && <chakra.span ml={ 2 }>@{ Number(data.token.exchange_rate).toLocaleString() }</chakra.span> } + <Flex alignItems="center" gap={ 1 } maxW={ exchangeRate ? '60%' : '100%' }> + { multiplier && <TokenMultiplierTag multiplier={ multiplier }/> } + <Truncate value={ text } type="end"/> + </Flex> + { exchangeRate && <Truncate value={ exchangeRate } type="end" maxW="40%" ml={ 2 }/> } </> ); } @@ -71,7 +86,7 @@ const TokenSelectItem = ({ data }: Props) => { switch (data.token.type) { case 'ERC-721': { const text = `${ BigNumber(data.value ?? '0').toFormat() } ${ data.token.symbol || '' }`; - return <TruncatedText text={ text }/>; + return <Truncate value={ text } type="end"/>; } case 'ERC-1155': { return ( @@ -138,14 +153,11 @@ const TokenSelectItem = ({ data }: Props) => { /> { isNativeToken && <NativeTokenTag mr={ 2 }/> } { data.usd && ( - <TruncatedText - text={ `$${ data.usd.toFormat(2) }` } - fontWeight={ 700 } + <Truncate value={ `$${ data.usd.toFormat(2) }` } type="end" fontWeight={ 700 } minW="120px" ml="auto" textAlign="right" - color={ isNativeToken ? 'text.secondary' : undefined } - /> + color={ isNativeToken ? 'text.secondary' : undefined }/> ) } </Flex> <Flex alignItems="center" justifyContent="space-between" w="100%" whiteSpace="nowrap" color={ isNativeToken ? 'text.secondary' : undefined }> diff --git a/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_dark-color-mode_base-view-dark-mode-1.png index ba1c4855d4c..327d1a38f25 100644 Binary files a/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and b/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_dark-color-mode_base-view-dark-mode-2.png b/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_dark-color-mode_base-view-dark-mode-2.png index a5f0b6d84fe..4a41527c675 100644 Binary files a/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_dark-color-mode_base-view-dark-mode-2.png and b/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_dark-color-mode_base-view-dark-mode-2.png differ diff --git a/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_base-view-dark-mode-1.png b/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_base-view-dark-mode-1.png index 494dba3ea52..d6fc211d4e1 100644 Binary files a/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_base-view-dark-mode-1.png and b/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_base-view-dark-mode-2.png b/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_base-view-dark-mode-2.png index 32655955d6a..103cbea1579 100644 Binary files a/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_base-view-dark-mode-2.png and b/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_base-view-dark-mode-2.png differ diff --git a/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_long-values-1.png b/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_long-values-1.png index 53b8417b7c7..997bb5a119b 100644 Binary files a/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_long-values-1.png and b/src/slices/address/pages/details/info/token-select/__screenshots__/TokenSelect.pw.tsx_default_long-values-1.png differ diff --git a/src/slices/address/pages/details/internal-txs/AddressInternalTxs.pw.tsx b/src/slices/address/pages/details/internal-txs/AddressInternalTxs.pw.tsx index 5b4f95aec9d..3f96ec3eccf 100644 --- a/src/slices/address/pages/details/internal-txs/AddressInternalTxs.pw.tsx +++ b/src/slices/address/pages/details/internal-txs/AddressInternalTxs.pw.tsx @@ -3,6 +3,8 @@ import React from 'react'; import * as internalTxsMock from 'src/slices/internal-tx/mocks'; +import * as csvExportMock from 'src/features/csv-export/mocks'; + import { test, expect } from 'playwright/lib'; import AddressInternalTxs from './AddressInternalTxs'; @@ -14,11 +16,12 @@ const hooksConfig = { }, }; -test('base view +@mobile', async({ render, mockApiResponse }) => { +test('base view', async({ render, mockApiResponse }) => { test.slow(); await mockApiResponse('core:address_internal_txs', internalTxsMock.baseResponse, { pathParams: { hash: ADDRESS_HASH } }); + await mockApiResponse('core:config_csv_export', csvExportMock.config); const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> + <Box pt={ 6 }> <AddressInternalTxs/> </Box>, { hooksConfig }, diff --git a/src/slices/address/pages/details/internal-txs/AddressInternalTxs.tsx b/src/slices/address/pages/details/internal-txs/AddressInternalTxs.tsx index 1cea32d9e1a..a5eddd5229c 100644 --- a/src/slices/address/pages/details/internal-txs/AddressInternalTxs.tsx +++ b/src/slices/address/pages/details/internal-txs/AddressInternalTxs.tsx @@ -25,7 +25,7 @@ const AddressInternalTxs = ({ shouldRender = true, isQueryEnabled = true }: Prop const isMounted = useIsMounted(); const { hash, query, filterValue, onFilterChange } = useAddressInternalTxsQuery({ enabled: isQueryEnabled }); - const { data, isPlaceholderData, isError, pagination } = query; + const { data, isInitialLoading, isTransitioning, isError, pagination } = query; if (!isMounted || !shouldRender) { return null; @@ -33,7 +33,7 @@ const AddressInternalTxs = ({ shouldRender = true, isQueryEnabled = true }: Prop const content = data?.items ? ( <TableContainerScrollable> - <InternalTxsTable data={ data.items } currentAddress={ hash } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> + <InternalTxsTable data={ data.items } currentAddress={ hash } isLoading={ isInitialLoading } resetKey={ query.queryHash }/> </TableContainerScrollable> ) : null ; @@ -65,6 +65,7 @@ const AddressInternalTxs = ({ shouldRender = true, isQueryEnabled = true }: Prop isError={ isError } itemsNum={ data?.items.length } hasActiveFilters={ Boolean(filterValue) } + isTransitioning={ isTransitioning } emptyStateProps={{ term: 'transaction', }} diff --git a/src/slices/address/pages/details/internal-txs/__screenshots__/AddressInternalTxs.pw.tsx_default_base-view-1.png b/src/slices/address/pages/details/internal-txs/__screenshots__/AddressInternalTxs.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..c6ae1225add Binary files /dev/null and b/src/slices/address/pages/details/internal-txs/__screenshots__/AddressInternalTxs.pw.tsx_default_base-view-1.png differ diff --git a/src/slices/address/pages/details/internal-txs/__screenshots__/AddressInternalTxs.pw.tsx_default_base-view-mobile-1.png b/src/slices/address/pages/details/internal-txs/__screenshots__/AddressInternalTxs.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 3493ea77969..00000000000 Binary files a/src/slices/address/pages/details/internal-txs/__screenshots__/AddressInternalTxs.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/internal-txs/__screenshots__/AddressInternalTxs.pw.tsx_mobile_base-view-mobile-1.png b/src/slices/address/pages/details/internal-txs/__screenshots__/AddressInternalTxs.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 0486c358a64..00000000000 Binary files a/src/slices/address/pages/details/internal-txs/__screenshots__/AddressInternalTxs.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/internal-txs/useAddressInternalTxsQuery.ts b/src/slices/address/pages/details/internal-txs/useAddressInternalTxsQuery.ts index 623f20af9ec..9433aa617b7 100644 --- a/src/slices/address/pages/details/internal-txs/useAddressInternalTxsQuery.ts +++ b/src/slices/address/pages/details/internal-txs/useAddressInternalTxsQuery.ts @@ -1,34 +1,32 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; +import type { ExternalChainExtended } from 'src/shared/external-chains/types'; import { AddressFromToFilterValues, type AddressFromToFilter } from 'src/slices/address/types/api'; import { INTERNAL_TX } from 'src/slices/internal-tx/stubs'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getFilterValueFromQuery from 'src/shared/router/get-filter-value-from-query'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; const getFilterValue = (getFilterValueFromQuery<AddressFromToFilter>).bind(null, AddressFromToFilterValues); interface Props { enabled: boolean; - isMultichain?: boolean; - chainIds?: Array<string>; + chain?: ExternalChainExtended; } -export default function useAddressInternalTxsQuery({ enabled, isMultichain, chainIds }: Props) { +export default function useAddressInternalTxsQuery({ enabled, chain }: Props) { const router = useRouter(); const hash = getQueryParamString(router.query.hash); - const [ filterValue, setFilterValue ] = React.useState<AddressFromToFilter>(getFilterValue(router.query.filter)); - const query = useQueryWithPages({ + const query = useApiPaginatedQuery({ resourceName: 'core:address_internal_txs', pathParams: { hash }, - filters: { filter: filterValue }, options: { enabled, placeholderData: generateListStub<'core:address_internal_txs'>( @@ -48,15 +46,15 @@ export default function useAddressInternalTxsQuery({ enabled, isMultichain, chai }, ), }, - isMultichain, - chainIds, + chain, }); + const filterValue = getFilterValue(query.filters.filter); + + const { onFilterChange: onQueryFilterChange } = query; const onFilterChange = React.useCallback((val: string | Array<string>) => { - const newVal = getFilterValue(val); - setFilterValue(newVal); - query.onFilterChange({ filter: newVal }); - }, [ query ]); + onQueryFilterChange({ filter: getFilterValue(val) }); + }, [ onQueryFilterChange ]); return React.useMemo(() => ({ hash, diff --git a/src/slices/address/pages/details/logs/AddressLogs.tsx b/src/slices/address/pages/details/logs/AddressLogs.tsx index 11b2ea2304b..2f74eaf70cc 100644 --- a/src/slices/address/pages/details/logs/AddressLogs.tsx +++ b/src/slices/address/pages/details/logs/AddressLogs.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import ActionBar from 'src/shell/page/action-bar/ActionBar'; @@ -15,9 +14,10 @@ import useIsMounted from 'src/shared/hooks/useIsMounted'; import DataList from 'src/shared/lists/DataList'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; // log rows are tall, so the initial window is smaller than the default const INITIAL_RENDERED_ITEMS_NUM = 10; @@ -32,7 +32,7 @@ const AddressLogs = ({ shouldRender = true, isQueryEnabled = true }: Props) => { const isMounted = useIsMounted(); const hash = getQueryParamString(router.query.hash); - const { data, isPlaceholderData, isError, pagination, queryHash } = useQueryWithPages({ + const { data, isInitialLoading, isTransitioning, isError, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:address_logs', pathParams: { hash }, options: { @@ -48,7 +48,7 @@ const AddressLogs = ({ shouldRender = true, isQueryEnabled = true }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data?.items, - isEnabled: !isPlaceholderData, + isEnabled: !isInitialLoading, minItemsNum: INITIAL_RENDERED_ITEMS_NUM, resetKey: queryHash, }); @@ -73,10 +73,10 @@ const AddressLogs = ({ shouldRender = true, isQueryEnabled = true }: Props) => { const renderedLogs = data?.items?.slice(0, renderedItemsNum).map((item, index) => ( <LogItem - key={ index } + key={ item.transaction_hash + '_' + item.index + (isInitialLoading ? index : '') } data={ item } type="address" - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } defaultDataType={ addressQuery.data?.zilliqa?.is_scilla_contract ? 'UTF-8' : undefined } /> )); @@ -94,6 +94,7 @@ const AddressLogs = ({ shouldRender = true, isQueryEnabled = true }: Props) => { itemsNum={ data?.items?.length } emptyText="There are no logs for this address." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/slices/address/pages/details/token-transfers/AddressTokenTransfers.pw.tsx b/src/slices/address/pages/details/token-transfers/AddressTokenTransfers.pw.tsx deleted file mode 100644 index 0d07f2372ba..00000000000 --- a/src/slices/address/pages/details/token-transfers/AddressTokenTransfers.pw.tsx +++ /dev/null @@ -1,236 +0,0 @@ -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import * as tokenTransferMock from 'src/slices/token-transfer/mocks'; - -import * as socketServer from 'playwright/fixtures/socketServer'; -import { test, expect, devices } from 'playwright/lib'; - -import AddressTokenTransfers from './AddressTokenTransfers'; - -const CURRENT_ADDRESS = '0xd789a607CEac2f0E14867de4EB15b15C9FFB5859'; -const hooksConfig = { - router: { - query: { hash: CURRENT_ADDRESS, tab: 'token_transfers' }, - }, -}; - -// FIXME -// test cases which use socket cannot run in parallel since the socket server always run on the same port -test.describe.configure({ mode: 'serial' }); - -const tokenTransfersWithPagination = { - items: [ tokenTransferMock.erc1155A ], - next_page_params: { block_number: 1, index: 1, items_count: 1 }, -}; -const tokenTransfersWoPagination = { - items: [ tokenTransferMock.erc1155A ], - next_page_params: null, -}; - -test('with pagination', async({ render, mockApiResponse }) => { - await mockApiResponse('core:address_token_transfers', tokenTransfersWithPagination, { - pathParams: { hash: CURRENT_ADDRESS }, - queryParams: { type: [] }, - }); - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTokenTransfers/> - </Box>, - { hooksConfig }, - ); - await expect(component).toHaveScreenshot(); -}); - -test('without pagination', async({ render, mockApiResponse }) => { - await mockApiResponse('core:address_token_transfers', tokenTransfersWoPagination, { - pathParams: { hash: CURRENT_ADDRESS }, - queryParams: { type: [] }, - }); - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTokenTransfers/> - </Box>, - { hooksConfig }, - ); - await expect(component).toHaveScreenshot(); -}); - -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - - test('with pagination', async({ render, mockApiResponse }) => { - await mockApiResponse('core:address_token_transfers', tokenTransfersWithPagination, { - pathParams: { hash: CURRENT_ADDRESS }, - queryParams: { type: [] }, - }); - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTokenTransfers/> - </Box>, - { hooksConfig }, - ); - await expect(component).toHaveScreenshot(); - }); - - test('without pagination', async({ render, mockApiResponse }) => { - await mockApiResponse('core:address_token_transfers', tokenTransfersWoPagination, { - pathParams: { hash: CURRENT_ADDRESS }, - queryParams: { type: [] }, - }); - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTokenTransfers/> - </Box>, - { hooksConfig }, - ); - await expect(component).toHaveScreenshot(); - }); -}); - -test.describe('socket', () => { - test('without overload', async({ render, mockApiResponse, createSocket, page }) => { - const hooksConfigNoToken = { - router: { - query: { hash: CURRENT_ADDRESS, tab: 'token_transfers' }, - }, - }; - await mockApiResponse('core:address_token_transfers', tokenTransfersWithPagination, { - pathParams: { hash: CURRENT_ADDRESS }, - queryParams: { type: [] }, - }); - await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTokenTransfers/> - </Box>, - { hooksConfig: hooksConfigNoToken }, - { withSocket: true }, - ); - - const socket = await createSocket(); - const channel = await socketServer.joinChannel(socket, `addresses:${ CURRENT_ADDRESS.toLowerCase() }`); - - const itemsCount = await page.locator('tbody tr').count(); - expect(itemsCount).toBe(2); - - socketServer.sendMessage(socket, channel, 'token_transfer', { token_transfers: [ tokenTransferMock.erc1155B, tokenTransferMock.erc1155C ] }); - - const thirdRow = page.locator('tbody tr:nth-child(3)'); - await thirdRow.waitFor(); - - const itemsCountNew = await page.locator('tbody tr').count(); - expect(itemsCountNew).toBe(4); - }); - - test('with overload', async({ render, mockApiResponse, page, createSocket }) => { - const hooksConfigNoToken = { - router: { - query: { hash: CURRENT_ADDRESS, tab: 'token_transfers' }, - }, - }; - await mockApiResponse('core:address_token_transfers', tokenTransfersWithPagination, { - pathParams: { hash: CURRENT_ADDRESS }, - queryParams: { type: [] }, - }); - await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTokenTransfers overloadCount={ 2 }/> - </Box>, - { hooksConfig: hooksConfigNoToken }, - { withSocket: true }, - ); - - const socket = await createSocket(); - const channel = await socketServer.joinChannel(socket, `addresses:${ CURRENT_ADDRESS.toLowerCase() }`); - - const itemsCount = await page.locator('tbody tr').count(); - expect(itemsCount).toBe(2); - - socketServer.sendMessage(socket, channel, 'token_transfer', { token_transfers: [ tokenTransferMock.erc1155B, tokenTransferMock.erc1155C ] }); - - const thirdRow = page.locator('tbody tr:nth-child(3)'); - await thirdRow.waitFor(); - - const itemsCountNew = await page.locator('tbody tr').count(); - expect(itemsCountNew).toBe(3); - - const counter = await page.locator('tbody tr:nth-child(1)').textContent(); - expect(counter?.startsWith('1 ')).toBe(true); - }); - - test('without overload, with filters', async({ render, mockApiResponse, page, createSocket }) => { - const hooksConfigWithFilter = { - router: { - query: { hash: CURRENT_ADDRESS, type: 'ERC-1155', tab: 'token_transfers' }, - }, - }; - await mockApiResponse('core:address_token_transfers', tokenTransfersWithPagination, { - pathParams: { hash: CURRENT_ADDRESS }, - queryParams: { type: 'ERC-1155' }, - }); - - await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTokenTransfers/> - </Box>, - { hooksConfig: hooksConfigWithFilter }, - { withSocket: true }, - ); - - const socket = await createSocket(); - const channel = await socketServer.joinChannel(socket, `addresses:${ CURRENT_ADDRESS.toLowerCase() }`); - - const itemsCount = await page.locator('tbody tr').count(); - expect(itemsCount).toBe(2); - - socketServer.sendMessage(socket, channel, 'token_transfer', { token_transfers: [ tokenTransferMock.erc1155B, tokenTransferMock.erc20 ] }); - - const thirdRow = page.locator('tbody tr:nth-child(3)'); - await thirdRow.waitFor(); - - const itemsCountNew = await page.locator('tbody tr').count(); - expect(itemsCountNew).toBe(3); - }); - - test('with overload, with filters', async({ render, mockApiResponse, page, createSocket }) => { - const hooksConfigWithFilter = { - router: { - query: { hash: CURRENT_ADDRESS, type: 'ERC-1155', tab: 'token_transfers' }, - }, - }; - await mockApiResponse('core:address_token_transfers', tokenTransfersWithPagination, { - pathParams: { hash: CURRENT_ADDRESS }, - queryParams: { type: 'ERC-1155' }, - }); - - await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTokenTransfers overloadCount={ 2 }/> - </Box>, - { hooksConfig: hooksConfigWithFilter }, - { withSocket: true }, - ); - - const socket = await createSocket(); - const channel = await socketServer.joinChannel(socket, `addresses:${ CURRENT_ADDRESS.toLowerCase() }`); - - const itemsCount = await page.locator('tbody tr').count(); - expect(itemsCount).toBe(2); - - socketServer.sendMessage( - socket, - channel, - 'token_transfer', - { token_transfers: [ tokenTransferMock.erc1155B, tokenTransferMock.erc20, tokenTransferMock.erc1155C, tokenTransferMock.erc721 ] }, - ); - - const thirdRow = page.locator('tbody tr:nth-child(3)'); - await thirdRow.waitFor(); - - const itemsCountNew = await page.locator('tbody tr').count(); - expect(itemsCountNew).toBe(3); - - const counter = await page.locator('tbody tr:nth-child(1)').textContent(); - expect(counter?.startsWith('1 ')).toBe(true); - }); -}); diff --git a/src/slices/address/pages/details/token-transfers/AddressTokenTransfers.spec.tsx b/src/slices/address/pages/details/token-transfers/AddressTokenTransfers.spec.tsx new file mode 100644 index 00000000000..762afac2a64 --- /dev/null +++ b/src/slices/address/pages/details/token-transfers/AddressTokenTransfers.spec.tsx @@ -0,0 +1,97 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import type { schemas } from '@blockscout/api-types'; + +import { SocketProvider } from 'src/api/socket/context'; + +import * as tokenTransferMock from 'src/slices/token-transfer/mocks'; + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { render, screen, cleanup, act, waitFor } from 'vitest/lib'; +import { MOCK_SOCKET_URL, sendSocketMessage } from 'vitest/utils/mockSocket'; +import { routerStandIn, RouterStandInProvider } from 'vitest/utils/routerStandIn'; + +vi.mock('phoenix', () => import('vitest/utils/mockSocket').then((m) => m.phoenixModule)); + +import AddressTokenTransfers from './AddressTokenTransfers'; + +const CURRENT_ADDRESS = '0xd789a607CEac2f0E14867de4EB15b15C9FFB5859'; +const TOPIC = `addresses:${ CURRENT_ADDRESS.toLowerCase() }`; + +const LIST_RESPONSE = { + items: [ tokenTransferMock.erc1155A ], + next_page_params: { block_number: 1, index: 1, items_count: 1 }, +}; + +beforeEach(() => { + fetchMock.resetMocks(); + fetchMock.mockResponse((request) => { + if (request.url.includes(`/addresses/${ CURRENT_ADDRESS }/token-transfers`)) { + return { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(LIST_RESPONSE) }; + } + return { status: 404, body: '{}' }; + }); +}); + +afterEach(cleanup); + +async function renderTab(query: Record<string, string>, overloadCount?: number) { + routerStandIn.reset({ pathname: '/address/[hash]', query: { hash: CURRENT_ADDRESS, tab: 'token_transfers', ...query } }); + render( + <RouterStandInProvider> + <SocketProvider url={ MOCK_SOCKET_URL }> + <AddressTokenTransfers overloadCount={ overloadCount }/> + </SocketProvider> + </RouterStandInProvider>, + ); + // the listed transfer plus the socket notice row + await waitFor(() => expect(getRows()).toHaveLength(2)); +} + +function getRows() { + return document.querySelectorAll('tbody tr'); +} + +function sendTransfers(transfers: Array<schemas['TokenTransfer']>) { + act(() => { + sendSocketMessage(TOPIC, 'token_transfer', { token_transfers: transfers }); + }); +} + +describe('address token transfers tab, live updates', () => { + it('prepends new transfers to the table', async() => { + await renderTab({}); + + sendTransfers([ tokenTransferMock.erc1155B, tokenTransferMock.erc1155C ]); + + await waitFor(() => expect(getRows()).toHaveLength(4)); + }); + + it('counts transfers in the notice instead of adding rows once the list is full', async() => { + await renderTab({}, 2); + + sendTransfers([ tokenTransferMock.erc1155B, tokenTransferMock.erc1155C ]); + + expect(await screen.findByText('1 more token transfer')).toBeTruthy(); + expect(getRows()).toHaveLength(3); + }); + + it('adds only the transfers that match the type filter', async() => { + await renderTab({ type: 'ERC-1155' }); + + sendTransfers([ tokenTransferMock.erc1155B, tokenTransferMock.erc20 ]); + + await waitFor(() => expect(getRows()).toHaveLength(3)); + }); + + it('counts only the transfers that match the type filter once the list is full', async() => { + await renderTab({ type: 'ERC-1155' }, 2); + + sendTransfers([ tokenTransferMock.erc1155B, tokenTransferMock.erc20, tokenTransferMock.erc1155C, tokenTransferMock.erc721 ]); + + expect(await screen.findByText('1 more token transfer')).toBeTruthy(); + expect(getRows()).toHaveLength(3); + }); +}); diff --git a/src/slices/address/pages/details/token-transfers/AddressTokenTransfers.tsx b/src/slices/address/pages/details/token-transfers/AddressTokenTransfers.tsx index ed667847d89..5b3129024e8 100644 --- a/src/slices/address/pages/details/token-transfers/AddressTokenTransfers.tsx +++ b/src/slices/address/pages/details/token-transfers/AddressTokenTransfers.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import TokenTransferFilter from 'src/slices/token-transfer/components/TokenTransferFilter'; +import { useTokenTransferColumns } from 'src/slices/token-transfer/hooks/useTokenTransferColumns'; import AddressAdvancedFilterLink from 'src/features/advanced-filter/components/AddressAdvancedFilterLink'; import TokenTransfersCrossChainContent from 'src/features/cross-chain-txs/components/token-transfers/TokenTransfersCrossChainContent'; @@ -16,10 +16,12 @@ import CsvExport from 'src/features/csv-export/components/CsvExport'; import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import useIsMounted from 'src/shared/hooks/useIsMounted'; +import ColumnsButton from 'src/shared/lists/columns/ColumnsButton'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -54,8 +56,9 @@ const AddressTokenTransfers = ({ shouldRender = true, overloadCount, isQueryEnab currentAddress: hash, enabled: isQueryEnabled && isLocalTab, }); + const columnsState = useTokenTransferColumns('address', { typeFilter: localQuery.filters.type }); - const crossChainQuery = useQueryWithPages({ + const crossChainQuery = useApiPaginatedQuery({ resourceName: 'interchainIndexer:address_transfers', pathParams: { hash }, options: { @@ -64,12 +67,6 @@ const AddressTokenTransfers = ({ shouldRender = true, overloadCount, isQueryEnab }, }); - const handleTabValueChange = React.useCallback(({ value }: { value: string }) => { - if (value === 'token_transfers_local') { - localQuery.setFilters({ type: [], filter: undefined }); - } - }, [ localQuery ]); - if (!isMounted || !shouldRender) { return null; } @@ -85,6 +82,7 @@ const AddressTokenTransfers = ({ shouldRender = true, overloadCount, isQueryEnab onTypeFilterChange={ localQuery.onTypeFilterChange } onAddressFilterChange={ localQuery.onAddressFilterChange } addressHash={ hash } + columnsState={ columnsState } overloadCount={ overloadCount } /> ), @@ -93,22 +91,23 @@ const AddressTokenTransfers = ({ shouldRender = true, overloadCount, isQueryEnab id: 'token_transfers_cross_chain', title: 'Cross-chain transfers', component: ( - <> - { isMobile && crossChainQuery.pagination.isVisible && ( + <TokenTransfersCrossChainContent + items={ crossChainQuery.data?.items } + isLoading={ crossChainQuery.isInitialLoading } + isTransitioning={ crossChainQuery.isTransitioning } + isError={ crossChainQuery.isError } + pagination={ crossChainQuery.pagination } + tableTop={ ACTION_BAR_HEIGHT_DESKTOP } + currentAddress={ hash } + resetKey={ crossChainQuery.queryHash } + filters={ crossChainQuery.filters } + onFilterChange={ crossChainQuery.onFilterChange } + actionBar={ isMobile && crossChainQuery.pagination.isVisible && ( <ActionBar> <Pagination ml="auto" { ...crossChainQuery.pagination }/> </ActionBar> ) } - <TokenTransfersCrossChainContent - items={ crossChainQuery.data?.items } - isLoading={ crossChainQuery.isPlaceholderData } - isError={ crossChainQuery.isError } - pagination={ crossChainQuery.pagination } - tableTop={ ACTION_BAR_HEIGHT_DESKTOP } - currentAddress={ hash } - resetKey={ crossChainQuery.queryHash } - /> - </> + /> ), }, ].filter(Boolean); @@ -135,7 +134,16 @@ const AddressTokenTransfers = ({ shouldRender = true, overloadCount, isQueryEnab withAddressFilter onAddressFilterChange={ localQuery.onAddressFilterChange } defaultAddressFilter={ localQuery.filters.filter } - isLoading={ localQuery.query.isPlaceholderData } + isLoading={ localQuery.query.isInitialLoading } + /> + <ColumnsButton + tableColumns={ columnsState.selectableColumns } + columns={ columnsState.checkedColumns } + onChange={ columnsState.onColumnsChange } + onOrderChange={ columnsState.onColumnsReorder } + selected={ columnsState.isCustomized } + onReset={ columnsState.onColumnsReset } + isLoading={ localQuery.query.isInitialLoading } /> <CsvExport type="address_token_transfers" @@ -145,10 +153,10 @@ const AddressTokenTransfers = ({ shouldRender = true, overloadCount, isQueryEnab filter_type: 'address', filter_value: localQuery.filters.filter, } : undefined } - loadingInitial={ localQuery.query.isPlaceholderData } + loadingInitial={ localQuery.query.isInitialLoading } /> <AddressAdvancedFilterLink - isLoading={ localQuery.query.isPlaceholderData } + isLoading={ localQuery.query.isInitialLoading } address={ hash } typeFilter={ localQuery.filters.type } directionFilter={ localQuery.filters.filter } @@ -183,7 +191,6 @@ const AddressTokenTransfers = ({ shouldRender = true, overloadCount, isQueryEnab variant="secondary" size="sm" tabs={ tabs } - onValueChange={ handleTabValueChange } rightSlot={ rightSlot } rightSlotProps={ rightSlotProps } listProps={ isMobile ? undefined : TAB_LIST_PROPS } diff --git a/src/slices/address/pages/details/token-transfers/AddressTokenTransfersLocal.tsx b/src/slices/address/pages/details/token-transfers/AddressTokenTransfersLocal.tsx index 40032d67bad..82e757becd1 100644 --- a/src/slices/address/pages/details/token-transfers/AddressTokenTransfersLocal.tsx +++ b/src/slices/address/pages/details/token-transfers/AddressTokenTransfersLocal.tsx @@ -5,42 +5,44 @@ import React from 'react'; import type { TokenType } from 'src/slices/token/types/api'; -import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; +import ActionBar from 'src/shell/page/action-bar/ActionBar'; -import TokenTransferTable from 'src/slices/token-transfer/components/list/TokenTransferTable'; +import TokenTransfersTable from 'src/slices/token-transfer/components/table/TokenTransfersTable'; import TokenTransferFilter from 'src/slices/token-transfer/components/TokenTransferFilter'; +import type { TokenTransferColumnsState } from 'src/slices/token-transfer/hooks/useTokenTransferColumns'; import AddressAdvancedFilterLink from 'src/features/advanced-filter/components/AddressAdvancedFilterLink'; import CsvExport from 'src/features/csv-export/components/CsvExport'; import { useMultichainContext } from 'src/features/multichain/context'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import ColumnsButton from 'src/shared/lists/columns/ColumnsButton'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; - -import { TableContainerScrollable } from 'src/toolkit/chakra/table'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; import type { Filters } from './useAddressTokenTransfersQuery'; import useAddressTokenTransfersSocket from './useAddressTokenTransfersSocket'; interface Props { - query: QueryWithPagesResult<'core:address_token_transfers'>; + query: ApiPaginatedQueryResult<'core:address_token_transfers'>; filters: Filters; addressHash: string; onTypeFilterChange: (type: Array<TokenType>) => void; onAddressFilterChange: (filter: string) => void; + columnsState: TokenTransferColumnsState; // for tests only overloadCount?: number; } -const AddressTokenTransfersLocal = ({ query, filters, addressHash, onTypeFilterChange, onAddressFilterChange, overloadCount }: Props) => { - const { isError, isPlaceholderData, data, pagination } = query; +const AddressTokenTransfersLocal = ({ query, filters, addressHash, onTypeFilterChange, onAddressFilterChange, columnsState, overloadCount }: Props) => { + const { isError, isInitialLoading, isTransitioning, data, pagination } = query; const isMobile = useIsMobile(); const multichainContext = useMultichainContext(); const { showSocketAlert, newItemsCount } = useAddressTokenTransfersSocket({ filters, + queryFilters: query.filters, addressHash, data, overloadCount, @@ -50,20 +52,17 @@ const AddressTokenTransfersLocal = ({ query, filters, addressHash, onTypeFilterC const numActiveFilters = (filters.type?.length || 0) + (filters.filter ? 1 : 0); const content = data?.items ? ( - <TableContainerScrollable> - <TokenTransferTable - data={ data?.items } - baseAddress={ addressHash } - showTxInfo - top={ ACTION_BAR_HEIGHT_DESKTOP } - enableTimeIncrement - showSocketInfo={ pagination.page === 1 } - showSocketErrorAlert={ showSocketAlert } - socketInfoNum={ newItemsCount } - isLoading={ isPlaceholderData } - resetKey={ query.queryHash } - /> - </TableContainerScrollable> + <TokenTransfersTable + columns={ columnsState.columns } + items={ data.items } + baseAddress={ addressHash } + enableTimeIncrement + showSocketInfo={ pagination.page === 1 } + showSocketErrorAlert={ showSocketAlert } + socketInfoNum={ newItemsCount } + isLoading={ isInitialLoading } + resetKey={ query.queryHash } + /> ) : null; const actionBar = isMobile ? ( @@ -76,9 +75,18 @@ const AddressTokenTransfersLocal = ({ query, filters, addressHash, onTypeFilterC withAddressFilter onAddressFilterChange={ onAddressFilterChange } defaultAddressFilter={ filters.filter } - isLoading={ query.isPlaceholderData } + isLoading={ isInitialLoading } chainConfig={ multichainContext?.chain?.app_config } /> + <ColumnsButton + tableColumns={ columnsState.selectableColumns } + columns={ columnsState.checkedColumns } + onChange={ columnsState.onColumnsChange } + onOrderChange={ columnsState.onColumnsReorder } + selected={ columnsState.isCustomized } + onReset={ columnsState.onColumnsReset } + isLoading={ isInitialLoading } + /> <CsvExport type="address_token_transfers" resourceName="core:address_csv_export_token_transfers" @@ -87,10 +95,10 @@ const AddressTokenTransfersLocal = ({ query, filters, addressHash, onTypeFilterC filter_type: 'address', filter_value: filters.filter, } : undefined } - loadingInitial={ isPlaceholderData } + loadingInitial={ isInitialLoading } /> <AddressAdvancedFilterLink - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } address={ addressHash } typeFilter={ filters.type } directionFilter={ filters.filter } @@ -106,6 +114,7 @@ const AddressTokenTransfersLocal = ({ query, filters, addressHash, onTypeFilterC itemsNum={ data?.items?.length } emptyText="There are no token transfers." hasActiveFilters={ Boolean(numActiveFilters) } + isTransitioning={ isTransitioning } emptyStateProps={{ term: 'token transfer', }} diff --git a/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_mobile-with-pagination-1.png b/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_mobile-with-pagination-1.png deleted file mode 100644 index 87371239f5c..00000000000 Binary files a/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_mobile-with-pagination-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_mobile-without-pagination-1.png b/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_mobile-without-pagination-1.png deleted file mode 100644 index 1a2e5271af5..00000000000 Binary files a/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_mobile-without-pagination-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_with-pagination-1.png b/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_with-pagination-1.png deleted file mode 100644 index 55342a214f0..00000000000 Binary files a/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_with-pagination-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_without-pagination-1.png b/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_without-pagination-1.png deleted file mode 100644 index 66683a13af2..00000000000 Binary files a/src/slices/address/pages/details/token-transfers/__screenshots__/AddressTokenTransfers.pw.tsx_default_without-pagination-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/token-transfers/useAddressTokenTransfersQuery.ts b/src/slices/address/pages/details/token-transfers/useAddressTokenTransfersQuery.ts index b77545265bc..c27a8b24c62 100644 --- a/src/slices/address/pages/details/token-transfers/useAddressTokenTransfersQuery.ts +++ b/src/slices/address/pages/details/token-transfers/useAddressTokenTransfersQuery.ts @@ -1,21 +1,20 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; import type { AddressFromToFilter } from 'src/slices/address/types/api'; import { AddressFromToFilterValues } from 'src/slices/address/types/api'; import type { TokenType } from 'src/slices/token/types/api'; import { getTokenTypes } from 'src/slices/token/utils/token-types'; -import { getTokenTransfersStub } from 'src/slices/token-transfer/stubs'; +import type { PaginationFilters } from 'src/api/resources'; -import multichainConfig from 'src/features/multichain/chains-config'; +import { getTokenTransfersStub } from 'src/slices/token-transfer/stubs'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import getFilterValueFromQuery from 'src/shared/router/get-filter-value-from-query'; import getFilterValuesFromQuery from 'src/shared/router/get-filter-values-from-query'; -import getQueryParamString from 'src/shared/router/get-query-param-string'; export type Filters = { type: Array<TokenType>; @@ -24,46 +23,26 @@ export type Filters = { const getAddressFilterValue = (getFilterValueFromQuery<AddressFromToFilter>).bind(null, AddressFromToFilterValues); -const getFilters = (query: Record<string, string | Array<string> | undefined>, chainIds?: Array<string>) => { - const chainIdParam = getQueryParamString(query.chain_id); - const filterParam = getQueryParamString(query.filter); - const typeParam = getQueryParamString(query.type); +const NO_TYPES: Array<TokenType> = []; - const currentChainId = chainIdParam && chainIds?.includes(chainIdParam) ? chainIdParam : chainIds?.[0]; - const chainConfig = multichainConfig()?.chains.find(chain => chain.id === currentChainId); - - return { - filter: getAddressFilterValue(filterParam), - type: getFilterValuesFromQuery( - Object.keys(getTokenTypes('all', chainConfig?.app_config)), - typeParam, - ) || [], - }; -}; +const getFilters = (queryFilters: PaginationFilters<'core:address_token_transfers'>, chain: ClusterChainConfig | undefined): Filters => ({ + filter: getAddressFilterValue(queryFilters.filter), + type: getFilterValuesFromQuery( + Object.keys(getTokenTypes('all', chain?.app_config)), + queryFilters.type, + ) || NO_TYPES, +}); interface Props { currentAddress: string; enabled?: boolean; - isMultichain?: boolean; - chainIds?: Array<string>; + chain?: ClusterChainConfig; } -export default function useAddressTokenTransfersQuery({ currentAddress, enabled, isMultichain, chainIds }: Props) { - const router = useRouter(); - - const [ filters, setFilters ] = React.useState<Filters>(getFilters(router.query, chainIds)); - - React.useEffect(() => { - if (enabled) { - setFilters(getFilters(router.query, chainIds)); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ enabled ]); - - const query = useQueryWithPages({ +export default function useAddressTokenTransfersQuery({ currentAddress, enabled, chain }: Props) { + const query = useApiPaginatedQuery({ resourceName: 'core:address_token_transfers', pathParams: { hash: currentAddress }, - filters, options: { enabled, placeholderData: getTokenTransfersStub(undefined, { @@ -72,26 +51,24 @@ export default function useAddressTokenTransfersQuery({ currentAddress, enabled, items_count: 50, }), }, - isMultichain, - chainIds, + chain, }); + const filters = React.useMemo(() => getFilters(query.filters, chain), [ query.filters, chain ]); + + const { onFilterChange } = query; const onTypeFilterChange = React.useCallback((nextValue: Array<TokenType>) => { - query.onFilterChange({ ...filters, type: nextValue }); - setFilters((prevState) => ({ ...prevState, type: nextValue })); - }, [ filters, query ]); + onFilterChange({ ...filters, type: nextValue }); + }, [ filters, onFilterChange ]); const onAddressFilterChange = React.useCallback((nextValue: string) => { - const filterVal = getAddressFilterValue(nextValue); - query.onFilterChange({ ...filters, filter: filterVal }); - setFilters((prevState) => ({ ...prevState, filter: filterVal })); - }, [ filters, query ]); + onFilterChange({ ...filters, filter: getAddressFilterValue(nextValue) }); + }, [ filters, onFilterChange ]); return React.useMemo(() => ({ query, filters, - setFilters, onTypeFilterChange, onAddressFilterChange, - }), [ query, filters, setFilters, onTypeFilterChange, onAddressFilterChange ]); + }), [ query, filters, onTypeFilterChange, onAddressFilterChange ]); } diff --git a/src/slices/address/pages/details/token-transfers/useAddressTokenTransfersSocket.ts b/src/slices/address/pages/details/token-transfers/useAddressTokenTransfersSocket.ts index 1f38e03e61f..520c16229cf 100644 --- a/src/slices/address/pages/details/token-transfers/useAddressTokenTransfersSocket.ts +++ b/src/slices/address/pages/details/token-transfers/useAddressTokenTransfersSocket.ts @@ -7,6 +7,7 @@ import type { paths, schemas } from '@blockscout/api-types'; import type { SocketMessage } from 'src/api/socket/types'; import { getResourceKey } from 'src/api/hooks/useApiQuery'; +import type { PaginationFilters } from 'src/api/resources'; import useSocketChannel from 'src/api/socket/useSocketChannel'; import useSocketMessage from 'src/api/socket/useSocketMessage'; @@ -47,13 +48,15 @@ type AddressTokenTransferResponse = paths['/api/v2/addresses/{address_hash_param interface Props { filters: Filters; + // raw URL filter values the list query is keyed by; on page 1 the paginated hook's query key is exactly these (or none) + queryFilters: PaginationFilters<'core:address_token_transfers'>; addressHash: string; data: AddressTokenTransferResponse | undefined; overloadCount?: number; enabled: boolean; } -export default function useAddressTokenTransfersSocket({ filters, addressHash, data, overloadCount = OVERLOAD_COUNT, enabled }: Props) { +export default function useAddressTokenTransfersSocket({ filters, queryFilters, addressHash, data, overloadCount = OVERLOAD_COUNT, enabled }: Props) { const { cookies: appCookies } = useAppContext(); const [ showSocketAlert, setShowSocketAlert ] = React.useState(false); const [ newItemsCount, setNewItemsCount ] = React.useState(0); @@ -88,7 +91,7 @@ export default function useAddressTokenTransfersSocket({ filters, addressHash, d if (newItems.length > 0) { const queryKey = getResourceKey('core:address_token_transfers', { pathParams: { hash: addressHash }, - queryParams: { ...filters }, + queryParams: Object.keys(queryFilters).length ? queryFilters : undefined, chainId: multichainContext?.chain?.id, }); queryClient.setQueryData( @@ -109,7 +112,7 @@ export default function useAddressTokenTransfersSocket({ filters, addressHash, d ); } - }, [ data?.items, overloadCount, enabled, filters, addressHash, multichainContext?.chain?.id, queryClient, shouldHideScamTokens ]); + }, [ data?.items, overloadCount, enabled, filters, queryFilters, addressHash, multichainContext?.chain?.id, queryClient, shouldHideScamTokens ]); const handleSocketClose = React.useCallback(() => { setShowSocketAlert(true); diff --git a/src/slices/address/pages/details/tokens/AddressTokens.pw.tsx b/src/slices/address/pages/details/tokens/AddressTokens.pw.tsx index 81205d49e86..a579446bc98 100644 --- a/src/slices/address/pages/details/tokens/AddressTokens.pw.tsx +++ b/src/slices/address/pages/details/tokens/AddressTokens.pw.tsx @@ -1,16 +1,19 @@ import { Box } from '@chakra-ui/react'; -import React from 'react'; import type { paths, schemas } from '@blockscout/api-types'; import * as addressMock from 'src/slices/address/mocks/address'; +import * as statsMock from 'src/slices/chain/stats/mocks'; import * as tokensMock from 'src/slices/token/mocks/address-tokens'; import * as tokenInfo from 'src/slices/token/mocks/info'; import * as tokenInstance from 'src/slices/token/mocks/instance'; import { toTokenModel } from 'src/slices/token/utils/model'; +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + import * as socketServer from 'playwright/fixtures/socketServer'; -import { test, expect, devices } from 'playwright/lib'; +import type { TestFnArgs } from 'playwright/lib'; +import { devices, expect, test } from 'playwright/lib'; import AddressTokens from './AddressTokens'; @@ -24,7 +27,7 @@ const nextPageParams = { fiat_value: '1', }; -test.beforeEach(async({ mockApiResponse }) => { +const mockAddressTokens = async(mockApiResponse: TestFnArgs['mockApiResponse'], mockAssetResponse: TestFnArgs['mockAssetResponse']) => { const response20: paths['/api/v2/addresses/{address_hash_param}/tokens']['get'] = { items: [ tokensMock.erc20a, tokensMock.erc20b, tokensMock.erc20c, tokensMock.erc20d ], next_page_params: nextPageParams, @@ -41,21 +44,52 @@ test.beforeEach(async({ mockApiResponse }) => { items: [ tokensMock.erc404a, tokensMock.erc404b ], next_page_params: nextPageParams, }; + const responseFungible: paths['/api/v2/addresses/{address_hash_param}/tokens']['get'] = { + items: [ tokensMock.erc20a, tokensMock.erc20b, tokensMock.erc20c, tokensMock.erc20d, tokensMock.erc8056 ], + next_page_params: null, + }; await mockApiResponse('core:address', addressMock.validator, { pathParams: { hash: ADDRESS_HASH } }); + await mockApiResponse('core:stats', statsMock.base); + await mockAssetResponse(tokenInfo.tokenInfoERC20a.icon_url as string, './playwright/mocks/image_s.jpg'); + + // data for stats widgets await mockApiResponse('core:address_tokens', response20, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-20' } }); await mockApiResponse('core:address_tokens', response721, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-721' } }); await mockApiResponse('core:address_tokens', response1155, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-1155' } }); await mockApiResponse('core:address_tokens', response404, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-404' } }); - await mockApiResponse('core:address_nfts', tokensMock.nfts, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: [] } }); - await mockApiResponse('core:address_collections', tokensMock.collections, { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: [] } }); -}); + await mockApiResponse( + 'core:address_tokens', + { items: [], next_page_params: null }, + { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-7984' } }, + ); + await mockApiResponse( + 'core:address_tokens', + { items: [ tokensMock.erc8056 ], next_page_params: null }, + { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: 'ERC-8056' } }, + ); + + // data for list + await mockApiResponse( + 'core:address_tokens', + responseFungible, + { pathParams: { hash: ADDRESS_HASH }, queryParams: { type: [ 'ERC-20', 'ERC-7984', 'ERC-8056' ] } }, + ); + + await mockApiResponse('core:address_nfts', tokensMock.nfts, { pathParams: { hash: ADDRESS_HASH } }); + await mockApiResponse('core:address_collections', tokensMock.collections, { pathParams: { hash: ADDRESS_HASH } }); +}; + +test('fungible tokens +@dark-mode', async({ render, mockEnvs, mockApiResponse, mockAssetResponse }) => { + await mockEnvs([ + [ 'NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS', tokenInfo.tokenInfoERC20c.address_hash ], + ...ENVS_MAP.additionalTokenTypes, + ]); + await mockAddressTokens(mockApiResponse, mockAssetResponse); -test('erc20 +@dark-mode', async({ render }) => { const hooksConfig = { router: { query: { hash: ADDRESS_HASH, tab: 'tokens_erc20' }, - isReady: true, }, }; @@ -69,11 +103,11 @@ test('erc20 +@dark-mode', async({ render }) => { await expect(component).toHaveScreenshot(); }); -test('collections +@dark-mode', async({ render }) => { +test('collections +@dark-mode', async({ render, mockApiResponse, mockAssetResponse }) => { + await mockAddressTokens(mockApiResponse, mockAssetResponse); const hooksConfig = { router: { query: { hash: ADDRESS_HASH, tab: 'tokens_nfts' }, - isReady: true, }, }; @@ -87,13 +121,13 @@ test('collections +@dark-mode', async({ render }) => { await expect(component).toHaveScreenshot(); }); -test('nfts +@dark-mode', async({ render, mockAssetResponse }) => { +test('nfts +@dark-mode', async({ render, mockAssetResponse, mockApiResponse }) => { + await mockAddressTokens(mockApiResponse, mockAssetResponse); await mockAssetResponse(tokenInstance.base.image_url as string, './playwright/mocks/image_s.jpg'); const hooksConfig = { router: { query: { hash: ADDRESS_HASH, tab: 'tokens_nfts' }, - isReady: true, }, }; @@ -112,11 +146,16 @@ test('nfts +@dark-mode', async({ render, mockAssetResponse }) => { test.describe('mobile', () => { test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - test('erc20', async({ render }) => { + test('fungible tokens', async({ render, mockEnvs, mockApiResponse, mockAssetResponse }) => { + await mockEnvs([ + [ 'NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS', tokenInfo.tokenInfoERC20c.address_hash ], + ...ENVS_MAP.additionalTokenTypes, + ]); + await mockAddressTokens(mockApiResponse, mockAssetResponse); + const hooksConfig = { router: { query: { hash: ADDRESS_HASH, tab: 'tokens_erc20' }, - isReady: true, }, }; @@ -130,13 +169,13 @@ test.describe('mobile', () => { await expect(component).toHaveScreenshot(); }); - test('nfts', async({ render, mockAssetResponse, page }) => { + test('nfts', async({ render, mockAssetResponse, page, mockApiResponse }) => { + await mockAddressTokens(mockApiResponse, mockAssetResponse); await mockAssetResponse(tokenInstance.base.image_url as string, './playwright/mocks/image_s.jpg'); const hooksConfig = { router: { query: { hash: ADDRESS_HASH, tab: 'tokens_nfts' }, - isReady: true, }, }; @@ -154,11 +193,11 @@ test.describe('mobile', () => { await expect(component).toHaveScreenshot(); }); - test('collections', async({ render }) => { + test('collections', async({ render, mockApiResponse, mockAssetResponse }) => { + await mockAddressTokens(mockApiResponse, mockAssetResponse); const hooksConfig = { router: { query: { hash: ADDRESS_HASH, tab: 'tokens_nfts' }, - isReady: true, }, }; @@ -176,13 +215,13 @@ test.describe('mobile', () => { test.describe('update balances via socket', () => { test.describe.configure({ mode: 'serial' }); - test('base flow', async({ render, page, createSocket, mockApiResponse }) => { + test('base flow', async({ render, page, createSocket, mockApiResponse, mockAssetResponse }) => { test.slow(); + await mockAddressTokens(mockApiResponse, mockAssetResponse); const hooksConfig = { router: { query: { hash: ADDRESS_HASH, tab: 'tokens_erc20' }, - isReady: true, }, }; @@ -271,17 +310,17 @@ test.describe('update balances via socket', () => { await expect(component).toHaveScreenshot(); }); - test('custom token ZRC-2', async({ render, page, createSocket, mockApiResponse, mockEnvs }) => { + test('custom token ZRC-2', async({ render, page, createSocket, mockApiResponse, mockEnvs, mockAssetResponse }) => { test.slow(); await mockEnvs([ [ 'NEXT_PUBLIC_NETWORK_ADDITIONAL_TOKEN_TYPES', '[{"id":"ZRC-2","name":"ZRC-2"}]' ], ]); + await mockAddressTokens(mockApiResponse, mockAssetResponse); const hooksConfig = { router: { query: { hash: ADDRESS_HASH, tab: 'tokens_erc20' }, - isReady: true, }, }; @@ -342,24 +381,3 @@ test.describe('update balances via socket', () => { await expect(component).toHaveScreenshot(); }); }); - -test('native token', async({ render, mockEnvs }) => { - await mockEnvs([ - [ 'NEXT_PUBLIC_VIEWS_ADDRESS_NATIVE_TOKEN_ADDRESS', tokenInfo.tokenInfoERC20c.address_hash ], - ]); - const hooksConfig = { - router: { - query: { hash: ADDRESS_HASH, tab: 'tokens_erc20' }, - isReady: true, - }, - }; - - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTokens/> - </Box>, - { hooksConfig }, - ); - - await expect(component).toHaveScreenshot(); -}); diff --git a/src/slices/address/pages/details/tokens/AddressTokens.tsx b/src/slices/address/pages/details/tokens/AddressTokens.tsx index 5e8e323653b..92eee147065 100644 --- a/src/slices/address/pages/details/tokens/AddressTokens.tsx +++ b/src/slices/address/pages/details/tokens/AddressTokens.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { PaginationParams } from 'src/shared/pagination/types'; @@ -17,11 +16,11 @@ import useAddressFungibleTokensQuery from 'src/slices/token/pages/address/useAdd import useAddressNftQuery from 'src/slices/token/pages/address/useAddressNftQuery'; import { FUNGIBLE_TOKEN_TYPES } from 'src/slices/token/pages/address/utils'; -import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import useIsMounted from 'src/shared/hooks/useIsMounted'; import Pagination from 'src/shared/pagination/Pagination'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -67,14 +66,12 @@ const AddressTokens = ({ shouldRender = true, isQueryEnabled = true }: Props) => const tabs = [ { id: 'tokens_erc20', - title: [ - `${ config.slices.token.standard }-20`, - ...config.slices.token.additionalTypes.map((item) => item.name), - ].join(' & '), + title: 'Tokens', component: ( <AddressFungibleTokens items={ fungibleTokensQuery.data?.items } - isLoading={ fungibleTokensQuery.isPlaceholderData } + isLoading={ fungibleTokensQuery.isInitialLoading } + isTransitioning={ fungibleTokensQuery.isTransitioning } pagination={ fungibleTokensQuery.pagination } isError={ fungibleTokensQuery.isError } tokenTypes={ fungibleTokenTypes } @@ -101,8 +98,8 @@ const AddressTokens = ({ shouldRender = true, isQueryEnabled = true }: Props) => } const hasNftData = - (!nftsQuery.isPlaceholderData && nftsQuery.data?.items.length) || - (!collectionsQuery.isPlaceholderData && collectionsQuery.data?.items.length); + Boolean(!nftsQuery.isInitialLoading && nftsQuery.data?.items.length) || + Boolean(!collectionsQuery.isInitialLoading && collectionsQuery.data?.items.length); const isNftTab = tab !== 'tokens' && tab !== 'tokens_erc20'; const hasFungibleTokenFilter = !isNftTab && (!isMobile || !pagination.isVisible) && FUNGIBLE_TOKEN_TYPES.length > 1; diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_collections-dark-mode-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_collections-dark-mode-1.png index ed29c12725d..026ffcc7109 100644 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_collections-dark-mode-1.png and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_collections-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_erc20-dark-mode-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_erc20-dark-mode-1.png deleted file mode 100644 index 2356a7cb57a..00000000000 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_erc20-dark-mode-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_fungible-tokens-dark-mode-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_fungible-tokens-dark-mode-1.png new file mode 100644 index 00000000000..ebdd7a03045 Binary files /dev/null and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_fungible-tokens-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_nfts-dark-mode-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_nfts-dark-mode-1.png index 55ef59adb93..6c888518224 100644 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_nfts-dark-mode-1.png and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_dark-color-mode_nfts-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_collections-dark-mode-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_collections-dark-mode-1.png index 6287b60b96c..8972fb32536 100644 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_collections-dark-mode-1.png and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_collections-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_erc20-dark-mode-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_erc20-dark-mode-1.png deleted file mode 100644 index 257d5c265bc..00000000000 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_erc20-dark-mode-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_fungible-tokens-dark-mode-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_fungible-tokens-dark-mode-1.png new file mode 100644 index 00000000000..79e4be31de4 Binary files /dev/null and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_fungible-tokens-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-collections-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-collections-1.png index cfae3f24fee..c01100df366 100644 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-collections-1.png and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-collections-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-erc20-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-erc20-1.png deleted file mode 100644 index 3e433e839f2..00000000000 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-erc20-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-fungible-tokens-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-fungible-tokens-1.png new file mode 100644 index 00000000000..d5c7425547b Binary files /dev/null and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-fungible-tokens-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-nfts-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-nfts-1.png index 1029a7894c9..aac8bfdcc91 100644 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-nfts-1.png and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_mobile-nfts-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_native-token-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_native-token-1.png deleted file mode 100644 index 8b114101fd3..00000000000 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_native-token-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_nfts-dark-mode-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_nfts-dark-mode-1.png index 5e135c42229..87f37357233 100644 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_nfts-dark-mode-1.png and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_nfts-dark-mode-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-base-flow-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-base-flow-1.png index d331153256e..d730f8424a0 100644 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-base-flow-1.png and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-base-flow-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-base-flow-2.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-base-flow-2.png index b109c72f777..c3d5ee970c3 100644 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-base-flow-2.png and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-base-flow-2.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-custom-token-ZRC-2-1.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-custom-token-ZRC-2-1.png index 3eadc1c1df4..7a060da1191 100644 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-custom-token-ZRC-2-1.png and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-custom-token-ZRC-2-1.png differ diff --git a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-custom-token-ZRC-2-2.png b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-custom-token-ZRC-2-2.png index d11bd04f0f0..2470aa1edb0 100644 Binary files a/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-custom-token-ZRC-2-2.png and b/src/slices/address/pages/details/tokens/__screenshots__/AddressTokens.pw.tsx_default_update-balances-via-socket-custom-token-ZRC-2-2.png differ diff --git a/src/slices/address/pages/details/txs/AddressTxs.pw.tsx b/src/slices/address/pages/details/txs/AddressTxs.pw.tsx index 4dcb4caaf4c..0afcc045f9f 100644 --- a/src/slices/address/pages/details/txs/AddressTxs.pw.tsx +++ b/src/slices/address/pages/details/txs/AddressTxs.pw.tsx @@ -4,6 +4,8 @@ import React from 'react'; import * as txMock from 'src/slices/tx/mocks/list'; +import * as csvExportMock from 'src/features/csv-export/mocks'; + import * as socketServer from 'playwright/fixtures/socketServer'; import { test, expect } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; @@ -19,6 +21,10 @@ const hooksConfig = { }; const DEFAULT_PAGINATION = { block_number: 1, index: 1, items_count: 1 }; +test.beforeEach(async({ mockApiResponse }) => { + await mockApiResponse('core:config_csv_export', csvExportMock.config); +}); + test.describe('base view', () => { let component: Locator; @@ -59,45 +65,6 @@ test.describe('base view', () => { }); }); -test.describe('mobile', () => { - test.use({ viewport: pwConfig.viewport.mobile }); - - test.beforeEach(async({ mockApiResponse }) => { - await mockApiResponse( - 'core:address_txs', - { - items: [ - txMock.base, - { ...txMock.base, hash: '0x62d597ebcf3e8d60096dd0363bc2f0f5e2df27ba1dacd696c51aa7c9409f3194' }, - ], - next_page_params: DEFAULT_PAGINATION, - }, - { pathParams: { hash: CURRENT_ADDRESS } }, - ); - }); - - test('base view', async({ render }) => { - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTxs/> - </Box>, - { hooksConfig }, - ); - await expect(component).toHaveScreenshot(); - }); - - test('table view', async({ render, mockFeatures }) => { - await mockFeatures([ [ 'txns_view_exp', 'table_view' ] ]); - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <AddressTxs/> - </Box>, - { hooksConfig }, - ); - await expect(component).toHaveScreenshot(); - }); -}); - test.describe('socket', () => { // FIXME // test cases which use socket cannot run in parallel since the socket server always run on the same port @@ -121,16 +88,14 @@ test.describe('socket', () => { const socket = await createSocket(); const channel = await socketServer.joinChannel(socket, `addresses:${ CURRENT_ADDRESS.toLowerCase() }`); - const itemsCount = await page.locator('tbody tr').count(); - expect(itemsCount).toBe(2); + await expect(page.locator('tbody tr')).toHaveCount(2); + await expect(page.locator('tbody tr').nth(1)).toContainText('Pending'); socketServer.sendMessage(socket, channel, 'transaction', { transactions: [ txMock.base ] }); - const secondRow = page.locator('tbody tr:nth-child(2)'); - await secondRow.waitFor(); - - const itemsCountNew = await page.locator('tbody tr').count(); - expect(itemsCountNew).toBe(2); + await expect(page.locator('tbody tr').nth(1)).toContainText(String(txMock.base.block_number)); + await expect(page.locator('tbody tr').nth(1)).not.toContainText('Pending'); + await expect(page.locator('tbody tr')).toHaveCount(2); }); test('with overload', async({ render, mockApiResponse, page, createSocket }) => { @@ -151,19 +116,13 @@ test.describe('socket', () => { const socket = await createSocket(); const channel = await socketServer.joinChannel(socket, `addresses:${ CURRENT_ADDRESS.toLowerCase() }`); - const itemsCount = await page.locator('tbody tr').count(); - expect(itemsCount).toBe(2); + await expect(page.locator('tbody tr')).toHaveCount(2); socketServer.sendMessage(socket, channel, 'transaction', { transactions: [ txMock.base2, txMock.base3, txMock.base4 ] }); - const thirdRow = page.locator('tbody tr:nth-child(3)'); - await thirdRow.waitFor(); - - const itemsCountNew = await page.locator('tbody tr').count(); - expect(itemsCountNew).toBe(3); + await expect(page.locator('tbody tr')).toHaveCount(3); - const counter = await page.locator('tbody tr:nth-child(1)').textContent(); - expect(counter?.startsWith('2 ')).toBe(true); + await expect(page.locator('tbody tr').first()).toHaveText(/^2 /); }); test('without overload, with filters', async({ render, mockApiResponse, page, createSocket }) => { @@ -190,16 +149,11 @@ test.describe('socket', () => { const socket = await createSocket(); const channel = await socketServer.joinChannel(socket, `addresses:${ CURRENT_ADDRESS.toLowerCase() }`); - const itemsCount = await page.locator('tbody tr').count(); - expect(itemsCount).toBe(2); + await expect(page.locator('tbody tr')).toHaveCount(2); socketServer.sendMessage(socket, channel, 'transaction', { transactions: [ txMock.base2 ] }); - const secondRow = page.locator('tbody tr:nth-child(2)'); - await secondRow.waitFor(); - - const itemsCountNew = await page.locator('tbody tr').count(); - expect(itemsCountNew).toBe(3); + await expect(page.locator('tbody tr')).toHaveCount(3); }); test('with overload, with filters', async({ render, mockApiResponse, page, createSocket }) => { @@ -226,18 +180,12 @@ test.describe('socket', () => { const socket = await createSocket(); const channel = await socketServer.joinChannel(socket, `addresses:${ CURRENT_ADDRESS.toLowerCase() }`); - const itemsCount = await page.locator('tbody tr').count(); - expect(itemsCount).toBe(2); + await expect(page.locator('tbody tr')).toHaveCount(2); socketServer.sendMessage(socket, channel, 'transaction', { transactions: [ txMock.base2, txMock.base3, txMock.base4 ] }); - const thirdRow = page.locator('tbody tr:nth-child(3)'); - await thirdRow.waitFor(); - - const itemsCountNew = await page.locator('tbody tr').count(); - expect(itemsCountNew).toBe(3); + await expect(page.locator('tbody tr')).toHaveCount(3); - const counter = await page.locator('tbody tr:nth-child(1)').textContent(); - expect(counter?.startsWith('1 ')).toBe(true); + await expect(page.locator('tbody tr').first()).toHaveText(/^1 /); }); }); diff --git a/src/slices/address/pages/details/txs/AddressTxs.tsx b/src/slices/address/pages/details/txs/AddressTxs.tsx index e1919334dac..e6098437f52 100644 --- a/src/slices/address/pages/details/txs/AddressTxs.tsx +++ b/src/slices/address/pages/details/txs/AddressTxs.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; @@ -16,9 +15,10 @@ import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import useIsMounted from 'src/shared/hooks/useIsMounted'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -52,7 +52,7 @@ const AddressTxs = ({ shouldRender = true, isQueryEnabled = true }: Props) => { enabled: isQueryEnabled && isLocalTab, }); - const crossChainQuery = useQueryWithPages({ + const crossChainQuery = useApiPaginatedQuery({ resourceName: 'interchainIndexer:address_messages', pathParams: { hash }, options: { @@ -61,15 +61,9 @@ const AddressTxs = ({ shouldRender = true, isQueryEnabled = true }: Props) => { }, }); - const handleTabValueChange = React.useCallback(({ value }: { value: string }) => { - if (value === 'txs_local') { - localQuery.setFilterValue(undefined); - } - }, [ localQuery ]); - const txsLocalFilter = isLocalTab ? ( <AddressTxsFilter - initialValue={ localQuery.initialFilterValue } + initialValue={ localQuery.filterValue } onFilterChange={ localQuery.onFilterChange } hasActiveFilter={ Boolean(localQuery.filterValue) } isLoading={ localQuery.query.pagination.isLoading } @@ -94,9 +88,7 @@ const AddressTxs = ({ shouldRender = true, isQueryEnabled = true }: Props) => { socketType="address_txs" top={ ACTION_BAR_HEIGHT_DESKTOP } sorting={ localQuery.sort } - setSort={ localQuery.setSort } showBlockInfo - showTableView /> ), }, @@ -107,10 +99,13 @@ const AddressTxs = ({ shouldRender = true, isQueryEnabled = true }: Props) => { <AddressTxsCrossChain pagination={ crossChainQuery.pagination } items={ crossChainQuery.data?.items } - isLoading={ crossChainQuery.isPlaceholderData } + isLoading={ crossChainQuery.isInitialLoading } + isTransitioning={ crossChainQuery.isTransitioning } isError={ crossChainQuery.isError } currentAddress={ hash } resetKey={ crossChainQuery.queryHash } + filters={ crossChainQuery.filters } + onFilterChange={ crossChainQuery.onFilterChange } /> ), }, @@ -172,7 +167,6 @@ const AddressTxs = ({ shouldRender = true, isQueryEnabled = true }: Props) => { variant="secondary" size="sm" tabs={ tabs } - onValueChange={ handleTabValueChange } defaultTabId="txs_local" rightSlot={ rightSlot } rightSlotProps={ rightSlotProps } diff --git a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-desktop-1.png b/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-desktop-1.png index 37bc8d5f06e..83a8bf390c7 100644 Binary files a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-desktop-1.png and b/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-desktop-1.png differ diff --git a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-desktop-2.png b/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-desktop-2.png index 34a17f5e432..4b997e0af28 100644 Binary files a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-desktop-2.png and b/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-desktop-2.png differ diff --git a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-mobile-1.png b/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 1b6a5b7c0d9..00000000000 Binary files a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-screen-xl-base-view-1.png b/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-screen-xl-base-view-1.png index 8e0d9e7550f..9f6e0103d55 100644 Binary files a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-screen-xl-base-view-1.png and b/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_base-view-screen-xl-base-view-1.png differ diff --git a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_mobile-base-view-1.png b/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_mobile-base-view-1.png deleted file mode 100644 index 15ded938c69..00000000000 Binary files a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_mobile-base-view-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_mobile-table-view-1.png b/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_mobile-table-view-1.png deleted file mode 100644 index 15ded938c69..00000000000 Binary files a/src/slices/address/pages/details/txs/__screenshots__/AddressTxs.pw.tsx_default_mobile-table-view-1.png and /dev/null differ diff --git a/src/slices/address/pages/details/txs/useAddressTxsQuery.ts b/src/slices/address/pages/details/txs/useAddressTxsQuery.ts index 68a555b6dd2..360eed4993b 100644 --- a/src/slices/address/pages/details/txs/useAddressTxsQuery.ts +++ b/src/slices/address/pages/details/txs/useAddressTxsQuery.ts @@ -1,19 +1,18 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; +import type { ExternalChainExtended } from 'src/shared/external-chains/types'; import type { AddressFromToFilter } from 'src/slices/address/types/api'; import { AddressFromToFilterValues } from 'src/slices/address/types/api'; -import type { TransactionsSorting, TransactionsSortingField, TransactionsSortingValue } from 'src/slices/tx/types/api'; +import type { TransactionsSortingValue } from 'src/slices/tx/types/api'; import { SORT_OPTIONS } from 'src/slices/tx/hooks/useTxsSort'; import { TX_ITEM } from 'src/slices/tx/stubs/tx'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getFilterValueFromQuery from 'src/shared/router/get-filter-value-from-query'; -import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; import getSortValueFromQuery from 'src/shared/sort/get-sort-value-from-query'; const getFilterValue = (getFilterValueFromQuery<AddressFromToFilter>).bind(null, AddressFromToFilterValues); @@ -21,23 +20,13 @@ const getFilterValue = (getFilterValueFromQuery<AddressFromToFilter>).bind(null, interface Props { addressHash: string; enabled: boolean; - isMultichain?: boolean; - chainIds?: Array<string>; + chain?: ExternalChainExtended; } -export default function useAddressTxsQuery({ addressHash, enabled, isMultichain, chainIds }: Props) { - const router = useRouter(); - - const [ sort, setSort ] = React.useState<TransactionsSortingValue>(getSortValueFromQuery<TransactionsSortingValue>(router.query, SORT_OPTIONS) || 'default'); - - const initialFilterValue = getFilterValue(router.query.filter); - const [ filterValue, setFilterValue ] = React.useState<AddressFromToFilter>(initialFilterValue); - - const query = useQueryWithPages({ +export default function useAddressTxsQuery({ addressHash, enabled, chain }: Props) { + const query = useApiPaginatedQuery({ resourceName: 'core:address_txs', pathParams: { hash: addressHash }, - filters: { filter: filterValue }, - sorting: getSortParamsFromValue<TransactionsSortingValue, TransactionsSortingField, TransactionsSorting['order']>(sort), options: { enabled: enabled, placeholderData: generateListStub<'core:address_txs'>(TX_ITEM, 50, { next_page_params: { @@ -46,23 +35,21 @@ export default function useAddressTxsQuery({ addressHash, enabled, isMultichain, items_count: 50, } }), }, - isMultichain, - chainIds, + chain, }); + const filterValue = getFilterValue(query.filters.filter); + const sort = getSortValueFromQuery<TransactionsSortingValue>({ ...query.sorting }, SORT_OPTIONS) ?? 'default'; + + const { onFilterChange: onQueryFilterChange } = query; const onFilterChange = React.useCallback((val: string | Array<string>) => { - const newVal = getFilterValue(val); - setFilterValue(newVal); - query.onFilterChange({ filter: newVal }); - }, [ query ]); + onQueryFilterChange({ filter: getFilterValue(val) }); + }, [ onQueryFilterChange ]); return React.useMemo(() => ({ query, filterValue, - setFilterValue, - initialFilterValue, onFilterChange, sort, - setSort, - }), [ query, filterValue, initialFilterValue, setFilterValue, onFilterChange, sort, setSort ]); + }), [ query, filterValue, onFilterChange, sort ]); } diff --git a/src/slices/address/pages/index/Accounts.pw.tsx b/src/slices/address/pages/index/Accounts.pw.tsx index cb9230d456c..01dad5c1954 100644 --- a/src/slices/address/pages/index/Accounts.pw.tsx +++ b/src/slices/address/pages/index/Accounts.pw.tsx @@ -37,7 +37,7 @@ const addresses: paths['/api/v2/addresses']['get'] = { next_page_params: null, }; -test('base view +@mobile +@dark-mode', async({ render, mockTextAd, mockApiResponse }) => { +test('base view +@dark-mode', async({ render, mockTextAd, mockApiResponse }) => { await mockTextAd(); await mockApiResponse('core:addresses', addresses); const component = await render(<Accounts/>); diff --git a/src/slices/address/pages/index/Accounts.tsx b/src/slices/address/pages/index/Accounts.tsx index 7673f1a82ba..10e204ed2bd 100644 --- a/src/slices/address/pages/index/Accounts.tsx +++ b/src/slices/address/pages/index/Accounts.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import BigNumber from 'bignumber.js'; import React from 'react'; @@ -12,14 +11,15 @@ import { TOP_ADDRESS } from 'src/slices/address/stubs/address'; import DataList from 'src/shared/lists/DataList'; import getItemIndex from 'src/shared/lists/get-item-index'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; -import AddressesList from './AddressesList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + import AddressesTable from './AddressesTable'; const Accounts = () => { - const { isError, isPlaceholderData, data, pagination, queryHash } = useQueryWithPages({ + const { isError, isInitialLoading, isTransitioning, data, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:addresses', options: { placeholderData: generateListStub<'core:addresses'>( @@ -50,27 +50,16 @@ const Accounts = () => { }, [ data?.total_supply ]); const content = data?.items ? ( - <> - <Box hideBelow="lg"> - <AddressesTable - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - items={ data.items } - totalSupply={ totalSupply } - pageStartIndex={ pageStartIndex } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - <Box hideFrom="lg"> - <AddressesList - items={ data.items } - totalSupply={ totalSupply } - pageStartIndex={ pageStartIndex } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <AddressesTable + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + items={ data.items } + totalSupply={ totalSupply } + pageStartIndex={ pageStartIndex } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; return ( @@ -81,6 +70,7 @@ const Accounts = () => { itemsNum={ data?.items.length } emptyText="There are no accounts." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/slices/address/pages/index/AddressesList.tsx b/src/slices/address/pages/index/AddressesList.tsx deleted file mode 100644 index eff426dbd9a..00000000000 --- a/src/slices/address/pages/index/AddressesList.tsx +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import type BigNumber from 'bignumber.js'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import AddressesListItem from './AddressesListItem'; - -interface Props { - items: Array<schemas['TopAddress']>; - totalSupply: BigNumber; - pageStartIndex: number; - isLoading?: boolean; - resetKey?: string; -} - -const AddressesList = ({ items, totalSupply, pageStartIndex, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <AddressesListItem - key={ item.hash + (isLoading ? index : '') } - item={ item } - index={ pageStartIndex + index } - totalSupply={ totalSupply } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(AddressesList); diff --git a/src/slices/address/pages/index/AddressesListItem.tsx b/src/slices/address/pages/index/AddressesListItem.tsx deleted file mode 100644 index 5141febd6b9..00000000000 --- a/src/slices/address/pages/index/AddressesListItem.tsx +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, HStack } from '@chakra-ui/react'; -import BigNumber from 'bignumber.js'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import { currencyUnits } from 'src/slices/chain/units'; - -import config from 'src/config'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Tag } from 'src/toolkit/chakra/tag'; -import { ZERO } from 'src/toolkit/utils/consts'; - -interface Props { - item: schemas['TopAddress']; - index: number; - totalSupply: BigNumber; - isLoading?: boolean; -}; - -const AddressesListItem = ({ - item, - index, - totalSupply, - isLoading, -}: Props) => { - - const addressBalance = BigNumber(item.coin_balance || 0).div(BigNumber(10 ** config.chain.currency.decimals)); - - return ( - <ListItemMobile rowGap={ 3 }> - <Flex alignItems="center" justifyContent="space-between" w="100%"> - <AddressEntity - address={ item } - isLoading={ isLoading } - fontWeight={ 700 } - mr={ 2 } - truncation="constant" - /> - <Skeleton loading={ isLoading } fontSize="sm" ml="auto" minW={ 6 } color="text.secondary"> - <span>{ index }</span> - </Skeleton> - </Flex> - { item.public_tags !== null && item.public_tags !== undefined && item.public_tags.length > 0 && item.public_tags.map(tag => ( - <Tag key={ tag.label } loading={ isLoading } truncated>{ tag.display_name }</Tag> - )) } - <HStack gap={ 3 } maxW="100%" alignItems="flex-start"> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 } flexShrink={ 0 }>{ `Balance ${ currencyUnits.ether }` }</Skeleton> - <Skeleton loading={ isLoading } fontSize="sm" color="text.secondary" minW="0" whiteSpace="pre-wrap"> - <span>{ addressBalance.dp(8).toFormat() }</span> - </Skeleton> - </HStack> - { !totalSupply.eq(ZERO) && ( - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 }>Percentage</Skeleton> - <Skeleton loading={ isLoading } fontSize="sm" color="text.secondary"> - <span>{ addressBalance.div(BigNumber(totalSupply)).multipliedBy(100).dp(8).toFormat() + '%' }</span> - </Skeleton> - </HStack> - ) } - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 }>Txn count</Skeleton> - <Skeleton loading={ isLoading } fontSize="sm" color="text.secondary"> - <span>{ Number(item.transactions_count).toLocaleString() }</span> - </Skeleton> - </HStack> - </ListItemMobile> - ); -}; - -export default React.memo(AddressesListItem); diff --git a/src/slices/address/pages/index/AddressesTable.spec.tsx b/src/slices/address/pages/index/AddressesTable.spec.tsx new file mode 100644 index 00000000000..6ded6982c9e --- /dev/null +++ b/src/slices/address/pages/index/AddressesTable.spec.tsx @@ -0,0 +1,47 @@ +// @vitest-environment jsdom +// SPDX-License-Identifier: LicenseRef-Blockscout + +import BigNumber from 'bignumber.js'; +import React from 'react'; + +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +import { MultichainContext } from 'src/features/multichain/context'; +import { chainA } from 'src/features/multichain/mocks/chains'; + +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, render, screen } from 'vitest/lib'; + +import AddressesTable from './AddressesTable'; + +const polygonChain = { + ...chainA, + id: '137', + app_config: { + ...chainA.app_config, + chain: { + ...chainA.app_config.chain, + currency: { name: 'POL', symbol: 'POL', decimals: 18 }, + }, + }, +} as unknown as ClusterChainConfig; + +describe('AddressesTable', () => { + afterEach(cleanup); + + it('labels the balance column with the instance\'s native coin', () => { + render(<AddressesTable items={ [] } totalSupply={ BigNumber(0) } pageStartIndex={ 1 } top={ 0 }/>); + + expect(screen.getByRole('columnheader', { name: /^Balance/ }).textContent).toBe('Balance ETH'); + }); + + it('labels the balance column with the selected chain\'s native coin in a multichain context', () => { + render( + <MultichainContext.Provider value={{ chain: polygonChain }}> + <AddressesTable items={ [] } totalSupply={ BigNumber(0) } pageStartIndex={ 1 } top={ 0 }/> + </MultichainContext.Provider>, + ); + + expect(screen.getByRole('columnheader', { name: /^Balance/ }).textContent).toBe('Balance POL'); + }); +}); diff --git a/src/slices/address/pages/index/AddressesTable.tsx b/src/slices/address/pages/index/AddressesTable.tsx index 135f1eeb9e3..ddcad6637b9 100644 --- a/src/slices/address/pages/index/AddressesTable.tsx +++ b/src/slices/address/pages/index/AddressesTable.tsx @@ -7,6 +7,9 @@ import type { schemas } from '@blockscout/api-types'; import { currencyUnits } from 'src/slices/chain/units'; +import { useMultichainContext } from 'src/features/multichain/context'; + +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -23,16 +26,21 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: schemas['TopAddress']): string => item.hash; + const AddressesTable = ({ items, totalSupply, pageStartIndex, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); const hasPercentage = !totalSupply.eq(ZERO); + const multichainContext = useMultichainContext(); + const currencySymbol = multichainContext?.chain.app_config.chain.currency.symbol ?? currencyUnits.ether; return ( - <TableRoot> + <TableRoot minW="900px"> <TableHeaderSticky top={ top }> <TableRow> <TableColumnHeader width="64px">Rank</TableColumnHeader> <TableColumnHeader width={ hasPercentage ? '50%' : '60%' }>Address</TableColumnHeader> - <TableColumnHeader width={ hasPercentage ? '20%' : '25%' } isNumeric>{ `Balance ${ currencyUnits.ether }` }</TableColumnHeader> + <TableColumnHeader width={ hasPercentage ? '20%' : '25%' } isNumeric>{ `Balance ${ currencySymbol }` }</TableColumnHeader> { hasPercentage && <TableColumnHeader width="15%" isNumeric>Percentage</TableColumnHeader> } <TableColumnHeader width="15%" isNumeric>Txn count</TableColumnHeader> </TableRow> @@ -40,7 +48,7 @@ const AddressesTable = ({ items, totalSupply, pageStartIndex, top, isLoading, re <TableBody> { items.slice(0, renderedItemsNum).map((item, index) => ( <AddressesTableItem - key={ item.hash + (isLoading ? index : '') } + key={ keys[index] } item={ item } totalSupply={ totalSupply } index={ pageStartIndex + index } diff --git a/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_dark-color-mode_base-view-dark-mode-1.png new file mode 100644 index 00000000000..1cb2caf976d Binary files /dev/null and b/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png b/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png deleted file mode 100644 index adb4917266c..00000000000 Binary files a/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_default_base-view-dark-mode-1.png b/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_default_base-view-dark-mode-1.png new file mode 100644 index 00000000000..341ffa59645 Binary files /dev/null and b/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_default_base-view-mobile-dark-mode-1.png b/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_default_base-view-mobile-dark-mode-1.png deleted file mode 100644 index ddde15b5fc4..00000000000 Binary files a/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_default_base-view-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_mobile_base-view-mobile-dark-mode-1.png b/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_mobile_base-view-mobile-dark-mode-1.png deleted file mode 100644 index e71a28f0882..00000000000 Binary files a/src/slices/address/pages/index/__screenshots__/Accounts.pw.tsx_mobile_base-view-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/block/components/entity/__screenshots__/BlockEntity.pw.tsx_default_loading-1.png b/src/slices/block/components/entity/__screenshots__/BlockEntity.pw.tsx_default_loading-1.png index 345f06992fe..0fdad122259 100644 Binary files a/src/slices/block/components/entity/__screenshots__/BlockEntity.pw.tsx_default_loading-1.png and b/src/slices/block/components/entity/__screenshots__/BlockEntity.pw.tsx_default_loading-1.png differ diff --git a/src/slices/block/config.ts b/src/slices/block/config.ts index a995c21c293..6b731df963d 100644 --- a/src/slices/block/config.ts +++ b/src/slices/block/config.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { BlockFieldId } from 'src/slices/block/types/config'; -import { BLOCK_FIELDS_IDS } from 'src/slices/block/types/config'; +import type { BlockFieldId, BlockViewId } from 'src/slices/block/types/config'; +import { BLOCK_FIELDS_IDS, BLOCK_VIEWS_IDS } from 'src/slices/block/types/config'; import { getEnvValue, parseEnvJson } from 'src/config/utils/envs'; @@ -20,8 +20,24 @@ const blockHiddenFields = (() => { return result; })(); +const hiddenViews = (() => { + const parsedValue = parseEnvJson<Array<BlockViewId>>(getEnvValue('NEXT_PUBLIC_VIEWS_BLOCK_HIDDEN_VIEWS')) || []; + + if (!Array.isArray(parsedValue) || parsedValue.length === 0) { + return undefined; + } + + const result = BLOCK_VIEWS_IDS.reduce((result, item) => { + result[item] = parsedValue.includes(item); + return result; + }, {} as Record<BlockViewId, boolean>); + + return result; +})(); + const config = Object.freeze({ hiddenFields: blockHiddenFields, + hiddenViews, pendingUpdateAlertEnabled: getEnvValue('NEXT_PUBLIC_VIEWS_BLOCK_PENDING_UPDATE_ALERT_ENABLED') !== 'false', }); diff --git a/src/slices/block/hooks/useBlockInternalTxsQuery.ts b/src/slices/block/hooks/useBlockInternalTxsQuery.ts index dca342ce0d0..96eeaff4500 100644 --- a/src/slices/block/hooks/useBlockInternalTxsQuery.ts +++ b/src/slices/block/hooks/useBlockInternalTxsQuery.ts @@ -3,7 +3,7 @@ import { INTERNAL_TX } from 'src/slices/internal-tx/stubs'; import type config from 'src/config'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import type { BlockQuery } from './useBlockQuery'; @@ -16,7 +16,7 @@ interface Params { } export default function useBlockInternalTxsQuery({ heightOrHash, blockQuery, tab, chainConfig }: Params) { - const apiQuery = useQueryWithPages({ + const apiQuery = useApiPaginatedQuery({ resourceName: 'core:block_internal_txs', pathParams: { height_or_hash: heightOrHash }, options: { diff --git a/src/slices/block/hooks/useBlockTxsQuery.spec.ts b/src/slices/block/hooks/useBlockTxsQuery.spec.ts new file mode 100644 index 00000000000..d92dbaffa61 --- /dev/null +++ b/src/slices/block/hooks/useBlockTxsQuery.spec.ts @@ -0,0 +1,60 @@ +// @vitest-environment jsdom + +import { TX_ITEM } from 'src/slices/tx/stubs/tx'; + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { renderHook, act, cleanup } from 'vitest/lib'; +import flushPromises from 'vitest/utils/flushPromises'; +import { routerStandIn } from 'vitest/utils/routerStandIn'; + +import type { BlockQuery } from './useBlockQuery'; +import useBlockTxsQuery from './useBlockTxsQuery'; + +const BLOCK_HEIGHT = '9004925'; +const RESPONSE = { items: [ TX_ITEM ], next_page_params: null }; +const RESPONSE_INIT = { headers: { 'Content-Type': 'application/json' } }; + +const loadedBlockQuery = { isPlaceholderData: false, isDegradedData: false } as BlockQuery; + +beforeEach(() => { + fetchMock.resetMocks(); + routerStandIn.reset({ pathname: '/block/[height_or_hash]', query: { height_or_hash: BLOCK_HEIGHT, tab: 'txs' } }); +}); + +afterEach(cleanup); + +describe('useBlockTxsQuery', () => { + it('serves the API transactions with pagination once the block is loaded', async() => { + fetchMock.mockResponse(JSON.stringify(RESPONSE), RESPONSE_INIT); + + const { result } = renderHook( + () => useBlockTxsQuery({ heightOrHash: BLOCK_HEIGHT, blockQuery: loadedBlockQuery, tab: 'txs' }), + { wrapper: routerStandIn.appWrapper }, + ); + await waitForApiResponse(); + + expect(result.current.data).toEqual(RESPONSE); + expect(result.current.isDegradedData).toBe(false); + expect(result.current.isTransitioning).toBe(false); + expect(result.current.pagination).toMatchObject({ page: 1, hasNextPage: false, isLoading: false }); + expect(fetchMock.mock.calls).toHaveLength(1); + expect(String(fetchMock.mock.calls[0][0])).toContain(`/blocks/${ BLOCK_HEIGHT }/transactions`); + }); + + it('does not request anything while another tab is active', async() => { + const { result } = renderHook( + () => useBlockTxsQuery({ heightOrHash: BLOCK_HEIGHT, blockQuery: loadedBlockQuery, tab: 'index' }), + { wrapper: routerStandIn.appWrapper }, + ); + await waitForApiResponse(); + + expect(fetchMock.mock.calls).toHaveLength(0); + expect(result.current.isPlaceholderData).toBe(true); + expect(result.current.isDegradedData).toBe(false); + }); +}); + +async function waitForApiResponse() { + await flushPromises(); + await act(flushPromises); +} diff --git a/src/slices/block/hooks/useBlockTxsQuery.ts b/src/slices/block/hooks/useBlockTxsQuery.ts index 2c2df61a9f2..ae0c7f88f61 100644 --- a/src/slices/block/hooks/useBlockTxsQuery.ts +++ b/src/slices/block/hooks/useBlockTxsQuery.ts @@ -18,8 +18,8 @@ import { getPublicClient, isPublicClientAvailable } from 'src/features/connect-w import hexToDecimal from 'src/shared/data/transformers/hex-to-decimal'; import dayjs from 'src/shared/date-and-time/dayjs'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub, emptyPagination } from 'src/shared/pagination/utils'; import { SECOND } from 'src/toolkit/utils/consts'; @@ -28,7 +28,7 @@ import type { BlockQuery } from './useBlockQuery'; type RpcResponseType = GetBlockReturnType<Chain, boolean, 'latest'> | null; -export type BlockTxsQuery = QueryWithPagesResult<'core:block_txs'> & { +export type BlockTxsQuery = ApiPaginatedQueryResult<'core:block_txs'> & { isDegradedData: boolean; }; @@ -41,7 +41,7 @@ interface Params { export default function useBlockTxsQuery({ heightOrHash, blockQuery, tab }: Params): BlockTxsQuery { const [ isRefetchEnabled, setRefetchEnabled ] = React.useState(false); - const apiQuery = useQueryWithPages({ + const apiQuery = useApiPaginatedQuery({ resourceName: 'core:block_txs', pathParams: { height_or_hash: heightOrHash }, options: { @@ -167,17 +167,19 @@ export default function useBlockTxsQuery({ heightOrHash, blockQuery, tab }: Para ((apiQuery.isError || apiQuery.isPlaceholderData) && apiQuery.errorUpdateCount > 0) ) && rpcQuery.data && isPublicClientAvailable); - const rpcQueryWithPages: QueryWithPagesResult<'core:block_txs'> = { + const rpcPaginatedQuery: ApiPaginatedQueryResult<'core:block_txs'> = { ...rpcQuery as UseQueryResult<operations['BlockController.transactions']['json'], ResourceError>, pagination: emptyPagination, onFilterChange: () => {}, onSortingChange: () => {}, - chainValue: undefined, - onChainValueChange: () => {}, + filters: apiQuery.filters, + sorting: apiQuery.sorting, queryHash: hashKey(rpcQueryKey), + isInitialLoading: rpcQuery.isPlaceholderData, + isTransitioning: false, }; - const query = isRpcQuery ? rpcQueryWithPages : apiQuery; + const query = isRpcQuery ? rpcPaginatedQuery : apiQuery; return { ...query, diff --git a/src/slices/block/pages/countdown-details/BlockCountdown.tsx b/src/slices/block/pages/countdown-details/BlockCountdown.tsx index 92b7b45d28d..27cda19706b 100644 --- a/src/slices/block/pages/countdown-details/BlockCountdown.tsx +++ b/src/slices/block/pages/countdown-details/BlockCountdown.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Center, Flex, Grid } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; +import { Box, Center, Flex } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -15,6 +14,8 @@ import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-e import ChainIcon from 'src/shared/external-chains/ChainIcon'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; import SpriteIcon from 'src/sprite/SpriteIcon'; @@ -23,7 +24,7 @@ import { Heading } from 'src/toolkit/chakra/heading'; import { Image } from 'src/toolkit/chakra/image'; import { Link } from 'src/toolkit/chakra/link'; import { ContentLoader } from 'src/toolkit/components/loaders/ContentLoader'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import { downloadBlob } from 'src/toolkit/utils/file'; import BlockCountdownTimer from './BlockCountdownTimer'; @@ -80,7 +81,7 @@ const BlockCountdown = ({ hideCapybaraRunner }: Props) => { <Heading level="1" > - <TruncatedText text={ `Block #${ height }` } w="100%"/> + <Truncate value={ `Block #${ height }` } type="end" w="100%"/> </Heading> <Box mt={ 2 } color="text.secondary"> <Box fontWeight={ 600 }>Estimated target date</Box> @@ -139,10 +140,10 @@ const BlockCountdown = ({ hideCapybaraRunner }: Props) => { value={ Math.ceil(Number(data.estimated_time_in_seconds)) } onFinish={ handleTimerFinish } /> - <Grid gridTemplateColumns="repeat(2, calc(50% - 4px))" columnGap={ 2 } mt={ 2 }> + <StatsContainer mt={{ base: 1, lg: 2 }}> <StatsWidget label="Remaining blocks" value={ data.remaining_blocks_count } icon="apps"/> <StatsWidget label="Current block" value={ data.current_block_number } icon="block"/> - </Grid> + </StatsContainer> { !hideCapybaraRunner && <CapybaraRunner/> } </Flex> </Center> diff --git a/src/slices/block/pages/countdown-details/BlockCountdownTimer.tsx b/src/slices/block/pages/countdown-details/BlockCountdownTimer.tsx index 101a782751a..d32799bac6d 100644 --- a/src/slices/block/pages/countdown-details/BlockCountdownTimer.tsx +++ b/src/slices/block/pages/countdown-details/BlockCountdownTimer.tsx @@ -19,20 +19,19 @@ const BlockCountdownTimer = ({ value: initialValue, onFinish }: Props) => { React.useEffect(() => { const intervalId = window.setInterval(() => { - setValue((prev) => { - if (prev > 1) { - return prev - 1; - } - - onFinish(); - return 0; - }); + setValue((prev) => Math.max(prev - 1, 0)); }, SECOND); return () => { window.clearInterval(intervalId); }; - }, [ initialValue, onFinish ]); + }, [ initialValue ]); + + React.useEffect(() => { + if (value === 0) { + onFinish(); + } + }, [ value, onFinish ]); const periods = splitSecondsInPeriods(value); diff --git a/src/slices/block/pages/countdown-details/BlockCountdownTimerItem.tsx b/src/slices/block/pages/countdown-details/BlockCountdownTimerItem.tsx index bc072761da7..f1f8d47cf29 100644 --- a/src/slices/block/pages/countdown-details/BlockCountdownTimerItem.tsx +++ b/src/slices/block/pages/countdown-details/BlockCountdownTimerItem.tsx @@ -3,7 +3,7 @@ import { Box } from '@chakra-ui/react'; import React from 'react'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props { label: string; @@ -18,14 +18,11 @@ const BlockCountdownTimerItem = ({ label, value }: Props) => { overflow="hidden" flex="1 1 auto" > - <TruncatedText - text={ value } - fontFamily="heading" + <Truncate value={ value } type="end" fontFamily="heading" fontSize={{ base: '40px', lg: '48px' }} lineHeight="48px" fontWeight={ 600 } - w="100%" - /> + w="100%"/> <Box fontSize="sm" lineHeight="20px" mt={ 1 } color="text.secondary">{ label }</Box> </Box> ); diff --git a/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_long-period-until-the-block-desktop-1.png b/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_long-period-until-the-block-desktop-1.png index 4d822cf71ec..6f105b86901 100644 Binary files a/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_long-period-until-the-block-desktop-1.png and b/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_long-period-until-the-block-desktop-1.png differ diff --git a/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_long-period-until-the-block-mobile-base-view-1.png b/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_long-period-until-the-block-mobile-base-view-1.png index f528224436a..c29a1eb6a4b 100644 Binary files a/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_long-period-until-the-block-mobile-base-view-1.png and b/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_long-period-until-the-block-mobile-base-view-1.png differ diff --git a/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_short-period-until-the-block-desktop-1.png b/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_short-period-until-the-block-desktop-1.png index b54a6e960b6..3736975d5a7 100644 Binary files a/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_short-period-until-the-block-desktop-1.png and b/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_short-period-until-the-block-desktop-1.png differ diff --git a/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_short-period-until-the-block-mobile-base-view-1.png b/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_short-period-until-the-block-mobile-base-view-1.png index c8f4c559b88..a3edebdba02 100644 Binary files a/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_short-period-until-the-block-mobile-base-view-1.png and b/src/slices/block/pages/countdown-details/__screenshots__/BlockCountdown.pw.tsx_default_short-period-until-the-block-mobile-base-view-1.png differ diff --git a/src/slices/block/pages/countdown-index/BlockCountdownIndex.tsx b/src/slices/block/pages/countdown-index/BlockCountdownIndex.tsx index bf388f738e5..17adf6663d4 100644 --- a/src/slices/block/pages/countdown-index/BlockCountdownIndex.tsx +++ b/src/slices/block/pages/countdown-index/BlockCountdownIndex.tsx @@ -1,13 +1,13 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, Box, Center } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import { useMultichainContext } from 'src/features/multichain/context'; import ChainIcon from 'src/shared/external-chains/ChainIcon'; import { routeParams } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Heading } from 'src/toolkit/chakra/heading'; @@ -24,7 +24,7 @@ const BlockCountdownIndex = () => { const searchTerm = formData.get('search_term'); if (typeof searchTerm === 'string' && searchTerm) { const url = routeParams({ pathname: '/block/countdown/[height]', query: { height: searchTerm } }, multichainContext); - router.push(url, undefined, { shallow: true }); + router.push(url, { shallow: true }); } }, [ router, multichainContext ]); diff --git a/src/slices/block/pages/countdown-index/__screenshots__/BlockCountdownIndex.pw.tsx_default_base-view-mobile-1.png b/src/slices/block/pages/countdown-index/__screenshots__/BlockCountdownIndex.pw.tsx_default_base-view-mobile-1.png index cf6b71d44eb..76910c2ead1 100644 Binary files a/src/slices/block/pages/countdown-index/__screenshots__/BlockCountdownIndex.pw.tsx_default_base-view-mobile-1.png and b/src/slices/block/pages/countdown-index/__screenshots__/BlockCountdownIndex.pw.tsx_default_base-view-mobile-1.png differ diff --git a/src/slices/block/pages/countdown-index/__screenshots__/BlockCountdownIndex.pw.tsx_mobile_base-view-mobile-1.png b/src/slices/block/pages/countdown-index/__screenshots__/BlockCountdownIndex.pw.tsx_mobile_base-view-mobile-1.png index 2dcfd49ad25..dd66895f60c 100644 Binary files a/src/slices/block/pages/countdown-index/__screenshots__/BlockCountdownIndex.pw.tsx_mobile_base-view-mobile-1.png and b/src/slices/block/pages/countdown-index/__screenshots__/BlockCountdownIndex.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/slices/block/pages/details/Block.tsx b/src/slices/block/pages/details/Block.tsx index 8b9a87c94f1..c6fb817479d 100644 --- a/src/slices/block/pages/details/Block.tsx +++ b/src/slices/block/pages/details/Block.tsx @@ -2,7 +2,6 @@ import { chakra, Flex } from '@chakra-ui/react'; import { capitalize } from 'es-toolkit'; -import { useRouter } from 'next/router'; import React from 'react'; import type { PaginationParams } from 'src/shared/pagination/types'; @@ -39,6 +38,7 @@ import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { routeParams } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -169,7 +169,7 @@ const BlockPageContent = () => { if (blockQuery.isError) { if (!blockQuery.isDegradedData && blockQuery.error.status === 404 && !heightOrHash.startsWith('0x') && blockQuery.isFutureBlock) { const url = routeParams({ pathname: '/block/countdown/[height]', query: { height: heightOrHash } }, multichainContext); - router.push(url, undefined, { shallow: true }); + router.push(url, { shallow: true }); return null; } else { throwOnResourceLoadError(blockQuery); diff --git a/src/slices/block/pages/details/BlockDetails.tsx b/src/slices/block/pages/details/BlockDetails.tsx index 41a542e21df..ea643138a65 100644 --- a/src/slices/block/pages/details/BlockDetails.tsx +++ b/src/slices/block/pages/details/BlockDetails.tsx @@ -3,7 +3,6 @@ import { GridItem, Text, Box } from '@chakra-ui/react'; import BigNumber from 'bignumber.js'; import { capitalize } from 'es-toolkit'; -import { useRouter } from 'next/router'; import React from 'react'; import { ZKSYNC_L2_TX_BATCH_STATUSES } from 'src/features/rollup/zk-sync/types/api'; @@ -35,9 +34,9 @@ import DetailedInfoTimestamp from 'src/shared/detailed-info/DetailedInfoTimestam import VerificationSteps from 'src/shared/lifecycle/steps/VerificationSteps'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import { route, routeParams } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import StatusTag from 'src/shared/tags/status-tag/StatusTag'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import GasPriceValue from 'src/shared/values/entity/GasPriceValue'; import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; import { WEI } from 'src/shared/values/entity/utils'; @@ -48,6 +47,7 @@ import { CollapsibleDetails } from 'src/toolkit/chakra/collapsible'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import { ZERO } from 'src/toolkit/utils/consts'; import { space } from 'src/toolkit/utils/htmlEntities'; @@ -178,7 +178,7 @@ const BlockDetails = ({ query }: Props) => { /> </DetailedInfo.ItemValue> - { rollupFeature.isEnabled && rollupFeature.type === 'arbitrum' && data.arbitrum && data.arbitrum.l1_block_number && ( + { rollupFeature.isEnabled && rollupFeature.type === 'arbitrum' && typeof data.arbitrum?.l1_block_number === 'number' && ( <> <DetailedInfo.ItemLabel hint={ `The most recent ${ layerLabels.parent } block height as of this ${ layerLabels.current } block` } @@ -567,7 +567,7 @@ const BlockDetails = ({ query }: Props) => { alignSelf="flex-start" > <Box whiteSpace="nowrap" overflow="hidden"> - <HashStringShortenDynamic hash={ data.bitcoin_merged_mining_header }/> + <Truncate value={ data.bitcoin_merged_mining_header }/> </Box> <CopyToClipboard text={ data.bitcoin_merged_mining_header }/> </DetailedInfo.ItemValue> @@ -622,7 +622,7 @@ const BlockDetails = ({ query }: Props) => { alignSelf="flex-start" > <Box whiteSpace="nowrap" overflow="hidden"> - <HashStringShortenDynamic hash={ data.hash_for_merged_mining }/> + <Truncate value={ data.hash_for_merged_mining }/> </Box> <CopyToClipboard text={ data.hash_for_merged_mining }/> </DetailedInfo.ItemValue> @@ -638,7 +638,7 @@ const BlockDetails = ({ query }: Props) => { </DetailedInfo.ItemLabel> <DetailedInfo.ItemValue> <Box overflow="hidden"> - <HashStringShortenDynamic hash={ BigNumber(data.difficulty).toFormat() }/> + <Truncate value={ BigNumber(data.difficulty).toFormat() }/> </Box> </DetailedInfo.ItemValue> </> @@ -652,7 +652,7 @@ const BlockDetails = ({ query }: Props) => { </DetailedInfo.ItemLabel> <DetailedInfo.ItemValue> <Box overflow="hidden"> - <HashStringShortenDynamic hash={ BigNumber(data.total_difficulty).toFormat() }/> + <Truncate value={ BigNumber(data.total_difficulty).toFormat() }/> </Box> </DetailedInfo.ItemValue> </> @@ -667,7 +667,7 @@ const BlockDetails = ({ query }: Props) => { </DetailedInfo.ItemLabel> <DetailedInfo.ItemValue flexWrap="nowrap"> <Box overflow="hidden" > - <HashStringShortenDynamic hash={ data.hash }/> + <Truncate value={ data.hash }/> </Box> <CopyToClipboard text={ data.hash }/> </DetailedInfo.ItemValue> @@ -685,9 +685,7 @@ const BlockDetails = ({ query }: Props) => { overflow="hidden" whiteSpace="nowrap" > - <HashStringShortenDynamic - hash={ data.parent_hash } - /> + <Truncate value={ data.parent_hash }/> </Link> <CopyToClipboard text={ data.parent_hash }/> </DetailedInfo.ItemValue> @@ -716,7 +714,7 @@ const BlockDetails = ({ query }: Props) => { { data.arbitrum.send_root } </DetailedInfo.ItemValue> - { data.arbitrum.delayed_messages && ( + { data.arbitrum.delayed_messages !== undefined && ( <> <DetailedInfo.ItemLabel hint={ `The number of delayed ${ layerLabels.parent } to ${ layerLabels.current } messages read as of this block` } diff --git a/src/slices/block/pages/details/BlockInternalTxs.tsx b/src/slices/block/pages/details/BlockInternalTxs.tsx index ef54de7f4f1..0a9a8fbe73f 100644 --- a/src/slices/block/pages/details/BlockInternalTxs.tsx +++ b/src/slices/block/pages/details/BlockInternalTxs.tsx @@ -1,31 +1,26 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; -import InternalTxsList from 'src/slices/internal-tx/components/InternalTxsList'; import InternalTxsTable from 'src/slices/internal-tx/components/InternalTxsTable'; import DataList from 'src/shared/lists/DataList'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; + +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; interface Props { - query: QueryWithPagesResult<'core:block_internal_txs'>; + query: ApiPaginatedQueryResult<'core:block_internal_txs'>; top?: number; } const BlockInternalTxs = ({ query, top }: Props) => { - const { data, isPlaceholderData, isError } = query; + const { data, isInitialLoading, isTransitioning, isError } = query; const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <InternalTxsList data={ data.items } isLoading={ isPlaceholderData } showBlockInfo={ false } resetKey={ query.queryHash }/> - </Box> - <Box hideBelow="lg"> - <InternalTxsTable data={ data.items } isLoading={ isPlaceholderData } top={ top } showBlockInfo={ false } resetKey={ query.queryHash }/> - </Box> - </> + <TableContainerScrollable> + <InternalTxsTable data={ data.items } isLoading={ isInitialLoading } top={ top } showBlockInfo={ false } resetKey={ query.queryHash }/> + </TableContainerScrollable> ) : null; return ( @@ -33,6 +28,7 @@ const BlockInternalTxs = ({ query, top }: Props) => { isError={ isError } itemsNum={ data?.items.length } emptyText="There are no internal transactions." + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-details-tab-1.png b/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-details-tab-1.png index 88ffd4e563d..bf0b127c31a 100644 Binary files a/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-details-tab-1.png and b/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-details-tab-1.png differ diff --git a/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-txs-tab-1.png b/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-txs-tab-1.png index 2db585b034b..5a38717890c 100644 Binary files a/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-txs-tab-1.png and b/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-txs-tab-1.png differ diff --git a/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-withdrawals-tab-1.png b/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-withdrawals-tab-1.png index d2c6dd7a8f7..c5f1a7a4a78 100644 Binary files a/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-withdrawals-tab-1.png and b/src/slices/block/pages/details/__screenshots__/Block.pw.tsx_default_degradation-view-withdrawals-tab-1.png differ diff --git a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_dark-color-mode_regular-block-mobile-dark-mode-1.png b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_dark-color-mode_regular-block-mobile-dark-mode-1.png index 69aa71cb577..4c58d29abd1 100644 Binary files a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_dark-color-mode_regular-block-mobile-dark-mode-1.png and b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_dark-color-mode_regular-block-mobile-dark-mode-1.png differ diff --git a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_genesis-block-1.png b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_genesis-block-1.png index d53ee073a59..2ef2d5811ed 100644 Binary files a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_genesis-block-1.png and b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_genesis-block-1.png differ diff --git a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_regular-block-mobile-dark-mode-1.png b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_regular-block-mobile-dark-mode-1.png index b09a1c58cbe..dfe7bc24a6d 100644 Binary files a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_regular-block-mobile-dark-mode-1.png and b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_regular-block-mobile-dark-mode-1.png differ diff --git a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_rootstock-custom-fields-1.png b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_rootstock-custom-fields-1.png index ec3a42f74cd..ab5bf2a1e64 100644 Binary files a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_rootstock-custom-fields-1.png and b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_rootstock-custom-fields-1.png differ diff --git a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_with-blob-txs-1.png b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_with-blob-txs-1.png index 9e5875bec20..e43ed24ddbc 100644 Binary files a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_with-blob-txs-1.png and b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_default_with-blob-txs-1.png differ diff --git a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_mobile_regular-block-mobile-dark-mode-1.png b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_mobile_regular-block-mobile-dark-mode-1.png index edfa791505a..bec6da1efcd 100644 Binary files a/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_mobile_regular-block-mobile-dark-mode-1.png and b/src/slices/block/pages/details/__screenshots__/BlockDetails.pw.tsx_mobile_regular-block-mobile-dark-mode-1.png differ diff --git a/src/slices/block/pages/index/Blocks.pw.tsx b/src/slices/block/pages/index/Blocks.pw.tsx index 74eed8a6583..3253eb18e45 100644 --- a/src/slices/block/pages/index/Blocks.pw.tsx +++ b/src/slices/block/pages/index/Blocks.pw.tsx @@ -6,14 +6,13 @@ import * as statsMock from 'src/slices/chain/stats/mocks'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; import * as socketServer from 'playwright/fixtures/socketServer'; -import { test, expect, devices } from 'playwright/lib'; +import { test, expect } from 'playwright/lib'; import Blocks from './Blocks'; const hooksConfig = { router: { query: { tab: 'blocks' }, - isReady: true, }, }; @@ -25,7 +24,7 @@ test.beforeEach(async({ mockTextAd }) => { await mockTextAd(); }); -test('base view +@dark-mode', async({ render, mockApiResponse }) => { +test('base view +@mobile +@dark-mode', async({ render, mockApiResponse }) => { await mockApiResponse('core:blocks', baseListResponse, { queryParams: { type: 'block' } }); await mockApiResponse('core:stats', statsMock.base); @@ -34,9 +33,10 @@ test('base view +@dark-mode', async({ render, mockApiResponse }) => { await expect(component).toHaveScreenshot(); }); -test('hidden fields', async({ render, mockApiResponse, mockEnvs }) => { +test('hidden fields and views', async({ render, mockApiResponse, mockEnvs }) => { await mockEnvs([ ...ENVS_MAP.blockHiddenFields, + ...ENVS_MAP.blockHiddenViews, [ 'NEXT_PUBLIC_VIEWS_BLOCK_PENDING_UPDATE_ALERT_ENABLED', 'false' ], ]); await mockApiResponse('core:blocks', baseListResponse, { queryParams: { type: 'block' } }); @@ -47,34 +47,9 @@ test('hidden fields', async({ render, mockApiResponse, mockEnvs }) => { await expect(component).toHaveScreenshot(); }); -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - - test('base view', async({ render, mockApiResponse }) => { - await mockApiResponse('core:blocks', baseListResponse, { queryParams: { type: 'block' } }); - await mockApiResponse('core:stats', statsMock.base); - - const component = await render(<Blocks/>, { hooksConfig }); - - await expect(component).toHaveScreenshot(); - }); - - test('hidden fields', async({ render, mockApiResponse, mockEnvs }) => { - await mockEnvs([ - ...ENVS_MAP.blockHiddenFields, - [ 'NEXT_PUBLIC_VIEWS_BLOCK_PENDING_UPDATE_ALERT_ENABLED', 'false' ], - ]); - await mockApiResponse('core:blocks', baseListResponse, { queryParams: { type: 'block' } }); - await mockApiResponse('core:stats', statsMock.base); - - const component = await render(<Blocks/>, { hooksConfig }); - - await expect(component).toHaveScreenshot(); - }); -}); - test('new item from socket', async({ render, mockApiResponse, createSocket }) => { await mockApiResponse('core:blocks', baseListResponse, { queryParams: { type: 'block' } }); + await mockApiResponse('core:stats', statsMock.base); const component = await render(<Blocks/>, { hooksConfig }, { withSocket: true }); @@ -94,6 +69,7 @@ test('new item from socket', async({ render, mockApiResponse, createSocket }) => test('socket error', async({ render, mockApiResponse, createSocket }) => { await mockApiResponse('core:blocks', baseListResponse, { queryParams: { type: 'block' } }); + await mockApiResponse('core:stats', statsMock.base); const component = await render(<Blocks/>, { hooksConfig }, { withSocket: true }); diff --git a/src/slices/block/pages/index/Blocks.spec.tsx b/src/slices/block/pages/index/Blocks.spec.tsx new file mode 100644 index 00000000000..f4da58e90fe --- /dev/null +++ b/src/slices/block/pages/index/Blocks.spec.tsx @@ -0,0 +1,55 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +describe('Blocks page with the Forked and Uncles views hidden', () => { + beforeEach(() => { + fetchMock.resetMocks(); + fetchMock.mockResponse(JSON.stringify({ items: [], next_page_params: null })); + }); + + afterEach(async() => { + const { cleanup } = await import('vitest/lib'); + cleanup(); + }); + + it('renders no tabs bar on mobile', async() => { + await withEnvs(ENVS_MAP.blockHiddenViews, async() => { + const { render, screen } = await import('vitest/lib'); + const { 'default': Blocks } = await import('./Blocks'); + + render(<Blocks/>); + + expect(await screen.findByRole('heading', { name: 'Blocks' })).toBeTruthy(); + expect(screen.queryByRole('tablist')).toBeNull(); + }); + }); + + it('keeps the tabs bar on desktop', async() => { + const mobileMatchMedia = window.matchMedia; + // jsdom's matchMedia stub matches nothing, which lands on the mobile breakpoint + window.matchMedia = ((query: string) => ({ + ...mobileMatchMedia(query), + matches: query.includes('min-width'), + })) as typeof window.matchMedia; + + try { + await withEnvs(ENVS_MAP.blockHiddenViews, async() => { + const { render, screen } = await import('vitest/lib'); + const { 'default': Blocks } = await import('./Blocks'); + + render(<Blocks/>); + + expect(await screen.findByRole('heading', { name: 'Blocks' })).toBeTruthy(); + expect(screen.getByRole('tablist')).toBeTruthy(); + }); + } finally { + window.matchMedia = mobileMatchMedia; + } + }); +}); diff --git a/src/slices/block/pages/index/Blocks.tsx b/src/slices/block/pages/index/Blocks.tsx index 03213bf47c7..891cc50f129 100644 --- a/src/slices/block/pages/index/Blocks.tsx +++ b/src/slices/block/pages/index/Blocks.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { upperFirst } from 'es-toolkit'; -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -16,13 +15,15 @@ import Flashblocks from 'src/features/flashblocks/pages/index/Flashblocks'; import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; const flashblocksFeature = config.features.flashblocks; +const hiddenViews = config.slices.block.hiddenViews; const TAB_LIST_PROPS = { marginBottom: 0, @@ -36,47 +37,53 @@ const BlocksPageContent = () => { const isMobile = useIsMobile(); const tab = getQueryParamString(router.query.tab); - const blocksQuery = useQueryWithPages({ + const isReorgsTab = !hiddenViews?.reorgs && tab === 'reorgs'; + const isUnclesTab = !hiddenViews?.uncles && tab === 'uncles'; + const isFlashblocksTab = flashblocksFeature.isEnabled && flashblocksFeature.tabIds.some((id) => id === tab); + +<<<<<<< HEAD + const isFlashblocksTab = flashblocksFeature.isEnabled && flashblocksFeature.tabIds.some((id) => id === tab); +======= + const blocksQuery = useApiPaginatedQuery({ resourceName: 'core:blocks', - filters: { type: 'block' }, + queryParams: { type: 'block' }, options: { - enabled: tab === 'blocks' || !tab, + enabled: !isReorgsTab && !isUnclesTab && !isFlashblocksTab, placeholderData: generateListStub<'core:blocks'>(BLOCK_ITEM, 50, { next_page_params: { block_number: 8988686, items_count: 50, } }), }, }); - const reorgsQuery = useQueryWithPages({ + const reorgsQuery = useApiPaginatedQuery({ resourceName: 'core:blocks', - filters: { type: 'reorg' }, + queryParams: { type: 'reorg' }, options: { - enabled: tab === 'reorgs', + enabled: isReorgsTab, placeholderData: generateListStub<'core:blocks'>(BLOCK_ITEM, 50, { next_page_params: { block_number: 8988686, items_count: 50, } }), }, }); - const unclesQuery = useQueryWithPages({ + const unclesQuery = useApiPaginatedQuery({ resourceName: 'core:blocks', - filters: { type: 'uncle' }, + queryParams: { type: 'uncle' }, options: { - enabled: tab === 'uncles', + enabled: isUnclesTab, placeholderData: generateListStub<'core:blocks'>(BLOCK_ITEM, 50, { next_page_params: { block_number: 8988686, items_count: 50, } }), }, }); - - const isFlashblocksTab = flashblocksFeature.isEnabled && flashblocksFeature.tabIds.some((id) => id === tab); +>>>>>>> v2.13.0 const pagination = (() => { - if (tab === 'reorgs') { + if (isReorgsTab) { return reorgsQuery.pagination; } - if (tab === 'uncles') { + if (isUnclesTab) { return unclesQuery.pagination; } if (isFlashblocksTab) { @@ -88,8 +95,13 @@ const BlocksPageContent = () => { const tabs: Array<TabItemRegular> = [ { id: 'blocks', title: 'All', component: <BlocksContent type="block" query={ blocksQuery }/> }, flashblocksFeature.isEnabled && { id: flashblocksFeature.tabIds, title: upperFirst(flashblocksFeature.name) + 's', component: <Flashblocks/> }, +<<<<<<< HEAD { id: 'reorgs', title: 'Forked', component: <BlocksContent type="reorg" query={ reorgsQuery }/> }, { id: 'uncles', title: 'Uncles', component: <BlocksContent type="uncle" query={ unclesQuery }/> }, +======= + !hiddenViews?.reorgs && { id: 'reorgs', title: 'Forked', component: <BlocksContent type="reorg" query={ reorgsQuery }/> }, + !hiddenViews?.uncles && { id: 'uncles', title: 'Uncles', component: <BlocksContent type="uncle" query={ unclesQuery }/> }, +>>>>>>> v2.13.0 ].filter(Boolean); return ( @@ -98,7 +110,7 @@ const BlocksPageContent = () => { <RoutedTabs tabs={ tabs } listProps={ isMobile ? undefined : TAB_LIST_PROPS } - rightSlot={ <BlocksTabSlot pagination={ pagination }/> } + rightSlot={ isMobile ? undefined : <BlocksTabSlot pagination={ pagination }/> } stickyEnabled={ !isMobile && !isFlashblocksTab } /> </> diff --git a/src/slices/block/pages/index/BlocksContent.tsx b/src/slices/block/pages/index/BlocksContent.tsx index c5c5c2d9c60..9d61465786e 100644 --- a/src/slices/block/pages/index/BlocksContent.tsx +++ b/src/slices/block/pages/index/BlocksContent.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; +import { HStack } from '@chakra-ui/react'; import { useQueryClient } from '@tanstack/react-query'; import React from 'react'; @@ -8,32 +8,32 @@ import type { operations, schemas } from '@blockscout/api-types'; import type { SocketMessage } from 'src/api/socket/types'; import { getResourceKey } from 'src/api/hooks/useApiQuery'; -import * as SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; import useSocketChannel from 'src/api/socket/useSocketChannel'; import useSocketMessage from 'src/api/socket/useSocketMessage'; import ActionBar from 'src/shell/page/action-bar/ActionBar'; -import BlocksList from 'src/slices/block/pages/index/BlocksList'; import BlocksTable from 'src/slices/block/pages/index/BlocksTable'; +import ChainUtilization from 'src/slices/chain/ChainUtilization'; import { useMultichainContext } from 'src/features/multichain/context'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Link } from 'src/toolkit/chakra/link'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; const OVERLOAD_COUNT = 75; const TABS_HEIGHT = 88; export interface Props { type?: schemas['BlockResponse']['type']; - query: QueryWithPagesResult<'core:blocks'> | QueryWithPagesResult<'core:optimistic_l2_txn_batch_blocks'>; + query: ApiPaginatedQueryResult<'core:blocks'> | ApiPaginatedQueryResult<'core:optimistic_l2_txn_batch_blocks'>; enableSocket?: boolean; top?: number; } @@ -97,7 +97,7 @@ const BlocksContent = ({ type, query, enableSocket = true, top }: Props) => { topic: 'blocks:new_block', onSocketClose: handleSocketClose, onSocketError: handleSocketError, - isDisabled: query.isPlaceholderData || query.isError || query.pagination.page !== 1 || !enableSocket, + isDisabled: query.isInitialLoading || query.isError || query.pagination.page !== 1 || !enableSocket, }); useSocketMessage({ channel, @@ -113,48 +113,34 @@ const BlocksContent = ({ type, query, enableSocket = true, top }: Props) => { const chainData = multichainContext?.chain; const content = query.data?.items ? ( - <> - <Box hideFrom="lg"> - { query.pagination.page === 1 && enableSocket && ( - <SocketNewItemsNotice.Mobile - num={ newItemsCount } - showErrorAlert={ showSocketAlert } - type="block" - isLoading={ query.isPlaceholderData } - /> - ) } - <BlocksList - data={ query.data.items } - isLoading={ query.isPlaceholderData } - page={ query.pagination.page } - chainData={ chainData } - resetKey={ query.queryHash } - /> - </Box> - <Box hideBelow="lg"> - <BlocksTable - data={ query.data.items } - top={ top || (query.pagination.isVisible ? TABS_HEIGHT : 0) } - page={ query.pagination.page } - isLoading={ query.isPlaceholderData } - showSocketInfo={ query.pagination.page === 1 && enableSocket } - socketInfoNum={ newItemsCount } - showSocketErrorAlert={ showSocketAlert } - chainData={ chainData } - resetKey={ query.queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <BlocksTable + data={ query.data.items } + top={ top || (query.pagination.isVisible ? TABS_HEIGHT : 0) } + page={ query.pagination.page } + isLoading={ query.isInitialLoading } + showSocketInfo={ query.pagination.page === 1 && enableSocket } + socketInfoNum={ newItemsCount } + showSocketErrorAlert={ showSocketAlert } + chainData={ chainData } + resetKey={ query.queryHash } + /> + </TableContainerScrollable> ) : null; const actionBar = isMobile ? ( - <ActionBar mt={ -6 }> - <Link href={ route({ pathname: '/block/countdown' }, multichainContext) }> - <SpriteIcon name="hourglass" boxSize={ 5 } mr={ 2 }/> - <span>Block countdown</span> - </Link> - <Pagination ml="auto" { ...query.pagination }/> - </ActionBar> + <> + <HStack gap={ 3 } mb={ 6 }> + <ChainUtilization/> + <Link href={ route({ pathname: '/block/countdown' }, multichainContext) } textStyle="sm"> + <SpriteIcon name="hourglass" boxSize={ 5 } mr={ 2 }/> + <span>Block countdown</span> + </Link> + </HStack> + <ActionBar mt={ -6 }> + <Pagination ml="auto" { ...query.pagination }/> + </ActionBar> + </> ) : null; return ( @@ -163,6 +149,7 @@ const BlocksContent = ({ type, query, enableSocket = true, top }: Props) => { itemsNum={ query.data?.items?.length } emptyText="There are no blocks." actionBar={ actionBar } + isTransitioning={ query.isTransitioning } > { content } </DataList> diff --git a/src/slices/block/pages/index/BlocksList.tsx b/src/slices/block/pages/index/BlocksList.tsx deleted file mode 100644 index e5144533366..00000000000 --- a/src/slices/block/pages/index/BlocksList.tsx +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; - -import BlocksListItem from 'src/slices/block/pages/index/BlocksListItem'; - -import useInitialList from 'src/shared/lists/useInitialList'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -interface Props { - data: Array<schemas['Block']>; - isLoading: boolean; - page: number; - chainData?: ClusterChainConfig; - resetKey?: string; -} - -const BlocksList = ({ data, isLoading, page, chainData, resetKey }: Props) => { - const initialList = useInitialList({ - data: data ?? [], - idFn: (item) => item.height, - enabled: !isLoading, - }); - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <BlocksListItem - key={ item.height + (isLoading ? String(index) : '') } - data={ item } - isLoading={ isLoading } - enableTimeIncrement={ page === 1 && !isLoading } - animation={ initialList.getAnimationProp(item) } - chainData={ chainData } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default BlocksList; diff --git a/src/slices/block/pages/index/BlocksListItem.tsx b/src/slices/block/pages/index/BlocksListItem.tsx deleted file mode 100644 index 8f4893707c5..00000000000 --- a/src/slices/block/pages/index/BlocksListItem.tsx +++ /dev/null @@ -1,155 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, Text, Box } from '@chakra-ui/react'; -import BigNumber from 'bignumber.js'; -import { capitalize } from 'es-toolkit'; -import { route } from 'nextjs-routes'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import getBlockTotalReward from 'src/slices/block/utils/get-block-total-reward'; -import { currencyUnits } from 'src/slices/chain/units'; -import getChainValidatorTitle from 'src/slices/chain/verification-type/utils/get-chain-validator-title'; -import GasUsed from 'src/slices/gas/components/GasUsed'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; -import SimpleValue from 'src/shared/values/entity/SimpleValue'; -import Utilization from 'src/shared/values/utilization/Utilization'; -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Tooltip } from 'src/toolkit/chakra/tooltip'; - -interface Props { - data: schemas['Block']; - isLoading?: boolean; - enableTimeIncrement?: boolean; - animation?: string; - chainData?: ClusterChainConfig; -} - -const isRollup = config.features.rollup.isEnabled; - -const BlocksListItem = ({ data, isLoading, enableTimeIncrement, animation, chainData }: Props) => { - const totalReward = getBlockTotalReward(data); - const burntFees = BigNumber(data.burnt_fees || 0); - const txFees = BigNumber(data.transaction_fees || 0); - - return ( - <ListItemMobile rowGap={ 3 } key={ String(data.height) } animation={ animation }> - <Flex justifyContent="space-between" w="100%"> - <Flex columnGap={ 2 } alignItems="center"> - <BlockEntity - isLoading={ isLoading } - number={ data.height } - hash={ data.type !== 'block' ? data.hash : undefined } - fontWeight={ 600 } - chain={ chainData } - isPendingUpdate={ data.is_pending_update ?? false } - /> - { data.celo?.l1_era_finalized_epoch_number && ( - <Tooltip content={ `Finalized epoch #${ data.celo.l1_era_finalized_epoch_number }` } disabled={ isLoading }> - <SpriteIcon name="checkered_flag" boxSize={ 5 } p="1px" isLoading={ isLoading } flexShrink={ 0 }/> - </Tooltip> - ) } - </Flex> - <TimeWithTooltip - timestamp={ data.timestamp } - enableIncrement={ enableTimeIncrement } - isLoading={ isLoading } - color="text.secondary" - fontWeight={ 400 } - display="inline-block" - /> - </Flex> - { data.size && ( - <Flex columnGap={ 2 }> - <Text fontWeight={ 500 }>Size</Text> - <Skeleton loading={ isLoading } display="inline-block" color="text.secondary"> - <span>{ data.size?.toLocaleString() } bytes</span> - </Skeleton> - </Flex> - ) } - { !config.slices.block.hiddenFields?.miner && ( - <Flex columnGap={ 2 } w="100%"> - <Text fontWeight={ 500 }>{ capitalize(getChainValidatorTitle()) }</Text> - <AddressEntity - address={ data.miner } - isLoading={ isLoading } - truncation="constant" - /> - </Flex> - ) } - <Flex columnGap={ 2 }> - <Text fontWeight={ 500 }>Txn</Text> - { data.transactions_count > 0 ? ( - <Skeleton loading={ isLoading } display="inline-block"> - <Link href={ route({ pathname: '/block/[height_or_hash]', query: { height_or_hash: String(data.height), tab: 'txs' } }) }> - { data.transactions_count } - </Link> - </Skeleton> - ) : - <Text color="text.secondary">{ data.transactions_count }</Text> - } - </Flex> - <Box> - <Text fontWeight={ 500 }>Gas used</Text> - <Flex mt={ 2 }> - <Skeleton loading={ isLoading } display="inline-block" color="text.secondary" mr={ 4 }> - <span>{ BigNumber(data.gas_used || 0).toFormat() }</span> - </Skeleton> - <GasUsed - gasUsed={ data.gas_used || undefined } - gasLimit={ data.gas_limit } - isLoading={ isLoading } - gasTarget={ data.gas_target_percentage || undefined } - /> - </Flex> - </Box> - { !isRollup && !config.slices.block.hiddenFields?.total_reward && ( - <Flex columnGap={ 2 }> - <Text fontWeight={ 500 }>Reward { currencyUnits.ether }</Text> - <SimpleValue value={ totalReward } loading={ isLoading } color="text.secondary"/> - </Flex> - ) } - { !isRollup && !config.slices.block.hiddenFields?.burnt_fees && ( - <Box> - <Text fontWeight={ 500 }>Burnt fees</Text> - <Flex columnGap={ 4 } mt={ 2 }> - <NativeCoinValue - amount={ data.burnt_fees } - noSymbol - startElement={ <SpriteIcon name="flame" mr={ 2 } boxSize={ 5 } color={{ _light: 'gray.500', _dark: 'inherit' }} isLoading={ isLoading }/> } - loading={ isLoading } - display="flex" - color="text.secondary" - /> - <Utilization value={ burntFees.div(txFees).toNumber() } isLoading={ isLoading }/> - </Flex> - </Box> - ) } - { !isRollup && !config.slices.block.hiddenFields?.base_fee && data.base_fee_per_gas && ( - <Flex columnGap={ 2 }> - <Text fontWeight={ 500 }>Base fee</Text> - <NativeCoinValue - amount={ data.base_fee_per_gas } - loading={ isLoading } - gweiThreshold={ 4 } - units="wei" - color="text.secondary" - /> - </Flex> - ) } - </ListItemMobile> - ); -}; - -export default BlocksListItem; diff --git a/src/slices/block/pages/index/BlocksTabSlot.tsx b/src/slices/block/pages/index/BlocksTabSlot.tsx index 2f4579ae2e2..af19ed12a6d 100644 --- a/src/slices/block/pages/index/BlocksTabSlot.tsx +++ b/src/slices/block/pages/index/BlocksTabSlot.tsx @@ -1,47 +1,27 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Flex, Box, Text } from '@chakra-ui/react'; -import { upperFirst } from 'es-toolkit'; -import { route } from 'nextjs-routes'; +import { Flex } from '@chakra-ui/react'; import React from 'react'; import type { PaginationParams } from 'src/shared/pagination/types'; -import getChainUtilizationParams from 'src/slices/chain/get-chain-utilization-params'; -import useStatsQuery from 'src/slices/chain/stats/useStatsQuery'; +import ChainUtilization from 'src/slices/chain/ChainUtilization'; import Pagination from 'src/shared/pagination/Pagination'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Tooltip } from 'src/toolkit/chakra/tooltip'; -import { nbsp } from 'src/toolkit/utils/htmlEntities'; interface Props { pagination: PaginationParams | null; } const BlocksTabSlot = ({ pagination }: Props) => { - const statsQuery = useStatsQuery(); - - const networkUtilization = getChainUtilizationParams(statsQuery.data?.network_utilization_percentage ?? 0); - return ( <Flex alignItems="center" columnGap={ 8 } display={{ base: 'none', lg: 'flex' }}> - { typeof statsQuery.data?.network_utilization_percentage === 'number' && ( - <Box> - <Text as="span" fontSize="sm"> - Network utilization (last 50 blocks):{ nbsp } - </Text> - <Tooltip content={ `${ upperFirst(networkUtilization.load) } load` }> - <Skeleton display="inline-block" fontSize="sm" color={ networkUtilization.color } fontWeight={ 600 } loading={ statsQuery.isPlaceholderData }> - <span>{ statsQuery.data.network_utilization_percentage.toFixed(2) }%</span> - </Skeleton> - </Tooltip> - </Box> - ) } - <Link href={ route({ pathname: '/block/countdown' }) }> + <ChainUtilization label="Utilization (last 50 blocks):"/> + <Link href={ route({ pathname: '/block/countdown' }) } textStyle="sm"> <SpriteIcon name="hourglass" boxSize={ 5 } mr={ 2 }/> <span>Block countdown</span> </Link> diff --git a/src/slices/block/pages/index/BlocksTable.tsx b/src/slices/block/pages/index/BlocksTable.tsx index b53ac7ab01e..68bf96d503d 100644 --- a/src/slices/block/pages/index/BlocksTable.tsx +++ b/src/slices/block/pages/index/BlocksTable.tsx @@ -55,7 +55,7 @@ const BlocksTable = ({ data, isLoading, top, page, showSocketInfo, socketInfoNum return ( <AddressHighlightProvider> - <TableRoot minWidth={ chainData ? '1100px' : '1070px' } fontWeight={ 500 }> + <TableRoot minWidth={ chainData ? '1200px' : '1150px' } fontWeight={ 500 }> <TableHeaderSticky top={ top }> <TableRow> { chainData && <TableColumnHeader width="38px"/> } diff --git a/src/slices/block/pages/index/BlocksTableItem.tsx b/src/slices/block/pages/index/BlocksTableItem.tsx index af042956654..743adab2648 100644 --- a/src/slices/block/pages/index/BlocksTableItem.tsx +++ b/src/slices/block/pages/index/BlocksTableItem.tsx @@ -2,7 +2,6 @@ import { Flex } from '@chakra-ui/react'; import BigNumber from 'bignumber.js'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -17,6 +16,7 @@ import GasUsed from 'src/slices/gas/components/GasUsed'; import config from 'src/config'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; import ChainIcon from 'src/shared/external-chains/ChainIcon'; +import { route } from 'src/shared/router/routes'; import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; import SimpleValue from 'src/shared/values/entity/SimpleValue'; import Utilization from 'src/shared/values/utilization/Utilization'; @@ -51,7 +51,7 @@ const BlocksTableItem = ({ data, isLoading, enableTimeIncrement, animation, chai ) } <TableCell > <Flex columnGap={ 2 } alignItems="center" mb={ 2 }> - { data.celo?.l1_era_finalized_epoch_number && ( + { typeof data.celo?.l1_era_finalized_epoch_number === 'number' && ( <Tooltip content={ `Finalized epoch #${ data.celo.l1_era_finalized_epoch_number }` }> <SpriteIcon name="checkered_flag" boxSize={ 5 } p="1px" isLoading={ isLoading } flexShrink={ 0 }/> </Tooltip> diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_dark-color-mode_base-view-dark-mode-1.png deleted file mode 100644 index c1c3bd1bcbe..00000000000 Binary files a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and /dev/null differ diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png new file mode 100644 index 00000000000..e98b6fe1b2a Binary files /dev/null and b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_dark-color-mode_base-view-mobile-dark-mode-1.png differ diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_base-view-dark-mode-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_base-view-dark-mode-1.png deleted file mode 100644 index 03f9b3085b5..00000000000 Binary files a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_base-view-dark-mode-1.png and /dev/null differ diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_base-view-mobile-dark-mode-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_base-view-mobile-dark-mode-1.png new file mode 100644 index 00000000000..377a4a06764 Binary files /dev/null and b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_base-view-mobile-dark-mode-1.png differ diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_hidden-fields-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_hidden-fields-1.png deleted file mode 100644 index b8812255c3b..00000000000 Binary files a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_hidden-fields-1.png and /dev/null differ diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_hidden-fields-and-views-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_hidden-fields-and-views-1.png new file mode 100644 index 00000000000..0b3a7554ce4 Binary files /dev/null and b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_hidden-fields-and-views-1.png differ diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_mobile-base-view-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_mobile-base-view-1.png deleted file mode 100644 index e883848f3c7..00000000000 Binary files a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_mobile-base-view-1.png and /dev/null differ diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_mobile-hidden-fields-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_mobile-hidden-fields-1.png deleted file mode 100644 index 4c21be1d3e4..00000000000 Binary files a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_mobile-hidden-fields-1.png and /dev/null differ diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_new-item-from-socket-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_new-item-from-socket-1.png index b6db1bb8bad..05e23221179 100644 Binary files a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_new-item-from-socket-1.png and b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_new-item-from-socket-1.png differ diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_socket-error-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_socket-error-1.png index 0a3c42d5d7b..fac94a97690 100644 Binary files a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_socket-error-1.png and b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_default_socket-error-1.png differ diff --git a/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_mobile_base-view-mobile-dark-mode-1.png b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_mobile_base-view-mobile-dark-mode-1.png new file mode 100644 index 00000000000..98523801b71 Binary files /dev/null and b/src/slices/block/pages/index/__screenshots__/Blocks.pw.tsx_mobile_base-view-mobile-dark-mode-1.png differ diff --git a/src/slices/block/types/config.ts b/src/slices/block/types/config.ts index e31bd1e652b..3b344746ce1 100644 --- a/src/slices/block/types/config.ts +++ b/src/slices/block/types/config.ts @@ -11,3 +11,10 @@ export const BLOCK_FIELDS_IDS = [ ] as const; export type BlockFieldId = (typeof BLOCK_FIELDS_IDS)[number]; + +export const BLOCK_VIEWS_IDS = [ + 'reorgs', + 'uncles', +] as const; + +export type BlockViewId = (typeof BLOCK_VIEWS_IDS)[number]; diff --git a/src/slices/chain/ChainUtilization.tsx b/src/slices/chain/ChainUtilization.tsx new file mode 100644 index 00000000000..e361b6f48ca --- /dev/null +++ b/src/slices/chain/ChainUtilization.tsx @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { chakra, HStack, Text } from '@chakra-ui/react'; +import { upperFirst } from 'es-toolkit'; +import React from 'react'; + +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +import getChainUtilizationParams from 'src/slices/chain/get-chain-utilization-params'; +import useStatsQuery from 'src/slices/chain/stats/useStatsQuery'; + +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { nbsp } from 'src/toolkit/utils/htmlEntities'; + +interface Props { + className?: string; + label?: string; + chain?: ClusterChainConfig; +} + +const ChainUtilization = ({ className, label, chain }: Props) => { + const statsQuery = useStatsQuery({ chain }); + const value = statsQuery.data?.network_utilization_percentage; + + if (typeof value !== 'number') { + return null; + } + + const { load, color } = getChainUtilizationParams(value); + + return ( + <Skeleton + className={ className } + loading={ statsQuery.isPlaceholderData } + display="inline-flex" + alignItems="center" + textStyle="sm" + > + { label && <Text as="span">{ label }{ nbsp }</Text> } + <Tooltip content={ `Network utilization: ${ upperFirst(load) } load` }> + <HStack gap={ 1 }> + { !label && <SpriteIcon name="utilization" boxSize={ 5 } color={ color }/> } + <Text as="span" color={ color } fontWeight="bold"> + { value.toFixed(2) }% + </Text> + </HStack> + </Tooltip> + </Skeleton> + ); +}; + +export default chakra(ChainUtilization); diff --git a/src/slices/chain/indexing-status/IndexingStatusInternalTxs.tsx b/src/slices/chain/indexing-status/IndexingStatusInternalTxs.tsx index d52d32b786d..7e24d253aa2 100644 --- a/src/slices/chain/indexing-status/IndexingStatusInternalTxs.tsx +++ b/src/slices/chain/indexing-status/IndexingStatusInternalTxs.tsx @@ -61,10 +61,13 @@ const IndexingStatusInternalTxs = () => { return null; } + const ratio = data.indexed_internal_transactions_ratio; + const hasRatio = ratio !== null && ratio !== undefined; + const hint = ( <Text textStyle="xs"> - { data.indexed_internal_transactions_ratio && - `${ Math.floor(Number(data.indexed_internal_transactions_ratio) * 100) }% Blocks With Internal Transactions Indexed${ nbsp }${ ndash } ` } + { hasRatio && + `${ Math.floor(Number(ratio) * 100) }% Blocks With Internal Transactions Indexed${ nbsp }${ ndash } ` } We{ apos }re indexing this chain right now. Some of the counts may be inaccurate. </Text> ); @@ -80,9 +83,9 @@ const IndexingStatusInternalTxs = () => { _hover={{ color: 'hover' }} > <SpriteIcon name="info" boxSize={ 5 }/> - { data.indexed_internal_transactions_ratio && ( + { hasRatio && ( <Text fontWeight={ 600 } textStyle="xs" color="inherit"> - { Math.floor(Number(data.indexed_internal_transactions_ratio) * 100) + '%' } + { Math.floor(Number(ratio) * 100) + '%' } </Text> ) } </Flex> diff --git a/src/slices/chain/indexing-status/mocks.ts b/src/slices/chain/indexing-status/mocks.ts new file mode 100644 index 00000000000..423af9f83b9 --- /dev/null +++ b/src/slices/chain/indexing-status/mocks.ts @@ -0,0 +1,24 @@ +import type { paths } from '@blockscout/api-types'; + +type IndexingStatus = paths['/api/v2/main-page/indexing-status']['get']; + +export const blocksInProgress: IndexingStatus = { + finished_indexing_blocks: false, + indexed_blocks_ratio: 0.1, + finished_indexing: true, + indexed_internal_transactions_ratio: 1, +}; + +export const inProgress: IndexingStatus = { + finished_indexing_blocks: false, + indexed_blocks_ratio: 0.1, + finished_indexing: false, + indexed_internal_transactions_ratio: 0.1, +}; + +export const finished: IndexingStatus = { + finished_indexing_blocks: true, + indexed_blocks_ratio: 1, + finished_indexing: true, + indexed_internal_transactions_ratio: 1, +}; diff --git a/src/slices/chain/logo/NetworkIcon.tsx b/src/slices/chain/logo/NetworkIcon.tsx index ef1711be1af..2e0a6d437b8 100644 --- a/src/slices/chain/logo/NetworkIcon.tsx +++ b/src/slices/chain/logo/NetworkIcon.tsx @@ -1,10 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { useColorModeValue } from 'src/toolkit/chakra/color-mode'; diff --git a/src/slices/chain/logo/NetworkLogo.tsx b/src/slices/chain/logo/NetworkLogo.tsx index a988307602f..21c29d61618 100644 --- a/src/slices/chain/logo/NetworkLogo.tsx +++ b/src/slices/chain/logo/NetworkLogo.tsx @@ -1,10 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { useColorModeValue } from 'src/toolkit/chakra/color-mode'; diff --git a/src/slices/chain/logo/__screenshots__/NetworkLogo.pw.tsx_dark-color-mode_placeholder-logo-dark-mode-1.png b/src/slices/chain/logo/__screenshots__/NetworkLogo.pw.tsx_dark-color-mode_placeholder-logo-dark-mode-1.png index 971bd2f2ca0..512d694fb80 100644 Binary files a/src/slices/chain/logo/__screenshots__/NetworkLogo.pw.tsx_dark-color-mode_placeholder-logo-dark-mode-1.png and b/src/slices/chain/logo/__screenshots__/NetworkLogo.pw.tsx_dark-color-mode_placeholder-logo-dark-mode-1.png differ diff --git a/src/slices/chain/mocks.ts b/src/slices/chain/mocks.ts new file mode 100644 index 00000000000..8373767d8db --- /dev/null +++ b/src/slices/chain/mocks.ts @@ -0,0 +1 @@ +export const backendVersion = { backend_version: 'v5.2.0-beta.+commit.1ce1a355' }; diff --git a/src/slices/chain/stats/useStatsQuery.ts b/src/slices/chain/stats/useStatsQuery.ts index 82e497af47a..0200cd2e026 100644 --- a/src/slices/chain/stats/useStatsQuery.ts +++ b/src/slices/chain/stats/useStatsQuery.ts @@ -1,5 +1,7 @@ // SPDX-License-Identifier: LicenseRef-Blockscout +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + import useApiQuery from 'src/api/hooks/useApiQuery'; import { useMultichainContext } from 'src/features/multichain/context'; @@ -8,13 +10,14 @@ import { STATS } from './stubs'; interface Props { enabled?: boolean; + chain?: ClusterChainConfig; } -export default function useStatsQuery({ enabled = true }: Props = {}) { +export default function useStatsQuery({ enabled = true, chain }: Props = {}) { const multichainContext = useMultichainContext(); return useApiQuery('core:stats', { - chain: multichainContext?.chain, + chain: chain ?? multichainContext?.chain, queryOptions: { enabled, refetchOnMount: false, diff --git a/src/slices/contract/hooks/useVerifiedContractsQuery.ts b/src/slices/contract/hooks/useVerifiedContractsQuery.ts index e5eccc7dfc1..b367af2ad99 100644 --- a/src/slices/contract/hooks/useVerifiedContractsQuery.ts +++ b/src/slices/contract/hooks/useVerifiedContractsQuery.ts @@ -1,8 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; +import type { ExternalChainExtended } from 'src/shared/external-chains/types'; import type { VerifiedContractsFilters, VerifiedContractsSorting, @@ -13,30 +13,20 @@ import type { import { SORT_OPTIONS } from 'src/slices/contract/pages/index/sort'; import { VERIFIED_CONTRACT_INFO } from 'src/slices/contract/stubs'; -import useDebounce from 'src/shared/hooks/useDebounce'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; import getSortValueFromQuery from 'src/shared/sort/get-sort-value-from-query'; interface Props { - isMultichain?: boolean; + chain?: ExternalChainExtended; } -export default function useVerifiedContractsQuery({ isMultichain }: Props = {}) { - const router = useRouter(); - const [ searchTerm, setSearchTerm ] = React.useState(getQueryParamString(router.query.q) || undefined); - const [ type, setType ] = React.useState(getQueryParamString(router.query.filter) as VerifiedContractsFilters['filter'] || undefined); - const [ sort, setSort ] = - React.useState<VerifiedContractsSortingValue>(getSortValueFromQuery<VerifiedContractsSortingValue>(router.query, SORT_OPTIONS) ?? 'default'); - - const debouncedSearchTerm = useDebounce(searchTerm || '', 300); - - const query = useQueryWithPages({ +export default function useVerifiedContractsQuery({ chain }: Props = {}) { + const query = useApiPaginatedQuery({ resourceName: 'core:verified_contracts', - filters: { q: debouncedSearchTerm, filter: type }, - sorting: getSortParamsFromValue<VerifiedContractsSortingValue, VerifiedContractsSortingField, VerifiedContractsSorting['order']>(sort), options: { placeholderData: generateListStub<'core:verified_contracts'>( VERIFIED_CONTRACT_INFO, @@ -49,14 +39,16 @@ export default function useVerifiedContractsQuery({ isMultichain }: Props = {}) }, ), }, - isMultichain, + chain, }); + + const searchTerm = getQueryParamString(query.filters.q) || undefined; + const type = getQueryParamString(query.filters.filter) as VerifiedContractsFilters['filter'] || undefined; + const sort = getSortValueFromQuery<VerifiedContractsSortingValue>({ ...query.sorting }, SORT_OPTIONS) ?? 'default'; + const { onFilterChange, onSortingChange } = query; - const onSearchTermChange = React.useCallback((value: string) => { - onFilterChange({ q: value, filter: type }); - setSearchTerm(value); - }, [ type, onFilterChange ]); + const onSearchTermChange = useDebouncedFilterChange((value) => onFilterChange({ q: value, filter: type })); const onTypeChange = React.useCallback((value: string | Array<string>) => { if (Array.isArray(value)) { @@ -65,23 +57,24 @@ export default function useVerifiedContractsQuery({ isMultichain }: Props = {}) const filter = value === 'all' ? undefined : value as VerifiedContractsFilters['filter']; - onFilterChange({ q: debouncedSearchTerm, filter }); - setType(filter); - }, [ debouncedSearchTerm, onFilterChange ]); + onFilterChange({ q: searchTerm, filter }); + }, [ searchTerm, onFilterChange ]); const onSortChange = React.useCallback(({ value }: { value: Array<string> }) => { - setSort(value[0] as VerifiedContractsSortingValue); - onSortingChange(value[0] === 'default' ? undefined : getSortParamsFromValue(value[0] as VerifiedContractsSortingValue)); + onSortingChange( + getSortParamsFromValue<VerifiedContractsSortingValue, VerifiedContractsSortingField, VerifiedContractsSorting['order']>( + value[0] as VerifiedContractsSortingValue, + ), + ); }, [ onSortingChange ]); return React.useMemo(() => ({ query, type, searchTerm, - debouncedSearchTerm, sort, onSearchTermChange, onTypeChange, onSortChange, - }), [ query, type, searchTerm, debouncedSearchTerm, sort, onSearchTermChange, onTypeChange, onSortChange ]); + }), [ query, type, searchTerm, sort, onSearchTermChange, onTypeChange, onSortChange ]); } diff --git a/src/slices/contract/pages/contract-verification/ContractVerificationForAddress.tsx b/src/slices/contract/pages/contract-verification/ContractVerificationForAddress.tsx index e76282b26b3..0ce1d9bd7c7 100644 --- a/src/slices/contract/pages/contract-verification/ContractVerificationForAddress.tsx +++ b/src/slices/contract/pages/contract-verification/ContractVerificationForAddress.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { SmartContractVerificationMethodApi } from 'src/slices/contract/types/api'; @@ -17,6 +16,7 @@ import type { SmartContractVerificationMethod } from 'src/slices/contract/pages/ import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { ContentLoader } from 'src/toolkit/components/loaders/ContentLoader'; @@ -39,7 +39,7 @@ const ContractVerificationForAddress = () => { React.useEffect(() => { if (method && hash) { - router.replace({ pathname: '/address/[hash]/contract-verification', query: { hash } }, undefined, { scroll: false, shallow: true }); + router.replace({ pathname: '/address/[hash]/contract-verification', query: { hash } }, { scroll: false, shallow: true }); } // onMount only // eslint-disable-next-line react-hooks/exhaustive-deps @@ -49,7 +49,7 @@ const ContractVerificationForAddress = () => { React.useEffect(() => { if (isVerifiedContract) { - router.push({ pathname: '/address/[hash]', query: { hash, tab: 'contract' } }, undefined, { scroll: false, shallow: true }); + router.push({ pathname: '/address/[hash]', query: { hash, tab: 'contract' } }, { scroll: false, shallow: true }); } }, [ hash, isVerifiedContract, router ]); diff --git a/src/slices/contract/pages/contract-verification/ContractVerificationForm.pw.tsx b/src/slices/contract/pages/contract-verification/ContractVerificationForm.pw.tsx index 1fd05b89735..f51955923f7 100644 --- a/src/slices/contract/pages/contract-verification/ContractVerificationForm.pw.tsx +++ b/src/slices/contract/pages/contract-verification/ContractVerificationForm.pw.tsx @@ -90,6 +90,10 @@ test('flatten source code method +@dark-mode +@mobile', async({ render, page }) await page.getByRole('textbox', { name: 'Contract code' }).fill('test'); + // The cursor is left where the "Add item" button was clicked. Which "Library address" input ends up + // under it depends on the scroll offset at capture time, so park it over the empty right margin. + await page.mouse.move(1190, 740); + await expect(component).toHaveScreenshot({ timeout: 10_000 }); }); diff --git a/src/slices/contract/pages/contract-verification/ContractVerificationForm.tsx b/src/slices/contract/pages/contract-verification/ContractVerificationForm.tsx index 981857af396..599ff488cff 100644 --- a/src/slices/contract/pages/contract-verification/ContractVerificationForm.tsx +++ b/src/slices/contract/pages/contract-verification/ContractVerificationForm.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Grid, Text, chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { SubmitHandler } from 'react-hook-form'; import { useForm, FormProvider } from 'react-hook-form'; @@ -18,8 +17,9 @@ import type { SmartContractVerificationConfig } from 'src/slices/contract/pages/ import useRewardsActivity from 'src/features/rewards/hooks/useRewardsActivity'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import getErrorObjStatusCode from 'src/shared/errors/get-error-obj-status-code'; +import { route } from 'src/shared/router/routes'; import capitalizeFirstLetter from 'src/shared/texts/capitalize-first-letter'; import delay from 'src/shared/utils/delay'; @@ -129,10 +129,10 @@ const ContractVerificationForm = ({ method: methodFromQuery, config, hash }: Pro description: 'Contract is successfully verified.', }); - mixpanel.logEvent( - mixpanel.EventTypes.CONTRACT_VERIFICATION, + analytics.logEvent( + analytics.EventTypes.CONTRACT_VERIFICATION, { Status: 'Finished', Method: methodNameRef.current || '' }, - { send_immediately: true }, + { sendImmediately: true }, ); window.location.assign(route({ pathname: '/address/[hash]', query: { hash: address, tab: 'contract' } })); @@ -190,7 +190,7 @@ const ContractVerificationForm = ({ method: methodFromQuery, config, hash }: Pro reset(getDefaultValues(methodValue, config, hash || address, licenseType)); const methodName = METHOD_LABELS[methodValue]; - mixpanel.logEvent(mixpanel.EventTypes.CONTRACT_VERIFICATION, { Status: 'Method selected', Method: methodName }); + analytics.logEvent(analytics.EventTypes.CONTRACT_VERIFICATION, { Status: 'Method selected', Method: methodName }); methodNameRef.current = methodName; } // !!! should run only when method is changed diff --git a/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_dark-color-mode_flatten-source-code-method-dark-mode-mobile-1.png b/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_dark-color-mode_flatten-source-code-method-dark-mode-mobile-1.png index 158b404e5df..09a6da838d8 100644 Binary files a/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_dark-color-mode_flatten-source-code-method-dark-mode-mobile-1.png and b/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_dark-color-mode_flatten-source-code-method-dark-mode-mobile-1.png differ diff --git a/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_default_verification-of-stylus-rust-contract-1.png b/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_default_verification-of-stylus-rust-contract-1.png index a0b58be2846..0b1977946f7 100644 Binary files a/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_default_verification-of-stylus-rust-contract-1.png and b/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_default_verification-of-stylus-rust-contract-1.png differ diff --git a/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_mobile_flatten-source-code-method-dark-mode-mobile-1.png b/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_mobile_flatten-source-code-method-dark-mode-mobile-1.png index c46b1a86ae5..199f41cf27e 100644 Binary files a/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_mobile_flatten-source-code-method-dark-mode-mobile-1.png and b/src/slices/contract/pages/contract-verification/__screenshots__/ContractVerificationForm.pw.tsx_mobile_flatten-source-code-method-dark-mode-mobile-1.png differ diff --git a/src/slices/contract/pages/contract-verification/methods/ContractVerificationSolidityFoundry.tsx b/src/slices/contract/pages/contract-verification/methods/ContractVerificationSolidityFoundry.tsx index fe52ac73a56..30d73ae263b 100644 --- a/src/slices/contract/pages/contract-verification/methods/ContractVerificationSolidityFoundry.tsx +++ b/src/slices/contract/pages/contract-verification/methods/ContractVerificationSolidityFoundry.tsx @@ -44,7 +44,11 @@ const ContractVerificationSolidityFoundry = () => { </Link> { config.chain.isProApiSupported && ( <Box mt={ 1 }> +<<<<<<< HEAD <span>Get your Pro API key in the </span> +======= + <span>Get your Blockscout API key in the </span> +>>>>>>> v2.13.0 <Link href="https://dev.blockscout.com/?utm_source=blockscout&utm_medium=contract_verification" external> Blockscout Dev Portal </Link> diff --git a/src/slices/contract/pages/contract-verification/methods/ContractVerificationSolidityHardhat.tsx b/src/slices/contract/pages/contract-verification/methods/ContractVerificationSolidityHardhat.tsx index 7278ad0d19e..a6fed67718d 100644 --- a/src/slices/contract/pages/contract-verification/methods/ContractVerificationSolidityHardhat.tsx +++ b/src/slices/contract/pages/contract-verification/methods/ContractVerificationSolidityHardhat.tsx @@ -69,7 +69,11 @@ const ContractVerificationSolidityHardhat = ({ config: formConfig }: { config: S </Link> { config.chain.isProApiSupported && ( <Box mt={ 1 }> +<<<<<<< HEAD <span>Get your Pro API key in the </span> +======= + <span>Get your Blockscout API key in the </span> +>>>>>>> v2.13.0 <Link href="https://dev.blockscout.com/?utm_source=blockscout&utm_medium=contract_verification" external> Blockscout Dev Portal </Link> diff --git a/src/slices/contract/pages/contract-verification/methods/utils.spec.ts b/src/slices/contract/pages/contract-verification/methods/utils.spec.ts index 1fbf227cbab..59749394f99 100644 --- a/src/slices/contract/pages/contract-verification/methods/utils.spec.ts +++ b/src/slices/contract/pages/contract-verification/methods/utils.spec.ts @@ -7,7 +7,11 @@ import withEnvs from 'vitest/utils/mockEnvs'; const NO_RPC_URL: Array<[ string, string ]> = [ [ 'NEXT_PUBLIC_NETWORK_RPC_URL', '' ] ]; +<<<<<<< HEAD describe('on a chain without Pro API support', () => { +======= +describe('on a chain without Blockscout API support', () => { +>>>>>>> v2.13.0 it('points Hardhat at the instance API and asks for no key', async() => { const { getHardhatVerificationParams } = await import('./utils'); @@ -48,37 +52,63 @@ describe('on a chain without Pro API support', () => { }); }); +<<<<<<< HEAD describe('on a chain with Pro API support', () => { it('points Hardhat at the Pro API and asks for a key', async() => { +======= +describe('on a chain with Blockscout API support', () => { + it('points Hardhat at the Blockscout API and asks for a key', async() => { +>>>>>>> v2.13.0 await withEnvs(ENVS_MAP.proApi, async() => { const { getHardhatVerificationParams } = await import('./utils'); expect(getHardhatVerificationParams()).toEqual({ rpcUrl: 'https://localhost:1111', +<<<<<<< HEAD apiKey: '{PRO_API_KEY}', +======= + apiKey: '{BLOCKSCOUT_API_KEY}', +>>>>>>> v2.13.0 apiUrl: 'https://api.blockscout.com/1/api', }); }); }); +<<<<<<< HEAD it('points Foundry at the Pro API and passes a key', async() => { +======= + it('points Foundry at the Blockscout API and passes a key', async() => { +>>>>>>> v2.13.0 await withEnvs(ENVS_MAP.proApi, async() => { const { getFoundryVerificationParams } = await import('./utils'); expect(getFoundryVerificationParams()).toEqual({ rpcUrl: 'https://localhost:1111', +<<<<<<< HEAD apiKey: '{PRO_API_KEY}', +======= + apiKey: '{BLOCKSCOUT_API_KEY}', +>>>>>>> v2.13.0 verifierUrl: 'https://api.blockscout.com/v2/api?chain_id=1', }); }); }); +<<<<<<< HEAD it('falls back to the Pro API json-rpc endpoint when the chain has no RPC url', async() => { await withEnvs([ ...ENVS_MAP.proApi, ...NO_RPC_URL ], async() => { const { getHardhatVerificationParams, getFoundryVerificationParams } = await import('./utils'); expect(getHardhatVerificationParams().rpcUrl).toBe('https://api.blockscout.com/1/json-rpc?apikey={PRO_API_KEY}'); expect(getFoundryVerificationParams().rpcUrl).toBe('https://api.blockscout.com/1/json-rpc?apikey={PRO_API_KEY}'); +======= + it('falls back to the Blockscout API json-rpc endpoint when the chain has no RPC url', async() => { + await withEnvs([ ...ENVS_MAP.proApi, ...NO_RPC_URL ], async() => { + const { getHardhatVerificationParams, getFoundryVerificationParams } = await import('./utils'); + + expect(getHardhatVerificationParams().rpcUrl).toBe('https://api.blockscout.com/1/json-rpc?apikey={BLOCKSCOUT_API_KEY}'); + expect(getFoundryVerificationParams().rpcUrl).toBe('https://api.blockscout.com/1/json-rpc?apikey={BLOCKSCOUT_API_KEY}'); +>>>>>>> v2.13.0 }); }); }); diff --git a/src/slices/contract/pages/contract-verification/methods/utils.ts b/src/slices/contract/pages/contract-verification/methods/utils.ts index 65f4d355a42..7ff0aa1e5d5 100644 --- a/src/slices/contract/pages/contract-verification/methods/utils.ts +++ b/src/slices/contract/pages/contract-verification/methods/utils.ts @@ -3,7 +3,11 @@ import config from 'src/config'; const PRO_API_URL = 'https://api.blockscout.com'; +<<<<<<< HEAD const PRO_API_KEY_PLACEHOLDER = '{PRO_API_KEY}'; +======= +const PRO_API_KEY_PLACEHOLDER = '{BLOCKSCOUT_API_KEY}'; +>>>>>>> v2.13.0 function getCoreApiEndpoint() { return config.apis.core ? `${ config.apis.core.endpoint }${ config.apis.core.basePath ?? '' }` : ''; diff --git a/src/slices/contract/pages/details/Contract.pw.tsx b/src/slices/contract/pages/details/Contract.pw.tsx index e6466cdbadc..64a09017102 100644 --- a/src/slices/contract/pages/details/Contract.pw.tsx +++ b/src/slices/contract/pages/details/Contract.pw.tsx @@ -7,6 +7,7 @@ import * as contractMethodsMock from 'src/slices/contract/mocks/methods'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; import * as socketServer from 'playwright/fixtures/socketServer'; +import type { TestFnArgs } from 'playwright/lib'; import { test, expect } from 'playwright/lib'; import Contract from './Contract'; @@ -14,21 +15,22 @@ import Contract from './Contract'; const hash = addressMock.contract.hash; test.describe('ABI functionality', () => { - test.beforeEach(async({ mockApiResponse }) => { + const mockContractData = async(mockApiResponse: TestFnArgs['mockApiResponse']) => { await mockApiResponse('core:address', addressMock.contract, { pathParams: { hash } }); await mockApiResponse( 'core:contract', { ...contractInfoMock.verified, abi: [ ...contractMethodsMock.read, ...contractMethodsMock.write ] as Abi }, { pathParams: { hash } }, ); - }); + }; - test('read', async({ render, createSocket }) => { + test('read', async({ render, createSocket, mockApiResponse }) => { const hooksConfig = { router: { query: { hash, tab: 'read_contract' }, }, }; + await mockContractData(mockApiResponse); const component = await render(<Contract addressData={ addressMock.contract }/>, { hooksConfig }, { withSocket: true }); const socket = await createSocket(); await socketServer.joinChannel(socket, 'addresses:' + addressMock.contract.hash.toLowerCase()); @@ -38,13 +40,14 @@ test.describe('ABI functionality', () => { await expect(component.getByLabel('FLASHLOAN_PREMIUM_TOTAL').getByRole('button', { name: 'Read' })).toBeVisible(); }); - test('read, no wallet client', async({ render, createSocket, mockEnvs }) => { + test('read, no wallet client', async({ render, createSocket, mockEnvs, mockApiResponse }) => { const hooksConfig = { router: { query: { hash, tab: 'read_contract' }, }, }; await mockEnvs(ENVS_MAP.noWalletClient); + await mockContractData(mockApiResponse); const component = await render(<Contract addressData={ addressMock.contract }/>, { hooksConfig }, { withSocket: true }); const socket = await createSocket(); await socketServer.joinChannel(socket, 'addresses:' + addressMock.contract.hash.toLowerCase()); @@ -54,12 +57,13 @@ test.describe('ABI functionality', () => { await expect(component.getByLabel('FLASHLOAN_PREMIUM_TOTAL').getByRole('button', { name: 'Read' })).toBeVisible(); }); - test('write', async({ render, createSocket }) => { + test('write', async({ render, createSocket, mockApiResponse }) => { const hooksConfig = { router: { query: { hash, tab: 'write_contract' }, }, }; + await mockContractData(mockApiResponse); const component = await render(<Contract addressData={ addressMock.contract }/>, { hooksConfig }, { withSocket: true }); const socket = await createSocket(); await socketServer.joinChannel(socket, 'addresses:' + addressMock.contract.hash.toLowerCase()); @@ -74,13 +78,14 @@ test.describe('ABI functionality', () => { await expect(component.getByLabel('5.').getByRole('button', { name: 'Write' })).toBeEnabled(); }); - test('write, no wallet client', async({ render, createSocket, mockEnvs }) => { + test('write, no wallet client', async({ render, createSocket, mockEnvs, mockApiResponse }) => { const hooksConfig = { router: { query: { hash, tab: 'write_contract' }, }, }; await mockEnvs(ENVS_MAP.noWalletClient); + await mockContractData(mockApiResponse); const component = await render(<Contract addressData={ addressMock.contract }/>, { hooksConfig }, { withSocket: true }); const socket = await createSocket(); @@ -99,19 +104,19 @@ test.describe('ABI functionality', () => { test.describe('auto verification status', () => { const addressData = { ...addressMock.contract, is_verified: false, implementations: [] }; - let contractApiUrl: string; - test.beforeEach(async({ mockApiResponse }) => { + const mockContractData = async(mockApiResponse: TestFnArgs['mockApiResponse']) => { await mockApiResponse('core:address', addressData, { pathParams: { hash } }); - contractApiUrl = await mockApiResponse('core:contract', contractInfoMock.nonVerified, { pathParams: { hash } }); - }); + return mockApiResponse('core:contract', contractInfoMock.nonVerified, { pathParams: { hash } }); + }; - test('base flow', async({ render, createSocket }) => { + test('base flow', async({ render, createSocket, mockApiResponse }) => { const hooksConfig = { router: { query: { hash, tab: 'contract' }, }, }; + await mockContractData(mockApiResponse); const component = await render(<Contract addressData={ addressData }/>, { hooksConfig }, { withSocket: true }); const socket = await createSocket(); @@ -122,12 +127,13 @@ test.describe('auto verification status', () => { await expect(tabs).toHaveScreenshot(); }); - test('after verification will refetch contract data', async({ page, render, createSocket }) => { + test('after verification will refetch contract data', async({ page, render, createSocket, mockApiResponse }) => { const hooksConfig = { router: { query: { hash, tab: 'contract' }, }, }; + const contractApiUrl = await mockContractData(mockApiResponse); await render(<Contract addressData={ addressData }/>, { hooksConfig }, { withSocket: true }); const socket = await createSocket(); @@ -139,7 +145,7 @@ test.describe('auto verification status', () => { expect(contractRequest).toBeTruthy(); }); - test('with one tab', async({ render, createSocket, mockEnvs }) => { + test('with one tab', async({ render, createSocket, mockEnvs, mockApiResponse }) => { const hooksConfig = { router: { query: { hash, tab: 'contract' }, @@ -148,6 +154,7 @@ test.describe('auto verification status', () => { await mockEnvs([ [ 'NEXT_PUBLIC_IS_ACCOUNT_SUPPORTED', 'false' ], ]); + await mockContractData(mockApiResponse); const component = await render(<Contract addressData={ addressData }/>, { hooksConfig }, { withSocket: true }); const socket = await createSocket(); diff --git a/src/slices/contract/pages/details/Contract.tsx b/src/slices/contract/pages/details/Contract.tsx index e7dc4d54876..5fa37f2f414 100644 --- a/src/slices/contract/pages/details/Contract.tsx +++ b/src/slices/contract/pages/details/Contract.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -18,6 +17,7 @@ import { CONTRACT_TAB_IDS } from 'src/slices/contract/utils/tabs'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import delay from 'src/shared/utils/delay'; import type { Props as RoutedTabsProps } from 'src/toolkit/components/AdaptiveTabs/AdaptiveTabs'; diff --git a/src/slices/contract/pages/details/__screenshots__/Contract.pw.tsx_default_auto-verification-status-base-flow-1.png b/src/slices/contract/pages/details/__screenshots__/Contract.pw.tsx_default_auto-verification-status-base-flow-1.png index 1c1a96b316b..45e395c61ea 100644 Binary files a/src/slices/contract/pages/details/__screenshots__/Contract.pw.tsx_default_auto-verification-status-base-flow-1.png and b/src/slices/contract/pages/details/__screenshots__/Contract.pw.tsx_default_auto-verification-status-base-flow-1.png differ diff --git a/src/slices/contract/pages/details/code/ContractCode.pwstory.ts b/src/slices/contract/pages/details/code/ContractCode.pwstory.ts new file mode 100644 index 00000000000..e0d36e1c45e --- /dev/null +++ b/src/slices/contract/pages/details/code/ContractCode.pwstory.ts @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import useApiQuery from 'src/api/hooks/useApiQuery'; +import useSocketChannel from 'src/api/socket/useSocketChannel'; + +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; + +import useContractTabs from '../useContractTabs'; + +const ContractDetails = () => { + const router = useRouter(); + const hash = getQueryParamString(router.query.hash); + const addressQuery = useApiQuery('core:address', { pathParams: { hash } }); + const channel = useSocketChannel({ + topic: `addresses:${ hash?.toLowerCase() }`, + isDisabled: !addressQuery.data, + }); + + const { tabs } = useContractTabs({ + addressData: addressQuery.data, + isEnabled: true, + channel, + }); + const content = tabs.find(({ id }) => id === 'contract_code')?.component; + return content ?? null; +}; + +export default ContractDetails; diff --git a/src/slices/contract/pages/details/code/ContractCode.pwstory.tsx b/src/slices/contract/pages/details/code/ContractCode.pwstory.tsx deleted file mode 100644 index a05ab022a43..00000000000 --- a/src/slices/contract/pages/details/code/ContractCode.pwstory.tsx +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useRouter } from 'next/router'; - -import useApiQuery from 'src/api/hooks/useApiQuery'; -import useSocketChannel from 'src/api/socket/useSocketChannel'; - -import getQueryParamString from 'src/shared/router/get-query-param-string'; - -import useContractTabs from '../useContractTabs'; - -const ContractDetails = () => { - const router = useRouter(); - const hash = getQueryParamString(router.query.hash); - const addressQuery = useApiQuery('core:address', { pathParams: { hash } }); - const channel = useSocketChannel({ - topic: `addresses:${ hash?.toLowerCase() }`, - isDisabled: !addressQuery.data, - }); - - const { tabs } = useContractTabs({ - addressData: addressQuery.data, - isEnabled: true, - channel, - }); - const content = tabs.find(({ id }) => id === 'contract_code')?.component; - return content ?? null; -}; - -export default ContractDetails; diff --git a/src/slices/contract/pages/details/code/ContractCode.tsx b/src/slices/contract/pages/details/code/ContractCode.tsx index 36eb646aa3a..77dda2e71dc 100644 --- a/src/slices/contract/pages/details/code/ContractCode.tsx +++ b/src/slices/contract/pages/details/code/ContractCode.tsx @@ -2,7 +2,6 @@ import { Grid } from '@chakra-ui/react'; import type { UseQueryResult } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import type { Channel } from 'phoenix'; import React from 'react'; @@ -18,6 +17,7 @@ import { useMultichainContext } from 'src/features/multichain/context'; import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; diff --git a/src/slices/contract/pages/details/code/ContractDetailsDeployedByteCode.tsx b/src/slices/contract/pages/details/code/ContractDetailsDeployedByteCode.tsx index 9ec87e69f22..79d60afd00b 100644 --- a/src/slices/contract/pages/details/code/ContractDetailsDeployedByteCode.tsx +++ b/src/slices/contract/pages/details/code/ContractDetailsDeployedByteCode.tsx @@ -27,6 +27,9 @@ const collection = createListCollection<SelectOption>({ export type DataType = (typeof OPTIONS)[number]['value']; +const DEFAULT_HEX: Array<DataType> = [ 'Hex' ]; +const DEFAULT_UTF8: Array<DataType> = [ 'UTF-8' ]; + interface Props { bytecode: string; isLoading: boolean; @@ -34,46 +37,40 @@ interface Props { showVerificationButton?: boolean; } -const ContractDetailsDeployedByteCode = ({ bytecode, isLoading: isLoadingProp, addressData, showVerificationButton }: Props) => { - const [ isLoading, setIsLoading ] = React.useState(isLoadingProp); - const [ showSelect, setShowSelect ] = React.useState(false); - const [ selectedDataType, setSelectedDataType ] = React.useState<Array<DataType>>([ 'Hex' ]); - - React.useEffect(() => { - if (!isLoadingProp) { - if (config.slices.contract.decodedBytecodeEnabled && !addressData.is_verified) { - // we don't want to decode the whole bytecode here - // the "scilla_version" should appear somewhere in the beginning of the bytecode - // but there could be some comments of arbitrary length before it - // adjust the value if needed - const SYMBOLS_TO_CHECK = 500; - const decodedBytecode = hexToUtf8(bytecode.slice(0, SYMBOLS_TO_CHECK * 2 + 2)); - const isScillaSourceCode = decodedBytecode.includes('scilla_version 0'); - if (isScillaSourceCode) { - setShowSelect(true); - setSelectedDataType([ 'UTF-8' ]); - } - } +// we don't want to decode the whole bytecode here +// the "scilla_version" should appear somewhere in the beginning of the bytecode +// but there could be some comments of arbitrary length before it +// adjust the value if needed +const SYMBOLS_TO_CHECK = 500; + +const ContractDetailsDeployedByteCode = ({ bytecode, isLoading, addressData, showVerificationButton }: Props) => { + const [ selectedDataType, setSelectedDataType ] = React.useState<Array<DataType> | null>(null); + + const isScillaSourceCode = React.useMemo(() => { + if (isLoading || !config.slices.contract.decodedBytecodeEnabled || addressData.is_verified) { + return false; } + const decodedBytecode = hexToUtf8(bytecode.slice(0, SYMBOLS_TO_CHECK * 2 + 2)); + return decodedBytecode.includes('scilla_version 0'); + }, [ isLoading, bytecode, addressData.is_verified ]); - setIsLoading(isLoadingProp); - }, [ isLoadingProp, bytecode, addressData.is_verified ]); + const dataType = selectedDataType ?? (isScillaSourceCode ? DEFAULT_UTF8 : DEFAULT_HEX); const handleSelectValueChange = React.useCallback(({ value }: { value: Array<string> }) => { setSelectedDataType(value as Array<DataType>); }, []); - const content = selectedDataType[0] === 'UTF-8' ? hexToUtf8(bytecode) : bytecode; + const content = dataType[0] === 'UTF-8' ? hexToUtf8(bytecode) : bytecode; const beforeSlot = ( <Flex alignItems="center" flexWrap="wrap" mb={ 3 } columnGap={ 3 } rowGap={ 1 }> <Skeleton fontWeight={ 500 } loading={ isLoading }>Deployed bytecode</Skeleton> <Flex alignItems="center" flexGrow={ 1 }> - { showSelect && ( + { isScillaSourceCode && ( <Select collection={ collection } placeholder="Select type" - value={ selectedDataType } + value={ dataType } onValueChange={ handleSelectValueChange } w="100px" loading={ isLoading } diff --git a/src/slices/contract/pages/details/code/ContractDetailsVerificationButton.tsx b/src/slices/contract/pages/details/code/ContractDetailsVerificationButton.tsx index 1a083bccafe..98490939090 100644 --- a/src/slices/contract/pages/details/code/ContractDetailsVerificationButton.tsx +++ b/src/slices/contract/pages/details/code/ContractDetailsVerificationButton.tsx @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { route } from 'nextjs-routes'; import React from 'react'; import { useMultichainContext } from 'src/features/multichain/context'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; import { Button } from 'src/toolkit/chakra/button'; import type { LinkProps } from 'src/toolkit/chakra/link'; diff --git a/src/slices/contract/pages/details/code/ContractSourceAddressSelector.tsx b/src/slices/contract/pages/details/code/ContractSourceAddressSelector.tsx index 55de226a3e6..b909a67cf38 100644 --- a/src/slices/contract/pages/details/code/ContractSourceAddressSelector.tsx +++ b/src/slices/contract/pages/details/code/ContractSourceAddressSelector.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, createListCollection, Flex } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -9,6 +8,7 @@ import type { schemas } from '@blockscout/api-types'; import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import LinkNewTab from 'src/shared/links/LinkNewTab'; +import { route } from 'src/shared/router/routes'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import { Select } from 'src/toolkit/chakra/select'; diff --git a/src/slices/contract/pages/details/code/ContractSourceCode.tsx b/src/slices/contract/pages/details/code/ContractSourceCode.tsx index cff066f8282..27481868adb 100644 --- a/src/slices/contract/pages/details/code/ContractSourceCode.tsx +++ b/src/slices/contract/pages/details/code/ContractSourceCode.tsx @@ -3,15 +3,14 @@ import { Flex, Text } from '@chakra-ui/react'; import React from 'react'; -import type { File } from 'src/shared/code-editor/types'; import type { SmartContract } from 'src/slices/contract/types/api'; +import { getEditorData } from 'src/slices/contract/utils/editor-data'; import { formatLanguageName } from 'src/slices/contract/utils/language'; import { useMultichainContext } from 'src/features/multichain/context'; import CodeEditor from 'src/shared/code-editor/CodeEditor'; -import formatFilePath from 'src/shared/code-editor/utils/formatFilePath'; import { route } from 'src/shared/router/routes'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; @@ -22,41 +21,6 @@ import { Tooltip } from 'src/toolkit/chakra/tooltip'; import ContractCodeIdes from './ContractCodeIdes'; import ContractExternalLibraries from './ContractExternalLibraries'; -function getEditorData(contractInfo: SmartContract | undefined): Array<File> | undefined { - if (!contractInfo || !contractInfo.source_code) { - return undefined; - } - - const extension = (() => { - switch (contractInfo.language) { - case 'vyper': - return 'vy'; - case 'yul': - return 'yul'; - case 'scilla': - return 'scilla'; - case 'stylus_rust': - return 'rs'; - case 'geas': - return 'eas'; - default: - return 'sol'; - } - })(); - - const result: Array<File> = [ - { file_path: formatFilePath(contractInfo.file_path || `index.${ extension }`), source_code: contractInfo.source_code }, - ...(contractInfo.additional_sources || []) - .filter((source) => source.file_path && source.source_code) - .map((source) => ({ - source_code: source.source_code || '', - file_path: formatFilePath(source.file_path || ''), - })), - ]; - - return result; -} - interface Props { data: SmartContract | undefined; sourceAddress: string; diff --git a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_dark-color-mode_full-view-source-code-dark-mode-1.png b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_dark-color-mode_full-view-source-code-dark-mode-1.png index 4ec28c0fefe..9c47999c74b 100644 Binary files a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_dark-color-mode_full-view-source-code-dark-mode-1.png and b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_dark-color-mode_full-view-source-code-dark-mode-1.png differ diff --git a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-abi-1.png b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-abi-1.png index de6e57f4b66..77412a6ec8b 100644 Binary files a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-abi-1.png and b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-abi-1.png differ diff --git a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-bytecode-1.png b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-bytecode-1.png index f923f018c38..f1a3e6f5919 100644 Binary files a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-bytecode-1.png and b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-bytecode-1.png differ diff --git a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-compiler-1.png b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-compiler-1.png index b375e461df5..2752aa07989 100644 Binary files a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-compiler-1.png and b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-compiler-1.png differ diff --git a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-source-code-dark-mode-1.png b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-source-code-dark-mode-1.png index addd139138a..2246f86964d 100644 Binary files a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-source-code-dark-mode-1.png and b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_full-view-source-code-dark-mode-1.png differ diff --git a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_mobile-view-source-code-1.png b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_mobile-view-source-code-1.png index 310f0fce051..81f121af8b9 100644 Binary files a/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_mobile-view-source-code-1.png and b/src/slices/contract/pages/details/code/__screenshots__/ContractCode.pw.tsx_default_mobile-view-source-code-1.png differ diff --git a/src/slices/contract/pages/details/code/alerts/ConflictingImplementationsModal.tsx b/src/slices/contract/pages/details/code/alerts/ConflictingImplementationsModal.tsx index b03dc94295d..83250515c56 100644 --- a/src/slices/contract/pages/details/code/alerts/ConflictingImplementationsModal.tsx +++ b/src/slices/contract/pages/details/code/alerts/ConflictingImplementationsModal.tsx @@ -70,7 +70,7 @@ const ConflictingImplementationsModal = ({ data, children }: Props) => { <DialogActionTrigger asChild> <Button>Got it, thanks</Button> </DialogActionTrigger> - <Link external noIcon href="https://discord.com/invite/blockscout"> + <Link external noIcon href="https://discord.gg/3yAWj8TXV2"> Contact us </Link> </HStack> diff --git a/src/slices/contract/pages/details/code/alerts/ContractDetailsAlerts.tsx b/src/slices/contract/pages/details/code/alerts/ContractDetailsAlerts.tsx index d5c8b89159d..298d3bfef54 100644 --- a/src/slices/contract/pages/details/code/alerts/ContractDetailsAlerts.tsx +++ b/src/slices/contract/pages/details/code/alerts/ContractDetailsAlerts.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, Box, Flex } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import type { Channel } from 'phoenix'; import React from 'react'; @@ -13,6 +12,8 @@ import useSocketMessage from 'src/api/socket/useSocketMessage'; import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; +import { route } from 'src/shared/router/routes'; + import { Alert } from 'src/toolkit/chakra/alert'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/slices/contract/pages/details/code/alerts/__screenshots__/ContractDetailsAlertProxyPattern.pw.tsx_mobile_proxy-type-with-link-mobile-1.png b/src/slices/contract/pages/details/code/alerts/__screenshots__/ContractDetailsAlertProxyPattern.pw.tsx_mobile_proxy-type-with-link-mobile-1.png index 6ca72d6e25e..f9af01a1587 100644 Binary files a/src/slices/contract/pages/details/code/alerts/__screenshots__/ContractDetailsAlertProxyPattern.pw.tsx_mobile_proxy-type-with-link-mobile-1.png and b/src/slices/contract/pages/details/code/alerts/__screenshots__/ContractDetailsAlertProxyPattern.pw.tsx_mobile_proxy-type-with-link-mobile-1.png differ diff --git a/src/slices/contract/pages/details/code/alerts/__screenshots__/ContractDetailsAlerts.pw.tsx_mobile_with-twin-address-alert-mobile-1.png b/src/slices/contract/pages/details/code/alerts/__screenshots__/ContractDetailsAlerts.pw.tsx_mobile_with-twin-address-alert-mobile-1.png index 9fb0a29f758..3c706547c69 100644 Binary files a/src/slices/contract/pages/details/code/alerts/__screenshots__/ContractDetailsAlerts.pw.tsx_mobile_with-twin-address-alert-mobile-1.png and b/src/slices/contract/pages/details/code/alerts/__screenshots__/ContractDetailsAlerts.pw.tsx_mobile_with-twin-address-alert-mobile-1.png differ diff --git a/src/slices/contract/pages/details/methods/ContractAbi.tsx b/src/slices/contract/pages/details/methods/ContractAbi.tsx index d0ca11023ef..707052a6b6a 100644 --- a/src/slices/contract/pages/details/methods/ContractAbi.tsx +++ b/src/slices/contract/pages/details/methods/ContractAbi.tsx @@ -2,13 +2,14 @@ import { Box, Flex } from '@chakra-ui/react'; import { range } from 'es-toolkit'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { SmartContractMethod } from './types'; import Web3Boundary from 'src/features/connect-wallet/components/Web3Boundary'; +import { route } from 'src/shared/router/routes'; + import { AccordionRoot } from 'src/toolkit/chakra/accordion'; import { Link } from 'src/toolkit/chakra/link'; import { ContentLoader } from 'src/toolkit/components/loaders/ContentLoader'; diff --git a/src/slices/contract/pages/details/methods/ContractMethodsAlerts.tsx b/src/slices/contract/pages/details/methods/ContractMethodsAlerts.tsx index a85aed2dc69..956fe99996e 100644 --- a/src/slices/contract/pages/details/methods/ContractMethodsAlerts.tsx +++ b/src/slices/contract/pages/details/methods/ContractMethodsAlerts.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { VStack } from '@chakra-ui/react'; +import { Flex, VStack } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -8,6 +8,7 @@ import type { schemas } from '@blockscout/api-types'; import ContractCodeProxyPattern from '../code/alerts/ContractDetailsAlertProxyPattern'; import ConnectWalletAlert from './alerts/ConnectWalletAlert'; import ContractCustomAbiAlert from './alerts/ContractCustomAbiAlert'; +import CustomRpcAlert from './alerts/CustomRpcAlert'; interface Props { isLoading?: boolean; @@ -19,7 +20,10 @@ interface Props { const ContractMethodsAlerts = ({ isLoading, isCustomAbi, proxyType, conflictingImplementations }: Props) => { return ( <VStack gap={ 1 } alignItems="stretch"> - <ConnectWalletAlert isLoading={ isLoading }/> + <Flex gap={ 1 } alignItems="stretch" _empty={{ display: 'none' }}> + <CustomRpcAlert isLoading={ isLoading }/> + <ConnectWalletAlert isLoading={ isLoading }/> + </Flex> { proxyType && <ContractCodeProxyPattern isLoading={ isLoading } type={ proxyType } conflictingImplementations={ conflictingImplementations }/> } { isCustomAbi && <ContractCustomAbiAlert isLoading={ isLoading }/> } </VStack> diff --git a/src/slices/contract/pages/details/methods/ContractMethodsCustom.pw.tsx b/src/slices/contract/pages/details/methods/ContractMethodsCustom.pw.tsx index a4c0651d720..f26de99e139 100644 --- a/src/slices/contract/pages/details/methods/ContractMethodsCustom.pw.tsx +++ b/src/slices/contract/pages/details/methods/ContractMethodsCustom.pw.tsx @@ -5,6 +5,8 @@ import type { Abi } from 'viem'; import * as addressParamMock from 'src/slices/address/mocks/address-param'; import * as methodsMock from 'src/slices/contract/mocks/methods'; +import * as profileMock from 'src/features/account/mocks/user-profile'; + import { contextWithAuth } from 'playwright/fixtures/auth'; import { test, expect } from 'playwright/lib'; @@ -16,7 +18,12 @@ const authTest = test.extend<{ context: BrowserContext }>({ context: contextWithAuth, }); -authTest('without data', async({ render }) => { +authTest.beforeEach(async({ mockApiResponse }) => { + await mockApiResponse('core:user_info', profileMock.base); +}); + +authTest('without data', async({ render, mockApiResponse }) => { + await mockApiResponse('core:custom_abi', []); const hooksConfig = { router: { query: { hash: addressHash, tab: 'read_write_custom_methods' }, diff --git a/src/slices/contract/pages/details/methods/ContractMethodsCustom.tsx b/src/slices/contract/pages/details/methods/ContractMethodsCustom.tsx index 7274e60606a..0955015f649 100644 --- a/src/slices/contract/pages/details/methods/ContractMethodsCustom.tsx +++ b/src/slices/contract/pages/details/methods/ContractMethodsCustom.tsx @@ -2,7 +2,6 @@ import { Flex } from '@chakra-ui/react'; import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React from 'react'; import type { SmartContract } from 'src/slices/contract/types/api'; @@ -15,6 +14,7 @@ import CustomAbiModal from 'src/features/account/pages/custom-abi/CustomAbiModal import RawDataSnippet from 'src/shared/data/RawDataSnippet'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import { Button } from 'src/toolkit/chakra/button'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; diff --git a/src/slices/contract/pages/details/methods/ContractMethodsProxy.pw.tsx b/src/slices/contract/pages/details/methods/ContractMethodsProxy.pw.tsx index 9c6e774986c..75ce8daf8f3 100644 --- a/src/slices/contract/pages/details/methods/ContractMethodsProxy.pw.tsx +++ b/src/slices/contract/pages/details/methods/ContractMethodsProxy.pw.tsx @@ -4,13 +4,16 @@ import * as addressParamMock from 'src/slices/address/mocks/address-param'; import * as contractMock from 'src/slices/contract/mocks/info'; import * as methodsMock from 'src/slices/contract/mocks/methods'; +import config from 'src/config'; +import * as cookies from 'src/shared/storage/cookies'; + import { test, expect } from 'playwright/lib'; import ContractMethodsProxy from './ContractMethodsProxy'; const addressHash = addressParamMock.hash; -test('with one implementation +@mobile', async({ render, mockApiResponse }) => { +test('with one implementation +@mobile', async({ render, mockApiResponse, mockRpcResponse, context }) => { const hooksConfig = { router: { query: { hash: addressHash, tab: 'read_proxy' }, @@ -20,8 +23,15 @@ test('with one implementation +@mobile', async({ render, mockApiResponse }) => { { address_hash: '0x2F4F4A52295940C576417d29F22EEb92B440eC89', name: 'HomeBridge' }, ]; await mockApiResponse('core:contract', { ...contractMock.verified, abi: methodsMock.read }, { pathParams: { hash: implementations[0].address_hash } }); + await context.addCookies([ + { name: cookies.NAMES.CUSTOM_RPC_URL, value: config.chain.rpcUrls[0], domain: config.app.host, path: '/' }, + { name: cookies.NAMES.CUSTOM_RPC_IN_USE, value: 'true', domain: config.app.host, path: '/' }, + ]); + // the ping posts `params: []`, which the fixture only matches when Parameters is set; viem types eth_chainId's as undefined + await mockRpcResponse([ { Method: 'eth_chainId', Parameters: [] as unknown as undefined, ReturnType: `0x${ Number(config.chain.id).toString(16) }` } ]); const component = await render(<ContractMethodsProxy implementations={ implementations } proxyType="eip1167"/>, { hooksConfig }); + await expect(component.getByRole('button', { name: 'Custom RPC: Connected' })).toBeVisible(); await expect(component).toHaveScreenshot(); }); diff --git a/src/slices/contract/pages/details/methods/ContractMethodsProxy.tsx b/src/slices/contract/pages/details/methods/ContractMethodsProxy.tsx index 3134aa44ee2..5d39e1b56c0 100644 --- a/src/slices/contract/pages/details/methods/ContractMethodsProxy.tsx +++ b/src/slices/contract/pages/details/methods/ContractMethodsProxy.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -9,6 +8,7 @@ import type { schemas } from '@blockscout/api-types'; import useApiQuery from 'src/api/hooks/useApiQuery'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import ContractSourceAddressSelector from '../code/ContractSourceAddressSelector'; import ContractAbi from './ContractAbi'; diff --git a/src/slices/contract/pages/details/methods/ContractMethodsRegular.pw.tsx b/src/slices/contract/pages/details/methods/ContractMethodsRegular.pw.tsx index c7c16807d73..302cdd6e669 100644 --- a/src/slices/contract/pages/details/methods/ContractMethodsRegular.pw.tsx +++ b/src/slices/contract/pages/details/methods/ContractMethodsRegular.pw.tsx @@ -1,9 +1,12 @@ +import type { Page } from '@playwright/test'; import React from 'react'; import type { Abi, AbiFunction } from 'viem'; import * as addressParamMock from 'src/slices/address/mocks/address-param'; import * as methodsMock from 'src/slices/contract/mocks/methods'; +import config from 'src/config'; + import { test, expect } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; @@ -11,6 +14,10 @@ import ContractMethodsRegular from './ContractMethodsRegular'; const addressHash = addressParamMock.hash; +async function mockRpcNodeDown(page: Page): Promise<void> { + await page.route(config.chain.rpcUrls[0], (route) => route.fulfill({ status: 503 })); +} + test('can read method', async({ render, mockContractReadResponse }) => { const hooksConfig = { router: { @@ -64,17 +71,18 @@ test('can simulate method', async({ render, mockContractReadResponse }) => { await expect(component).toHaveScreenshot(); }); -test('all methods +@dark-mode', async({ render }) => { +test('all methods +@dark-mode', async({ render, page }) => { const hooksConfig = { router: { query: { hash: addressHash, tab: 'read_write_contract' }, }, }; + await mockRpcNodeDown(page); const abi: Abi = [ ...methodsMock.read, ...methodsMock.write ] as Abi; const component = await render(<ContractMethodsRegular abi={ abi }/>, { hooksConfig }); await component.getByText(/expand all/i).click(); - await expect(component.getByText('HTTP request failed')).toBeVisible(); + await expect(component.getByText('The RPC node is not responding')).toBeVisible(); await expect(component).toHaveScreenshot(); }); @@ -82,7 +90,7 @@ test('all methods +@dark-mode', async({ render }) => { test.describe('all methods', () => { test.use({ viewport: pwConfig.viewport.mobile }); - test('mobile', async({ render }) => { + test('mobile', async({ render, page }) => { test.slow(); const hooksConfig = { @@ -91,10 +99,11 @@ test.describe('all methods', () => { }, }; + await mockRpcNodeDown(page); const abi: Abi = [ ...methodsMock.read, ...methodsMock.write ] as Abi; const component = await render(<ContractMethodsRegular abi={ abi }/>, { hooksConfig }); await component.getByText(/expand all/i).click(); - // await expect(component.getByText('HTTP request failed')).toBeVisible(); + await expect(component.getByText('The RPC node is not responding')).toBeVisible(); await expect(component).toHaveScreenshot(); }); diff --git a/src/slices/contract/pages/details/methods/ContractMethodsRegular.tsx b/src/slices/contract/pages/details/methods/ContractMethodsRegular.tsx index 41776e224b1..5850af85389 100644 --- a/src/slices/contract/pages/details/methods/ContractMethodsRegular.tsx +++ b/src/slices/contract/pages/details/methods/ContractMethodsRegular.tsx @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { Abi } from 'viem'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import ContractAbi from './ContractAbi'; import ContractMethodsAlerts from './ContractMethodsAlerts'; diff --git a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsCustom.pw.tsx_default_with-data-1.png b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsCustom.pw.tsx_default_with-data-1.png index 14fc0232fb0..91af9df414c 100644 Binary files a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsCustom.pw.tsx_default_with-data-1.png and b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsCustom.pw.tsx_default_with-data-1.png differ diff --git a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_default_with-multiple-implementations-mobile-1.png b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_default_with-multiple-implementations-mobile-1.png index 71c49bfe42b..5dc32f0330f 100644 Binary files a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_default_with-multiple-implementations-mobile-1.png and b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_default_with-multiple-implementations-mobile-1.png differ diff --git a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_default_with-one-implementation-mobile-1.png b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_default_with-one-implementation-mobile-1.png index 863269cd19b..aea3026e98c 100644 Binary files a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_default_with-one-implementation-mobile-1.png and b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_default_with-one-implementation-mobile-1.png differ diff --git a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_mobile_with-multiple-implementations-mobile-1.png b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_mobile_with-multiple-implementations-mobile-1.png index d0b02122e3c..e0cb382ae28 100644 Binary files a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_mobile_with-multiple-implementations-mobile-1.png and b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_mobile_with-multiple-implementations-mobile-1.png differ diff --git a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_mobile_with-one-implementation-mobile-1.png b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_mobile_with-one-implementation-mobile-1.png index bf5e206f950..eb0f8b80aa3 100644 Binary files a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_mobile_with-one-implementation-mobile-1.png and b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsProxy.pw.tsx_mobile_with-one-implementation-mobile-1.png differ diff --git a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_dark-color-mode_all-methods-dark-mode-1.png b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_dark-color-mode_all-methods-dark-mode-1.png index 0dc2d5a2423..d4e0d6b5650 100644 Binary files a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_dark-color-mode_all-methods-dark-mode-1.png and b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_dark-color-mode_all-methods-dark-mode-1.png differ diff --git a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_all-methods-dark-mode-1.png b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_all-methods-dark-mode-1.png index d66df15ecee..13b8ffcd02b 100644 Binary files a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_all-methods-dark-mode-1.png and b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_all-methods-dark-mode-1.png differ diff --git a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_all-methods-mobile-1.png b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_all-methods-mobile-1.png index 6827634337a..6628e6e1895 100644 Binary files a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_all-methods-mobile-1.png and b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_all-methods-mobile-1.png differ diff --git a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_can-simulate-method-1.png b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_can-simulate-method-1.png index 0e42253818a..85ce5bfb4b1 100644 Binary files a/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_can-simulate-method-1.png and b/src/slices/contract/pages/details/methods/__screenshots__/ContractMethodsRegular.pw.tsx_default_can-simulate-method-1.png differ diff --git a/src/slices/contract/pages/details/methods/alerts/ConnectWalletAlert.tsx b/src/slices/contract/pages/details/methods/alerts/ConnectWalletAlert.tsx index a29b32003c9..d078fe7e5cd 100644 --- a/src/slices/contract/pages/details/methods/alerts/ConnectWalletAlert.tsx +++ b/src/slices/contract/pages/details/methods/alerts/ConnectWalletAlert.tsx @@ -72,7 +72,7 @@ const ConnectWalletAlert = ({ isLoading }: Props) => { })(); return ( - <Skeleton loading={ isLoading }> + <Skeleton loading={ isLoading } flexGrow={ 1 }> <Alert status="info" descriptionProps={{ alignItems: 'center' }}> { content } </Alert> diff --git a/src/slices/contract/pages/details/methods/alerts/CustomRpcAlert.spec.tsx b/src/slices/contract/pages/details/methods/alerts/CustomRpcAlert.spec.tsx new file mode 100644 index 00000000000..bf9c1bf0c78 --- /dev/null +++ b/src/slices/contract/pages/details/methods/alerts/CustomRpcAlert.spec.tsx @@ -0,0 +1,51 @@ +// @vitest-environment jsdom + +import Cookies from 'js-cookie'; +import React from 'react'; + +import * as cookies from 'src/shared/storage/cookies'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { cleanup, render, screen, waitFor } from 'vitest/lib'; + +import CustomRpcAlert from './CustomRpcAlert'; + +describe('CustomRpcAlert', () => { + beforeEach(() => { + fetchMock.resetMocks(); + }); + + afterEach(() => { + cleanup(); + Cookies.remove(cookies.NAMES.CUSTOM_RPC_URL); + Cookies.remove(cookies.NAMES.CUSTOM_RPC_IN_USE); + }); + + it('renders nothing with the default node', () => { + render(<CustomRpcAlert/>); + + expect(screen.queryByText('Custom RPC')).toBeNull(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('renders nothing while the saved URL is disconnected', () => { + Cookies.set(cookies.NAMES.CUSTOM_RPC_URL, 'https://rpc.example.com'); + + render(<CustomRpcAlert/>); + + expect(screen.queryByText('Custom RPC')).toBeNull(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('pings the node in use and reports the outcome', async() => { + Cookies.set(cookies.NAMES.CUSTOM_RPC_URL, 'https://rpc.example.com'); + Cookies.set(cookies.NAMES.CUSTOM_RPC_IN_USE, 'true'); + fetchMock.mockResponse(JSON.stringify({ jsonrpc: '2.0', id: 1, result: '0x5' })); + + render(<CustomRpcAlert/>); + + await waitFor(() => expect(screen.getByRole('button', { name: 'Custom RPC: Connected' })).toBeTruthy()); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0]).toBe('https://rpc.example.com'); + }); +}); diff --git a/src/slices/contract/pages/details/methods/alerts/CustomRpcAlert.tsx b/src/slices/contract/pages/details/methods/alerts/CustomRpcAlert.tsx new file mode 100644 index 00000000000..b05b6c2f49f --- /dev/null +++ b/src/slices/contract/pages/details/methods/alerts/CustomRpcAlert.tsx @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { chakra } from '@chakra-ui/react'; +import React from 'react'; + +import { useCustomRpcNodeStatus } from 'src/shell/top-bar/settings/fields/rpc-node/useCustomRpcNodeStatus'; +import { useSettingsModalContext } from 'src/shell/top-bar/settings/modal/context'; + +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { Button } from 'src/toolkit/chakra/button'; + +interface Props { + isLoading?: boolean; +} + +const CustomRpcAlert = ({ isLoading }: Props) => { + const customRpc = useCustomRpcNodeStatus(); + const settingsModal = useSettingsModalContext(); + + const handleClick = React.useCallback(() => { + settingsModal?.open('rpc-node'); + }, [ settingsModal ]); + + if (!customRpc) { + return null; + } + + const { status, isPending } = customRpc; + + return ( + <Button + cursor="pointer" + aria-label={ `Custom RPC: ${ status.tag.label }` } + onClick={ handleClick } + loadingSkeleton={ isLoading || isPending } + variant="dropdown" + selected + textStyle="sm" + fontWeight="medium" + h="auto" + > + <SpriteIcon name={ status.plug.icon } boxSize={ 5 } color={ status.plug.color }/> + <chakra.span hideBelow="lg">Custom RPC</chakra.span> + </Button> + ); +}; + +export default React.memo(CustomRpcAlert); diff --git a/src/slices/contract/pages/details/methods/form/ContractMethodForm.tsx b/src/slices/contract/pages/details/methods/form/ContractMethodForm.tsx index 98a27097139..5bf9d882716 100644 --- a/src/slices/contract/pages/details/methods/form/ContractMethodForm.tsx +++ b/src/slices/contract/pages/details/methods/form/ContractMethodForm.tsx @@ -9,7 +9,7 @@ import { encodeFunctionData, type AbiFunction } from 'viem'; import type { FormSubmitHandler, FormSubmitResult, MethodCallStrategy, SmartContractMethod } from '../types'; import config from 'src/config'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; @@ -111,7 +111,7 @@ const ContractMethodForm = ({ data, attempt, onSubmit, onReset, isOpen }: Props) setLoading(false); }) .finally(() => { - mixpanel.logEvent(mixpanel.EventTypes.CONTRACT_INTERACTION, { + analytics.logEvent(analytics.EventTypes.CONTRACT_INTERACTION, { 'Method type': methodType === 'write' ? 'Write' : 'Read', 'Method name': 'name' in data ? data.name : 'Fallback', }); diff --git a/src/slices/contract/pages/details/methods/form/ContractMethodResultPublicClient.spec.tsx b/src/slices/contract/pages/details/methods/form/ContractMethodResultPublicClient.spec.tsx new file mode 100644 index 00000000000..190f26ade26 --- /dev/null +++ b/src/slices/contract/pages/details/methods/form/ContractMethodResultPublicClient.spec.tsx @@ -0,0 +1,76 @@ +// @vitest-environment jsdom + +import Cookies from 'js-cookie'; +import React from 'react'; +import { BaseError, HttpRequestError } from 'viem'; + +import { SettingsModalContextProvider } from 'src/shell/top-bar/settings/modal/context'; + +import * as cookies from 'src/shared/storage/cookies'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from 'vitest/lib'; + +import ContractMethodResultPublicClient from './ContractMethodResultPublicClient'; + +const noop = () => {}; + +function nodeFailure(): Error { + return new BaseError('call failed', { cause: new HttpRequestError({ url: 'https://rpc.example.com', status: 503 }) }); +} + +describe('ContractMethodResultPublicClient', () => { + afterEach(() => { + cleanup(); + Cookies.remove(cookies.NAMES.CUSTOM_RPC_URL); + Cookies.remove(cookies.NAMES.CUSTOM_RPC_IN_USE); + }); + + it('suggests a custom node when the default node fails', () => { + render(<ContractMethodResultPublicClient data={ nodeFailure() } onSettle={ noop }/>); + + expect(screen.getByText(/The RPC node is not responding/)).toBeTruthy(); + expect(screen.getByText('Try your own RPC node.')).toBeTruthy(); + }); + + it('asks to change the URL when the custom node fails', () => { + Cookies.set(cookies.NAMES.CUSTOM_RPC_URL, 'https://rpc.example.com'); + Cookies.set(cookies.NAMES.CUSTOM_RPC_IN_USE, 'true'); + + render(<ContractMethodResultPublicClient data={ nodeFailure() } onSettle={ noop }/>); + + expect(screen.getByText(/Your RPC node is not responding/)).toBeTruthy(); + expect(screen.getByText('Check the RPC node URL and try again.')).toBeTruthy(); + }); + + it('opens the settings modal on the RPC node tab from the link', async() => { + render( + <SettingsModalContextProvider> + <ContractMethodResultPublicClient data={ nodeFailure() } onSettle={ noop }/> + </SettingsModalContextProvider>, + ); + + fireEvent.click(screen.getByText('Try your own RPC node.')); + + await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy()); + expect(screen.getByRole('textbox', { name: 'RPC node URL' })).toBeTruthy(); + }); + + it('keeps the short message for a contract error', () => { + const revert = new BaseError('Execution reverted for an unknown reason.'); + + render(<ContractMethodResultPublicClient data={ revert } onSettle={ noop }/>); + + expect(screen.getByText(revert.shortMessage)).toBeTruthy(); + expect(screen.queryByText(/not responding/)).toBeNull(); + }); + + it('calls onSettle once rendered', () => { + const onSettle = vi.fn(); + + render(<ContractMethodResultPublicClient data={ undefined } estimatedGas={ BigInt(21000) } onSettle={ onSettle }/>); + + expect(onSettle).toHaveBeenCalledTimes(1); + expect(screen.getByText(/Estimated gas: 21,000/)).toBeTruthy(); + }); +}); diff --git a/src/slices/contract/pages/details/methods/form/ContractMethodResultPublicClient.tsx b/src/slices/contract/pages/details/methods/form/ContractMethodResultPublicClient.tsx index 0bbd409499e..39cb1a6c57d 100644 --- a/src/slices/contract/pages/details/methods/form/ContractMethodResultPublicClient.tsx +++ b/src/slices/contract/pages/details/methods/form/ContractMethodResultPublicClient.tsx @@ -2,7 +2,14 @@ import React from 'react'; +import { useSettingsModalContext } from 'src/shell/top-bar/settings/modal/context'; + +import { getCustomRpcUrl } from 'src/features/connect-wallet/utils/rpc-urls'; + import { Alert } from 'src/toolkit/chakra/alert'; +import { Link } from 'src/toolkit/chakra/link'; + +import { classifyRpcError, getRpcNotRespondingCopy } from './rpcError'; export interface Props { data: unknown; @@ -10,6 +17,22 @@ export interface Props { estimatedGas?: bigint; } +const RpcNotRespondingAlert = () => { + const settingsModal = useSettingsModalContext(); + const copy = getRpcNotRespondingCopy(Boolean(getCustomRpcUrl())); + + const handleLinkClick = React.useCallback(() => { + settingsModal?.open('rpc-node'); + }, [ settingsModal ]); + + return ( + <Alert status="error" textStyle="sm" wordBreak="break-word" whiteSpace="pre-wrap"> + { copy.text }{ ' ' } + <Link onClick={ handleLinkClick }>{ copy.linkText }</Link> + </Alert> + ); +}; + const ContractMethodResultPublicClient = ({ data, estimatedGas, onSettle }: Props) => { React.useEffect(() => { @@ -17,6 +40,10 @@ const ContractMethodResultPublicClient = ({ data, estimatedGas, onSettle }: Prop }, [ onSettle ]); if (data instanceof Error) { + if (classifyRpcError(data) === 'not-responding') { + return <RpcNotRespondingAlert/>; + } + return ( <Alert status="error" textStyle="sm" wordBreak="break-word" whiteSpace="pre-wrap"> { 'shortMessage' in data && typeof data.shortMessage === 'string' ? data.shortMessage : data.message } diff --git a/src/slices/contract/pages/details/methods/form/ContractMethodResultWalletClient.tsx b/src/slices/contract/pages/details/methods/form/ContractMethodResultWalletClient.tsx index 32df5439326..c5227d9f429 100644 --- a/src/slices/contract/pages/details/methods/form/ContractMethodResultWalletClient.tsx +++ b/src/slices/contract/pages/details/methods/form/ContractMethodResultWalletClient.tsx @@ -1,13 +1,14 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, Spinner, Box } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { UseWaitForTransactionReceiptReturnType } from 'wagmi'; import { useWaitForTransactionReceipt } from 'wagmi'; import type { FormSubmitResultWalletClient } from '../types'; +import { route } from 'src/shared/router/routes'; + import { Alert } from 'src/toolkit/chakra/alert'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/slices/contract/pages/details/methods/form/__screenshots__/ContractMethodForm.pw.tsx_mobile_base-view-mobile-dark-mode-1.png b/src/slices/contract/pages/details/methods/form/__screenshots__/ContractMethodForm.pw.tsx_mobile_base-view-mobile-dark-mode-1.png index b1f5114f045..c1a907f74c0 100644 Binary files a/src/slices/contract/pages/details/methods/form/__screenshots__/ContractMethodForm.pw.tsx_mobile_base-view-mobile-dark-mode-1.png and b/src/slices/contract/pages/details/methods/form/__screenshots__/ContractMethodForm.pw.tsx_mobile_base-view-mobile-dark-mode-1.png differ diff --git a/src/slices/contract/pages/details/methods/form/__screenshots__/ContractMethodResultWalletClient.pw.tsx_mobile_error-mobile-1.png b/src/slices/contract/pages/details/methods/form/__screenshots__/ContractMethodResultWalletClient.pw.tsx_mobile_error-mobile-1.png index a85fd156bcf..7997716cae8 100644 Binary files a/src/slices/contract/pages/details/methods/form/__screenshots__/ContractMethodResultWalletClient.pw.tsx_mobile_error-mobile-1.png and b/src/slices/contract/pages/details/methods/form/__screenshots__/ContractMethodResultWalletClient.pw.tsx_mobile_error-mobile-1.png differ diff --git a/src/slices/contract/pages/details/methods/form/resultPublicClient/ItemPrimitive.tsx b/src/slices/contract/pages/details/methods/form/resultPublicClient/ItemPrimitive.tsx index 474739d23fe..ef9e47d143d 100644 --- a/src/slices/contract/pages/details/methods/form/resultPublicClient/ItemPrimitive.tsx +++ b/src/slices/contract/pages/details/methods/form/resultPublicClient/ItemPrimitive.tsx @@ -1,10 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { AbiParameter } from 'viem'; +import { route } from 'src/shared/router/routes'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/slices/contract/pages/details/methods/form/rpcError.spec.ts b/src/slices/contract/pages/details/methods/form/rpcError.spec.ts new file mode 100644 index 00000000000..7d303ed6b2e --- /dev/null +++ b/src/slices/contract/pages/details/methods/form/rpcError.spec.ts @@ -0,0 +1,68 @@ +import { BaseError, ContractFunctionExecutionError, HttpRequestError, InternalRpcError, LimitExceededRpcError, TimeoutError } from 'viem'; + +import { describe, expect, it } from 'vitest'; + +import { classifyRpcError, getRpcNotRespondingCopy } from './rpcError'; + +const URL = 'https://rpc.example.com'; + +function httpError(): HttpRequestError { + return new HttpRequestError({ url: URL, status: 503 }); +} + +describe('classifyRpcError', () => { + it.each([ + [ 'HttpRequestError', httpError() ], + [ 'TimeoutError', new TimeoutError({ body: {}, url: URL }) ], + [ 'LimitExceededRpcError', new LimitExceededRpcError(new Error('rate limited')) ], + [ 'InternalRpcError', new InternalRpcError(new Error('internal')) ], + ])('returns "not-responding" for a top-level %s', (_, error) => { + expect(classifyRpcError(error)).toBe('not-responding'); + }); + + it('finds the node failure deep in the cause chain', () => { + const inner = httpError(); + const middle = new BaseError('wrapped', { cause: inner }); + const outer = new Error('outer', { cause: middle }); + + expect(classifyRpcError(outer)).toBe('not-responding'); + }); + + it('falls through for a contract revert', () => { + const revert = new ContractFunctionExecutionError(new BaseError('execution reverted'), { + abi: [], + functionName: 'foo', + }); + + expect(classifyRpcError(revert)).toBe('other'); + }); + + it('falls through for a plain error and for non-errors', () => { + expect(classifyRpcError(new Error('boom'))).toBe('other'); + expect(classifyRpcError('boom')).toBe('other'); + expect(classifyRpcError(undefined)).toBe('other'); + }); + + it('terminates on a self-referencing cause chain', () => { + const error = new Error('loop'); + error.cause = error; + + expect(classifyRpcError(error)).toBe('other'); + }); +}); + +describe('getRpcNotRespondingCopy', () => { + it('offers a custom node while the default node is in use', () => { + expect(getRpcNotRespondingCopy(false)).toEqual({ + text: 'The RPC node is not responding.', + linkText: 'Try your own RPC node.', + }); + }); + + it('asks to change the URL while a custom node is in use', () => { + expect(getRpcNotRespondingCopy(true)).toEqual({ + text: 'Your RPC node is not responding.', + linkText: 'Check the RPC node URL and try again.', + }); + }); +}); diff --git a/src/slices/contract/pages/details/methods/form/rpcError.ts b/src/slices/contract/pages/details/methods/form/rpcError.ts new file mode 100644 index 00000000000..59dc8e0aa9e --- /dev/null +++ b/src/slices/contract/pages/details/methods/form/rpcError.ts @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { HttpRequestError, InternalRpcError, LimitExceededRpcError, TimeoutError } from 'viem'; + +export type RpcErrorKind = 'not-responding' | 'other'; + +function isNodeFailure(error: unknown): boolean { + return ( + error instanceof HttpRequestError || + error instanceof TimeoutError || + error instanceof LimitExceededRpcError || + error instanceof InternalRpcError + ); +} + +export function classifyRpcError(error: unknown): RpcErrorKind { + const seen = new Set<unknown>(); + let current: unknown = error; + + while (current instanceof Error && !seen.has(current)) { + if (isNodeFailure(current)) { + return 'not-responding'; + } + + seen.add(current); + current = current.cause; + } + + return 'other'; +} + +export interface RpcNotRespondingCopy { + readonly text: string; + readonly linkText: string; +} + +export function getRpcNotRespondingCopy(isCustomRpcInUse: boolean): RpcNotRespondingCopy { + return isCustomRpcInUse ? + { text: 'Your RPC node is not responding.', linkText: 'Check the RPC node URL and try again.' } : + { text: 'The RPC node is not responding.', linkText: 'Try your own RPC node.' }; +} diff --git a/src/slices/contract/pages/details/methods/form/useFormatFieldValue.tsx b/src/slices/contract/pages/details/methods/form/useFormatFieldValue.ts similarity index 100% rename from src/slices/contract/pages/details/methods/form/useFormatFieldValue.tsx rename to src/slices/contract/pages/details/methods/form/useFormatFieldValue.ts diff --git a/src/slices/contract/pages/details/methods/form/useValidateField.tsx b/src/slices/contract/pages/details/methods/form/useValidateField.ts similarity index 100% rename from src/slices/contract/pages/details/methods/form/useValidateField.tsx rename to src/slices/contract/pages/details/methods/form/useValidateField.ts diff --git a/src/slices/contract/pages/details/methods/useMethodsFilters.ts b/src/slices/contract/pages/details/methods/useMethodsFilters.ts index 75713c106c5..cff901f3132 100644 --- a/src/slices/contract/pages/details/methods/useMethodsFilters.ts +++ b/src/slices/contract/pages/details/methods/useMethodsFilters.ts @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { pickBy } from 'es-toolkit'; -import { useRouter } from 'next/router'; import React from 'react'; import type { MethodType, SmartContractMethod } from './types'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import type { CONTRACT_MAIN_TAB_IDS } from '../../../utils/tabs'; import { TYPE_FILTER_OPTIONS, isReadMethod, isWriteMethod } from './utils'; @@ -66,11 +66,7 @@ export default function useMethodsFilters({ abi }: Params) { } const queryForPathname = pickBy(router.query, (value, key) => router.pathname.includes(`[${ key }]`)); - router.push( - { pathname: router.pathname, query: { ...queryForPathname, tab: nextTab } }, - undefined, - { shallow: true }, - ); + router.push({ pathname: router.pathname, query: { ...queryForPathname, tab: nextTab } }, { shallow: true }); }, [ router ]); diff --git a/src/slices/contract/pages/index/VerifiedContracts.pw.tsx b/src/slices/contract/pages/index/VerifiedContracts.pw.tsx index f4f9b35287a..30cfc268db2 100644 --- a/src/slices/contract/pages/index/VerifiedContracts.pw.tsx +++ b/src/slices/contract/pages/index/VerifiedContracts.pw.tsx @@ -7,7 +7,7 @@ import { test, expect } from 'playwright/lib'; import VerifiedContracts from './VerifiedContracts'; -test('base view +@mobile', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { +test('base view', async({ render, mockApiResponse, mockEnvs, mockTextAd }) => { test.slow(); await mockTextAd(); await mockEnvs([ [ 'NEXT_PUBLIC_STATS_API_HOST', '' ] ]); diff --git a/src/slices/contract/pages/index/VerifiedContracts.tsx b/src/slices/contract/pages/index/VerifiedContracts.tsx index c81903c2455..3cd6389adab 100644 --- a/src/slices/contract/pages/index/VerifiedContracts.tsx +++ b/src/slices/contract/pages/index/VerifiedContracts.tsx @@ -9,7 +9,6 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import useVerifiedContractsQuery from 'src/slices/contract/hooks/useVerifiedContractsQuery'; import VerifiedContractsCounters from 'src/slices/contract/pages/index/VerifiedContractsCounters'; import VerifiedContractsFilter from 'src/slices/contract/pages/index/VerifiedContractsFilter'; -import VerifiedContractsList from 'src/slices/contract/pages/index/VerifiedContractsList'; import VerifiedContractsTable from 'src/slices/contract/pages/index/VerifiedContractsTable'; import useIsMobile from 'src/shared/hooks/useIsMobile'; @@ -17,6 +16,7 @@ import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; import Sort from 'src/shared/sort/Sort'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { FilterInput } from 'src/toolkit/components/filters/FilterInput'; import { SORT_OPTIONS } from './sort'; @@ -28,8 +28,8 @@ const sortCollection = createListCollection({ const VerifiedContracts = () => { const isMobile = useIsMobile(); - const { query, type, searchTerm, debouncedSearchTerm, sort, onSearchTermChange, onTypeChange, onSortChange } = useVerifiedContractsQuery(); - const { isError, isPlaceholderData, data, pagination } = query; + const { query, type, searchTerm, sort, onSearchTermChange, onTypeChange, onSortChange } = useVerifiedContractsQuery(); + const { isError, isInitialLoading, isTransitioning, data, pagination } = query; const typeFilter = ( <VerifiedContractsFilter @@ -55,7 +55,7 @@ const VerifiedContracts = () => { defaultValue={ [ sort ] } collection={ sortCollection } onValueChange={ onSortChange } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } /> ); @@ -79,14 +79,9 @@ const VerifiedContracts = () => { ); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <VerifiedContractsList data={ data.items } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> - </Box> - <Box hideBelow="lg"> - <VerifiedContractsTable data={ data.items } sort={ sort } setSorting={ onSortChange } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> - </Box> - </> + <TableContainerScrollable> + <VerifiedContractsTable data={ data.items } sort={ sort } setSorting={ onSortChange } isLoading={ isInitialLoading } resetKey={ query.queryHash }/> + </TableContainerScrollable> ) : null; return ( @@ -97,11 +92,12 @@ const VerifiedContracts = () => { isError={ isError } itemsNum={ data?.items.length } emptyText="There are no verified contracts." - hasActiveFilters={ Boolean(debouncedSearchTerm || type) } + hasActiveFilters={ Boolean(searchTerm || type) } emptyStateProps={{ term: 'contract', }} actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/slices/contract/pages/index/VerifiedContractsCounters.tsx b/src/slices/contract/pages/index/VerifiedContractsCounters.tsx index 50f420e9e1a..fa50ca847e8 100644 --- a/src/slices/contract/pages/index/VerifiedContractsCounters.tsx +++ b/src/slices/contract/pages/index/VerifiedContractsCounters.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -10,8 +9,14 @@ import { VERIFIED_CONTRACTS_COUNTERS, VERIFIED_CONTRACTS_COUNTERS_MICROSERVICE } import { useMultichainContext } from 'src/features/multichain/context'; import config from 'src/config'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; +const COLUMNS_NUM = { + desktop: 2, + mobile: 1, +}; + const VerifiedContractsCounters = () => { const multichainContext = useMultichainContext(); @@ -49,7 +54,7 @@ const VerifiedContractsCounters = () => { countersApiQuery.data?.new_verified_smart_contracts_24h; return ( - <Box columnGap={ 3 } rowGap={ 3 } mb={ 6 } display="grid" gridTemplateColumns={{ base: '1fr', lg: 'repeat(2, 1fr)' }}> + <StatsContainer columnsNum={ COLUMNS_NUM } mb={ 6 }> <StatsWidget label="Total contracts" value={ Number(contractsCount).toLocaleString() } @@ -74,7 +79,7 @@ const VerifiedContractsCounters = () => { undefined } /> - </Box> + </StatsContainer> ); }; diff --git a/src/slices/contract/pages/index/VerifiedContractsList.tsx b/src/slices/contract/pages/index/VerifiedContractsList.tsx deleted file mode 100644 index 957783c708c..00000000000 --- a/src/slices/contract/pages/index/VerifiedContractsList.tsx +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import VerifiedContractsListItem from './VerifiedContractsListItem'; - -interface Props { - data: Array<schemas['SmartContractListItem']>; - isLoading: boolean; - resetKey?: string; -} - -const VerifiedContractsList = ({ data, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <VerifiedContractsListItem - key={ `${ item.address?.hash ?? '' }${ isLoading ? index : '' }` } - data={ item } - isLoading={ isLoading } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(VerifiedContractsList); diff --git a/src/slices/contract/pages/index/VerifiedContractsListItem.tsx b/src/slices/contract/pages/index/VerifiedContractsListItem.tsx deleted file mode 100644 index c1da5331869..00000000000 --- a/src/slices/contract/pages/index/VerifiedContractsListItem.tsx +++ /dev/null @@ -1,122 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box, Flex } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import { currencyUnits } from 'src/slices/chain/units'; -import ContractCertifiedLabel from 'src/slices/contract/components/ContractCertifiedLabel'; -import { formatLanguageName } from 'src/slices/contract/utils/language'; -import { CONTRACT_LICENSES } from 'src/slices/contract/utils/licenses'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - data: schemas['SmartContractListItem']; - isLoading?: boolean; -} - -const VerifiedContractsListItem = ({ data, isLoading }: Props) => { - const license = (() => { - const license = CONTRACT_LICENSES.find((license) => license.type === data.license_type); - if (!license || license.type === 'none') { - return '-'; - } - - return license.label; - })(); - - return ( - <ListItemMobile rowGap={ 3 }> - <Flex w="100%"> - <Flex alignItems="center" overflow="hidden"> - <AddressEntity - isLoading={ isLoading } - address={ data.address } - query={{ tab: 'contract' }} - noCopy - /> - { data.certified && <ContractCertifiedLabel iconSize={ 5 } boxSize={ 5 } mx={ 2 }/> } - </Flex> - <AddressEntity - address={{ hash: data.address.filecoin?.robust ?? data.address.hash }} - isLoading={ isLoading } - noLink - noIcon - truncation="constant" - ml="auto" - color="text.secondary" - flexShrink={ 0 } - /> - </Flex> - <Flex columnGap={ 3 } w="100%"> - <Skeleton loading={ isLoading } fontWeight={ 500 } flexShrink="0">Balance { currencyUnits.ether }</Skeleton> - <NativeCoinValue - amount={ data.coin_balance } - noSymbol - loading={ isLoading } - color="text.secondary" - /> - </Flex> - <Flex columnGap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 }>Txs count</Skeleton> - <Skeleton loading={ isLoading } color="text.secondary"> - <span>{ data.transactions_count ? data.transactions_count.toLocaleString() : '0' }</span> - </Skeleton> - </Flex> - <Flex columnGap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 } flexShrink="0">Language</Skeleton> - <Skeleton loading={ isLoading } display="flex" flexWrap="wrap"> - <Box>{ data.language ? formatLanguageName(data.language) : '-' }</Box> - <Box color="text.secondary" wordBreak="break-all" whiteSpace="pre-wrap"> ({ data.compiler_version })</Box> - </Skeleton> - </Flex> - { data.zk_compiler_version && ( - <Flex columnGap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 } flexShrink="0">ZK compiler</Skeleton> - <Skeleton loading={ isLoading } color="text.secondary" wordBreak="break-all" whiteSpace="pre-wrap"> - { data.zk_compiler_version } - </Skeleton> - </Flex> - ) } - <Flex columnGap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 }>Optimization</Skeleton> - { data.optimization_enabled ? - <SpriteIcon name="check" boxSize={ 6 } color="green.500" cursor="pointer" isLoading={ isLoading }/> : - <SpriteIcon name="cross" boxSize={ 6 } color="red.600" cursor="pointer" isLoading={ isLoading }/> } - </Flex> - <Flex columnGap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 }>Constructor args</Skeleton> - { data.has_constructor_args ? - <SpriteIcon name="check" boxSize={ 6 } color="green.500" cursor="pointer" isLoading={ isLoading }/> : - <SpriteIcon name="cross" boxSize={ 6 } color="red.600" cursor="pointer" isLoading={ isLoading }/> } - </Flex> - <Flex columnGap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 }>Verified</Skeleton> - <Flex alignItems="center" columnGap={ 2 }> - <SpriteIcon name="status/success" boxSize={ 4 } color="green.500" isLoading={ isLoading }/> - <TimeWithTooltip - timestamp={ data.verified_at } - isLoading={ isLoading } - color="text.secondary" - /> - </Flex> - </Flex> - <Flex columnGap={ 3 }> - <Skeleton loading={ isLoading } fontWeight={ 500 }>License</Skeleton> - <Skeleton loading={ isLoading } color="text.secondary"> - <span>{ license }</span> - </Skeleton> - </Flex> - </ListItemMobile> - ); -}; - -export default React.memo(VerifiedContractsListItem); diff --git a/src/slices/contract/pages/index/VerifiedContractsTable.tsx b/src/slices/contract/pages/index/VerifiedContractsTable.tsx index 980fc6031ff..98be4e060c0 100644 --- a/src/slices/contract/pages/index/VerifiedContractsTable.tsx +++ b/src/slices/contract/pages/index/VerifiedContractsTable.tsx @@ -13,6 +13,7 @@ import { SORT_SEQUENCE } from 'src/slices/contract/pages/index/sort'; import { useMultichainContext } from 'src/features/multichain/context'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import getNextSortValue from 'src/shared/sort/get-next-sort-value'; @@ -28,10 +29,13 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: schemas['SmartContractListItem']): string => item.address?.hash ?? ''; + const VerifiedContractsTable = ({ data, sort, setSorting, isLoading, resetKey }: Props) => { const multichainContext = useMultichainContext(); const chainData = multichainContext?.chain; const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); const onSortToggle = React.useCallback((field: VerifiedContractsSortingField) => { const value = getNextSortValue<VerifiedContractsSortingField, VerifiedContractsSortingValue>(SORT_SEQUENCE, field)(sort); @@ -76,7 +80,7 @@ const VerifiedContractsTable = ({ data, sort, setSorting, isLoading, resetKey }: <TableBody> { data.slice(0, renderedItemsNum).map((item, index) => ( <VerifiedContractsTableItem - key={ `${ item.address?.hash ?? '' }${ isLoading ? index : '' }` } + key={ keys[index] } data={ item } isLoading={ isLoading } chainData={ chainData } diff --git a/src/slices/contract/pages/index/__screenshots__/VerifiedContracts.pw.tsx_default_base-view-1.png b/src/slices/contract/pages/index/__screenshots__/VerifiedContracts.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..564605eb254 Binary files /dev/null and b/src/slices/contract/pages/index/__screenshots__/VerifiedContracts.pw.tsx_default_base-view-1.png differ diff --git a/src/slices/contract/pages/index/__screenshots__/VerifiedContracts.pw.tsx_default_base-view-mobile-1.png b/src/slices/contract/pages/index/__screenshots__/VerifiedContracts.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index fe97e0f37bf..00000000000 Binary files a/src/slices/contract/pages/index/__screenshots__/VerifiedContracts.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/contract/pages/index/__screenshots__/VerifiedContracts.pw.tsx_mobile_base-view-mobile-1.png b/src/slices/contract/pages/index/__screenshots__/VerifiedContracts.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 780009d25f5..00000000000 Binary files a/src/slices/contract/pages/index/__screenshots__/VerifiedContracts.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/contract/utils/editor-data.spec.ts b/src/slices/contract/utils/editor-data.spec.ts new file mode 100644 index 00000000000..87b79b49823 --- /dev/null +++ b/src/slices/contract/utils/editor-data.spec.ts @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { SmartContract } from 'src/slices/contract/types/api'; + +import { describe, expect, test } from 'vitest'; + +import { getEditorData } from './editor-data'; + +function makeContract(overrides: Partial<SmartContract>): SmartContract { + return { + language: 'solidity', + file_path: 'contracts/proxies/SafeProxy.sol', + source_code: 'contract SafeProxy {}', + additional_sources: [], + ...overrides, + } as SmartContract; +} + +describe('getEditorData', () => { + test('returns undefined without source code', () => { + expect(getEditorData(undefined)).toBeUndefined(); + expect(getEditorData(makeContract({ source_code: '' }))).toBeUndefined(); + }); + + test('puts the normalized main file first, followed by additional sources', () => { + const result = getEditorData(makeContract({ + additional_sources: [ + { file_path: './contracts/common/Enum.sol', source_code: 'enum' }, + { file_path: '@openzeppelin/contracts/utils/Address.sol', source_code: 'address' }, + ], + })); + + expect(result).toEqual([ + { file_path: '/contracts/proxies/SafeProxy.sol', source_code: 'contract SafeProxy {}' }, + { file_path: '/contracts/common/Enum.sol', source_code: 'enum' }, + { file_path: '/@openzeppelin/contracts/utils/Address.sol', source_code: 'address' }, + ]); + }); + + test.each([ + [ 'solidity', '/index.sol' ], + [ 'vyper', '/index.vy' ], + [ 'yul', '/index.yul' ], + [ 'scilla', '/index.scilla' ], + [ 'stylus_rust', '/index.rs' ], + [ 'geas', '/index.eas' ], + [ null, '/index.sol' ], + ] as const)('names the main file by language when the API gives no path (%s)', (language, expected) => { + expect(getEditorData(makeContract({ file_path: null, language }))?.[0].file_path).toBe(expected); + }); + + test('keeps distinct paths whose content happens to be identical', () => { + const result = getEditorData(makeContract({ + additional_sources: [ + { file_path: 'contracts/interfaces/IERC165.sol', source_code: 'interface' }, + { file_path: 'contracts/external/IERC165.sol', source_code: 'interface' }, + ], + })); + + expect(result?.map((file) => file.file_path)).toEqual([ + '/contracts/proxies/SafeProxy.sol', + '/contracts/interfaces/IERC165.sol', + '/contracts/external/IERC165.sol', + ]); + }); + + test('drops additional sources without a path or content', () => { + const result = getEditorData(makeContract({ + additional_sources: [ + { file_path: '', source_code: 'orphan' }, + { file_path: 'contracts/Empty.sol', source_code: '' }, + { file_path: 'contracts/Kept.sol', source_code: 'kept' }, + ], + })); + + expect(result?.map((file) => file.file_path)).toEqual([ '/contracts/proxies/SafeProxy.sol', '/contracts/Kept.sol' ]); + }); + + test('keeps a single copy of a file repeated under prefix-only path variants with identical content', () => { + const result = getEditorData(makeContract({ + additional_sources: [ + { file_path: 'contracts/proxies/IProxyCreationCallback.sol', source_code: 'callback' }, + { file_path: '/contracts/proxies/SafeProxy.sol', source_code: 'contract SafeProxy {}' }, + { file_path: '/contracts/proxies/IProxyCreationCallback.sol', source_code: 'callback' }, + { file_path: './contracts/proxies/IProxyCreationCallback.sol', source_code: 'callback' }, + ], + })); + + expect(result).toEqual([ + { file_path: '/contracts/proxies/SafeProxy.sol', source_code: 'contract SafeProxy {}' }, + { file_path: '/contracts/proxies/IProxyCreationCallback.sol', source_code: 'callback' }, + ]); + }); + + test('keeps both entries when the same path carries different content', () => { + const result = getEditorData(makeContract({ + additional_sources: [ + { file_path: 'contracts/A.sol', source_code: 'version one' }, + { file_path: '/contracts/A.sol', source_code: 'version two' }, + ], + })); + + expect(result?.slice(1)).toEqual([ + { file_path: '/contracts/A.sol', source_code: 'version one' }, + { file_path: '/contracts/A.sol', source_code: 'version two' }, + ]); + }); +}); diff --git a/src/slices/contract/utils/editor-data.ts b/src/slices/contract/utils/editor-data.ts new file mode 100644 index 00000000000..d6faa9dfcf9 --- /dev/null +++ b/src/slices/contract/utils/editor-data.ts @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { File } from 'src/shared/code-editor/types'; +import type { SmartContract } from 'src/slices/contract/types/api'; + +import formatFilePath from 'src/shared/code-editor/utils/formatFilePath'; + +function getMainFileExtension(language: SmartContract['language']): string { + switch (language) { + case 'vyper': + return 'vy'; + case 'yul': + return 'yul'; + case 'scilla': + return 'scilla'; + case 'stylus_rust': + return 'rs'; + case 'geas': + return 'eas'; + default: + return 'sol'; + } +} + +// The API may list the same source several times with paths that differ only by prefix +// (`a.sol`, `/a.sol`, `./a.sol`), sometimes repeating the main file in `additional_sources`. +// After normalization they map to one Monaco model URI, and creating it twice crashes the editor. +// Only byte-identical repeats are dropped; the same path with different content is a backend bug +// that should stay visible rather than be silently resolved here. +function isRepeat(file: File, index: number, files: Array<File>): boolean { + return files.findIndex((item) => item.file_path === file.file_path && item.source_code === file.source_code) !== index; +} + +export function getEditorData(contractInfo: SmartContract | undefined): Array<File> | undefined { + if (!contractInfo || !contractInfo.source_code) { + return undefined; + } + + const mainFile: File = { + file_path: formatFilePath(contractInfo.file_path || `index.${ getMainFileExtension(contractInfo.language) }`), + source_code: contractInfo.source_code, + }; + + const additionalFiles: Array<File> = (contractInfo.additional_sources || []) + .filter((source) => source.file_path && source.source_code) + .map((source) => ({ + source_code: source.source_code || '', + file_path: formatFilePath(source.file_path || ''), + })); + + return [ mainFile, ...additionalFiles ].filter((file, index, files) => !isRepeat(file, index, files)); +} diff --git a/src/slices/gas/components/GasInfoTooltip.tsx b/src/slices/gas/components/GasInfoTooltip.tsx index db40fe475dc..40b45de8b1c 100644 --- a/src/slices/gas/components/GasInfoTooltip.tsx +++ b/src/slices/gas/components/GasInfoTooltip.tsx @@ -5,7 +5,6 @@ import { Flex, Grid, } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -13,6 +12,7 @@ import type { ExcludeUndefined } from 'src/shared/types/utils'; import config from 'src/config'; import Time from 'src/shared/date-and-time/Time'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import type { TooltipProps } from 'src/toolkit/chakra/tooltip'; @@ -24,7 +24,7 @@ import GasInfoUpdateTimer from './GasInfoUpdateTimer'; interface Props { children: React.ReactNode; - data: schemas['StatsResponse']; + data: Pick<schemas['StatsResponse'], 'gas_prices' | 'gas_price_updated_at' | 'gas_prices_update_in'>; dataUpdatedAt: number; placement?: ExcludeUndefined<TooltipProps['positioning']>['placement']; } diff --git a/src/slices/gas/components/GasUsed.tsx b/src/slices/gas/components/GasUsed.tsx index 6da89609f0e..9f3ffb22b15 100644 --- a/src/slices/gas/components/GasUsed.tsx +++ b/src/slices/gas/components/GasUsed.tsx @@ -41,7 +41,7 @@ const GasUsed = ({ className, gasUsed, gasLimit, gasTarget, isLoading }: Props) className={ className } /> </Tooltip> - { gasTarget && ( + { gasTarget !== undefined && ( <> <TextSeparator/> <GasUsedToTargetRatio value={ gasTarget } isLoading={ isLoading }/> diff --git a/src/slices/home/contexts/home-data-context.tsx b/src/slices/home/contexts/home-data-context.tsx index b50e74edd65..e93d86457e4 100644 --- a/src/slices/home/contexts/home-data-context.tsx +++ b/src/slices/home/contexts/home-data-context.tsx @@ -2,25 +2,27 @@ import React from 'react'; -import useHomeBlocksData, { type HomeBlocksQueryResult } from 'src/slices/home/hooks/useHomeBlocksData'; +import useHomeBlocksData, { type HomeBlocksData, type HomeBlocksQueryResult } from 'src/slices/home/hooks/useHomeBlocksData'; import useHomeLatestBatchData, { type HomeLatestBatchQueryResult } from 'src/features/rollup/common/hooks/useHomeLatestBatchData'; type HomeDataContextValue = { blocksQuery: HomeBlocksQueryResult | undefined; + blocksSocket: Pick<HomeBlocksData, 'newBlocksCount' | 'showSocketErrorAlert'> | undefined; latestBatchQuery: HomeLatestBatchQueryResult | undefined; }; const HomeDataContext = React.createContext<HomeDataContextValue | null>(null); export function HomeDataContextProvider({ children }: { children: React.ReactNode }) { - const blocksQuery = useHomeBlocksData(); + const blocksData = useHomeBlocksData(); const latestBatchQuery = useHomeLatestBatchData(); const value = React.useMemo<HomeDataContextValue>(() => ({ - blocksQuery, + blocksQuery: blocksData?.query, + blocksSocket: blocksData, latestBatchQuery, - }), [ blocksQuery, latestBatchQuery ]); + }), [ blocksData, latestBatchQuery ]); return ( <HomeDataContext.Provider value={ value }> diff --git a/src/slices/home/contexts/rpc-data-context.tsx b/src/slices/home/contexts/rpc-data-context.tsx index 61ca9b7aee2..b9147719dea 100644 --- a/src/slices/home/contexts/rpc-data-context.tsx +++ b/src/slices/home/contexts/rpc-data-context.tsx @@ -1,7 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useQueries, useQuery } from '@tanstack/react-query'; +import { useQueries } from '@tanstack/react-query'; import React from 'react'; +import type { OnBlockParameter, Chain } from 'viem'; import type { schemas } from '@blockscout/api-types'; @@ -12,7 +13,8 @@ import { getPublicClient, isPublicClientAvailable } from 'src/features/connect-w import { SECOND } from 'src/toolkit/utils/consts'; -export type SubscriptionId = 'latest-blocks' | 'latest-txs' | 'stats-widgets'; +export type SubscriptionId = 'latest-blocks' | 'latest-txs' | 'stats-widgets' | +'stats-widgets-latest-block' | 'stats-widgets-average-block-time'; interface HomeRpcDataContext { blocks: Array<schemas['Block']>; @@ -33,60 +35,68 @@ export function HomeRpcDataContextProvider({ children }: { children: React.React const [ blocks, setBlocks ] = React.useState<Array<schemas['Block']>>([]); const [ txs, setTxs ] = React.useState<Array<schemas['Transaction']>>([]); const [ totalTxs, setTotalTxs ] = React.useState(0); - const [ isLoading, setIsLoading ] = React.useState(true); + const [ isLoaded, setIsLoaded ] = React.useState(false); const [ isError, setIsError ] = React.useState(false); - const [ isEnabled, setIsEnabled ] = React.useState(false); const [ subscriptions, setSubscriptions ] = React.useState<Array<SubscriptionId>>([]); - const query = useQuery({ - queryKey: [ 'RPC', 'watch-blocks' ], - queryFn: async() => { - const publicClient = await getPublicClient(); - if (!publicClient) { - return null; - } - - return publicClient.watchBlocks({ - onBlock: (block) => { - setTxs((prevTxs) => { - try { - const newTxs = block.transactions.map((tx) => formatTxListRpcData({ tx, receipt: null, confirmations: null, block })).filter(Boolean); - const nextTxs = prevTxs.length < ITEMS_LIMIT ? [ ...prevTxs, ...newTxs ].slice(0, ITEMS_LIMIT) : prevTxs; - - const totalTxs = prevTxs.length + newTxs.length; - setTotalTxs(totalTxs); - - return nextTxs; - } catch (_) { - setIsError(true); - return prevTxs; - } - }); - setBlocks((prev) => { - try { - return [ - formatBlockListData({ - ...block, - transactions: block.transactions.map((tx) => tx.hash), - }), - ...prev, - ].filter(Boolean).slice(0, ITEMS_LIMIT); - } catch (_) { - setIsError(true); - return prev; - } - }); - }, - onError: () => { - setIsError(true); - setIsLoading(false); - }, - pollingInterval: 5 * SECOND, - includeTransactions: true, + const isEnabled = isPublicClientAvailable && subscriptions.length > 0; + + const handleBlock = React.useCallback((block: OnBlockParameter<Chain | undefined, true, 'latest'>) => { + let newTxs: Array<schemas['Transaction']>; + let newBlock: ReturnType<typeof formatBlockListData>; + + try { + newTxs = block.transactions.map((tx) => formatTxListRpcData({ tx, receipt: null, confirmations: null, block })).filter(Boolean); + newBlock = formatBlockListData({ + ...block, + transactions: block.transactions.map((tx) => tx.hash), }); - }, - enabled: isPublicClientAvailable && isEnabled, - }); + } catch (_) { + setIsError(true); + return; + } + + setTxs((prev) => prev.length < ITEMS_LIMIT ? [ ...prev, ...newTxs ].slice(0, ITEMS_LIMIT) : prev); + setTotalTxs((prev) => prev + newTxs.length); + setBlocks((prev) => [ newBlock, ...prev ].filter(Boolean).slice(0, ITEMS_LIMIT)); + }, []); + + React.useEffect(() => { + if (!isEnabled) { + return; + } + + let isCancelled = false; + let unwatch: (() => void) | undefined; + + const handleError = () => setIsError(true); + + getPublicClient() + .then((publicClient) => { + if (isCancelled) { + return; + } + + if (!publicClient) { + handleError(); + return; + } + + unwatch = publicClient.watchBlocks({ + onBlock: handleBlock, + onError: handleError, + pollingInterval: 5 * SECOND, + includeTransactions: true, + emitOnBegin: true, + }); + }) + .catch(handleError); + + return () => { + isCancelled = true; + unwatch?.(); + }; + }, [ isEnabled, handleBlock ]); const receiptQueries = useQueries({ queries: txs.map((tx) => ({ @@ -103,10 +113,11 @@ export function HomeRpcDataContextProvider({ children }: { children: React.React })), }); - const areReceiptsLoading = txs.length === 0 || receiptQueries.some((query) => query.isPending); + const hasBlocks = blocks.length > 0; + const areReceiptsLoading = receiptQueries.some((query) => query.isPending); React.useEffect(() => { - if (!areReceiptsLoading) { + if (hasBlocks && !areReceiptsLoading) { setTxs((prev) => { return prev.map((tx) => { const receipt = receiptQueries.find((query) => query.data?.transactionHash === tx.hash); @@ -115,58 +126,39 @@ export function HomeRpcDataContextProvider({ children }: { children: React.React } return { ...tx, - status: receipt?.status === 'success' ? 'ok' : 'error', + status: receipt.data?.status === 'success' ? 'ok' : 'error', }; }); }); - setIsLoading(false); + setIsLoaded(true); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ areReceiptsLoading ]); - - const unwatch = query.data; - const isQueryError = query.isError; - - React.useEffect(() => { - return () => { - unwatch?.(); - }; - }, [ unwatch ]); + // eslint-disable-next-line react-hooks/exhaustive-deps -- receiptQueries is a new array on every render; areReceiptsLoading tracks its settled state + }, [ areReceiptsLoading, hasBlocks ]); const enable = React.useCallback((isEnabled: boolean, id: SubscriptionId) => { if (!isPublicClientAvailable) { setIsError(true); - setIsLoading(false); - setIsEnabled(false); return; } - setIsEnabled(isEnabled); - if (isEnabled) { - setIsLoading(true); - setSubscriptions((prev) => [ ...prev, id ]); - } else { - setIsLoading(false); - setSubscriptions((prev) => { - const next = prev.filter((subscription) => subscription !== id); - if (next.length === 0) { - unwatch?.(); - } - return next; - }); - } - }, [ unwatch ]); + setSubscriptions((prev) => { + const next = prev.filter((subscription) => subscription !== id); + return isEnabled ? [ ...next, id ] : next; + }); + }, []); + + const isLoading = !isError && !isLoaded; const value = React.useMemo(() => ({ blocks, txs, totalTxs, - isError: isQueryError || isError, + isError, isLoading, isEnabled, enable, subscriptions, - }), [ blocks, txs, totalTxs, isQueryError, isError, isLoading, isEnabled, enable, subscriptions ]); + }), [ blocks, txs, totalTxs, isError, isLoading, isEnabled, enable, subscriptions ]); return ( <HomeRpcDataContext.Provider value={ value }> diff --git a/src/slices/home/hooks/useHomeBlocksData.ts b/src/slices/home/hooks/useHomeBlocksData.ts index 5fd5cb9468c..2f0e34c97fd 100644 --- a/src/slices/home/hooks/useHomeBlocksData.ts +++ b/src/slices/home/hooks/useHomeBlocksData.ts @@ -15,6 +15,7 @@ import useSocketMessage from 'src/api/socket/useSocketMessage'; import { BLOCK_ITEM } from 'src/slices/block/stubs/list'; import config from 'src/config'; +import useGradualIncrement from 'src/shared/numbers/useGradualIncrement'; /** Max blocks kept in React Query cache for `core:homepage_blocks` (fetch + socket). */ const HOME_BLOCKS_QUERY_LIMIT = 5; @@ -33,8 +34,16 @@ export type HomeBlocksQueryResult = UseQueryResult< ResourceError<unknown> >; -export default function useHomeBlocksData(): HomeBlocksQueryResult | undefined { +export interface HomeBlocksData { + readonly query: HomeBlocksQueryResult; + readonly newBlocksCount: number; + readonly showSocketErrorAlert: boolean; +} + +export default function useHomeBlocksData(): HomeBlocksData | undefined { const queryClient = useQueryClient(); + const [ newBlocksCount, incrementNewBlocksCount ] = useGradualIncrement(0); + const [ showSocketErrorAlert, setShowSocketErrorAlert ] = React.useState(false); const blocksQuery = useApiQuery('core:homepage_blocks', { queryOptions: { @@ -55,8 +64,20 @@ export default function useHomeBlocksData(): HomeBlocksQueryResult | undefined { }); }, [ queryClient ]); + const handleNewBlocksCountMessage: SocketMessage.NewBlockCount['handler'] = React.useCallback((payload) => { + if ((payload.type ?? 'block') === 'block') { + incrementNewBlocksCount(payload.count); + } + }, [ incrementNewBlocksCount ]); + + const handleSocketFailure = React.useCallback(() => { + setShowSocketErrorAlert(true); + }, []); + const channel = useSocketChannel({ topic: 'blocks:new_block', + onSocketClose: handleSocketFailure, + onSocketError: handleSocketFailure, isDisabled: !isHomepageBlocksDataEnabled || blocksQuery.isPlaceholderData || blocksQuery.isError, }); useSocketMessage({ @@ -64,6 +85,16 @@ export default function useHomeBlocksData(): HomeBlocksQueryResult | undefined { event: 'new_block', handler: handleNewBlockMessage, }); + useSocketMessage({ + channel, + event: 'new_blocks_count', + handler: handleNewBlocksCountMessage, + }); - return isHomepageBlocksDataEnabled ? blocksQuery : undefined; + return React.useMemo(() => { + if (!isHomepageBlocksDataEnabled) { + return undefined; + } + return { query: blocksQuery, newBlocksCount, showSocketErrorAlert }; + }, [ blocksQuery, newBlocksCount, showSocketErrorAlert ]); } diff --git a/src/slices/home/mocks/indexing-status.ts b/src/slices/home/mocks/indexing-status.ts deleted file mode 100644 index a26145f4321..00000000000 --- a/src/slices/home/mocks/indexing-status.ts +++ /dev/null @@ -1,6 +0,0 @@ -export const indexingStatus = { - finished_indexing_blocks: false, - indexed_blocks_ratio: 0.1, - finished_indexing: true, - indexed_internal_transactions_ratio: 1, -}; diff --git a/src/slices/home/pages/index/HeroBanner.pw.tsx b/src/slices/home/pages/index/HeroBanner.pw.tsx index 94a41b2d1c8..347f9b7efa2 100644 --- a/src/slices/home/pages/index/HeroBanner.pw.tsx +++ b/src/slices/home/pages/index/HeroBanner.pw.tsx @@ -6,6 +6,8 @@ import type { HeroBannerConfig } from 'src/slices/home/types/config'; import * as profileMock from 'src/features/account/mocks/user-profile'; import * as rewardsBalanceMock from 'src/features/rewards/mocks/balance'; import * as dailyRewardMock from 'src/features/rewards/mocks/daily-reward'; +import * as referralsMock from 'src/features/rewards/mocks/referrals'; +import * as rewardsConfigMock from 'src/features/rewards/mocks/rewards-config'; import { contextWithAuth } from 'playwright/fixtures/auth'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; @@ -59,6 +61,8 @@ authTest('customization +@dark-mode', async({ render, page, mockEnvs, mockApiRes await mockApiResponse('core:user_info', profileMock.withEmailAndWallet); await mockApiResponse('rewards:user_balances', rewardsBalanceMock.base); await mockApiResponse('rewards:user_daily_check', dailyRewardMock.base); + await mockApiResponse('rewards:user_referrals', referralsMock.base); + await mockApiResponse('rewards:config', rewardsConfigMock.base); const component = await render(<HeroBanner/>); diff --git a/src/slices/home/pages/index/Home.tsx b/src/slices/home/pages/index/Home.tsx index d09e8628a30..67e1d82b0b8 100644 --- a/src/slices/home/pages/index/Home.tsx +++ b/src/slices/home/pages/index/Home.tsx @@ -16,7 +16,7 @@ import LatestBlocks from './blocks/LatestBlocks'; import ChainIndicators from './charts/ChainIndicators'; import HeroBanner from './HeroBanner'; import Highlights from './highlights/Highlights'; -import Stats from './stats/Stats'; +import HomeStats from './stats/HomeStats'; import Transactions from './txs/Transactions'; const rollupFeature = config.features.rollup; @@ -41,7 +41,7 @@ const Home = () => { <Box as="main"> <HeroBanner/> <Flex flexDir={{ base: 'column', lg: 'row' }} columnGap={ 2 } rowGap={ 1 } mt={ 3 } _empty={{ mt: 0 }}> - <Stats/> + <HomeStats/> <ChainIndicators/> </Flex> { !isMobile && config.slices.home.highlights && <Highlights mt={ 3 }/> } diff --git a/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_default-view-screen-xl-base-view-1.png b/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_default-view-screen-xl-base-view-1.png index 157d760eb99..f7491b0fa16 100644 Binary files a/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_default-view-screen-xl-base-view-1.png and b/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_default-view-screen-xl-base-view-1.png differ diff --git a/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_degradation-view-1.png b/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_degradation-view-1.png index c716265b7d3..9102de5e673 100644 Binary files a/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_degradation-view-1.png and b/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_degradation-view-1.png differ diff --git a/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_error-view-1.png b/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_error-view-1.png index 0972193fd12..322bc40f2b2 100644 Binary files a/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_error-view-1.png and b/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_error-view-1.png differ diff --git a/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_mobile-base-view-1.png b/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_mobile-base-view-1.png index d477482e183..ad59f7aa0e7 100644 Binary files a/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_mobile-base-view-1.png and b/src/slices/home/pages/index/__screenshots__/Home.pw.tsx_default_mobile-base-view-1.png differ diff --git a/src/slices/home/pages/index/blocks/LatestBlocks.pw.tsx b/src/slices/home/pages/index/blocks/LatestBlocks.pw.tsx index 16c14b0b481..e71ff4fe323 100644 --- a/src/slices/home/pages/index/blocks/LatestBlocks.pw.tsx +++ b/src/slices/home/pages/index/blocks/LatestBlocks.pw.tsx @@ -92,4 +92,23 @@ test.describe('socket', () => { }); await expect(component).toHaveScreenshot(); }); + + test('new blocks count', async({ render, mockApiResponse, createSocket }) => { + await mockApiResponse('core:stats', statsMock.base); + await mockApiResponse('core:homepage_blocks', blockMock.baseListResponse.items); + const component = await render( + <HomeDataContextProvider> + <HomeRpcDataContextProvider> + <LatestBlocks/> + </HomeRpcDataContextProvider> + </HomeDataContextProvider>, + undefined, + { withSocket: true }, + ); + const socket = await createSocket(); + const channel = await socketServer.joinChannel(socket, 'blocks:new_block'); + socketServer.sendMessage(socket, channel, 'new_blocks_count', { count: 3, type: 'block' }); + await expect(component.getByText('3 more blocks')).toBeVisible(); + await expect(component).toHaveScreenshot(); + }); }); diff --git a/src/slices/home/pages/index/blocks/LatestBlocks.tsx b/src/slices/home/pages/index/blocks/LatestBlocks.tsx index 66972f2de32..0cd4f11af18 100644 --- a/src/slices/home/pages/index/blocks/LatestBlocks.tsx +++ b/src/slices/home/pages/index/blocks/LatestBlocks.tsx @@ -1,25 +1,23 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { chakra, Box, Flex, Text, VStack } from '@chakra-ui/react'; -import { upperFirst } from 'es-toolkit'; -import { route } from 'nextjs-routes'; +import { chakra, Box, Flex, VStack } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; -import getChainUtilizationParams from 'src/slices/chain/get-chain-utilization-params'; +import SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; + +import ChainUtilization from 'src/slices/chain/ChainUtilization'; import useStatsQuery from 'src/slices/chain/stats/useStatsQuery'; import { useHomeDataContext } from 'src/slices/home/contexts/home-data-context'; import config from 'src/config'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import useInitialList from 'src/shared/lists/useInitialList'; +import { route } from 'src/shared/router/routes'; import { Heading } from 'src/toolkit/chakra/heading'; import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Tooltip } from 'src/toolkit/chakra/tooltip'; -import { nbsp } from 'src/toolkit/utils/htmlEntities'; import LatestBlocksDegraded from './LatestBlocksDegraded'; import LatestBlocksItem from './LatestBlocksItem'; @@ -33,7 +31,7 @@ const LatestBlocks = () => { } else { blocksMaxCount = isMobile ? 2 : 3; } - const { blocksQuery } = useHomeDataContext(); + const { blocksQuery, blocksSocket } = useHomeDataContext(); const initialList = useInitialList<schemas['Block']>({ data: blocksQuery?.data ?? [], idFn: (block) => block.height, @@ -42,6 +40,19 @@ const LatestBlocks = () => { const statsQueryResult = useStatsQuery(); + const hasNewBlocksNotice = Boolean(blocksSocket && (blocksSocket.newBlocksCount > 0 || blocksSocket.showSocketErrorAlert)); + const newBlocksNotice = hasNewBlocksNotice && blocksQuery && ( + <SocketNewItemsNotice + type="block" + url={ route({ pathname: '/blocks' }) } + num={ blocksSocket?.newBlocksCount } + showErrorAlert={ blocksSocket?.showSocketErrorAlert } + isLoading={ blocksQuery.isPlaceholderData } + mb={ 2 } + borderBottomRadius={ 0 } + /> + ); + const content = (() => { if (blocksQuery?.isError) { return <LatestBlocksDegraded maxNum={ blocksMaxCount }/>; @@ -51,6 +62,7 @@ const LatestBlocks = () => { return ( <> + { newBlocksNotice } <VStack gap={ 2 } mb={ 3 } overflow="hidden" alignItems="stretch"> { dataToShow.map(((block, index) => ( <LatestBlocksItem @@ -67,26 +79,20 @@ const LatestBlocks = () => { </> ); } - return <Box textStyle="sm">No latest blocks found.</Box>; + return ( + <> + { newBlocksNotice } + <Box textStyle="sm">No latest blocks found.</Box> + </> + ); })(); - const networkUtilization = getChainUtilizationParams(statsQueryResult.data?.network_utilization_percentage ?? 0); - return ( <Box width={{ base: '100%', lg: '280px' }} flexShrink={ 0 }> - <Heading level="3">Latest blocks</Heading> - { typeof statsQueryResult.data?.network_utilization_percentage === 'number' && ( - <Skeleton loading={ statsQueryResult.isPlaceholderData } mt={ 2 } display="inline-block" textStyle="sm"> - <Text as="span"> - Network utilization:{ nbsp } - </Text> - <Tooltip content={ `${ upperFirst(networkUtilization.load) } load` }> - <Text as="span" color={ networkUtilization.color } fontWeight={ 700 }> - { statsQueryResult.data?.network_utilization_percentage.toFixed(2) }% - </Text> - </Tooltip> - </Skeleton> - ) } + <Flex alignItems="center" justifyContent="space-between" columnGap={ 2 }> + <Heading level="3">Latest blocks</Heading> + <ChainUtilization/> + </Flex> { statsQueryResult.data?.celo && ( <Box whiteSpace="pre-wrap" textStyle="sm" mt={ 2 }> <span>Current epoch: </span> diff --git a/src/slices/home/pages/index/blocks/LatestBlocksDegraded.tsx b/src/slices/home/pages/index/blocks/LatestBlocksDegraded.tsx index d3e976f32ab..89c76c1d828 100644 --- a/src/slices/home/pages/index/blocks/LatestBlocksDegraded.tsx +++ b/src/slices/home/pages/index/blocks/LatestBlocksDegraded.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex, VStack } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -12,6 +11,7 @@ import { useHomeRpcDataContext } from 'src/slices/home/contexts/rpc-data-context import { isPublicClientAvailable } from 'src/features/connect-wallet/utils/public-client'; import useInitialList from 'src/shared/lists/useInitialList'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/slices/home/pages/index/blocks/LatestBlocksItem.tsx b/src/slices/home/pages/index/blocks/LatestBlocksItem.tsx index 0f83bb78456..9dcd3dcab2c 100644 --- a/src/slices/home/pages/index/blocks/LatestBlocksItem.tsx +++ b/src/slices/home/pages/index/blocks/LatestBlocksItem.tsx @@ -46,7 +46,7 @@ const LatestBlocksItem = ({ block, isLoading, animation }: Props) => { fontWeight={ 500 } mr="auto" /> - { block.celo?.l1_era_finalized_epoch_number && ( + { typeof block.celo?.l1_era_finalized_epoch_number === 'number' && ( <Tooltip content={ `Finalized epoch #${ block.celo.l1_era_finalized_epoch_number }` }> <SpriteIcon name="checkered_flag" boxSize={ 5 } p="1px" ml={ 2 } isLoading={ isLoading } flexShrink={ 0 }/> </Tooltip> @@ -86,7 +86,6 @@ const LatestBlocksItem = ({ block, isLoading, animation }: Props) => { address={ block.miner } isLoading={ isLoading } noIcon - noCopy truncation="constant" /> </> diff --git a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png index b5dd5743555..3e2ea157aa4 100644 Binary files a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png and b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_dark-color-mode_default-view-mobile-dark-mode-1.png differ diff --git a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_L2-view-1.png b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_L2-view-1.png index 2584832a476..affaa1ccb2a 100644 Binary files a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_L2-view-1.png and b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_L2-view-1.png differ diff --git a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_default-view-mobile-dark-mode-1.png b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_default-view-mobile-dark-mode-1.png index b19db07e5a6..2e0943d9be5 100644 Binary files a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_default-view-mobile-dark-mode-1.png and b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_default-view-mobile-dark-mode-1.png differ diff --git a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_no-reward-view-1.png b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_no-reward-view-1.png index 7166e661201..07676dd13fd 100644 Binary files a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_no-reward-view-1.png and b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_no-reward-view-1.png differ diff --git a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_socket-new-blocks-count-1.png b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_socket-new-blocks-count-1.png new file mode 100644 index 00000000000..9ef0526502d Binary files /dev/null and b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_socket-new-blocks-count-1.png differ diff --git a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_socket-new-item-1.png b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_socket-new-item-1.png index 75d80a9e17b..1fc6c5332e5 100644 Binary files a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_socket-new-item-1.png and b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_socket-new-item-1.png differ diff --git a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_with-long-block-height-1.png b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_with-long-block-height-1.png index 8b667ca8e14..cb1532cfd89 100644 Binary files a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_with-long-block-height-1.png and b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_default_with-long-block-height-1.png differ diff --git a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_mobile_default-view-mobile-dark-mode-1.png b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_mobile_default-view-mobile-dark-mode-1.png index a6c777f62cf..923b6913008 100644 Binary files a/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_mobile_default-view-mobile-dark-mode-1.png and b/src/slices/home/pages/index/blocks/__screenshots__/LatestBlocks.pw.tsx_mobile_default-view-mobile-dark-mode-1.png differ diff --git a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_daily-txs-chart-dark-mode-mobile-1.png b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_daily-txs-chart-dark-mode-mobile-1.png index 5306b1d3891..ff2bcfab0de 100644 Binary files a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_daily-txs-chart-dark-mode-mobile-1.png and b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_daily-txs-chart-dark-mode-mobile-1.png differ diff --git a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_daily-txs-chart-mobile-1.png b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_daily-txs-chart-mobile-1.png index 55d6d674781..50935185214 100644 Binary files a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_daily-txs-chart-mobile-1.png and b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_daily-txs-chart-mobile-1.png differ diff --git a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_no-data-1.png b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_no-data-1.png index 16e8d8957ea..efcd4361e93 100644 Binary files a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_no-data-1.png and b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_no-data-1.png differ diff --git a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_partial-data-1.png b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_partial-data-1.png index 7d6cbdd93c7..0a7a2c31e05 100644 Binary files a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_partial-data-1.png and b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_default_partial-data-1.png differ diff --git a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_mobile_daily-txs-chart-dark-mode-mobile-1.png b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_mobile_daily-txs-chart-dark-mode-mobile-1.png index 7064efda633..6b9a342f077 100644 Binary files a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_mobile_daily-txs-chart-dark-mode-mobile-1.png and b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_mobile_daily-txs-chart-dark-mode-mobile-1.png differ diff --git a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_mobile_daily-txs-chart-mobile-1.png b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_mobile_daily-txs-chart-mobile-1.png index 58df6f4f145..91cf967f973 100644 Binary files a/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_mobile_daily-txs-chart-mobile-1.png and b/src/slices/home/pages/index/charts/__screenshots__/ChainIndicators.pw.tsx_mobile_daily-txs-chart-mobile-1.png differ diff --git a/src/slices/home/pages/index/stats/HomeStats.pw.tsx b/src/slices/home/pages/index/stats/HomeStats.pw.tsx new file mode 100644 index 00000000000..f5bd5904448 --- /dev/null +++ b/src/slices/home/pages/index/stats/HomeStats.pw.tsx @@ -0,0 +1,86 @@ +import type { Locator } from '@playwright/test'; +import React from 'react'; + +import * as blockListMock from 'src/slices/block/mocks/list'; +import * as statsMock from 'src/slices/chain/stats/mocks'; +import { HomeDataContextProvider } from 'src/slices/home/contexts/home-data-context'; +import { HomeRpcDataContextProvider } from 'src/slices/home/contexts/rpc-data-context'; + +import { test, expect } from 'playwright/lib'; + +import HomeStats from './HomeStats'; + +test.describe('all items', () => { + let component: Locator; + + test.beforeEach(async({ render, mockApiResponse, mockEnvs }) => { + await mockEnvs([ + [ 'NEXT_PUBLIC_HOMEPAGE_STATS', '["total_blocks","average_block_time","total_txs","wallet_addresses","gas_tracker","btc_locked"]' ], + [ 'NEXT_PUBLIC_STATS_API_HOST', '' ], + ]); + await mockApiResponse('core:stats', statsMock.withBtcLocked); + await mockApiResponse('core:homepage_blocks', blockListMock.baseListResponse.items); + component = await render( + <HomeDataContextProvider> + <HomeRpcDataContextProvider> + <HomeStats/> + </HomeRpcDataContextProvider> + </HomeDataContextProvider>, + ); + }); + + test('+@mobile +@dark-mode', async() => { + await expect(component).toHaveScreenshot(); + }); +}); + +test('no gas info', async({ render, mockApiResponse, mockEnvs }) => { + await mockEnvs([ + [ 'NEXT_PUBLIC_STATS_API_HOST', '' ], + ]); + await mockApiResponse('core:stats', statsMock.withoutGasInfo); + await mockApiResponse('core:homepage_blocks', blockListMock.baseListResponse.items); + const component = await render( + <HomeDataContextProvider> + <HomeRpcDataContextProvider> + <HomeStats/> + </HomeRpcDataContextProvider> + </HomeDataContextProvider>, + ); + + await expect(component).toHaveScreenshot(); +}); + +test('4 items default view +@mobile -@default', async({ render, mockApiResponse, mockEnvs }) => { + await mockEnvs([ + [ 'NEXT_PUBLIC_HOMEPAGE_STATS', '["total_txs","gas_tracker","wallet_addresses","total_blocks"]' ], + [ 'NEXT_PUBLIC_STATS_API_HOST', '' ], + ]); + await mockApiResponse('core:stats', statsMock.base); + await mockApiResponse('core:homepage_blocks', blockListMock.baseListResponse.items); + const component = await render( + <HomeDataContextProvider> + <HomeRpcDataContextProvider> + <HomeStats/> + </HomeRpcDataContextProvider> + </HomeDataContextProvider>, + ); + await expect(component).toHaveScreenshot(); +}); + +test('3 items default view +@mobile -@default', async({ render, mockApiResponse, mockEnvs }) => { + await mockEnvs([ + [ 'NEXT_PUBLIC_HOMEPAGE_STATS', '["total_txs","wallet_addresses","total_blocks"]' ], + [ 'NEXT_PUBLIC_STATS_API_HOST', '' ], + ]); + await mockApiResponse('core:stats', statsMock.base); + await mockApiResponse('core:homepage_blocks', blockListMock.baseListResponse.items); + const component = await render( + <HomeDataContextProvider> + <HomeRpcDataContextProvider> + <HomeStats/> + </HomeRpcDataContextProvider> + </HomeDataContextProvider>, + ); + await expect(component).toHaveScreenshot(); +}); diff --git a/src/slices/home/pages/index/stats/HomeStats.tsx b/src/slices/home/pages/index/stats/HomeStats.tsx new file mode 100644 index 00000000000..22007481cd7 --- /dev/null +++ b/src/slices/home/pages/index/stats/HomeStats.tsx @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { isHomeStatsItemEnabled, sortHomeStatsItems } from 'src/slices/home/utils/stats'; + +import StatsContainer from 'src/shared/stats/StatsContainer'; + +import HomeStatsAverageBlockTime from './widgets/HomeStatsAverageBlockTime'; +import HomeStatsBtcLocked from './widgets/HomeStatsBtcLocked'; +import HomeStatsCurrentEpoch from './widgets/HomeStatsCurrentEpoch'; +import HomeStatsGasTracker from './widgets/HomeStatsGasTracker'; +import HomeStatsLatestBatch from './widgets/HomeStatsLatestBatch'; +import HomeStatsLatestBlock from './widgets/HomeStatsLatestBlock'; +import HomeStatsLatestL1StateBatch from './widgets/HomeStatsLatestL1StateBatch'; +import HomeStatsTotalAddresses from './widgets/HomeStatsTotalAddresses'; +import HomeStatsTotalOperationalTxs from './widgets/HomeStatsTotalOperationalTxs'; +import HomeStatsTotalTxs from './widgets/HomeStatsTotalTxs'; + +const COLUMNS_NUM = { + desktop: 2, + mobile: 2, +}; + +const HomeStats = () => { + const items = React.useMemo(() => { + return [ + { + id: 'latest_batch' as const, + component: <HomeStatsLatestBatch/>, + }, + { + id: 'total_blocks' as const, + component: <HomeStatsLatestBlock/>, + }, + { + id: 'average_block_time' as const, + component: <HomeStatsAverageBlockTime/>, + }, + { + id: 'total_txs' as const, + component: <HomeStatsTotalTxs/>, + }, + { + id: 'total_operational_txs' as const, + component: <HomeStatsTotalOperationalTxs/>, + }, + { + id: 'wallet_addresses' as const, + component: <HomeStatsTotalAddresses/>, + }, + { + id: 'gas_tracker' as const, + component: <HomeStatsGasTracker/>, + }, + { + id: 'latest_l1_state_batch' as const, + component: <HomeStatsLatestL1StateBatch/>, + }, + { + id: 'btc_locked' as const, + component: <HomeStatsBtcLocked/>, + }, + { + id: 'current_epoch' as const, + component: <HomeStatsCurrentEpoch/>, + }, + ] + .filter(Boolean) + .filter(isHomeStatsItemEnabled) + .sort(sortHomeStatsItems); + }, []); + + if (items.length === 0) { + return null; + } + + return ( + <StatsContainer + columnsNum={ COLUMNS_NUM } + flexBasis="50%" + flexGrow={ 1 } + > + { items.map(({ id, component }) => { + return ( + <React.Fragment key={ id }> + { component } + </React.Fragment> + ); + }) } + </StatsContainer> + ); +}; + +export default React.memo(HomeStats); diff --git a/src/slices/home/pages/index/stats/HomeStatsWidget.tsx b/src/slices/home/pages/index/stats/HomeStatsWidget.tsx new file mode 100644 index 00000000000..11ce1abdccc --- /dev/null +++ b/src/slices/home/pages/index/stats/HomeStatsWidget.tsx @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { Props as StatsWidgetProps } from 'src/shared/stats/StatsWidget'; +import StatsWidget from 'src/shared/stats/StatsWidget'; + +const HomeStatsWidget = React.forwardRef<HTMLDivElement, StatsWidgetProps>((props, ref) => { + return <StatsWidget ref={ ref } _odd={{ _last: { gridColumn: 'span 2' } }} { ...props }/>; +}); + +export default React.memo(HomeStatsWidget); diff --git a/src/slices/home/pages/index/stats/LatestBatchStatsWidget.tsx b/src/slices/home/pages/index/stats/LatestBatchStatsWidget.tsx deleted file mode 100644 index 8002b70b684..00000000000 --- a/src/slices/home/pages/index/stats/LatestBatchStatsWidget.tsx +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { BoxProps } from '@chakra-ui/react'; -import { chakra } from '@chakra-ui/react'; -import React from 'react'; - -import { useHomeDataContext } from 'src/slices/home/contexts/home-data-context'; - -import StatsWidget from 'src/shared/stats/StatsWidget'; - -interface Props extends BoxProps { - isLoading: boolean; -}; - -const LatestBatchStatsWidget = ({ isLoading, ...props }: Props) => { - const { latestBatchQuery } = useHomeDataContext(); - - if (latestBatchQuery?.data === undefined) { - return null; - } - - return ( - <StatsWidget - icon="txn_batches" - label="Latest batch" - value={ latestBatchQuery.data.toLocaleString() } - href={{ pathname: '/batches' }} - isLoading={ isLoading } - { ...props } - /> - ); -}; - -export default chakra(React.memo(LatestBatchStatsWidget)); diff --git a/src/slices/home/pages/index/stats/LatestBlockStatsWidget.tsx b/src/slices/home/pages/index/stats/LatestBlockStatsWidget.tsx deleted file mode 100644 index 6a60bc7c569..00000000000 --- a/src/slices/home/pages/index/stats/LatestBlockStatsWidget.tsx +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { BoxProps } from '@chakra-ui/react'; -import { chakra } from '@chakra-ui/react'; -import React from 'react'; - -import { useHomeDataContext } from 'src/slices/home/contexts/home-data-context'; - -import StatsWidget from 'src/shared/stats/StatsWidget'; - -interface Props extends BoxProps { - isLoading: boolean; - fallbackValue: number | string | undefined; -}; - -const LatestBlockStatsWidget = ({ isLoading, fallbackValue, ...props }: Props) => { - const { blocksQuery } = useHomeDataContext(); - - const value = blocksQuery?.data?.[0]?.height ?? fallbackValue; - if (value === undefined) { - return null; - } - - return ( - <StatsWidget - icon="block" - label="Latest block" - value={ Number(value).toLocaleString() } - href={{ pathname: '/blocks' }} - isLoading={ isLoading } - { ...props } - /> - ); -}; - -export default chakra(React.memo(LatestBlockStatsWidget)); diff --git a/src/slices/home/pages/index/stats/Stats.pw.tsx b/src/slices/home/pages/index/stats/Stats.pw.tsx deleted file mode 100644 index 00700516e3a..00000000000 --- a/src/slices/home/pages/index/stats/Stats.pw.tsx +++ /dev/null @@ -1,77 +0,0 @@ -import type { Locator } from '@playwright/test'; -import React from 'react'; - -import * as blockListMock from 'src/slices/block/mocks/list'; -import * as statsMock from 'src/slices/chain/stats/mocks'; -import { HomeDataContextProvider } from 'src/slices/home/contexts/home-data-context'; - -import { test, expect } from 'playwright/lib'; - -import Stats from './Stats'; - -test.describe('all items', () => { - let component: Locator; - - test.beforeEach(async({ render, mockApiResponse, mockEnvs }) => { - await mockEnvs([ - [ 'NEXT_PUBLIC_HOMEPAGE_STATS', '["total_blocks","average_block_time","total_txs","wallet_addresses","gas_tracker","btc_locked"]' ], - [ 'NEXT_PUBLIC_STATS_API_HOST', '' ], - ]); - await mockApiResponse('core:stats', statsMock.withBtcLocked); - await mockApiResponse('core:homepage_blocks', blockListMock.baseListResponse.items); - component = await render( - <HomeDataContextProvider> - <Stats/> - </HomeDataContextProvider>, - ); - }); - - test('+@mobile +@dark-mode', async() => { - await expect(component).toHaveScreenshot(); - }); -}); - -test('no gas info', async({ render, mockApiResponse, mockEnvs }) => { - await mockEnvs([ - [ 'NEXT_PUBLIC_STATS_API_HOST', '' ], - ]); - await mockApiResponse('core:stats', statsMock.withoutGasInfo); - await mockApiResponse('core:homepage_blocks', blockListMock.baseListResponse.items); - const component = await render( - <HomeDataContextProvider> - <Stats/> - </HomeDataContextProvider>, - ); - - await expect(component).toHaveScreenshot(); -}); - -test('4 items default view +@mobile -@default', async({ render, mockApiResponse, mockEnvs }) => { - await mockEnvs([ - [ 'NEXT_PUBLIC_HOMEPAGE_STATS', '["total_txs","gas_tracker","wallet_addresses","total_blocks"]' ], - [ 'NEXT_PUBLIC_STATS_API_HOST', '' ], - ]); - await mockApiResponse('core:stats', statsMock.base); - await mockApiResponse('core:homepage_blocks', blockListMock.baseListResponse.items); - const component = await render( - <HomeDataContextProvider> - <Stats/> - </HomeDataContextProvider>, - ); - await expect(component).toHaveScreenshot(); -}); - -test('3 items default view +@mobile -@default', async({ render, mockApiResponse, mockEnvs }) => { - await mockEnvs([ - [ 'NEXT_PUBLIC_HOMEPAGE_STATS', '["total_txs","wallet_addresses","total_blocks"]' ], - [ 'NEXT_PUBLIC_STATS_API_HOST', '' ], - ]); - await mockApiResponse('core:stats', statsMock.base); - await mockApiResponse('core:homepage_blocks', blockListMock.baseListResponse.items); - const component = await render( - <HomeDataContextProvider> - <Stats/> - </HomeDataContextProvider>, - ); - await expect(component).toHaveScreenshot(); -}); diff --git a/src/slices/home/pages/index/stats/Stats.tsx b/src/slices/home/pages/index/stats/Stats.tsx deleted file mode 100644 index 9ce0798ec59..00000000000 --- a/src/slices/home/pages/index/stats/Stats.tsx +++ /dev/null @@ -1,221 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Grid } from '@chakra-ui/react'; -import BigNumber from 'bignumber.js'; -import React from 'react'; - -import useApiQuery from 'src/api/hooks/useApiQuery'; - -import useStatsQuery from 'src/slices/chain/stats/useStatsQuery'; -import GasInfoTooltip from 'src/slices/gas/components/GasInfoTooltip'; -import GasPrice from 'src/slices/gas/components/GasPrice'; -import discriminateDetailedPrices from 'src/slices/gas/utils/price'; -import { useHomeDataContext } from 'src/slices/home/contexts/home-data-context'; -import type { HomeStatsItem } from 'src/slices/home/utils/stats'; -import { homeStatsWidgetCommonStyles, isHomeStatsItemEnabled, sortHomeStatsItems } from 'src/slices/home/utils/stats'; - -import { HOMEPAGE_STATS_MICROSERVICE } from 'src/features/chain-stats/stubs/home'; -import { layerLabels } from 'src/features/rollup/common/utils/layer'; - -import config from 'src/config'; -import StatsWidget from 'src/shared/stats/StatsWidget'; -import { WEI } from 'src/shared/values/entity/utils'; -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import LatestBatchStatsWidget from './LatestBatchStatsWidget'; -import LatestBlockStatsWidget from './LatestBlockStatsWidget'; -import StatsDegraded from './StatsDegraded'; - -const rollupFeature = config.features.rollup; -const isOptimisticRollup = rollupFeature.isEnabled && rollupFeature.type === 'optimistic'; -const isArbitrumRollup = rollupFeature.isEnabled && rollupFeature.type === 'arbitrum'; -const isStatsFeatureEnabled = config.features.stats.isEnabled; - -const Stats = () => { - const [ hasGasTracker, setHasGasTracker ] = React.useState(config.features.gasTracker.isEnabled); - const { blocksQuery, latestBatchQuery } = useHomeDataContext(); - - // data from stats microservice is prioritized over data from stats api - const statsQuery = useApiQuery('stats:pages_main', { - queryOptions: { - refetchOnMount: false, - placeholderData: isStatsFeatureEnabled ? HOMEPAGE_STATS_MICROSERVICE : undefined, - enabled: isStatsFeatureEnabled, - refetchInterval: (query) => { - if (query.state.status === 'error') { - return false; - } - - return config.apis.stats?.refetchInterval?.[ 'stats:pages_main' ]; - }, - }, - }); - - const apiQuery = useStatsQuery(); - - const isPlaceholderData = statsQuery.isPlaceholderData || apiQuery.isPlaceholderData || blocksQuery?.isPlaceholderData; - - React.useEffect(() => { - if (!isPlaceholderData && !apiQuery.data?.gas_prices?.average) { - setHasGasTracker(false); - } - // should run only after initial fetch - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ isPlaceholderData ]); - - const hasStatsError = apiQuery.isError || (statsQuery.isError && !statsQuery.isRefetchError) || blocksQuery?.isError || latestBatchQuery?.isError; - - if (hasStatsError) { - return <StatsDegraded/>; - } - - const isLoading = isPlaceholderData || latestBatchQuery?.isPlaceholderData; - - const apiData = apiQuery.data; - const statsData = statsQuery.data; - - const items: Array<HomeStatsItem> = (() => { - if (!statsData && !apiData) { - return []; - } - - const gasPrices = discriminateDetailedPrices(apiData?.gas_prices); - - const gasInfoTooltip = hasGasTracker && apiData?.gas_prices && apiData.gas_prices.average ? ( - <GasInfoTooltip data={ apiData } dataUpdatedAt={ apiQuery.dataUpdatedAt }> - <SpriteIcon - isLoading={ isLoading } - name="info" - boxSize={ 5 } - flexShrink={ 0 } - cursor="pointer" - color="icon.secondary" - _hover={{ color: 'hover' }} - /> - </GasInfoTooltip> - ) : null; - - return [ - latestBatchQuery?.data !== undefined && { - id: 'latest_batch' as const, - component: <LatestBatchStatsWidget isLoading={ Boolean(isLoading) } { ...homeStatsWidgetCommonStyles }/>, - }, - (blocksQuery?.data?.[0]?.height ?? statsData?.total_blocks?.value ?? apiData?.total_blocks) && { - id: 'total_blocks' as const, - component: ( - <LatestBlockStatsWidget - isLoading={ Boolean(isLoading) } - fallbackValue={ statsData?.total_blocks?.value ?? apiData?.total_blocks } - { ...homeStatsWidgetCommonStyles } - /> - ), - }, - (statsData?.average_block_time?.value || apiData?.average_block_time) && { - id: 'average_block_time' as const, - icon: 'clock-light' as const, - label: statsData?.average_block_time?.title || 'Average block time', - value: `${ - statsData?.average_block_time?.value ? - Number(statsData.average_block_time.value).toFixed(1) : - (apiData!.average_block_time / 1000).toFixed(1) - }s`, - isLoading, - }, - (statsData?.total_transactions?.value || apiData?.total_transactions) && { - id: 'total_txs' as const, - icon: 'transactions' as const, - label: statsData?.total_transactions?.title || 'Total transactions', - value: Number(statsData?.total_transactions?.value || apiData?.total_transactions).toLocaleString(), - href: { pathname: '/txs' as const }, - isLoading, - }, - (isArbitrumRollup && statsData?.total_operational_transactions?.value) && { - id: 'total_operational_txs' as const, - icon: 'transactions' as const, - label: statsData?.total_operational_transactions?.title || 'Total operational transactions', - value: Number(statsData?.total_operational_transactions?.value).toLocaleString(), - href: { pathname: '/txs' as const }, - isLoading, - }, - (isOptimisticRollup && statsData?.op_stack_total_operational_transactions?.value) && { - id: 'total_operational_txs' as const, - icon: 'transactions' as const, - label: statsData?.op_stack_total_operational_transactions?.title || 'Total operational transactions', - value: Number(statsData?.op_stack_total_operational_transactions?.value).toLocaleString(), - href: { pathname: '/txs' as const }, - isLoading, - }, - apiData?.last_output_root_size && { - id: 'latest_l1_state_batch' as const, - icon: 'txn_batches' as const, - label: `Latest ${ layerLabels.parent } state batch`, - value: apiData?.last_output_root_size, - href: { pathname: '/batches' as const }, - isLoading, - }, - (statsData?.total_addresses?.value || apiData?.total_addresses) && { - id: 'wallet_addresses' as const, - icon: 'wallet' as const, - label: statsData?.total_addresses?.title || 'Wallet addresses', - value: Number(statsData?.total_addresses?.value || apiData?.total_addresses).toLocaleString(), - isLoading, - }, - hasGasTracker && gasPrices && { - id: 'gas_tracker' as const, - icon: 'gas' as const, - label: 'Gas tracker', - value: gasPrices?.average ? <GasPrice data={ gasPrices.average }/> : 'N/A', - hint: gasInfoTooltip, - isLoading, - }, - apiData?.rootstock_locked_btc && { - id: 'btc_locked' as const, - icon: 'coins/bitcoin' as const, - label: 'BTC Locked in 2WP', - value: `${ BigNumber(apiData.rootstock_locked_btc).div(WEI).dp(0).toFormat() } RBTC`, - isLoading, - }, - apiData?.celo && { - id: 'current_epoch' as const, - icon: 'hourglass' as const, - label: 'Current epoch', - value: `#${ apiData.celo.epoch_number }`, - href: { pathname: '/epochs/[number]' as const, query: { number: String(apiData.celo.epoch_number) } }, - isLoading, - }, - ] - .filter(Boolean) - .filter(isHomeStatsItemEnabled) - .sort(sortHomeStatsItems); - })(); - - if (items.length === 0) { - return null; - } - - return ( - <Grid - gridTemplateColumns="1fr 1fr" - gridGap={{ base: 1, lg: 2 }} - flexBasis="50%" - flexGrow={ 1 } - > - { items.map(({ id, ...item }) => { - if ('component' in item) { - return <React.Fragment key={ id }>{ item.component }</React.Fragment>; - } - - return ( - <StatsWidget - key={ id } - { ...item } - { ...homeStatsWidgetCommonStyles } - isLoading={ isLoading } - /> - ); - }) } - </Grid> - ); -}; - -export default Stats; diff --git a/src/slices/home/pages/index/stats/StatsDegraded.tsx b/src/slices/home/pages/index/stats/StatsDegraded.tsx deleted file mode 100644 index 465e5327c8b..00000000000 --- a/src/slices/home/pages/index/stats/StatsDegraded.tsx +++ /dev/null @@ -1,196 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Grid } from '@chakra-ui/react'; -import { useQuery } from '@tanstack/react-query'; -import BigNumber from 'bignumber.js'; -import React from 'react'; - -import GasPrice from 'src/slices/gas/components/GasPrice'; -import { useHomeRpcDataContext } from 'src/slices/home/contexts/rpc-data-context'; -import type { HomeStatsWidgetItem } from 'src/slices/home/utils/stats'; -import { homeStatsWidgetCommonStyles, isHomeStatsItemEnabled, sortHomeStatsItems } from 'src/slices/home/utils/stats'; - -import { getPublicClient, isPublicClientAvailable } from 'src/features/connect-wallet/utils/public-client'; - -import dayjs from 'src/shared/date-and-time/dayjs'; -import StatsWidget from 'src/shared/stats/StatsWidget'; -import { GWEI } from 'src/shared/values/entity/utils'; - -import { Tooltip } from 'src/toolkit/chakra/tooltip'; -import { mdash } from 'src/toolkit/utils/htmlEntities'; - -const TOOLTIP_CONTENT_VALUE = 'Our indexer is experiencing problems, you see the data directly from RPC'; -const TOOLTIP_CONTENT_NO_VALUE = 'Our indexer is experiencing problems and we couldn\'t get this data directly from RPC'; - -const StatsDegraded = () => { - - const [ averageBlockTime, setAverageBlockTime ] = React.useState<number | undefined>(undefined); - - const { blocks, isLoading, enable } = useHomeRpcDataContext(); - - const gasPriceQuery = useQuery({ - queryKey: [ 'RPC', 'gas-price' ], - queryFn: async() => { - const publicClient = await getPublicClient(); - if (!publicClient) { - return null; - } - return publicClient.getGasPrice(); - }, - select: (data) => { - if (!data) { - return null; - } - const price = BigNumber(data.toString()).div(GWEI).toNumber(); - return { - price, - fiat_price: null, - time: null, - base_fee: null, - priority_fee: null, - priority_fee_wei: null, - wei: null, - }; - }, - enabled: isPublicClientAvailable, - }); - - React.useEffect(() => { - enable(true, 'stats-widgets'); - return () => { - enable(false, 'stats-widgets'); - }; - }, [ enable ]); - - React.useEffect(() => { - if (blocks.length > 1) { - const timeDiffs = blocks - .map((block, index) => { - if (index > 0) { - return dayjs(blocks[index - 1].timestamp).diff(dayjs(block.timestamp), 'seconds'); - } - return 0; - }) - .slice(1); - const totalDiff = timeDiffs.reduce((acc, diff) => acc + diff, 0); - setAverageBlockTime((prev) => { - if (prev === undefined) { - return totalDiff / timeDiffs.length; - } - return (prev + totalDiff) / (timeDiffs.length + 1); - }); - } - }, [ blocks ]); - - const items: Array<HomeStatsWidgetItem> = (() => { - return [ - { - id: 'latest_batch' as const, - icon: 'txn_batches' as const, - label: 'Latest batch', - value: mdash, - isFallback: true, - }, - { - id: 'total_blocks' as const, - icon: 'block' as const, - label: 'Latest block', - value: blocks[0] ? blocks[0].height.toLocaleString() : mdash, - isFallback: blocks[0] === undefined, - }, - { - id: 'average_block_time' as const, - icon: 'clock-light' as const, - label: 'Average block time', - value: averageBlockTime ? `${ averageBlockTime.toFixed(1) }s` : mdash, - isFallback: averageBlockTime === undefined, - }, - { - id: 'total_txs' as const, - icon: 'transactions' as const, - label: 'Total transactions', - value: mdash, - isFallback: true, - }, - { - id: 'total_operational_txs' as const, - icon: 'transactions' as const, - label: 'Total operational transactions', - value: mdash, - isFallback: true, - }, - { - id: 'latest_l1_state_batch' as const, - icon: 'txn_batches' as const, - label: 'Latest L1 state batch', - value: mdash, - isFallback: true, - }, - { - id: 'wallet_addresses' as const, - icon: 'wallet' as const, - label: 'Wallet addresses', - value: mdash, - isFallback: true, - }, - { - id: 'gas_tracker' as const, - icon: 'gas' as const, - label: 'Gas tracker', - value: gasPriceQuery.data ? <GasPrice data={ gasPriceQuery.data }/> : mdash, - isFallback: !gasPriceQuery.data, - isLoading: gasPriceQuery.isLoading, - }, - { - id: 'btc_locked' as const, - icon: 'coins/bitcoin' as const, - label: 'BTC Locked in 2WP', - value: mdash, - isFallback: true, - }, - { - id: 'current_epoch' as const, - icon: 'hourglass' as const, - label: 'Current epoch', - value: mdash, - isFallback: true, - }, - ] - .filter(Boolean) - .filter(isHomeStatsItemEnabled) - .sort(sortHomeStatsItems);; - })(); - - if (items.length === 0) { - return null; - } - - return ( - <Grid - gridTemplateColumns="1fr 1fr" - gridGap={{ base: 1, lg: 2 }} - flexBasis="50%" - flexGrow={ 1 } - > - { items.map(({ id, ...item }) => { - const isLoadingState = item.isLoading || isLoading; - return ( - <Tooltip - key={ id } - content={ item.value !== mdash ? TOOLTIP_CONTENT_VALUE : TOOLTIP_CONTENT_NO_VALUE } - disabled={ isLoadingState } - > - <StatsWidget - { ...item } - isLoading={ isLoadingState } - { ...homeStatsWidgetCommonStyles } - /> - </Tooltip> - ); - }) } - </Grid> - - ); -}; - -export default React.memo(StatsDegraded); diff --git a/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_dark-color-mode_all-items-mobile-dark-mode-1.png b/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_dark-color-mode_all-items-mobile-dark-mode-1.png similarity index 100% rename from src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_dark-color-mode_all-items-mobile-dark-mode-1.png rename to src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_dark-color-mode_all-items-mobile-dark-mode-1.png diff --git a/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_default_all-items-mobile-dark-mode-1.png b/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_default_all-items-mobile-dark-mode-1.png similarity index 100% rename from src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_default_all-items-mobile-dark-mode-1.png rename to src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_default_all-items-mobile-dark-mode-1.png diff --git a/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_default_no-gas-info-1.png b/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_default_no-gas-info-1.png similarity index 100% rename from src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_default_no-gas-info-1.png rename to src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_default_no-gas-info-1.png diff --git a/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_mobile_3-items-default-view-mobile---default-1.png b/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_mobile_3-items-default-view-mobile---default-1.png new file mode 100644 index 00000000000..abb007f2973 Binary files /dev/null and b/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_mobile_3-items-default-view-mobile---default-1.png differ diff --git a/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_mobile_4-items-default-view-mobile---default-1.png b/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_mobile_4-items-default-view-mobile---default-1.png new file mode 100644 index 00000000000..4aac9ccc560 Binary files /dev/null and b/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_mobile_4-items-default-view-mobile---default-1.png differ diff --git a/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_mobile_all-items-mobile-dark-mode-1.png b/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_mobile_all-items-mobile-dark-mode-1.png new file mode 100644 index 00000000000..855500e4af4 Binary files /dev/null and b/src/slices/home/pages/index/stats/__screenshots__/HomeStats.pw.tsx_mobile_all-items-mobile-dark-mode-1.png differ diff --git a/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_mobile_3-items-default-view-mobile---default-1.png b/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_mobile_3-items-default-view-mobile---default-1.png deleted file mode 100644 index 797e95154d5..00000000000 Binary files a/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_mobile_3-items-default-view-mobile---default-1.png and /dev/null differ diff --git a/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_mobile_4-items-default-view-mobile---default-1.png b/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_mobile_4-items-default-view-mobile---default-1.png deleted file mode 100644 index 65be4e56534..00000000000 Binary files a/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_mobile_4-items-default-view-mobile---default-1.png and /dev/null differ diff --git a/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_mobile_all-items-mobile-dark-mode-1.png b/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_mobile_all-items-mobile-dark-mode-1.png deleted file mode 100644 index a6f0bf72aac..00000000000 Binary files a/src/slices/home/pages/index/stats/__screenshots__/Stats.pw.tsx_mobile_all-items-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/home/pages/index/stats/useStatsHome.ts b/src/slices/home/pages/index/stats/useStatsHome.ts new file mode 100644 index 00000000000..1fe51a11843 --- /dev/null +++ b/src/slices/home/pages/index/stats/useStatsHome.ts @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import useApiQuery from 'src/api/hooks/useApiQuery'; + +import useStatsQuery from 'src/slices/chain/stats/useStatsQuery'; + +import { HOMEPAGE_STATS_MICROSERVICE } from 'src/features/chain-stats/stubs/home'; + +import config from 'src/config'; + +const isStatsFeatureEnabled = config.features.stats.isEnabled; + +export default function useStatsHome() { + const statsApiQuery = useApiQuery('stats:pages_main', { + queryOptions: { + refetchOnMount: false, + placeholderData: isStatsFeatureEnabled ? HOMEPAGE_STATS_MICROSERVICE : undefined, + enabled: isStatsFeatureEnabled, + refetchInterval: (query) => { + if (query.state.status === 'error') { + return false; + } + + return config.apis.stats?.refetchInterval?.[ 'stats:pages_main' ]; + }, + }, + }); + + const coreApiQuery = useStatsQuery(); + + return React.useMemo(() => { + return { + coreApiQuery: coreApiQuery, + statsApiQuery: statsApiQuery, + }; + }, [ statsApiQuery, coreApiQuery ]); +} diff --git a/src/slices/home/pages/index/stats/utils.ts b/src/slices/home/pages/index/stats/utils.ts new file mode 100644 index 00000000000..775c7fb5425 --- /dev/null +++ b/src/slices/home/pages/index/stats/utils.ts @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { UseQueryResult } from '@tanstack/react-query'; + +import type { schemas } from '@blockscout/api-types'; +import type { MainPageStats } from '@blockscout/stats-types'; + +import config from 'src/config'; + +const isStatsFeatureEnabled = config.features.stats.isEnabled; +const rollupFeature = config.features.rollup; + +export const RPC_TOOLTIP_CONTENT_VALUE = 'Our indexer is experiencing problems, you see the data directly from RPC'; +export const RPC_TOOLTIP_CONTENT_NO_VALUE = 'Our indexer is experiencing problems and we couldn\'t get this data directly from RPC'; + +type StatsHomeDataId = 'total_blocks' | +'average_block_time' | +'total_transactions' | +'total_operational_transactions' | +'op_stack_total_operational_transactions' | +'last_output_root_size' | +'total_addresses' | +'gas_prices' | +'rootstock_locked_btc' | +'celo_epoch_number'; + +export function getStatsHomeDataItem( + id: StatsHomeDataId, + coreApiQuery: UseQueryResult<schemas['StatsResponse'], unknown>, + statsApiQuery: UseQueryResult<MainPageStats, unknown>, +) { + const isLoading = (isStatsFeatureEnabled && statsApiQuery.isPlaceholderData) || coreApiQuery.isPlaceholderData; + const isError = coreApiQuery.isError && (!isStatsFeatureEnabled || (statsApiQuery.isError && !statsApiQuery.isRefetchError)); + + switch (id) { + case 'total_blocks': + return { + id, + data: statsApiQuery.data?.total_blocks?.value ?? coreApiQuery.data?.total_blocks, + title: statsApiQuery.data?.total_blocks?.title, + isLoading, + isError, + }; + case 'average_block_time': + return { + id, + data: statsApiQuery.data?.average_block_time?.value ?? + (coreApiQuery.data?.average_block_time ? coreApiQuery.data.average_block_time / 1000 : undefined), + title: statsApiQuery.data?.average_block_time?.title, + isLoading, + isError, + }; + case 'total_transactions': + return { + id, + data: statsApiQuery.data?.total_transactions?.value ?? coreApiQuery.data?.total_transactions, + title: statsApiQuery.data?.total_transactions?.title, + isLoading, + isError, + }; + case 'total_operational_transactions': { + if (!rollupFeature.isEnabled) { + return null; + } + + if (rollupFeature.type === 'optimistic') { + return { + id, + data: statsApiQuery.data?.op_stack_total_operational_transactions?.value, + title: statsApiQuery.data?.op_stack_total_operational_transactions?.title, + isLoading: statsApiQuery.isPlaceholderData, + isError: statsApiQuery.isError, + }; + } + + return { + id, + data: statsApiQuery.data?.total_operational_transactions?.value, + title: statsApiQuery.data?.total_operational_transactions?.title, + isLoading: statsApiQuery.isPlaceholderData, + isError: statsApiQuery.isError, + }; + } + case 'last_output_root_size': + return { + id, + data: coreApiQuery.data?.last_output_root_size, + isLoading: coreApiQuery.isPlaceholderData, + isError: coreApiQuery.isError, + }; + case 'total_addresses': + return { + id, + data: statsApiQuery.data?.total_addresses?.value ?? coreApiQuery.data?.total_addresses, + title: statsApiQuery.data?.total_addresses?.title, + isLoading, + isError, + }; + case 'gas_prices': + return { + id, + data: { + gas_prices: coreApiQuery.data?.gas_prices, + gas_price_updated_at: coreApiQuery.data?.gas_price_updated_at, + gas_prices_update_in: coreApiQuery.data?.gas_prices_update_in, + }, + isLoading: coreApiQuery.isPlaceholderData, + isError: coreApiQuery.isError, + dataUpdatedAt: coreApiQuery.dataUpdatedAt, + isRefetchError: coreApiQuery.isRefetchError, + }; + case 'rootstock_locked_btc': + return { + id, + data: coreApiQuery.data?.rootstock_locked_btc, + isLoading: coreApiQuery.isPlaceholderData, + isError: coreApiQuery.isError, + }; + case 'celo_epoch_number': + return { + id, + data: coreApiQuery.data?.celo?.epoch_number, + isLoading: coreApiQuery.isPlaceholderData, + isError: coreApiQuery.isError, + }; + default: + return null; + } +} diff --git a/src/slices/home/pages/index/stats/widgets/HomeStatsAverageBlockTime.tsx b/src/slices/home/pages/index/stats/widgets/HomeStatsAverageBlockTime.tsx new file mode 100644 index 00000000000..d97ebc3be45 --- /dev/null +++ b/src/slices/home/pages/index/stats/widgets/HomeStatsAverageBlockTime.tsx @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { useHomeRpcDataContext } from 'src/slices/home/contexts/rpc-data-context'; + +import dayjs from 'src/shared/date-and-time/dayjs'; + +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import HomeStatsWidget from '../HomeStatsWidget'; +import useStatsHome from '../useStatsHome'; +import { getStatsHomeDataItem, RPC_TOOLTIP_CONTENT_NO_VALUE, RPC_TOOLTIP_CONTENT_VALUE } from '../utils'; + +const HomeStatsAverageBlockTime = () => { + + const [ rpcData, setRpcData ] = React.useState<number | undefined>(undefined); + + const { coreApiQuery, statsApiQuery } = useStatsHome(); + const itemQuery = getStatsHomeDataItem('average_block_time', coreApiQuery, statsApiQuery); + const { enable: enableRpcData, blocks: blocksRpc, isLoading: isLoadingRpc } = useHomeRpcDataContext(); + + const isError = itemQuery?.isError; + + React.useEffect(() => { + if (isError) { + enableRpcData(true, 'stats-widgets-average-block-time'); + } + return () => { + enableRpcData(false, 'stats-widgets-average-block-time'); + }; + }, [ isError, enableRpcData ]); + + React.useEffect(() => { + if (blocksRpc.length > 1) { + const timeDiffs = blocksRpc + .map((block, index) => { + if (index > 0) { + return dayjs(blocksRpc[index - 1].timestamp).diff(dayjs(block.timestamp), 'seconds'); + } + return 0; + }) + .slice(1); + const totalDiff = timeDiffs.reduce((acc, diff) => acc + diff, 0); + setRpcData((prev) => { + if (prev === undefined) { + return totalDiff / timeDiffs.length; + } + return (prev + totalDiff) / (timeDiffs.length + 1); + }); + } + }, [ blocksRpc ]); + + if (!itemQuery || itemQuery.id !== 'average_block_time') { + return null; + } + + const isLoading = itemQuery.isLoading || (isError && isLoadingRpc); + + const value = (() => { + if (isError) { + return rpcData ? `${ rpcData.toFixed(1) }s` : mdash; + } + if (itemQuery.data) { + return `${ Number(itemQuery.data).toFixed(1) }s`; + } + })(); + + if (!value) { + return null; + } + + const isRpcData = isError && !isLoadingRpc; + + return ( + <Tooltip + content={ value !== mdash ? RPC_TOOLTIP_CONTENT_VALUE : RPC_TOOLTIP_CONTENT_NO_VALUE } + disabled={ !isRpcData } + > + <HomeStatsWidget + label={ itemQuery.title || 'Average block time' } + icon="clock-light" + value={ value } + isLoading={ isLoading } + isFallback={ isRpcData && value === mdash } + /> + </Tooltip> + ); +}; + +export default React.memo(HomeStatsAverageBlockTime); diff --git a/src/slices/home/pages/index/stats/widgets/HomeStatsBtcLocked.tsx b/src/slices/home/pages/index/stats/widgets/HomeStatsBtcLocked.tsx new file mode 100644 index 00000000000..be5fa65331a --- /dev/null +++ b/src/slices/home/pages/index/stats/widgets/HomeStatsBtcLocked.tsx @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import BigNumber from 'bignumber.js'; +import React from 'react'; + +import { WEI } from 'src/shared/values/entity/utils'; + +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import HomeStatsWidget from '../HomeStatsWidget'; +import useStatsHome from '../useStatsHome'; +import { getStatsHomeDataItem, RPC_TOOLTIP_CONTENT_NO_VALUE } from '../utils'; + +const HomeStatsBtcLocked = () => { + const { coreApiQuery, statsApiQuery } = useStatsHome(); + const itemQuery = getStatsHomeDataItem('rootstock_locked_btc', coreApiQuery, statsApiQuery); + + if (!itemQuery || itemQuery.id !== 'rootstock_locked_btc') { + return null; + } + + const value = (() => { + if (itemQuery.isError) { + return mdash; + } + + if (typeof itemQuery.data !== 'string') { + return; + } + return `${ BigNumber(itemQuery.data ?? 0).div(WEI).dp(0).toFormat() } RBTC`; + })(); + + if (!value) { + return null; + } + + return ( + <Tooltip + content={ RPC_TOOLTIP_CONTENT_NO_VALUE } + disabled={ !itemQuery.isError } + > + <HomeStatsWidget + label="BTC Locked in 2WP" + icon="coins/bitcoin" + value={ value } + isLoading={ itemQuery.isLoading } + isFallback={ itemQuery.isError } + /> + </Tooltip> + ); +}; + +export default React.memo(HomeStatsBtcLocked); diff --git a/src/slices/home/pages/index/stats/widgets/HomeStatsCurrentEpoch.tsx b/src/slices/home/pages/index/stats/widgets/HomeStatsCurrentEpoch.tsx new file mode 100644 index 00000000000..7c0b0d41e3d --- /dev/null +++ b/src/slices/home/pages/index/stats/widgets/HomeStatsCurrentEpoch.tsx @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import HomeStatsWidget from '../HomeStatsWidget'; +import useStatsHome from '../useStatsHome'; +import { getStatsHomeDataItem, RPC_TOOLTIP_CONTENT_NO_VALUE } from '../utils'; + +const HomeStatsCurrentEpoch = () => { + const { coreApiQuery, statsApiQuery } = useStatsHome(); + const itemQuery = getStatsHomeDataItem('celo_epoch_number', coreApiQuery, statsApiQuery); + + if (!itemQuery || itemQuery.id !== 'celo_epoch_number') { + return null; + } + + const value = (() => { + if (itemQuery.isError) { + return mdash; + } + if (typeof itemQuery.data !== 'number') { + return; + } + return `#${ itemQuery.data }`; + })(); + + if (!value) { + return null; + } + + return ( + <Tooltip + content={ RPC_TOOLTIP_CONTENT_NO_VALUE } + disabled={ !itemQuery.isError } + > + <HomeStatsWidget + label="Current epoch" + icon="hourglass" + value={ value } + href={{ pathname: '/epochs/[number]' as const, query: { number: String(itemQuery.data ?? 0) } }} + isLoading={ itemQuery.isLoading } + isFallback={ itemQuery.isError } + /> + </Tooltip> + ); +}; + +export default React.memo(HomeStatsCurrentEpoch); diff --git a/src/slices/home/pages/index/stats/widgets/HomeStatsGasTracker.tsx b/src/slices/home/pages/index/stats/widgets/HomeStatsGasTracker.tsx new file mode 100644 index 00000000000..a13ee434676 --- /dev/null +++ b/src/slices/home/pages/index/stats/widgets/HomeStatsGasTracker.tsx @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { useQuery } from '@tanstack/react-query'; +import BigNumber from 'bignumber.js'; +import React from 'react'; + +import GasInfoTooltip from 'src/slices/gas/components/GasInfoTooltip'; +import GasPrice from 'src/slices/gas/components/GasPrice'; +import discriminateDetailedPrices from 'src/slices/gas/utils/price'; + +import { getPublicClient, isPublicClientAvailable } from 'src/features/connect-wallet/utils/public-client'; + +import { GWEI } from 'src/shared/values/entity/utils'; +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import HomeStatsWidget from '../HomeStatsWidget'; +import useStatsHome from '../useStatsHome'; +import { getStatsHomeDataItem, RPC_TOOLTIP_CONTENT_NO_VALUE, RPC_TOOLTIP_CONTENT_VALUE } from '../utils'; + +const HomeStatsGasTracker = () => { + const { coreApiQuery, statsApiQuery } = useStatsHome(); + const itemQuery = getStatsHomeDataItem('gas_prices', coreApiQuery, statsApiQuery); + + const isRpcEnabled = isPublicClientAvailable && itemQuery?.isError; + + const rpcQuery = useQuery({ + queryKey: [ 'RPC', 'gas-price' ], + queryFn: async() => { + const publicClient = await getPublicClient(); + if (!publicClient) { + return null; + } + return publicClient.getGasPrice(); + }, + select: (data) => { + if (!data) { + return null; + } + const price = BigNumber(data.toString()).div(GWEI).toNumber(); + return { + price, + fiat_price: null, + time: null, + base_fee: null, + priority_fee: null, + priority_fee_wei: null, + wei: null, + }; + }, + enabled: isRpcEnabled, + }); + + const isLoading = itemQuery?.isLoading || (isRpcEnabled && rpcQuery.isLoading); + + const gasPricesData = React.useMemo(() => { + if (itemQuery?.id === 'gas_prices' && itemQuery?.data && itemQuery.data.gas_prices && itemQuery.data.gas_prices.average) { + return { + gas_prices: itemQuery.data.gas_prices, + gas_price_updated_at: itemQuery.data.gas_price_updated_at ?? null, + gas_prices_update_in: itemQuery.data.gas_prices_update_in ?? null, + }; + } + }, [ itemQuery?.data, itemQuery?.id ]); + + const infoTooltip = !isRpcEnabled && gasPricesData && itemQuery?.dataUpdatedAt ? ( + <GasInfoTooltip data={ gasPricesData } dataUpdatedAt={ itemQuery.dataUpdatedAt }> + <SpriteIcon + isLoading={ itemQuery.isLoading } + name="info" + boxSize={ 5 } + flexShrink={ 0 } + cursor="pointer" + color="icon.secondary" + _hover={{ color: 'hover' }} + /> + </GasInfoTooltip> + ) : null; + + const value = (() => { + if (isRpcEnabled) { + return rpcQuery.data ? <GasPrice data={ rpcQuery.data }/> : mdash; + } + const gasPrices = itemQuery?.id === 'gas_prices' && itemQuery?.data && itemQuery.data.gas_prices ? + discriminateDetailedPrices(itemQuery.data.gas_prices) : + null; + if (!gasPrices) { + return; + } + return gasPrices.average ? <GasPrice data={ gasPrices.average }/> : mdash; + })(); + + if (!value) { + return null; + } + + const isRpcData = isRpcEnabled && !rpcQuery.isLoading; + + return ( + <Tooltip + content={ value !== mdash ? RPC_TOOLTIP_CONTENT_VALUE : RPC_TOOLTIP_CONTENT_NO_VALUE } + disabled={ !isRpcData } + > + <HomeStatsWidget + label="Gas tracker" + icon="gas" + value={ value } + href={{ pathname: '/gas-tracker' }} + hint={ infoTooltip } + isLoading={ isLoading } + isFallback={ value === mdash } + /> + </Tooltip> + ); +}; + +export default React.memo(HomeStatsGasTracker); diff --git a/src/slices/home/pages/index/stats/widgets/HomeStatsLatestBatch.tsx b/src/slices/home/pages/index/stats/widgets/HomeStatsLatestBatch.tsx new file mode 100644 index 00000000000..baea066d4ae --- /dev/null +++ b/src/slices/home/pages/index/stats/widgets/HomeStatsLatestBatch.tsx @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { useHomeDataContext } from 'src/slices/home/contexts/home-data-context'; + +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import HomeStatsWidget from '../HomeStatsWidget'; +import { RPC_TOOLTIP_CONTENT_NO_VALUE } from '../utils'; + +const HomeStatsLatestBatch = () => { + const { latestBatchQuery } = useHomeDataContext(); + + if (!latestBatchQuery) { + return null; + } + + const value = (() => { + if (latestBatchQuery.isError) { + return mdash; + } + if (latestBatchQuery.data) { + return Number(latestBatchQuery.data).toLocaleString(); + } + })(); + + if (!value) { + return null; + } + + const isFallback = latestBatchQuery.isError; + + return ( + <Tooltip + content={ RPC_TOOLTIP_CONTENT_NO_VALUE } + disabled={ !isFallback } + > + <HomeStatsWidget + label="Latest batch" + icon="txn_batches" + value={ value } + href={{ pathname: '/batches' as const }} + isLoading={ latestBatchQuery.isPlaceholderData } + isFallback={ isFallback } + /> + </Tooltip> + ); +}; + +export default React.memo(HomeStatsLatestBatch); diff --git a/src/slices/home/pages/index/stats/widgets/HomeStatsLatestBlock.tsx b/src/slices/home/pages/index/stats/widgets/HomeStatsLatestBlock.tsx new file mode 100644 index 00000000000..13803c69183 --- /dev/null +++ b/src/slices/home/pages/index/stats/widgets/HomeStatsLatestBlock.tsx @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { useHomeDataContext } from 'src/slices/home/contexts/home-data-context'; +import { useHomeRpcDataContext } from 'src/slices/home/contexts/rpc-data-context'; + +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import HomeStatsWidget from '../HomeStatsWidget'; +import useStatsHome from '../useStatsHome'; +import { getStatsHomeDataItem, RPC_TOOLTIP_CONTENT_NO_VALUE, RPC_TOOLTIP_CONTENT_VALUE } from '../utils'; + +const HomeStatsLatestBlock = () => { + + const { coreApiQuery, statsApiQuery } = useStatsHome(); + const itemQuery = getStatsHomeDataItem('total_blocks', coreApiQuery, statsApiQuery); + + const { blocksQuery } = useHomeDataContext(); + const { enable: enableRpcData, blocks: blocksRpc, isLoading: isLoadingRpc } = useHomeRpcDataContext(); + + const isError = blocksQuery?.isError && itemQuery?.isError; + const isLoading = blocksQuery?.isPlaceholderData || itemQuery?.isLoading || (isError && isLoadingRpc); + + React.useEffect(() => { + if (isError) { + enableRpcData(true, 'stats-widgets-latest-block'); + } + return () => { + enableRpcData(false, 'stats-widgets-latest-block'); + }; + }, [ isError, enableRpcData ]); + + const value = (() => { + if (isError) { + return blocksRpc[0] ? blocksRpc[0].height.toLocaleString() : mdash; + } + const latestBlock = blocksQuery?.data?.[0]?.height ?? + (itemQuery?.id === 'total_blocks' && itemQuery?.data ? itemQuery.data : undefined); + if (latestBlock !== undefined) { + return Number(latestBlock).toLocaleString(); + } + })(); + + if (!value) { + return null; + } + + const label = (() => { + if (blocksQuery?.data?.[0]?.height !== undefined || isError) { + return 'Latest block'; + } + if (itemQuery?.id === 'total_blocks' && itemQuery?.title) { + return itemQuery.title; + } + return 'Total blocks'; + })(); + + const isRpcData = isError && !isLoadingRpc; + + return ( + <Tooltip + content={ value !== mdash ? RPC_TOOLTIP_CONTENT_VALUE : RPC_TOOLTIP_CONTENT_NO_VALUE } + disabled={ !isRpcData } + > + <HomeStatsWidget + label={ label } + icon="block" + value={ value } + href={{ pathname: '/blocks' }} + isLoading={ isLoading } + isFallback={ isRpcData && value === mdash } + /> + </Tooltip> + ); +}; + +export default React.memo(HomeStatsLatestBlock); diff --git a/src/slices/home/pages/index/stats/widgets/HomeStatsLatestL1StateBatch.tsx b/src/slices/home/pages/index/stats/widgets/HomeStatsLatestL1StateBatch.tsx new file mode 100644 index 00000000000..27e62c9904c --- /dev/null +++ b/src/slices/home/pages/index/stats/widgets/HomeStatsLatestL1StateBatch.tsx @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { layerLabels } from 'src/features/rollup/common/utils/layer'; + +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import HomeStatsWidget from '../HomeStatsWidget'; +import useStatsHome from '../useStatsHome'; +import { getStatsHomeDataItem, RPC_TOOLTIP_CONTENT_NO_VALUE } from '../utils'; + +const HomeStatsLatestL1StateBatch = () => { + const { coreApiQuery, statsApiQuery } = useStatsHome(); + const itemQuery = getStatsHomeDataItem('last_output_root_size', coreApiQuery, statsApiQuery); + + if (!itemQuery || itemQuery.id !== 'last_output_root_size') { + return null; + } + + const value = (() => { + if (itemQuery.isError) { + return mdash; + } + if (itemQuery.data) { + return Number(itemQuery.data).toLocaleString(); + } + })(); + + if (!value) { + return null; + } + + return ( + <Tooltip + content={ RPC_TOOLTIP_CONTENT_NO_VALUE } + disabled={ !itemQuery.isError } + > + <HomeStatsWidget + label={ `Latest ${ layerLabels.parent } state batch` } + icon="txn_batches" + value={ value } + href={{ pathname: '/batches' as const }} + isLoading={ itemQuery.isLoading } + isFallback={ itemQuery.isError } + /> + </Tooltip> + ); +}; + +export default React.memo(HomeStatsLatestL1StateBatch); diff --git a/src/slices/home/pages/index/stats/widgets/HomeStatsTotalAddresses.tsx b/src/slices/home/pages/index/stats/widgets/HomeStatsTotalAddresses.tsx new file mode 100644 index 00000000000..9548615f842 --- /dev/null +++ b/src/slices/home/pages/index/stats/widgets/HomeStatsTotalAddresses.tsx @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import HomeStatsWidget from '../HomeStatsWidget'; +import useStatsHome from '../useStatsHome'; +import { getStatsHomeDataItem, RPC_TOOLTIP_CONTENT_NO_VALUE } from '../utils'; + +const HomeStatsTotalAddresses = () => { + const { coreApiQuery, statsApiQuery } = useStatsHome(); + const itemQuery = getStatsHomeDataItem('total_addresses', coreApiQuery, statsApiQuery); + + if (!itemQuery || itemQuery.id !== 'total_addresses') { + return null; + } + + const value = (() => { + if (itemQuery.isError) { + return mdash; + } + if (itemQuery.data) { + return Number(itemQuery.data).toLocaleString(); + } + })(); + + if (!value) { + return null; + } + + return ( + <Tooltip + content={ RPC_TOOLTIP_CONTENT_NO_VALUE } + disabled={ !itemQuery.isError } + > + <HomeStatsWidget + label={ itemQuery.title || 'Wallet addresses' } + icon="wallet" + value={ value } + isLoading={ itemQuery.isLoading } + isFallback={ itemQuery.isError } + /> + </Tooltip> + ); +}; + +export default React.memo(HomeStatsTotalAddresses); diff --git a/src/slices/home/pages/index/stats/widgets/HomeStatsTotalOperationalTxs.tsx b/src/slices/home/pages/index/stats/widgets/HomeStatsTotalOperationalTxs.tsx new file mode 100644 index 00000000000..60e24984491 --- /dev/null +++ b/src/slices/home/pages/index/stats/widgets/HomeStatsTotalOperationalTxs.tsx @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import config from 'src/config'; + +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import HomeStatsWidget from '../HomeStatsWidget'; +import useStatsHome from '../useStatsHome'; +import { getStatsHomeDataItem, RPC_TOOLTIP_CONTENT_NO_VALUE } from '../utils'; + +const rollupFeature = config.features.rollup; + +const HomeStatsTotalOperationalTxs = () => { + const { coreApiQuery, statsApiQuery } = useStatsHome(); + const itemQuery = getStatsHomeDataItem('total_operational_transactions', coreApiQuery, statsApiQuery); + + if (!rollupFeature.isEnabled || !(rollupFeature.type === 'arbitrum' || rollupFeature.type === 'optimistic')) { + return null; + } + + if (!itemQuery) { + return null; + } + + const value = (() => { + if (itemQuery.isError) { + return mdash; + } + if ((rollupFeature.type === 'arbitrum' || rollupFeature.type === 'optimistic') && itemQuery.id === 'total_operational_transactions' && itemQuery.data) { + return Number(itemQuery.data).toLocaleString(); + } + })(); + + if (!value) { + return null; + } + + const label = (() => { + if ((rollupFeature.type === 'arbitrum' || rollupFeature.type === 'optimistic') && itemQuery.id === 'total_operational_transactions') { + return itemQuery.title; + } + })(); + + return ( + <Tooltip + content={ RPC_TOOLTIP_CONTENT_NO_VALUE } + disabled={ !itemQuery.isError } + > + <HomeStatsWidget + label={ label || 'Total operational transactions' } + icon="transactions" + value={ value } + href={{ pathname: '/txs' as const }} + isLoading={ itemQuery.isLoading } + isFallback={ itemQuery.isError } + /> + </Tooltip> + ); +}; + +export default React.memo(HomeStatsTotalOperationalTxs); diff --git a/src/slices/home/pages/index/stats/widgets/HomeStatsTotalTxs.tsx b/src/slices/home/pages/index/stats/widgets/HomeStatsTotalTxs.tsx new file mode 100644 index 00000000000..26abe48aaf0 --- /dev/null +++ b/src/slices/home/pages/index/stats/widgets/HomeStatsTotalTxs.tsx @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import { Tooltip } from 'src/toolkit/chakra/tooltip'; +import { mdash } from 'src/toolkit/utils/htmlEntities'; + +import HomeStatsWidget from '../HomeStatsWidget'; +import useStatsHome from '../useStatsHome'; +import { getStatsHomeDataItem, RPC_TOOLTIP_CONTENT_NO_VALUE } from '../utils'; + +const HomeStatsTotalTxs = () => { + const { coreApiQuery, statsApiQuery } = useStatsHome(); + const itemQuery = getStatsHomeDataItem('total_transactions', coreApiQuery, statsApiQuery); + + if (!itemQuery || itemQuery.id !== 'total_transactions') { + return null; + } + + const value = (() => { + if (itemQuery.isError) { + return mdash; + } + if (itemQuery.data) { + return Number(itemQuery.data).toLocaleString(); + } + })(); + + if (!value) { + return null; + } + + return ( + <Tooltip + content={ RPC_TOOLTIP_CONTENT_NO_VALUE } + disabled={ !itemQuery.isError } + > + <HomeStatsWidget + label={ itemQuery.title || 'Total transactions' } + icon="transactions" + value={ value } + href={{ pathname: '/txs' as const }} + isLoading={ itemQuery.isLoading } + isFallback={ itemQuery.isError } + /> + </Tooltip> + ); +}; + +export default React.memo(HomeStatsTotalTxs); diff --git a/src/slices/home/pages/index/txs/LatestTxs.pw.tsx b/src/slices/home/pages/index/txs/LatestTxs.pw.tsx index 322222e171c..88bd5e0c959 100644 --- a/src/slices/home/pages/index/txs/LatestTxs.pw.tsx +++ b/src/slices/home/pages/index/txs/LatestTxs.pw.tsx @@ -6,7 +6,7 @@ import type { schemas } from '@blockscout/api-types'; import * as txMock from 'src/slices/tx/mocks/list'; import * as socketServer from 'playwright/fixtures/socketServer'; -import { test as base, expect, devices } from 'playwright/lib'; +import { test as base, expect } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; import LatestTxs from './LatestTxs'; @@ -15,21 +15,6 @@ export const test = base.extend<socketServer.SocketServerFixture>({ createSocket: socketServer.createSocket, }); -test.describe('mobile', () => { - test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - test('default view', async({ render, mockApiResponse }) => { - await mockApiResponse('core:homepage_txs', [ - txMock.base, - txMock.withContractCreation, - txMock.withTokenTransfer, - txMock.withWatchListNames, - ]); - - const component = await render(<LatestTxs/>); - await expect(component).toHaveScreenshot(); - }); -}); - test('default view +@dark-mode', async({ render, mockApiResponse }) => { await mockApiResponse('core:homepage_txs', [ txMock.base, diff --git a/src/slices/home/pages/index/txs/LatestTxs.tsx b/src/slices/home/pages/index/txs/LatestTxs.tsx index 362a841994d..00db0d103ab 100644 --- a/src/slices/home/pages/index/txs/LatestTxs.tsx +++ b/src/slices/home/pages/index/txs/LatestTxs.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, Flex, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -12,19 +11,18 @@ import useNewTxsSocket from 'src/slices/tx/hooks/useTxsSocketTypeAll'; import { TX } from 'src/slices/tx/stubs/tx'; import config from 'src/config'; -import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; +import { TableBody, TableContainerScrollable, TableRoot } from 'src/toolkit/chakra/table'; import LatestTxsDegraded from './LatestTxsDegraded'; -import LatestTxsItem from './LatestTxsItem'; -import LatestTxsItemMobile from './LatestTxsItemMobile'; +import LatestTxsItem, { LATEST_TXS_TABLE_MIN_WIDTH } from './LatestTxsItem'; const zetachainFeature = config.features.zetachain; const LatestTxs = () => { - const isMobile = useIsMobile(); - const txsCount = isMobile ? 2 : 5; + const txsCount = 5; const { data, isPlaceholderData, isError } = useApiQuery('core:homepage_txs', { queryOptions: { placeholderData: Array(txsCount).fill(TX), @@ -41,25 +39,29 @@ const LatestTxs = () => { const txsUrl = route({ pathname: `/txs`, query: zetachainFeature.isEnabled ? { tab: 'evm' } : undefined }); return ( <> - <SocketNewItemsNotice borderBottomRadius={ 0 } url={ txsUrl } num={ num } showErrorAlert={ showErrorAlert } isLoading={ isPlaceholderData }/> - <Box mb={ 3 } display={{ base: 'block', lg: 'none' }} textStyle="sm"> - { data.slice(0, txsCount).map(((tx, index) => ( - <LatestTxsItemMobile - key={ tx.hash + (isPlaceholderData ? index : '') } - tx={ tx } - isLoading={ isPlaceholderData } - /> - ))) } - </Box> <AddressHighlightProvider> - <Box mb={ 3 } display={{ base: 'none', lg: 'block' }} textStyle="sm"> - { data.slice(0, txsCount).map(((tx, index) => ( - <LatestTxsItem - key={ tx.hash + (isPlaceholderData ? index : '') } - tx={ tx } + <Box mb={ 3 } textStyle="sm"> + <TableContainerScrollable> + <SocketNewItemsNotice + borderBottomRadius={ 0 } + minW={ LATEST_TXS_TABLE_MIN_WIDTH } + url={ txsUrl } + num={ num } + showErrorAlert={ showErrorAlert } isLoading={ isPlaceholderData } /> - ))) } + <TableRoot minW={ LATEST_TXS_TABLE_MIN_WIDTH }> + <TableBody> + { data.slice(0, txsCount).map(((tx, index) => ( + <LatestTxsItem + key={ tx.hash + (isPlaceholderData ? index : '') } + tx={ tx } + isLoading={ isPlaceholderData } + /> + ))) } + </TableBody> + </TableRoot> + </TableContainerScrollable> </Box> </AddressHighlightProvider> <Flex justifyContent="center"> diff --git a/src/slices/home/pages/index/txs/LatestTxsDegraded.spec.tsx b/src/slices/home/pages/index/txs/LatestTxsDegraded.spec.tsx new file mode 100644 index 00000000000..94cb70fd8f2 --- /dev/null +++ b/src/slices/home/pages/index/txs/LatestTxsDegraded.spec.tsx @@ -0,0 +1,101 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import { rpcBlockWithTxsInfo } from 'src/slices/block/mocks/rpc'; +import { HomeRpcDataContextProvider } from 'src/slices/home/contexts/rpc-data-context'; +import { rpcTxReceipt } from 'src/slices/tx/mocks/rpc'; + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor } from 'vitest/lib'; +import flushPromises from 'vitest/utils/flushPromises'; +import { mockApiAndRpc, rpcRequests } from 'vitest/utils/mockJsonRpc'; + +import LatestBlocksDegraded from '../blocks/LatestBlocksDegraded'; +import LatestTxsDegraded from './LatestTxsDegraded'; + +const RPC_TX_HASH = '0xae5624c77f06d0164301380afa7780ebe49debe77eb3d5167004d69bd188a09f'; + +const RPC_NODE = { + eth_getBlockByNumber: rpcBlockWithTxsInfo, + eth_getTransactionReceipt: { ...rpcTxReceipt, transactionHash: RPC_TX_HASH }, +}; + +const EMPTY_MESSAGE = 'No latest transactions found.'; + +beforeEach(() => { + fetchMock.resetMocks(); + mockApiAndRpc({ api: () => undefined, rpc: RPC_NODE }); +}); + +afterEach(() => { + cleanup(); +}); + +describe('LatestTxsDegraded', () => { + it('shows transactions from the RPC node when it is the only widget in degraded mode', async() => { + render( + <HomeRpcDataContextProvider> + <LatestTxsDegraded maxNum={ 5 }/> + </HomeRpcDataContextProvider>, + ); + + expect(await screen.findAllByText(RPC_TX_HASH)).not.toHaveLength(0); + expect(screen.queryByText(EMPTY_MESSAGE)).toBeNull(); + }); + + it('shows transactions from the RPC node when the widget remounts', async() => { + render( + <React.StrictMode> + <HomeRpcDataContextProvider> + <LatestTxsDegraded maxNum={ 5 }/> + </HomeRpcDataContextProvider> + </React.StrictMode>, + ); + + expect(await screen.findAllByText(RPC_TX_HASH)).not.toHaveLength(0); + expect(screen.queryByText(EMPTY_MESSAGE)).toBeNull(); + }); + + it('marks a reverted transaction as failed', async() => { + mockApiAndRpc({ + api: () => undefined, + rpc: { ...RPC_NODE, eth_getTransactionReceipt: { ...RPC_NODE.eth_getTransactionReceipt, status: '0x0' } }, + }); + + render( + <HomeRpcDataContextProvider> + <LatestTxsDegraded maxNum={ 5 }/> + </HomeRpcDataContextProvider>, + ); + + expect(await screen.findAllByText('Failed')).not.toHaveLength(0); + }); + + it('shows no failed status for a successful transaction', async() => { + render( + <HomeRpcDataContextProvider> + <LatestTxsDegraded maxNum={ 5 }/> + </HomeRpcDataContextProvider>, + ); + + await screen.findAllByText(RPC_TX_HASH); + await waitFor(() => expect(rpcRequests()).toContain('eth_getTransactionReceipt')); + await flushPromises(); + + expect(screen.queryByText('Failed')).toBeNull(); + }); + + it('never shows the empty message while waiting for the first block', async() => { + render( + <HomeRpcDataContextProvider> + <LatestTxsDegraded maxNum={ 5 }/> + <LatestBlocksDegraded maxNum={ 5 }/> + </HomeRpcDataContextProvider>, + ); + + expect(screen.queryByText(EMPTY_MESSAGE)).toBeNull(); + await screen.findAllByText(RPC_TX_HASH); + expect(screen.queryByText(EMPTY_MESSAGE)).toBeNull(); + }); +}); diff --git a/src/slices/home/pages/index/txs/LatestTxsDegraded.tsx b/src/slices/home/pages/index/txs/LatestTxsDegraded.tsx index 5e13db01ad8..5b30b8004df 100644 --- a/src/slices/home/pages/index/txs/LatestTxsDegraded.tsx +++ b/src/slices/home/pages/index/txs/LatestTxsDegraded.tsx @@ -2,9 +2,10 @@ import { Box, Flex } from '@chakra-ui/react'; import { clamp } from 'es-toolkit'; -import { route } from 'nextjs-routes'; import React from 'react'; +import type { schemas } from '@blockscout/api-types'; + import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; import { useHomeRpcDataContext } from 'src/slices/home/contexts/rpc-data-context'; import { TX } from 'src/slices/tx/stubs/tx'; @@ -12,13 +13,15 @@ import { TX } from 'src/slices/tx/stubs/tx'; import { isPublicClientAvailable } from 'src/features/connect-wallet/utils/public-client'; import config from 'src/config'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; +import { TableBody, TableContainerScrollable, TableRoot } from 'src/toolkit/chakra/table'; import LatestTxsDegradedNewItems from './LatestTxsDegradedNewItems'; import LatestTxsFallback from './LatestTxsFallback'; -import LatestTxsItem from './LatestTxsItem'; -import LatestTxsItemMobile from './LatestTxsItemMobile'; +import LatestTxsItem, { LATEST_TXS_TABLE_MIN_WIDTH } from './LatestTxsItem'; const zetachainFeature = config.features.zetachain; @@ -26,6 +29,8 @@ interface Props { maxNum: number; } +const getBaseKey = (tx: schemas['Transaction']): string => tx.hash; + const LatestTxsDegraded = ({ maxNum }: Props) => { const { txs, totalTxs, isError, isLoading, enable } = useHomeRpcDataContext(); @@ -36,12 +41,13 @@ const LatestTxsDegraded = ({ maxNum }: Props) => { }; }, [ enable ]); + const items = React.useMemo(() => isLoading ? Array(maxNum).fill(TX) : txs.slice(0, maxNum), [ isLoading, maxNum, txs ]); + const keys = useUniqueKeys(items, getBaseKey); + if (isError || !isPublicClientAvailable) { return <LatestTxsFallback/>; } - const items = isLoading ? Array(maxNum).fill(TX) : txs.slice(0, maxNum); - if (items.length === 0) { return <Box textStyle="sm">No latest transactions found.</Box>; } @@ -51,25 +57,22 @@ const LatestTxsDegraded = ({ maxNum }: Props) => { return ( <> - <LatestTxsDegradedNewItems overflow={ overflow } url={ txsUrl } isLoading={ isLoading }/> - <Box mb={ 3 } display={{ base: 'block', lg: 'none' }} textStyle="sm"> - { items.map(((tx, index) => ( - <LatestTxsItemMobile - key={ tx.hash + (isLoading ? index : '') } - tx={ tx } - isLoading={ isLoading } - /> - ))) } - </Box> <AddressHighlightProvider> - <Box mb={ 3 } display={{ base: 'none', lg: 'block' }} textStyle="sm"> - { items.map(((tx, index) => ( - <LatestTxsItem - key={ tx.hash + (isLoading ? index : '') } - tx={ tx } - isLoading={ isLoading } - /> - ))) } + <Box mb={ 3 } textStyle="sm"> + <TableContainerScrollable> + <LatestTxsDegradedNewItems overflow={ overflow } url={ txsUrl } isLoading={ isLoading }/> + <TableRoot minW={ LATEST_TXS_TABLE_MIN_WIDTH }> + <TableBody> + { items.map(((tx, index) => ( + <LatestTxsItem + key={ keys[index] } + tx={ tx } + isLoading={ isLoading } + /> + ))) } + </TableBody> + </TableRoot> + </TableContainerScrollable> </Box> </AddressHighlightProvider> <Flex justifyContent="center"> diff --git a/src/slices/home/pages/index/txs/LatestTxsDegradedNewItems.tsx b/src/slices/home/pages/index/txs/LatestTxsDegradedNewItems.tsx index 831d483661c..f61f5ede04c 100644 --- a/src/slices/home/pages/index/txs/LatestTxsDegradedNewItems.tsx +++ b/src/slices/home/pages/index/txs/LatestTxsDegradedNewItems.tsx @@ -6,6 +6,8 @@ import SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; import useGradualIncrement from 'src/shared/numbers/useGradualIncrement'; +import { LATEST_TXS_TABLE_MIN_WIDTH } from './LatestTxsItem'; + interface Props { overflow: number; url: string; @@ -21,7 +23,16 @@ const LatestTxsDegradedNewItems = ({ overflow, url, isLoading }: Props) => { } }, [ isLoading, overflow, setNum ]); - return <SocketNewItemsNotice borderBottomRadius={ 0 } num={ num } url={ url } showErrorAlert={ false } isLoading={ isLoading }/>; + return ( + <SocketNewItemsNotice + borderBottomRadius={ 0 } + minW={ LATEST_TXS_TABLE_MIN_WIDTH } + num={ num } + url={ url } + showErrorAlert={ false } + isLoading={ isLoading } + /> + ); }; export default React.memo(LatestTxsDegradedNewItems); diff --git a/src/slices/home/pages/index/txs/LatestTxsItem.tsx b/src/slices/home/pages/index/txs/LatestTxsItem.tsx index 6627a84a378..f44214ba289 100644 --- a/src/slices/home/pages/index/txs/LatestTxsItem.tsx +++ b/src/slices/home/pages/index/txs/LatestTxsItem.tsx @@ -1,11 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { - Box, Flex, HStack, Text, - Grid, + VStack, } from '@chakra-ui/react'; import React from 'react'; @@ -20,12 +19,18 @@ import TxType from 'src/slices/tx/components/TxType'; import TxWatchListTags from 'src/features/account/components/TxWatchListTags'; import MetadataTag from 'src/features/address-metadata/components/tag/MetadataTag'; +import { getVisibleProtocolTags } from 'src/features/address-metadata/utils/get-visible-protocol-tags'; import config from 'src/config'; import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableCell, TableRow } from 'src/toolkit/chakra/table'; + +const hasValueColumn = !(config.slices.tx.hiddenFields?.value && config.slices.tx.hiddenFields?.tx_fee); + +export const LATEST_TXS_TABLE_MIN_WIDTH = hasValueColumn ? '750px' : '700px'; interface Props { tx: schemas['Transaction']; @@ -34,9 +39,8 @@ interface Props { const LatestTxsItem = ({ tx, isLoading }: Props) => { const dataTo = tx.to ? tx.to : tx.created_contract; - const columnNum = config.slices.tx.hiddenFields?.value && config.slices.tx.hiddenFields?.tx_fee ? 2 : 3; - const protocolTag = tx.to?.metadata?.tags?.find(tag => tag.tagType === 'protocol'); + const protocolTag = getVisibleProtocolTags(tx.to?.metadata?.tags)[0]; const tagsCount = [ 1, // tx type @@ -47,33 +51,19 @@ const LatestTxsItem = ({ tx, isLoading }: Props) => { ].filter(Boolean).length; return ( - <Grid - gridTemplateColumns={{ - lg: columnNum === 2 ? '3fr minmax(auto, 200px)' : '3fr minmax(auto, 200px) 170px', - xl: columnNum === 2 ? '3fr minmax(auto, 270px)' : '3fr minmax(auto, 300px) 170px', - }} - gridGap={ 3 } - width="100%" - minW={ columnNum === 2 ? '700px' : '750px' } - borderBottom="1px solid" - borderColor="border.divider" - p={ 4 } - display={{ base: 'none', lg: 'grid' }} - > - <Flex overflow="hidden" w="100%"> - <TxAdditionalInfo tx={ tx } isLoading={ isLoading } my="3px"/> - <Box ml={ 3 } w="calc(100% - 40px)"> - <HStack flexWrap={ tagsCount <= 3 ? 'nowrap' : 'wrap' } my="3px"> + <TableRow> + <TableCell w="42px"> + <TxAdditionalInfo tx={ tx } isLoading={ isLoading } my="2px"/> + </TableCell> + <TableCell> + <VStack w="100%" overflow="hidden" alignItems="flex-start" gap="10px"> + <HStack flexWrap={ tagsCount <= 3 ? 'nowrap' : 'wrap' } w="100%"> <TxType types={ tx.transaction_types } isLoading={ isLoading }/> { tx.status !== 'ok' && <TxStatus status={ tx.status } errorText={ tx.status === 'error' ? tx.result : undefined } isLoading={ isLoading }/> } <TxWatchListTags tx={ tx } isLoading={ isLoading }/> { protocolTag && <MetadataTag data={ protocolTag } isLoading={ isLoading } minW="0" noColors/> } </HStack> - <Flex - alignItems="center" - mt="7px" - mb="3px" - > + <HStack w="100%"> <TxEntity isLoading={ isLoading } hash={ tx.hash } @@ -88,37 +78,42 @@ const LatestTxsItem = ({ tx, isLoading }: Props) => { flexShrink={ 0 } ml={ 2 } /> + </HStack> + </VStack> + </TableCell> + <TableCell w={{ base: '224px', xl: hasValueColumn ? '324px' : '294px' }}> + <AddressFromTo + from={ tx.from } + to={ dataTo } + isLoading={ isLoading } + mode="compact" + mt="2px" + /> + </TableCell> + { hasValueColumn && ( + <TableCell w="182px"> + <Flex flexDir="column" rowGap={ 3 } mt="2px"> + { !config.slices.tx.hiddenFields?.value && ( + <Skeleton loading={ isLoading }> + <Text as="span" whiteSpace="pre">Value </Text> + <NativeCoinValue + amount={ tx.value } + accuracy={ 5 } + loading={ isLoading } + color="text.secondary" + /> + </Skeleton> + ) } + { !config.slices.tx.hiddenFields?.tx_fee && ( + <Skeleton loading={ isLoading } display="flex" whiteSpace="pre"> + <Text as="span">Fee </Text> + <TxFee tx={ tx } accuracy={ 5 } color="text.secondary" noUsd/> + </Skeleton> + ) } </Flex> - </Box> - </Flex> - <AddressFromTo - from={ tx.from } - to={ dataTo } - isLoading={ isLoading } - mode="compact" - /> - { !(config.slices.tx.hiddenFields?.value && config.slices.tx.hiddenFields?.tx_fee) ? ( - <Flex flexDir="column" rowGap={ 3 }> - { !config.slices.tx.hiddenFields?.value && ( - <Skeleton loading={ isLoading }> - <Text as="span" whiteSpace="pre">Value </Text> - <NativeCoinValue - amount={ tx.value } - accuracy={ 5 } - loading={ isLoading } - color="text.secondary" - /> - </Skeleton> - ) } - { !config.slices.tx.hiddenFields?.tx_fee && ( - <Skeleton loading={ isLoading } display="flex" whiteSpace="pre"> - <Text as="span">Fee </Text> - <TxFee tx={ tx } accuracy={ 5 } color="text.secondary" noUsd/> - </Skeleton> - ) } - </Flex> - ) : null } - </Grid> + </TableCell> + ) } + </TableRow> ); }; diff --git a/src/slices/home/pages/index/txs/LatestTxsItemMobile.tsx b/src/slices/home/pages/index/txs/LatestTxsItemMobile.tsx deleted file mode 100644 index 0f6d616657a..00000000000 --- a/src/slices/home/pages/index/txs/LatestTxsItemMobile.tsx +++ /dev/null @@ -1,111 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { - Box, - Flex, - HStack, - Text, - VStack, -} from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressFromTo from 'src/slices/address/components/from-to/AddressFromTo'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; -import TxAdditionalInfo from 'src/slices/tx/components/TxAdditionalInfo'; -import TxFee from 'src/slices/tx/components/TxFee'; -import TxStatus from 'src/slices/tx/components/TxStatus'; -import TxType from 'src/slices/tx/components/TxType'; - -import TxWatchListTags from 'src/features/account/components/TxWatchListTags'; -import MetadataTag from 'src/features/address-metadata/components/tag/MetadataTag'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - tx: schemas['Transaction']; - isLoading?: boolean; -}; - -const LatestTxsItem = ({ tx, isLoading }: Props) => { - const dataTo = tx.to ? tx.to : tx.created_contract; - - const protocolTag = tx.to?.metadata?.tags?.find(tag => tag.tagType === 'protocol'); - - return ( - <Box - width="100%" - borderBottom="1px solid" - borderColor="border.divider" - py={ 4 } - display={{ base: 'block', lg: 'none' }} - > - <Flex justifyContent="space-between"> - <HStack> - <TxType types={ tx.transaction_types } isLoading={ isLoading }/> - { tx.status !== 'ok' && <TxStatus status={ tx.status } errorText={ tx.status === 'error' ? tx.result : undefined } isLoading={ isLoading }/> } - <TxWatchListTags tx={ tx } isLoading={ isLoading }/> - { protocolTag && <MetadataTag data={ protocolTag } isLoading={ isLoading } minW="0" noColors/> } - </HStack> - <TxAdditionalInfo tx={ tx } isMobile isLoading={ isLoading }/> - </Flex> - <Flex - mt={ 2 } - alignItems="center" - width="100%" - justifyContent="space-between" - mb={ 6 } - > - <TxEntity - isLoading={ isLoading } - hash={ tx.hash } - fontWeight="700" - truncation="constant_long" - /> - <TimeWithTooltip - timestamp={ tx.timestamp } - enableIncrement - timeFormat="relative" - isLoading={ isLoading } - color="text.secondary" - fontWeight="400" - ml={ 3 } - /> - </Flex> - <AddressFromTo - from={ tx.from } - to={ dataTo } - isLoading={ isLoading } - fontWeight="500" - /> - { !(config.slices.tx.hiddenFields?.value && config.slices.tx.hiddenFields?.tx_fee) ? ( - <VStack rowGap={ 2 } mt={ 3 } alignItems="flex-start"> - { !config.slices.tx.hiddenFields?.value && ( - <Skeleton loading={ isLoading } w="fit-content"> - <Text as="span">Value </Text> - <NativeCoinValue - amount={ tx.value } - accuracy={ 5 } - loading={ isLoading } - color="text.secondary" - /> - </Skeleton> - ) } - { !config.slices.tx.hiddenFields?.tx_fee && ( - <Skeleton loading={ isLoading } w="fit-content" display="flex" whiteSpace="pre"> - <Text as="span">Fee </Text> - <TxFee tx={ tx } accuracy={ 5 } color="text.secondary" noUsd/> - </Skeleton> - ) } - </VStack> - ) : null } - </Box> - ); -}; - -export default React.memo(LatestTxsItem); diff --git a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_dark-color-mode_default-view-dark-mode-1.png b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_dark-color-mode_default-view-dark-mode-1.png index 9dc489d6fee..42947a456eb 100644 Binary files a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_dark-color-mode_default-view-dark-mode-1.png and b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_dark-color-mode_default-view-dark-mode-1.png differ diff --git a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_default-view-dark-mode-1.png b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_default-view-dark-mode-1.png index b713cc39bfe..f9c384a5481 100644 Binary files a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_default-view-dark-mode-1.png and b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_default-view-dark-mode-1.png differ diff --git a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_mobile-default-view-1.png b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_mobile-default-view-1.png deleted file mode 100644 index 42b30a36731..00000000000 Binary files a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_mobile-default-view-1.png and /dev/null differ diff --git a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_small-desktop-one-tag-1.png b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_small-desktop-one-tag-1.png index 3a10261a4c6..7d0104754c0 100644 Binary files a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_small-desktop-one-tag-1.png and b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_small-desktop-one-tag-1.png differ diff --git a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_small-desktop-two-or-more-tags-1.png b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_small-desktop-two-or-more-tags-1.png index 57ddbd59a1b..d269222a070 100644 Binary files a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_small-desktop-two-or-more-tags-1.png and b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_small-desktop-two-or-more-tags-1.png differ diff --git a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_socket-new-item-1.png b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_socket-new-item-1.png index 563f2736b86..a6f04cb4068 100644 Binary files a/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_socket-new-item-1.png and b/src/slices/home/pages/index/txs/__screenshots__/LatestTxs.pw.tsx_default_socket-new-item-1.png differ diff --git a/src/slices/home/types/client.ts b/src/slices/home/types/client.ts index c40d3f67187..452a7e6cadb 100644 --- a/src/slices/home/types/client.ts +++ b/src/slices/home/types/client.ts @@ -1,12 +1,15 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type React from 'react'; -import type { ReactElement } from 'react'; import type { ColorModeValue } from 'src/config/types'; +<<<<<<< HEAD import type { ChainIndicatorId, HomeStatsWidgetId } from 'src/slices/home/types/config'; import type { Props as StatsWidgetProps } from 'src/shared/stats/StatsWidget'; +======= +import type { ChainIndicatorId } from 'src/slices/home/types/config'; +>>>>>>> v2.13.0 export interface HighlightsBannerConfig { title: string; @@ -29,8 +32,3 @@ export interface TChainIndicator { icon: React.ReactNode; hint?: string; } - -export type HomeStatsComponentItem = { id: HomeStatsWidgetId; component: ReactElement }; -export type HomeStatsWidgetItem = StatsWidgetProps & { id: HomeStatsWidgetId; component?: undefined }; - -export type HomeStatsItem = HomeStatsComponentItem | HomeStatsWidgetItem; diff --git a/src/slices/home/utils/stats.ts b/src/slices/home/utils/stats.ts index 9fb51aa72f7..c756b6b64c0 100644 --- a/src/slices/home/utils/stats.ts +++ b/src/slices/home/utils/stats.ts @@ -1,24 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { ReactElement } from 'react'; - import type { HomeStatsWidgetId } from 'src/slices/home/types/config'; import config from 'src/config'; -import type { Props as StatsWidgetProps } from 'src/shared/stats/StatsWidget'; - -export type HomeStatsComponentItem = { id: HomeStatsWidgetId; component: ReactElement }; -export type HomeStatsWidgetItem = StatsWidgetProps & { id: HomeStatsWidgetId; component?: undefined }; - -export type HomeStatsItem = HomeStatsComponentItem | HomeStatsWidgetItem; - -export const homeStatsWidgetCommonStyles = { - _odd: { - _last: { - gridColumn: 'span 2', - }, - }, -} as const; export const isHomeStatsItemEnabled = (item: { id: HomeStatsWidgetId }) => config.slices.home.stats.includes(item.id); diff --git a/src/slices/internal-tx/components/InternalTxsList.tsx b/src/slices/internal-tx/components/InternalTxsList.tsx deleted file mode 100644 index 342644937a7..00000000000 --- a/src/slices/internal-tx/components/InternalTxsList.tsx +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import { useMultichainContext } from 'src/features/multichain/context'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import InternalTxsListItem from './InternalTxsListItem'; - -interface Props { - data: Array<schemas['InternalTransaction']>; - currentAddress?: string; - isLoading?: boolean; - showBlockInfo?: boolean; - resetKey?: string; -}; - -const InternalTxsList = ({ data, currentAddress, isLoading, showBlockInfo = true, resetKey }: Props) => { - const multichainContext = useMultichainContext(); - const chainData = multichainContext?.chain; - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <InternalTxsListItem - key={ item.transaction_hash + '_' + index } - data={ item } - currentAddress={ currentAddress } - isLoading={ isLoading } - showBlockInfo={ showBlockInfo } - chainData={ chainData } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default InternalTxsList; diff --git a/src/slices/internal-tx/components/InternalTxsListItem.tsx b/src/slices/internal-tx/components/InternalTxsListItem.tsx deleted file mode 100644 index 16d8d372707..00000000000 --- a/src/slices/internal-tx/components/InternalTxsListItem.tsx +++ /dev/null @@ -1,97 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, HStack } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; - -import AddressFromTo from 'src/slices/address/components/from-to/AddressFromTo'; -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import { currencyUnits } from 'src/slices/chain/units'; -import { TX_INTERNALS_ITEMS } from 'src/slices/internal-tx/utils/utils'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; -import TxStatus from 'src/slices/tx/components/TxStatus'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Badge } from 'src/toolkit/chakra/badge'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - data: schemas['InternalTransaction']; - currentAddress?: string; - isLoading?: boolean; - showBlockInfo?: boolean; - chainData?: ClusterChainConfig; -} - -const InternalTxsListItem = ({ - data, - currentAddress, - isLoading, - showBlockInfo = true, - chainData, -}: Props) => { - const typeTitle = TX_INTERNALS_ITEMS.find(({ id }) => id === data.type)?.title; - const toData = data.to ? data.to : data.created_contract; - - return ( - <ListItemMobile rowGap={ 3 }> - <Flex columnGap={ 2 }> - { typeTitle && <Badge colorPalette="cyan" loading={ isLoading }>{ typeTitle }</Badge> } - { !data.success && <TxStatus status="error" errorText={ data.error } isLoading={ isLoading }/> } - </Flex> - <Flex justifyContent="space-between" width="100%"> - <TxEntity - hash={ data.transaction_hash } - isLoading={ isLoading } - fontWeight={ 700 } - truncation="constant_long" - chain={ chainData } - /> - <TimeWithTooltip - timestamp={ data.timestamp } - isLoading={ isLoading } - color="text.secondary" - fontWeight="400" - fontSize="sm" - /> - </Flex> - { showBlockInfo && ( - <HStack gap={ 1 }> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 }>Block</Skeleton> - <BlockEntity - isLoading={ isLoading } - number={ data.block_number } - noIcon - textStyle="sm" - /> - </HStack> - ) } - <AddressFromTo - from={ data.from } - to={ toData } - current={ currentAddress } - isLoading={ isLoading } - w="100%" - /> - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 }>Value { currencyUnits.ether }</Skeleton> - <NativeCoinValue - amount={ data.value } - noSymbol - accuracy={ 0 } - loading={ isLoading } - minW={ 6 } - fontSize="sm" - color="text.secondary" - /> - </HStack> - </ListItemMobile> - ); -}; - -export default InternalTxsListItem; diff --git a/src/slices/internal-tx/components/InternalTxsTable.tsx b/src/slices/internal-tx/components/InternalTxsTable.tsx index a89fb2f6506..83d95fea72a 100644 --- a/src/slices/internal-tx/components/InternalTxsTable.tsx +++ b/src/slices/internal-tx/components/InternalTxsTable.tsx @@ -10,6 +10,7 @@ import { currencyUnits } from 'src/slices/chain/units'; import { useMultichainContext } from 'src/features/multichain/context'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -25,14 +26,17 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: schemas['InternalTransaction']): string => item.transaction_hash + '_' + item.index; + const InternalTxsTable = ({ data, currentAddress, isLoading, top, showBlockInfo = true, resetKey }: Props) => { const multichainContext = useMultichainContext(); const chainData = multichainContext?.chain; const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); return ( <AddressHighlightProvider> - <TableRoot minW="900px"> + <TableRoot minW="1000px"> <TableHeaderSticky top={ top ?? 68 }> <TableRow> { chainData && <TableColumnHeader width="38px"></TableColumnHeader> } @@ -51,7 +55,7 @@ const InternalTxsTable = ({ data, currentAddress, isLoading, top, showBlockInfo <TableBody> { data.slice(0, renderedItemsNum).map((item, index) => ( <InternalTxsTableItem - key={ item.transaction_hash + '_' + index } + key={ keys[index] } data={ item } currentAddress={ currentAddress } isLoading={ isLoading } diff --git a/src/slices/internal-tx/components/InternalTxsTableItem.tsx b/src/slices/internal-tx/components/InternalTxsTableItem.tsx index ed518c33a45..b054f9a8cc6 100644 --- a/src/slices/internal-tx/components/InternalTxsTableItem.tsx +++ b/src/slices/internal-tx/components/InternalTxsTableItem.tsx @@ -89,6 +89,7 @@ const InternalTxsTableItem = ({ from={ data.from } to={ toData } current={ currentAddress } + mode={{ base: 'compact', lg: 'compact', xl: 'long' }} isLoading={ isLoading } my="2px" /> diff --git a/src/slices/internal-tx/hooks/useInternalTxsQuery.ts b/src/slices/internal-tx/hooks/useInternalTxsQuery.ts index 5182235f897..0b6d41081b9 100644 --- a/src/slices/internal-tx/hooks/useInternalTxsQuery.ts +++ b/src/slices/internal-tx/hooks/useInternalTxsQuery.ts @@ -1,27 +1,23 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; +import type { ExternalChainExtended } from 'src/shared/external-chains/types'; + import { INTERNAL_TX } from 'src/slices/internal-tx/stubs'; -import useDebounce from 'src/shared/hooks/useDebounce'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; interface Props { - isMultichain?: boolean; + chain?: ExternalChainExtended; } -export default function useInternalTxsQuery({ isMultichain }: Props = {}) { - const router = useRouter(); - const [ searchTerm, setSearchTerm ] = React.useState(getQueryParamString(router.query.transaction_hash) || undefined); - const debouncedSearchTerm = useDebounce(searchTerm || '', 300); - - const query = useQueryWithPages({ +export default function useInternalTxsQuery({ chain }: Props = {}) { + const query = useApiPaginatedQuery({ resourceName: 'core:internal_txs', - filters: { transaction_hash: debouncedSearchTerm }, options: { placeholderData: generateListStub<'core:internal_txs'>( INTERNAL_TX, @@ -41,18 +37,17 @@ export default function useInternalTxsQuery({ isMultichain }: Props = {}) { }, ), }, - isMultichain, + chain, }); - const onSearchTermChange = React.useCallback((value: string) => { - query.onFilterChange({ transaction_hash: value }); - setSearchTerm(value); - }, [ query ]); + const searchTerm = getQueryParamString(query.filters.transaction_hash) || undefined; + + const { onFilterChange } = query; + const onSearchTermChange = useDebouncedFilterChange((value) => onFilterChange({ transaction_hash: value })); return React.useMemo(() => ({ query, searchTerm, - debouncedSearchTerm, onSearchTermChange, - }), [ query, searchTerm, debouncedSearchTerm, onSearchTermChange ]); + }), [ query, searchTerm, onSearchTermChange ]); } diff --git a/src/slices/internal-tx/pages/index/InternalTxs.tsx b/src/slices/internal-tx/pages/index/InternalTxs.tsx index d9fe56b9428..0299aa5a4e8 100644 --- a/src/slices/internal-tx/pages/index/InternalTxs.tsx +++ b/src/slices/internal-tx/pages/index/InternalTxs.tsx @@ -6,7 +6,6 @@ import React from 'react'; import ActionBar from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; -import InternalTxsList from 'src/slices/internal-tx/components/InternalTxsList'; import InternalTxsTable from 'src/slices/internal-tx/components/InternalTxsTable'; import useInternalTxsQuery from 'src/slices/internal-tx/hooks/useInternalTxsQuery'; @@ -14,14 +13,15 @@ import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { FilterInput } from 'src/toolkit/components/filters/FilterInput'; const InternalTxs = () => { const isMobile = useIsMobile(); - const { query, searchTerm, debouncedSearchTerm, onSearchTermChange } = useInternalTxsQuery(); - const { isError, isPlaceholderData, data, pagination } = query; + const { query, searchTerm, onSearchTermChange } = useInternalTxsQuery(); + const { isError, isInitialLoading, isTransitioning, data, pagination } = query; const filterInput = ( <FilterInput @@ -50,14 +50,9 @@ const InternalTxs = () => { ); const content = data?.items ? ( - <> - <Box hideFrom="lg"> - <InternalTxsList data={ data.items } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> - </Box> - <Box hideBelow="lg"> - <InternalTxsTable data={ data.items } isLoading={ isPlaceholderData } resetKey={ query.queryHash }/> - </Box> - </> + <TableContainerScrollable> + <InternalTxsTable data={ data.items } isLoading={ isInitialLoading } resetKey={ query.queryHash }/> + </TableContainerScrollable> ) : null; return ( @@ -70,7 +65,8 @@ const InternalTxs = () => { isError={ isError } itemsNum={ data?.items.length } emptyText="There are no internal transactions." - hasActiveFilters={ Boolean(debouncedSearchTerm) } + hasActiveFilters={ Boolean(searchTerm) } + isTransitioning={ isTransitioning } emptyStateProps={{ term: 'internal transaction', }} diff --git a/src/slices/internal-tx/pages/tx/TxInternals.pw.tsx b/src/slices/internal-tx/pages/tx/TxInternals.pw.tsx index 8230f1abae9..cbd9855cc00 100644 --- a/src/slices/internal-tx/pages/tx/TxInternals.pw.tsx +++ b/src/slices/internal-tx/pages/tx/TxInternals.pw.tsx @@ -15,7 +15,7 @@ const hooksConfig = { }, }; -test('base view +@mobile', async({ render, mockApiResponse }) => { +test('base view', async({ render, mockApiResponse }) => { await mockApiResponse('core:tx_internal_txs', internalTxsMock.baseResponse, { pathParams: { hash: TX_HASH } }); const txQuery = { data: txMock.base, diff --git a/src/slices/internal-tx/pages/tx/TxInternals.tsx b/src/slices/internal-tx/pages/tx/TxInternals.tsx index ae835d5a12b..0904af9ecec 100644 --- a/src/slices/internal-tx/pages/tx/TxInternals.tsx +++ b/src/slices/internal-tx/pages/tx/TxInternals.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; +import { createListCollection } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -12,25 +12,28 @@ import TxPendingAlert from 'src/slices/tx/components/TxPendingAlert'; import TxSocketAlert from 'src/slices/tx/components/TxSocketAlert'; import type { TxQuery } from 'src/slices/tx/hooks/useTxQuery'; +import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import compareBns from 'src/shared/numbers/compareBns'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import { default as getNextSortValueShared } from 'src/shared/sort/get-next-sort-value'; +import Sort from 'src/shared/sort/Sort'; -import type { Sort, SortField } from '../../utils/utils'; -import TxInternalsList from './TxInternalsList'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + +import type { Sort as SortValue, SortField } from '../../utils/utils'; +import { SORT_OPTIONS, SORT_SEQUENCE } from './sort'; import TxInternalsTable from './TxInternalsTable'; -const SORT_SEQUENCE: Record<SortField, Array<Sort>> = { - value: [ 'value-desc', 'value-asc', 'default' ], - 'gas-limit': [ 'gas-limit-desc', 'gas-limit-asc', 'default' ], -}; +const sortCollection = createListCollection({ + items: SORT_OPTIONS, +}); -const getNextSortValue = (getNextSortValueShared<SortField, Sort>).bind(undefined, SORT_SEQUENCE); +const getNextSortValue = (getNextSortValueShared<SortField, SortValue>).bind(undefined, SORT_SEQUENCE); -const sortFn = (sort: Sort) => (a: schemas['InternalTransaction'], b: schemas['InternalTransaction']) => { +const sortFn = (sort: SortValue) => (a: schemas['InternalTransaction'], b: schemas['InternalTransaction']) => { switch (sort) { case 'value-desc': { return compareBns(b.value, a.value); @@ -69,8 +72,9 @@ const TxInternals = ({ txQuery }: Props) => { // filters are not implemented yet in api // const [ filters, setFilters ] = React.useState<Array<TxInternalsType>>([]); // const [ searchTerm, setSearchTerm ] = React.useState<string>(''); - const [ sort, setSort ] = React.useState<Sort>('default'); - const { data, isPlaceholderData, isError, pagination, queryHash } = useQueryWithPages({ + const isMobile = useIsMobile(); + const [ sort, setSort ] = React.useState<SortValue>('default'); + const { data, isInitialLoading, isTransitioning, isError, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:tx_internal_txs', pathParams: { hash: txQuery.data?.hash }, options: { @@ -84,12 +88,16 @@ const TxInternals = ({ txQuery }: Props) => { // }, []); const handleSortToggle = React.useCallback((field: SortField) => { - if (isPlaceholderData) { + if (isInitialLoading) { return; } setSort(getNextSortValue(field)); - }, [ isPlaceholderData ]); + }, [ isInitialLoading ]); + + const handleSortValueChange = React.useCallback(({ value }: { value: Array<string> }) => { + setSort(value[0] as SortValue); + }, []); if (!txQuery.isPlaceholderData && !txQuery.isError && !txQuery.data?.status) { return txQuery.socketStatus ? <TxSocketAlert status={ txQuery.socketStatus }/> : <TxPendingAlert/>; @@ -102,24 +110,29 @@ const TxInternals = ({ txQuery }: Props) => { .sort(sortFn(sort)); const content = filteredData ? ( - <> - <Box hideFrom="lg"><TxInternalsList data={ filteredData } isLoading={ isPlaceholderData } resetKey={ queryHash }/></Box> - <Box hideBelow="lg"> - <TxInternalsTable - data={ filteredData } - sort={ sort } - onSortToggle={ handleSortToggle } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ isPlaceholderData } - resetKey={ queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <TxInternalsTable + data={ filteredData } + sort={ sort } + onSortToggle={ handleSortToggle } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ isInitialLoading } + resetKey={ queryHash } + /> + </TableContainerScrollable> ) : null; - const actionBar = pagination.isVisible ? ( + const actionBar = (isMobile || pagination.isVisible) ? ( <ActionBar mt={ -6 }> { /* <FilterInput onChange={ setSearchTerm } maxW="360px" ml={ 3 } size="xs" placeholder="Search by addresses, hash, method..."/> */ } + <Sort + name="tx_internal_txs_sorting" + defaultValue={ [ sort ] } + collection={ sortCollection } + onValueChange={ handleSortValueChange } + isLoading={ isInitialLoading } + hideFrom="lg" + /> <Pagination ml="auto" { ...pagination }/> </ActionBar> ) : null; @@ -134,6 +147,7 @@ const TxInternals = ({ txQuery }: Props) => { // hasActiveFilters: Boolean(filters.length || searchTerm), // }} actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/slices/internal-tx/pages/tx/TxInternalsList.tsx b/src/slices/internal-tx/pages/tx/TxInternalsList.tsx deleted file mode 100644 index ac08f909b5b..00000000000 --- a/src/slices/internal-tx/pages/tx/TxInternalsList.tsx +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import TxInternalsListItem from './TxInternalsListItem'; - -const TxInternalsList = ({ data, isLoading, resetKey }: { data: Array<schemas['InternalTransaction']>; isLoading?: boolean; resetKey?: string }) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <TxInternalsListItem key={ item.index.toString() + (isLoading ? index : '') } data={ item } isLoading={ isLoading }/> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default TxInternalsList; diff --git a/src/slices/internal-tx/pages/tx/TxInternalsListItem.tsx b/src/slices/internal-tx/pages/tx/TxInternalsListItem.tsx deleted file mode 100644 index b7137b4b957..00000000000 --- a/src/slices/internal-tx/pages/tx/TxInternalsListItem.tsx +++ /dev/null @@ -1,65 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, HStack } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressFromTo from 'src/slices/address/components/from-to/AddressFromTo'; -import { currencyUnits } from 'src/slices/chain/units'; -import TxStatus from 'src/slices/tx/components/TxStatus'; - -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Badge } from 'src/toolkit/chakra/badge'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -import { TX_INTERNALS_ITEMS } from '../../utils/utils'; - -interface Props { - data: schemas['InternalTransaction']; - isLoading?: boolean; -} - -const TxInternalsListItem = ({ data, isLoading }: Props) => { - const typeTitle = TX_INTERNALS_ITEMS.find(({ id }) => id === data.type)?.title; - const toData = data.to ? data.to : data.created_contract; - - return ( - <ListItemMobile rowGap={ 3 }> - <Flex columnGap={ 2 }> - { typeTitle && <Badge colorPalette="cyan" loading={ isLoading }>{ typeTitle }</Badge> } - { !data.success && <TxStatus status="error" errorText={ data.error } isLoading={ isLoading }/> } - </Flex> - <AddressFromTo - from={ data.from } - to={ toData } - isLoading={ isLoading } - w="100%" - fontWeight="500" - /> - <HStack gap={ 3 } textStyle="sm" > - <Skeleton loading={ isLoading } fontWeight={ 500 }><span>Value { currencyUnits.ether }</span></Skeleton> - <NativeCoinValue - amount={ data.value } - noSymbol - loading={ isLoading } - color="text.secondary" - /> - </HStack> - <HStack gap={ 3 } textStyle="sm" > - <Skeleton loading={ isLoading } fontWeight={ 500 }><span>Gas limit</span></Skeleton> - <NativeCoinValue - amount={ data.gas_limit } - units="wei" - noSymbol - loading={ isLoading } - color="text.secondary" - /> - </HStack> - </ListItemMobile> - ); -}; - -export default TxInternalsListItem; diff --git a/src/slices/internal-tx/pages/tx/TxInternalsTable.tsx b/src/slices/internal-tx/pages/tx/TxInternalsTable.tsx index 79f7c36138e..f1f13a44536 100644 --- a/src/slices/internal-tx/pages/tx/TxInternalsTable.tsx +++ b/src/slices/internal-tx/pages/tx/TxInternalsTable.tsx @@ -7,6 +7,7 @@ import type { schemas } from '@blockscout/api-types'; import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; import { currencyUnits } from 'src/slices/chain/units'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableColumnHeaderSortable, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -23,12 +24,15 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: schemas['InternalTransaction']): string => item.index.toString(); + const TxInternalsTable = ({ data, sort, onSortToggle, top, isLoading, resetKey }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); return ( <AddressHighlightProvider> - <TableRoot> + <TableRoot minW="900px"> <TableHeaderSticky top={ top }> <TableRow> <TableColumnHeader width="28%">Type</TableColumnHeader> @@ -55,7 +59,7 @@ const TxInternalsTable = ({ data, sort, onSortToggle, top, isLoading, resetKey } </TableHeaderSticky> <TableBody> { data.slice(0, renderedItemsNum).map((item, index) => ( - <TxInternalsTableItem key={ item.index.toString() + (isLoading ? index : '') } data={ item } isLoading={ isLoading }/> + <TxInternalsTableItem key={ keys[index] } data={ item } isLoading={ isLoading }/> )) } </TableBody> </TableRoot> diff --git a/src/slices/internal-tx/pages/tx/__screenshots__/TxInternals.pw.tsx_default_base-view-1.png b/src/slices/internal-tx/pages/tx/__screenshots__/TxInternals.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..58d0a9e16d9 Binary files /dev/null and b/src/slices/internal-tx/pages/tx/__screenshots__/TxInternals.pw.tsx_default_base-view-1.png differ diff --git a/src/slices/internal-tx/pages/tx/__screenshots__/TxInternals.pw.tsx_default_base-view-mobile-1.png b/src/slices/internal-tx/pages/tx/__screenshots__/TxInternals.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 5fa5877ca96..00000000000 Binary files a/src/slices/internal-tx/pages/tx/__screenshots__/TxInternals.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/internal-tx/pages/tx/__screenshots__/TxInternals.pw.tsx_mobile_base-view-mobile-1.png b/src/slices/internal-tx/pages/tx/__screenshots__/TxInternals.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 706907d2745..00000000000 Binary files a/src/slices/internal-tx/pages/tx/__screenshots__/TxInternals.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/internal-tx/pages/tx/sort.ts b/src/slices/internal-tx/pages/tx/sort.ts new file mode 100644 index 00000000000..dda5a839663 --- /dev/null +++ b/src/slices/internal-tx/pages/tx/sort.ts @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { SelectOption } from 'src/toolkit/chakra/select'; + +import type { Sort, SortField } from '../../utils/utils'; + +export const SORT_OPTIONS: Array<SelectOption<Sort>> = [ + { label: 'Default', value: 'default' }, + { label: 'Value descending', value: 'value-desc' }, + { label: 'Value ascending', value: 'value-asc' }, + { label: 'Gas limit descending', value: 'gas-limit-desc' }, + { label: 'Gas limit ascending', value: 'gas-limit-asc' }, +]; + +export const SORT_SEQUENCE: Record<SortField, Array<Sort>> = { + value: [ 'value-desc', 'value-asc', 'default' ], + 'gas-limit': [ 'gas-limit-desc', 'gas-limit-asc', 'default' ], +}; diff --git a/src/slices/log/components/LogDecodedInputDataTable.tsx b/src/slices/log/components/LogDecodedInputDataTable.tsx index 40191ecfe03..e751c846829 100644 --- a/src/slices/log/components/LogDecodedInputDataTable.tsx +++ b/src/slices/log/components/LogDecodedInputDataTable.tsx @@ -10,7 +10,7 @@ import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props extends JsxStyleProps { data: schemas['DecodedLogInput']['parameters'] | schemas['DecodedInput']['parameters']; @@ -53,7 +53,7 @@ const Row = ({ const text = JSON.stringify(value, undefined, 4); return ( <Flex alignItems="flex-start" whiteSpace="normal" wordBreak="break-all"> - <TruncatedText text={ text } loading={ isLoading }/> + <Truncate value={ text } type="end" loading={ isLoading }/> <CopyToClipboard text={ text } isLoading={ isLoading }/> </Flex> ); @@ -61,7 +61,7 @@ const Row = ({ return ( <Flex alignItems="flex-start" whiteSpace="normal" wordBreak="break-all"> - <TruncatedText text={ value } loading={ isLoading }/> + <Truncate value={ value } type="end" loading={ isLoading }/> <CopyToClipboard text={ value } isLoading={ isLoading }/> </Flex> ); @@ -69,8 +69,8 @@ const Row = ({ return ( <> - <TruncatedText text={ name } loading={ isLoading }/> - <TruncatedText text={ type } loading={ isLoading }/> + <Truncate value={ name } type="end" loading={ isLoading }/> + <Truncate value={ type } type="end" loading={ isLoading }/> { indexed !== undefined && ( <Skeleton loading={ isLoading } display="inline-block">{ indexed ? 'true' : 'false' }</Skeleton> ) } diff --git a/src/slices/log/components/LogItem.tsx b/src/slices/log/components/LogItem.tsx index 7c7e8b68b00..4a2ad8bfc52 100644 --- a/src/slices/log/components/LogItem.tsx +++ b/src/slices/log/components/LogItem.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Grid, GridItem } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -14,6 +13,7 @@ import TxEntity from 'src/slices/tx/components/entity/TxEntity'; import type { DataType } from 'src/shared/data/RawInputData'; import RawInputData from 'src/shared/data/RawInputData'; import DetailedInfoTimestamp from 'src/shared/detailed-info/DetailedInfoTimestamp'; +import { route } from 'src/shared/router/routes'; import { Alert } from 'src/toolkit/chakra/alert'; import { Link } from 'src/toolkit/chakra/link'; diff --git a/src/slices/log/components/LogTopic.tsx b/src/slices/log/components/LogTopic.tsx index 3dd0a1e9ccb..3776fa3903f 100644 --- a/src/slices/log/components/LogTopic.tsx +++ b/src/slices/log/components/LogTopic.tsx @@ -9,10 +9,10 @@ import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import hexToAddress from 'src/shared/data/transformers/hex-to-address'; import hexToUtf8 from 'src/shared/data/transformers/hex-to-utf8'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import { SelectContent, SelectControl, SelectItem, SelectRoot, SelectValueText } from 'src/toolkit/chakra/select'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import LogIndex from './LogIndex'; @@ -56,7 +56,7 @@ const LogTopic = ({ hex, index, isLoading }: Props) => { return ( <> <Skeleton loading={ isLoading } overflow="hidden" whiteSpace="nowrap"> - <HashStringShortenDynamic hash={ value }/> + <Truncate value={ value }/> </Skeleton> <CopyToClipboard text={ value } isLoading={ isLoading }/> </> diff --git a/src/slices/log/components/__screenshots__/LogDecodedInputData.pw.tsx_mobile_with-indexed-fields-mobile-dark-mode-1.png b/src/slices/log/components/__screenshots__/LogDecodedInputData.pw.tsx_mobile_with-indexed-fields-mobile-dark-mode-1.png index da8aecd7d85..e9e21031fa7 100644 Binary files a/src/slices/log/components/__screenshots__/LogDecodedInputData.pw.tsx_mobile_with-indexed-fields-mobile-dark-mode-1.png and b/src/slices/log/components/__screenshots__/LogDecodedInputData.pw.tsx_mobile_with-indexed-fields-mobile-dark-mode-1.png differ diff --git a/src/slices/log/components/__screenshots__/LogDecodedInputData.pw.tsx_mobile_without-indexed-fields-mobile-1.png b/src/slices/log/components/__screenshots__/LogDecodedInputData.pw.tsx_mobile_without-indexed-fields-mobile-1.png index 402c0c680a2..f7036dad4c3 100644 Binary files a/src/slices/log/components/__screenshots__/LogDecodedInputData.pw.tsx_mobile_without-indexed-fields-mobile-1.png and b/src/slices/log/components/__screenshots__/LogDecodedInputData.pw.tsx_mobile_without-indexed-fields-mobile-1.png differ diff --git a/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_with-decoded-input-data-mobile-dark-mode-1.png b/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_with-decoded-input-data-mobile-dark-mode-1.png index e6526adbc4a..3ca8dfdaee7 100644 Binary files a/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_with-decoded-input-data-mobile-dark-mode-1.png and b/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_with-decoded-input-data-mobile-dark-mode-1.png differ diff --git a/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_with-default-data-type-1.png b/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_with-default-data-type-1.png index 0ac112fc27b..219dff7c774 100644 Binary files a/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_with-default-data-type-1.png and b/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_with-default-data-type-1.png differ diff --git a/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_without-decoded-input-data-mobile-1.png b/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_without-decoded-input-data-mobile-1.png index e1df302fc71..ce1b48895a1 100644 Binary files a/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_without-decoded-input-data-mobile-1.png and b/src/slices/log/components/__screenshots__/LogItem.pw.tsx_default_without-decoded-input-data-mobile-1.png differ diff --git a/src/slices/log/components/__screenshots__/LogItem.pw.tsx_mobile_with-decoded-input-data-mobile-dark-mode-1.png b/src/slices/log/components/__screenshots__/LogItem.pw.tsx_mobile_with-decoded-input-data-mobile-dark-mode-1.png index 38708c39d11..e51cfe2f4a7 100644 Binary files a/src/slices/log/components/__screenshots__/LogItem.pw.tsx_mobile_with-decoded-input-data-mobile-dark-mode-1.png and b/src/slices/log/components/__screenshots__/LogItem.pw.tsx_mobile_with-decoded-input-data-mobile-dark-mode-1.png differ diff --git a/src/slices/log/components/__screenshots__/LogItem.pw.tsx_mobile_without-decoded-input-data-mobile-1.png b/src/slices/log/components/__screenshots__/LogItem.pw.tsx_mobile_without-decoded-input-data-mobile-1.png index 9818e893b8a..4071c3f9624 100644 Binary files a/src/slices/log/components/__screenshots__/LogItem.pw.tsx_mobile_without-decoded-input-data-mobile-1.png and b/src/slices/log/components/__screenshots__/LogItem.pw.tsx_mobile_without-decoded-input-data-mobile-1.png differ diff --git a/src/slices/log/components/__screenshots__/LogTopic.pw.tsx_mobile_address-view-mobile---default-1.png b/src/slices/log/components/__screenshots__/LogTopic.pw.tsx_mobile_address-view-mobile---default-1.png index 5d0d5b5b778..7c268bd3385 100644 Binary files a/src/slices/log/components/__screenshots__/LogTopic.pw.tsx_mobile_address-view-mobile---default-1.png and b/src/slices/log/components/__screenshots__/LogTopic.pw.tsx_mobile_address-view-mobile---default-1.png differ diff --git a/src/slices/log/components/__screenshots__/LogTopic.pw.tsx_mobile_hex-view-mobile---default-1.png b/src/slices/log/components/__screenshots__/LogTopic.pw.tsx_mobile_hex-view-mobile---default-1.png index 6cac6a733fd..a13353bfb2b 100644 Binary files a/src/slices/log/components/__screenshots__/LogTopic.pw.tsx_mobile_hex-view-mobile---default-1.png and b/src/slices/log/components/__screenshots__/LogTopic.pw.tsx_mobile_hex-view-mobile---default-1.png differ diff --git a/src/slices/search/components/search-bar/SearchBarDesktop.pw.tsx b/src/slices/search/components/search-bar/SearchBarDesktop.pw.tsx index 8479c215519..8c8bb596ed1 100644 --- a/src/slices/search/components/search-bar/SearchBarDesktop.pw.tsx +++ b/src/slices/search/components/search-bar/SearchBarDesktop.pw.tsx @@ -10,10 +10,14 @@ import { domain1 } from 'src/features/name-services/domains/mocks/search'; import { userOp1 } from 'src/features/user-ops/mocks/search'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; +import type { TestFnArgs } from 'playwright/lib'; import { test, expect } from 'playwright/lib'; import SearchBarDesktop from './SearchBarDesktop'; +const mockNoRedirect = (mockApiResponse: TestFnArgs['mockApiResponse'], q: string | number) => + mockApiResponse('core:search_check_redirect', searchMock.noRedirect, { queryParams: { q } }); + test.beforeEach(async({ mockAssetResponse, mockEnvs, mockTextAd }) => { await mockTextAd(); await mockAssetResponse(searchMock.token1.icon_url as string, './playwright/mocks/image_s.jpg'); @@ -27,6 +31,7 @@ test('search by token name +@dark-mode', async({ render, page, mockApiResponse } searchMock.token1, searchMock.token2, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill('o'); await page.waitForResponse(apiUrl); @@ -40,6 +45,7 @@ test('search by contract name +@dark-mode', async({ render, page, mockApiRespons searchMock.contract2, searchMock.address2, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill('o'); @@ -54,6 +60,7 @@ test('search by name homepage +@dark-mode', async({ render, page, mockApiRespons searchMock.token2, searchMock.contract1, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarDesktop isHeroBanner/>); await page.getByPlaceholder(/search/i).fill('o'); await page.waitForResponse(apiUrl); @@ -65,6 +72,7 @@ test('search by tag +@dark-mode', async({ render, page, mockApiResponse }) => { const apiUrl = await mockApiResponse('core:quick_search', [ searchMock.label1, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill('o'); await page.waitForResponse(apiUrl); @@ -76,6 +84,7 @@ test('search by address hash', async({ render, page, mockApiResponse }) => { const apiUrl = await mockApiResponse('core:quick_search', [ searchMock.address1, ], { queryParams: { q: searchMock.address1.address_hash } }); + await mockNoRedirect(mockApiResponse, searchMock.address1.address_hash); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill(searchMock.address1.address_hash); await page.waitForResponse(apiUrl); @@ -89,6 +98,7 @@ test('search by meta tag +@dark-mode', async({ render, page, mockApiResponse }) metatag2, metatag3, ], { queryParams: { q: 'utko' } }); + await mockNoRedirect(mockApiResponse, 'utko'); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill('utko'); await page.waitForResponse(apiUrl); @@ -102,6 +112,7 @@ test('search by block number', async({ render, page, mockApiResponse }) => { searchMock.block2, searchMock.block3, ], { queryParams: { q: searchMock.block1.block_number } }); + await mockNoRedirect(mockApiResponse, searchMock.block1.block_number); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill(String(searchMock.block1.block_number)); await page.waitForResponse(apiUrl); @@ -113,6 +124,7 @@ test('search by block hash', async({ render, page, mockApiResponse }) => { const apiUrl = await mockApiResponse('core:quick_search', [ searchMock.block1, ], { queryParams: { q: searchMock.block1.block_hash } }); + await mockNoRedirect(mockApiResponse, searchMock.block1.block_hash); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill(searchMock.block1.block_hash); await page.waitForResponse(apiUrl); @@ -124,6 +136,7 @@ test('search by tx hash', async({ render, page, mockApiResponse }) => { const apiUrl = await mockApiResponse('core:quick_search', [ searchMock.tx1, ], { queryParams: { q: searchMock.tx1.transaction_hash } }); + await mockNoRedirect(mockApiResponse, searchMock.tx1.transaction_hash); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill(searchMock.tx1.transaction_hash); await page.waitForResponse(apiUrl); @@ -135,6 +148,7 @@ test('search by tac operation hash', async({ render, page, mockApiResponse }) => const apiUrl = await mockApiResponse('core:quick_search', [ tacOperation1, ], { queryParams: { q: tacOperation1.tac_operation.operation_id } }); + await mockNoRedirect(mockApiResponse, tacOperation1.tac_operation.operation_id); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill(tacOperation1.tac_operation.operation_id); await page.waitForResponse(apiUrl); @@ -147,6 +161,7 @@ test('search by blob hash', async({ render, page, mockApiResponse, mockEnvs }) = const apiUrl = await mockApiResponse('core:quick_search', [ blob1, ], { queryParams: { q: blob1.blob_hash } }); + await mockNoRedirect(mockApiResponse, blob1.blob_hash); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill(blob1.blob_hash); await page.waitForResponse(apiUrl); @@ -159,6 +174,7 @@ test('search by domain name', async({ render, page, mockApiResponse, mockEnvs }) const apiUrl = await mockApiResponse('core:quick_search', [ domain1, ], { queryParams: { q: domain1.ens_info.name } }); + await mockNoRedirect(mockApiResponse, domain1.ens_info.name); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill(domain1.ens_info.name); @@ -172,6 +188,7 @@ test('search by user op hash', async({ render, page, mockApiResponse, mockEnvs } const apiUrl = await mockApiResponse('core:quick_search', [ userOp1, ], { queryParams: { q: searchMock.tx1.transaction_hash } }); + await mockNoRedirect(mockApiResponse, searchMock.tx1.transaction_hash); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill(searchMock.tx1.transaction_hash); await page.waitForResponse(apiUrl); @@ -186,6 +203,7 @@ test('search with view all link', async({ render, page, mockApiResponse }) => { searchMock.contract1, ...Array(47).fill(searchMock.contract1), ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill('o'); await page.waitForResponse(apiUrl); @@ -208,6 +226,7 @@ test('scroll suggest to category', async({ render, page, mockApiResponse }) => { searchMock.token2, searchMock.contract1, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill('o'); await page.waitForResponse(apiUrl); @@ -237,6 +256,7 @@ test.describe('with apps', () => { const apiUrl = await mockApiResponse('core:quick_search', [ searchMock.token1, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await mockConfigResponse('NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', MARKETPLACE_CONFIG_URL, appsMock); await mockAssetResponse(appsMock[0].logo, './playwright/mocks/image_s.jpg'); await mockAssetResponse(appsMock[1].logo, './playwright/mocks/image_s.jpg'); @@ -256,6 +276,7 @@ test.describe('with apps', () => { test.describe('block countdown', () => { test('no results', async({ render, page, mockApiResponse }) => { const apiUrl = await mockApiResponse('core:quick_search', [], { queryParams: { q: '1234567890' } }); + await mockNoRedirect(mockApiResponse, '1234567890'); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill('1234567890'); await page.waitForResponse(apiUrl); @@ -267,6 +288,7 @@ test.describe('block countdown', () => { const apiUrl = await mockApiResponse('core:quick_search', [ { ...searchMock.token1, name: '1234567890123456789' }, ], { queryParams: { q: '1234567890' } }); + await mockNoRedirect(mockApiResponse, '1234567890'); await render(<SearchBarDesktop/>); await page.getByPlaceholder(/search/i).fill('1234567890'); await page.waitForResponse(apiUrl); diff --git a/src/slices/search/components/search-bar/SearchBarDesktop.tsx b/src/slices/search/components/search-bar/SearchBarDesktop.tsx index 201bdb6fac2..eddd64449a7 100644 --- a/src/slices/search/components/search-bar/SearchBarDesktop.tsx +++ b/src/slices/search/components/search-bar/SearchBarDesktop.tsx @@ -1,9 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { useClickAway } from '@uidotdev/usehooks'; -import { useRouter } from 'next/router'; -import type { Route } from 'nextjs-routes'; -import { route } from 'nextjs-routes'; import type { FormEvent } from 'react'; import React from 'react'; @@ -11,8 +8,11 @@ import { getRecentSearchKeywords, saveToRecentKeywords } from 'src/slices/search import useSearchWithClusters from 'src/features/name-services/clusters/hooks/useSearchWithClusters'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { route } from 'src/shared/router/routes'; +import type { Route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import { Link } from 'src/toolkit/chakra/link'; import { PopoverBody, PopoverContent, PopoverFooter, PopoverRoot, PopoverTrigger } from 'src/toolkit/chakra/popover'; @@ -42,13 +42,13 @@ const SearchBarDesktop = ({ isHeroBanner }: Props) => { if (searchTerm) { const resultRoute: Route = { pathname: '/search-results', query: { q: searchTerm, redirect: redirect ? 'true' : 'false' } }; const url = route(resultRoute); - mixpanel.logEvent(mixpanel.EventTypes.SEARCH_QUERY, { + analytics.logEvent(analytics.EventTypes.SEARCH_QUERY, { 'Search query': searchTerm, - 'Source page type': mixpanel.getPageType(router.pathname), + 'Source page type': analytics.getPageType(router.pathname), 'Result URL': url, }); saveToRecentKeywords(searchTerm); - router.push(resultRoute, undefined, { shallow: true }); + router.push(resultRoute, { shallow: true }); } }, [ searchTerm, router ]); @@ -95,9 +95,9 @@ const SearchBarDesktop = ({ isHeroBanner }: Props) => { }, [ handleSearchTermChange ]); const handleItemClick = React.useCallback((event: React.MouseEvent<HTMLAnchorElement>) => { - mixpanel.logEvent(mixpanel.EventTypes.SEARCH_QUERY, { + analytics.logEvent(analytics.EventTypes.SEARCH_QUERY, { 'Search query': searchTerm, - 'Source page type': mixpanel.getPageType(router.pathname), + 'Source page type': analytics.getPageType(router.pathname), 'Result URL': event.currentTarget.href, }); saveToRecentKeywords(searchTerm); diff --git a/src/slices/search/components/search-bar/SearchBarMobile.pw.tsx b/src/slices/search/components/search-bar/SearchBarMobile.pw.tsx index ac8a479c9d2..0b73c3053bf 100644 --- a/src/slices/search/components/search-bar/SearchBarMobile.pw.tsx +++ b/src/slices/search/components/search-bar/SearchBarMobile.pw.tsx @@ -11,10 +11,14 @@ import { domain1 } from 'src/features/name-services/domains/mocks/search'; import { userOp1 } from 'src/features/user-ops/mocks/search'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; +import type { TestFnArgs } from 'playwright/lib'; import { test, expect, devices } from 'playwright/lib'; import SearchBarMobile from './SearchBarMobile'; +const mockNoRedirect = (mockApiResponse: TestFnArgs['mockApiResponse'], q: string | number) => + mockApiResponse('core:search_check_redirect', searchMock.noRedirect, { queryParams: { q } }); + // Helper function to open search drawer and wait for input const openSearchDrawer = async(page: Page, isHeroBanner = false) => { if (isHeroBanner) { @@ -52,6 +56,7 @@ test('search by token name +@dark-mode', async({ render, page, mockApiResponse } searchMock.token1, searchMock.token2, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill('o'); @@ -66,6 +71,7 @@ test('search by contract name', async({ render, page, mockApiResponse }) => { searchMock.contract2, searchMock.address2, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarMobile/>); await openSearchDrawer(page); @@ -81,6 +87,7 @@ test('search by name homepage +@dark-mode', async({ render, page, mockApiRespons searchMock.token2, searchMock.contract1, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarMobile isHeroBanner/>); await openSearchDrawer(page, true); await getSearchInput(page, true).fill('o'); @@ -93,6 +100,7 @@ test('search by tag', async({ render, page, mockApiResponse }) => { const apiUrl = await mockApiResponse('core:quick_search', [ searchMock.label1, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill('o'); @@ -105,6 +113,7 @@ test('search by address hash', async({ render, page, mockApiResponse }) => { const apiUrl = await mockApiResponse('core:quick_search', [ searchMock.address1, ], { queryParams: { q: searchMock.address1.address_hash } }); + await mockNoRedirect(mockApiResponse, searchMock.address1.address_hash); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill(searchMock.address1.address_hash); @@ -119,6 +128,7 @@ test('search by meta tag', async({ render, page, mockApiResponse }) => { metatag2, metatag3, ], { queryParams: { q: 'utko' } }); + await mockNoRedirect(mockApiResponse, 'utko'); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill('utko'); @@ -133,6 +143,7 @@ test('search by block number', async({ render, page, mockApiResponse }) => { searchMock.block2, searchMock.block3, ], { queryParams: { q: searchMock.block1.block_number } }); + await mockNoRedirect(mockApiResponse, searchMock.block1.block_number); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill(String(searchMock.block1.block_number)); @@ -145,6 +156,7 @@ test('search by block hash', async({ render, page, mockApiResponse }) => { const apiUrl = await mockApiResponse('core:quick_search', [ searchMock.block1, ], { queryParams: { q: searchMock.block1.block_hash } }); + await mockNoRedirect(mockApiResponse, searchMock.block1.block_hash); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill(searchMock.block1.block_hash); @@ -157,6 +169,7 @@ test('search by tx hash', async({ render, page, mockApiResponse }) => { const apiUrl = await mockApiResponse('core:quick_search', [ searchMock.tx1, ], { queryParams: { q: searchMock.tx1.transaction_hash } }); + await mockNoRedirect(mockApiResponse, searchMock.tx1.transaction_hash); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill(searchMock.tx1.transaction_hash); @@ -169,6 +182,7 @@ test('search by tac operation hash', async({ render, page, mockApiResponse }) => const apiUrl = await mockApiResponse('core:quick_search', [ tacOperation1, ], { queryParams: { q: tacOperation1.tac_operation.operation_id } }); + await mockNoRedirect(mockApiResponse, tacOperation1.tac_operation.operation_id); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill(tacOperation1.tac_operation.operation_id); @@ -182,6 +196,7 @@ test('search by blob hash', async({ render, page, mockApiResponse, mockEnvs }) = const apiUrl = await mockApiResponse('core:quick_search', [ blob1, ], { queryParams: { q: blob1.blob_hash } }); + await mockNoRedirect(mockApiResponse, blob1.blob_hash); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill(blob1.blob_hash); @@ -195,6 +210,7 @@ test('search by domain name', async({ render, page, mockApiResponse, mockEnvs }) const apiUrl = await mockApiResponse('core:quick_search', [ domain1, ], { queryParams: { q: domain1.ens_info.name } }); + await mockNoRedirect(mockApiResponse, domain1.ens_info.name); await render(<SearchBarMobile/>); await openSearchDrawer(page); @@ -209,6 +225,7 @@ test('search by user op hash', async({ render, page, mockApiResponse, mockEnvs } const apiUrl = await mockApiResponse('core:quick_search', [ userOp1, ], { queryParams: { q: searchMock.tx1.transaction_hash } }); + await mockNoRedirect(mockApiResponse, searchMock.tx1.transaction_hash); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill(searchMock.tx1.transaction_hash); @@ -224,6 +241,7 @@ test('search with view all link', async({ render, page, mockApiResponse }) => { searchMock.contract1, ...Array(47).fill(searchMock.contract1), ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill('o'); @@ -247,6 +265,7 @@ test('scroll suggest to category', async({ render, page, mockApiResponse }) => { searchMock.token2, searchMock.contract1, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill('o'); @@ -278,6 +297,7 @@ test.describe('with apps', () => { const apiUrl = await mockApiResponse('core:quick_search', [ searchMock.token1, ], { queryParams: { q: 'o' } }); + await mockNoRedirect(mockApiResponse, 'o'); await mockConfigResponse('NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', MARKETPLACE_CONFIG_URL, appsMock); await mockAssetResponse(appsMock[0].logo, './playwright/mocks/image_s.jpg'); await mockAssetResponse(appsMock[1].logo, './playwright/mocks/image_s.jpg'); @@ -298,6 +318,7 @@ test.describe('with apps', () => { test.describe('block countdown', () => { test('no results', async({ render, page, mockApiResponse }) => { const apiUrl = await mockApiResponse('core:quick_search', [], { queryParams: { q: '1234567890' } }); + await mockNoRedirect(mockApiResponse, '1234567890'); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill('1234567890'); @@ -310,6 +331,7 @@ test.describe('block countdown', () => { const apiUrl = await mockApiResponse('core:quick_search', [ { ...searchMock.token1, name: '1234567890123456789' }, ], { queryParams: { q: '1234567890' } }); + await mockNoRedirect(mockApiResponse, '1234567890'); await render(<SearchBarMobile/>); await openSearchDrawer(page); await getSearchInput(page).fill('1234567890'); diff --git a/src/slices/search/components/search-bar/SearchBarMobile.tsx b/src/slices/search/components/search-bar/SearchBarMobile.tsx index 67b14cb60b4..74558329a93 100644 --- a/src/slices/search/components/search-bar/SearchBarMobile.tsx +++ b/src/slices/search/components/search-bar/SearchBarMobile.tsx @@ -1,16 +1,16 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; -import type { Route } from 'nextjs-routes'; -import { route } from 'nextjs-routes'; import type { FormEvent } from 'react'; import React from 'react'; import useQuickSearchQuery from 'src/slices/search/hooks/useQuickSearchQuery'; import { getRecentSearchKeywords, saveToRecentKeywords } from 'src/slices/search/utils/recent-search-keywords'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; +import { route } from 'src/shared/router/routes'; +import type { Route } from 'src/shared/router/routes'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import { Button } from 'src/toolkit/chakra/button'; @@ -48,13 +48,13 @@ const SearchBarMobile = ({ isHeroBanner, onGoToSearchResults }: Props) => { if (searchTerm) { const resultRoute: Route = { pathname: '/search-results', query: { q: searchTerm, redirect: redirect ? 'true' : 'false' } }; const url = route(resultRoute); - mixpanel.logEvent(mixpanel.EventTypes.SEARCH_QUERY, { + analytics.logEvent(analytics.EventTypes.SEARCH_QUERY, { 'Search query': searchTerm, - 'Source page type': mixpanel.getPageType(router.pathname), + 'Source page type': analytics.getPageType(router.pathname), 'Result URL': url, }); saveToRecentKeywords(searchTerm); - router.push(resultRoute, undefined, { shallow: true }); + router.push(resultRoute, { shallow: true }); onGoToSearchResults?.(searchTerm); onClose(); } @@ -77,9 +77,9 @@ const SearchBarMobile = ({ isHeroBanner, onGoToSearchResults }: Props) => { const handleItemClick = React.useCallback((event: React.MouseEvent<HTMLAnchorElement>) => { onClose(); - mixpanel.logEvent(mixpanel.EventTypes.SEARCH_QUERY, { + analytics.logEvent(analytics.EventTypes.SEARCH_QUERY, { 'Search query': searchTerm, - 'Source page type': mixpanel.getPageType(router.pathname), + 'Source page type': analytics.getPageType(router.pathname), 'Result URL': event.currentTarget.href, }); saveToRecentKeywords(searchTerm); diff --git a/src/slices/search/components/search-bar/SearchBarRecentKeywords.tsx b/src/slices/search/components/search-bar/SearchBarRecentKeywords.tsx index dc75542d826..b7e4a2f4942 100644 --- a/src/slices/search/components/search-bar/SearchBarRecentKeywords.tsx +++ b/src/slices/search/components/search-bar/SearchBarRecentKeywords.tsx @@ -8,10 +8,10 @@ import { clearRecentSearchKeywords, getRecentSearchKeywords, removeRecentSearchK import TextAd from 'src/features/ads/text/components/TextAd'; import useIsMobile from 'src/shared/hooks/useIsMobile'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import { Link } from 'src/toolkit/chakra/link'; import { ClearButton } from 'src/toolkit/components/buttons/ClearButton'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; type Props = { onClick: (kw: string) => void; @@ -87,7 +87,7 @@ const SearchBarRecentKeywords = ({ onClick, onClear }: Props) => { > { kw.startsWith('0x') ? ( <Box overflow="hidden" whiteSpace="nowrap"> - <HashStringShortenDynamic hash={ kw } noTooltip/> + <Truncate value={ kw } tooltip={ false }/> </Box> ) : <Text overflow="hidden" whiteSpace="nowrap" textOverflow="ellipsis">{ kw }</Text> diff --git a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestAddress.tsx b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestAddress.tsx index d24b0c11958..9c1fa42aa1e 100644 --- a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestAddress.tsx +++ b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestAddress.tsx @@ -16,9 +16,9 @@ import SearchResultMetadataTag from 'src/slices/search/pages/search-results/Sear import * as contract from 'src/features/multichain/utils/contract'; import dayjs from 'src/shared/date-and-time/dayjs'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import highlightText from 'src/shared/texts/highlight-text'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import { ADDRESS_REGEXP } from 'src/toolkit/utils/regexp'; type Props = ItemsProps<schemas['SearchResultAddressOrContract'] | schemas['SearchResultMetadataTag'] | multichain.QuickSearchResultAddress>; @@ -81,7 +81,7 @@ const SearchBarSuggestAddress = ({ data, isMobile, searchTerm, addressFormat }: const tagEl = data.type === 'metadata_tag' ? ( <SearchResultMetadataTag metadata={ data.metadata } addressHash={ hash } searchTerm={ searchTerm } ml={{ base: 0, lg: 'auto' }}/> ) : null; - const addressEl = <HashStringShortenDynamic hash={ hash } noTooltip/>; + const addressEl = <Truncate value={ hash } tooltip={ false }/>; if (isMobile) { return ( diff --git a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestBlock.tsx b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestBlock.tsx index de7ac842e38..cb9310fd309 100644 --- a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestBlock.tsx +++ b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestBlock.tsx @@ -10,10 +10,10 @@ import type { SearchResultBlock } from 'src/slices/search/types/client'; import * as BlockEntity from 'src/slices/block/components/entity/BlockEntity'; import Time from 'src/shared/date-and-time/Time'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import highlightText from 'src/shared/texts/highlight-text'; import { Tag } from 'src/toolkit/chakra/tag'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const SearchBarSuggestBlock = ({ data, isMobile, searchTerm, chainInfo }: ItemsProps<SearchResultBlock | multichain.QuickSearchResultBlock>) => { const icon = <BlockEntity.Icon chain={ chainInfo }/>; @@ -29,7 +29,7 @@ const SearchBarSuggestBlock = ({ data, isMobile, searchTerm, chainInfo }: ItemsP as="mark" display="block" > - <HashStringShortenDynamic hash={ data.block_hash } noTooltip/> + <Truncate value={ data.block_hash } tooltip={ false }/> </Box> ); return ( @@ -58,7 +58,7 @@ const SearchBarSuggestBlock = ({ data, isMobile, searchTerm, chainInfo }: ItemsP as={ shouldHighlightHash ? 'mark' : 'span' } display="block" > - <HashStringShortenDynamic hash={ data.block_hash } noTooltip/> + <Truncate value={ data.block_hash } tooltip={ false }/> </Text> ) : null; const date = 'timestamp' in data && data.timestamp && !isFutureBlock ? <Time timestamp={ data.timestamp } color="text.secondary" format="lll_s"/> : undefined; diff --git a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestBlockCountdown.tsx b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestBlockCountdown.tsx index a8e250e3cd5..06eb5412c45 100644 --- a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestBlockCountdown.tsx +++ b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestBlockCountdown.tsx @@ -1,9 +1,10 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, Box } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; +import { route } from 'src/shared/router/routes'; + import { Link } from 'src/toolkit/chakra/link'; interface Props { diff --git a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestLabel.tsx b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestLabel.tsx index b5ed7ada49a..b91c12db090 100644 --- a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestLabel.tsx +++ b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestLabel.tsx @@ -8,10 +8,11 @@ import type { schemas } from '@blockscout/api-types'; import { toBech32Address } from 'src/slices/address/utils/bech32'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import highlightText from 'src/shared/texts/highlight-text'; import SpriteIcon from 'src/sprite/SpriteIcon'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; + const SearchBarSuggestLabel = ({ data, isMobile, searchTerm, addressFormat }: ItemsProps<schemas['SearchResultLabel']>) => { const icon = <SpriteIcon name="publictags" boxSize={ 5 } color="icon.primary"/>; const hash = data.filecoin_robust_address || (addressFormat === 'bech32' ? toBech32Address(data.address_hash) : data.address_hash); @@ -33,7 +34,7 @@ const SearchBarSuggestLabel = ({ data, isMobile, searchTerm, addressFormat }: It whiteSpace="nowrap" color="text.secondary" > - <HashStringShortenDynamic hash={ hash } noTooltip/> + <Truncate value={ hash } tooltip={ false }/> </Text> ); diff --git a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestToken.tsx b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestToken.tsx index 4bfaa4ee28a..2ec177ecf0e 100644 --- a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestToken.tsx +++ b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestToken.tsx @@ -7,6 +7,7 @@ import React from 'react'; import type { ItemsProps } from './types'; import type { schemas } from '@blockscout/api-types'; import type * as multichain from 'src/features/multichain/types/client'; +import { isFungibleTokenType } from 'src/slices/token/utils/token-types'; import { toBech32Address } from 'src/slices/address/utils/bech32'; import ContractCertifiedLabel from 'src/slices/contract/components/ContractCertifiedLabel'; @@ -14,10 +15,11 @@ import * as TokenEntity from 'src/slices/token/components/entity/TokenEntity'; import * as contract from 'src/features/multichain/utils/contract'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import highlightText from 'src/shared/texts/highlight-text'; import SpriteIcon from 'src/sprite/SpriteIcon'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; + const SearchBarSuggestToken = ({ data, isMobile, searchTerm, addressFormat, chainInfo }: ItemsProps<schemas['SearchResultToken'] | multichain.QuickSearchResultToken>) => { const icon = <TokenEntity.Icon token={{ ...data, type: data.token_type }} chain={ chainInfo }/>; @@ -50,22 +52,23 @@ const SearchBarSuggestToken = const address = ( <Text color="text.secondary" whiteSpace="nowrap" overflow="hidden"> - <HashStringShortenDynamic hash={ hash } noTooltip/> + <Truncate value={ hash } tooltip={ false }/> </Text> ); const contractVerifiedIcon = isVerified && <SpriteIcon name="status/success" boxSize="14px" color="green.500" ml={ 1 } flexShrink={ 0 }/>; + const isFungible = isFungibleTokenType(data.token_type); const additionalInfo = ( <Text overflow="hidden" whiteSpace="nowrap" fontWeight={ 700 }> - { data.token_type === 'ERC-20' && 'exchange_rate' in data && data.exchange_rate && `$${ Number(data.exchange_rate).toLocaleString() }` } - { data.token_type !== 'ERC-20' && data.total_supply && `Items ${ Number(data.total_supply).toLocaleString() }` } + { isFungible && 'exchange_rate' in data && data.exchange_rate && `$${ Number(data.exchange_rate).toLocaleString() }` } + { !isFungible && data.total_supply && `Items ${ Number(data.total_supply).toLocaleString() }` } </Text> ); if (isMobile) { const templateCols = `1fr - ${ (data.token_type === 'ERC-20' && 'exchange_rate' in data && data.exchange_rate) || - (data.token_type !== 'ERC-20' && 'total_supply' in data && data.total_supply) ? ' auto' : '' }`; + ${ (isFungible && 'exchange_rate' in data && data.exchange_rate) || + (!isFungible && 'total_supply' in data && data.total_supply) ? ' auto' : '' }`; return ( <> diff --git a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestTx.tsx b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestTx.tsx index 2ecd90f7770..766409c9c07 100644 --- a/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestTx.tsx +++ b/src/slices/search/components/search-bar/SearchBarSuggest/SearchBarSuggestTx.tsx @@ -10,13 +10,14 @@ import type * as multichain from 'src/features/multichain/types/client'; import * as TxEntity from 'src/slices/tx/components/entity/TxEntity'; import Time from 'src/shared/date-and-time/Time'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; + +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const SearchBarSuggestTx = ({ data, isMobile, chainInfo }: ItemsProps<schemas['SearchResultTransaction'] | multichain.QuickSearchResultTransaction>) => { const icon = <TxEntity.Icon chain={ chainInfo }/>; const hash = ( <chakra.mark overflow="hidden" whiteSpace="nowrap" fontWeight={ 700 }> - <HashStringShortenDynamic hash={ data.transaction_hash } noTooltip/> + <Truncate value={ data.transaction_hash } tooltip={ false }/> </chakra.mark> ); const date = 'timestamp' in data && data.timestamp ? <Time timestamp={ data.timestamp } format="lll_s"/> : undefined; diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-meta-tag-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-meta-tag-dark-mode-1.png index c93b8fe3205..7d349f5c17b 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-meta-tag-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-meta-tag-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-name-homepage-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-name-homepage-dark-mode-1.png index d1a0132b77e..ac382b23a4c 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-name-homepage-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-name-homepage-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-token-name-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-token-name-dark-mode-1.png index 1ff3d115e98..0d6191e382f 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-token-name-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_dark-color-mode_search-by-token-name-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_block-countdown-with-results-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_block-countdown-with-results-1.png index f252a7b91ff..3b19ef42a2a 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_block-countdown-with-results-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_block-countdown-with-results-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_scroll-suggest-to-category-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_scroll-suggest-to-category-1.png index 3479c0a2de9..41995e45cf9 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_scroll-suggest-to-category-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_scroll-suggest-to-category-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-address-hash-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-address-hash-1.png index a7f6625815a..02d6bfcabae 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-address-hash-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-address-hash-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-blob-hash-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-blob-hash-1.png index bffee67d0fe..aacc17cdc6a 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-blob-hash-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-blob-hash-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-meta-tag-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-meta-tag-dark-mode-1.png index 9fc394daa8e..b4dbd6d30c0 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-meta-tag-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-meta-tag-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-name-homepage-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-name-homepage-dark-mode-1.png index 4df78da25b8..f245c00daf3 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-name-homepage-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-name-homepage-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-tag-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-tag-dark-mode-1.png index 3d2007a8948..c8b9d377784 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-tag-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-tag-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-token-name-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-token-name-dark-mode-1.png index edfff1b2470..947ec650e80 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-token-name-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-token-name-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-tx-hash-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-tx-hash-1.png index 37a1262dd56..0ce9a6e5307 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-tx-hash-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-tx-hash-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-user-op-hash-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-user-op-hash-1.png index 78350a1dcf8..29e85027b26 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-user-op-hash-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-by-user-op-hash-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-with-view-all-link-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-with-view-all-link-1.png index 58d1e5c1b22..dc22221e196 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-with-view-all-link-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_search-with-view-all-link-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_with-apps-default-view-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_with-apps-default-view-1.png index 3a6ec0fcd13..cac4e2d5a48 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_with-apps-default-view-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarDesktop.pw.tsx_default_with-apps-default-view-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarInput.pw.tsx_mobile_input-on-home-page-mobile-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarInput.pw.tsx_mobile_input-on-home-page-mobile-dark-mode-1.png index c22fc09673e..f072c0cb6be 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarInput.pw.tsx_mobile_input-on-home-page-mobile-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarInput.pw.tsx_mobile_input-on-home-page-mobile-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarInput.pw.tsx_mobile_input-on-regular-page-mobile-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarInput.pw.tsx_mobile_input-on-regular-page-mobile-dark-mode-1.png index 8f95ce8fa8c..8c6fd049abf 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarInput.pw.tsx_mobile_input-on-regular-page-mobile-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarInput.pw.tsx_mobile_input-on-regular-page-mobile-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_dark-color-mode_search-by-name-homepage-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_dark-color-mode_search-by-name-homepage-dark-mode-1.png index d9d351b7008..090a8f0e6c1 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_dark-color-mode_search-by-name-homepage-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_dark-color-mode_search-by-name-homepage-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_dark-color-mode_search-by-token-name-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_dark-color-mode_search-by-token-name-dark-mode-1.png index 35fb9b9c1de..afd089bc6c5 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_dark-color-mode_search-by-token-name-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_dark-color-mode_search-by-token-name-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_block-countdown-no-results-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_block-countdown-no-results-1.png index 39781998748..bcc3ff7fd85 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_block-countdown-no-results-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_block-countdown-no-results-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_block-countdown-with-results-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_block-countdown-with-results-1.png index d0366ea4f3d..fb578bb2e0a 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_block-countdown-with-results-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_block-countdown-with-results-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_recent-keywords-suggest-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_recent-keywords-suggest-1.png index 87422bc6006..f3bf8df4e44 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_recent-keywords-suggest-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_recent-keywords-suggest-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_scroll-suggest-to-category-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_scroll-suggest-to-category-1.png index cc1c0fe2047..a10aa0a032c 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_scroll-suggest-to-category-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_scroll-suggest-to-category-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-address-hash-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-address-hash-1.png index d638045722d..4618ee4b2b7 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-address-hash-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-address-hash-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-blob-hash-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-blob-hash-1.png index 7bbdb6b332e..3b31769544a 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-blob-hash-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-blob-hash-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-block-hash-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-block-hash-1.png index c841cf6c142..8c5e943fe71 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-block-hash-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-block-hash-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-block-number-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-block-number-1.png index a57eb35abc5..e8d571dd7a6 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-block-number-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-block-number-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-contract-name-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-contract-name-1.png index fd4d65b381e..ec3a4915d91 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-contract-name-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-contract-name-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-domain-name-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-domain-name-1.png index 2b53f818e8f..95051a4cd41 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-domain-name-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-domain-name-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-meta-tag-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-meta-tag-1.png index 63c932dc3bc..3d70db02c9f 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-meta-tag-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-meta-tag-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-name-homepage-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-name-homepage-dark-mode-1.png index 9112629bb73..8e4e72a62ae 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-name-homepage-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-name-homepage-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tac-operation-hash-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tac-operation-hash-1.png index e5eceba9669..02d5df3bb8c 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tac-operation-hash-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tac-operation-hash-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tag-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tag-1.png index ec0434dbdac..a05ae4afe70 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tag-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tag-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-token-name-dark-mode-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-token-name-dark-mode-1.png index c98d9479e8b..4490b0df872 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-token-name-dark-mode-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-token-name-dark-mode-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tx-hash-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tx-hash-1.png index bc8fd939bda..456838c776b 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tx-hash-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-tx-hash-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-user-op-hash-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-user-op-hash-1.png index 8584bb2fc82..7176119a984 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-user-op-hash-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-by-user-op-hash-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-with-view-all-link-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-with-view-all-link-1.png index 0e793d4fdef..4cba76ba479 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-with-view-all-link-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_search-with-view-all-link-1.png differ diff --git a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_with-apps-default-view-1.png b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_with-apps-default-view-1.png index 4bf5beac976..77d4896c27d 100644 Binary files a/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_with-apps-default-view-1.png and b/src/slices/search/components/search-bar/__screenshots__/SearchBarMobile.pw.tsx_default_with-apps-default-view-1.png differ diff --git a/src/slices/search/hooks/useSearchQuery.ts b/src/slices/search/hooks/useSearchQuery.ts index 67ee7266683..5cfea8414a3 100644 --- a/src/slices/search/hooks/useSearchQuery.ts +++ b/src/slices/search/hooks/useSearchQuery.ts @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -11,27 +10,26 @@ import { SEARCH_RESULT_ITEM } from 'src/slices/search/stubs'; import { getExternalSearchItem } from 'src/features/chain-variants/zeta-chain/utils/external-search'; import config from 'src/config'; -import useDebounce from 'src/shared/hooks/useDebounce'; -import useUpdateValueEffect from 'src/shared/hooks/useUpdateValueEffect'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; +import { usePaginationParams } from 'src/shared/pagination/usePaginationParams'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; export default function useSearchQuery(withRedirectCheck?: boolean) { const router = useRouter(); const q = React.useRef(getQueryParamString(router.query.q)); - const initialValue = q.current; - - const [ searchTerm, setSearchTerm ] = React.useState(initialValue); - - const debouncedSearchTerm = useDebounce(searchTerm, 300); const pathname = router.pathname; - const query = useQueryWithPages({ + const appliedSearchTerm = getQueryParamString(usePaginationParams('core:search').filters.q); + const [ searchTerm, setSearchTerm ] = React.useState(appliedSearchTerm); + + const query = useApiPaginatedQuery({ resourceName: 'core:search', - filters: { q: isBech32Address(debouncedSearchTerm) ? fromBech32Address(debouncedSearchTerm) : debouncedSearchTerm }, + queryParams: isBech32Address(appliedSearchTerm) ? { q: fromBech32Address(appliedSearchTerm) } : undefined, options: { - enabled: debouncedSearchTerm.trim().length > 0, + enabled: appliedSearchTerm.trim().length > 0, placeholderData: generateListStub<'core:search'>(SEARCH_RESULT_ITEM, 50, { next_page_params: {} }), }, }); @@ -44,26 +42,30 @@ export default function useSearchQuery(withRedirectCheck?: boolean) { const zetaChainCCTXQuery = useApiQuery('zetachain:transactions', { queryParams: { - hash: debouncedSearchTerm, + hash: appliedSearchTerm, limit: 50, offset: 0, direction: 'DESC', }, - queryOptions: { enabled: config.features.zetachain.isEnabled && debouncedSearchTerm.trim().length > 0 }, + queryOptions: { enabled: config.features.zetachain.isEnabled && appliedSearchTerm.trim().length > 0 }, }); - useUpdateValueEffect(() => { - query.onFilterChange({ q: debouncedSearchTerm }); - }, debouncedSearchTerm); + const { onFilterChange } = query; + const applySearchTerm = useDebouncedFilterChange((value) => onFilterChange({ q: value })); + + const handleSearchTermChange = React.useCallback((value: string) => { + setSearchTerm(value); + applySearchTerm(value); + }, [ applySearchTerm ]); return React.useMemo(() => ({ searchTerm, - debouncedSearchTerm, - handleSearchTermChange: setSearchTerm, + appliedSearchTerm, + handleSearchTermChange, query, redirectCheckQuery, pathname, zetaChainCCTXQuery, - externalSearchItem: getExternalSearchItem(debouncedSearchTerm), - }), [ debouncedSearchTerm, pathname, query, redirectCheckQuery, searchTerm, zetaChainCCTXQuery ]); + externalSearchItem: getExternalSearchItem(appliedSearchTerm), + }), [ appliedSearchTerm, pathname, query, redirectCheckQuery, searchTerm, zetaChainCCTXQuery, handleSearchTermChange ]); } diff --git a/src/slices/search/mocks.ts b/src/slices/search/mocks.ts index 952c09c3bb8..a49b55094ae 100644 --- a/src/slices/search/mocks.ts +++ b/src/slices/search/mocks.ts @@ -161,3 +161,5 @@ export const baseResponse: SearchResult = { ], next_page_params: null, }; + +export const noRedirect = { parameter: null, redirect: false, type: null }; diff --git a/src/slices/search/pages/search-results/SearchResultListItem.tsx b/src/slices/search/pages/search-results/SearchResultListItem.tsx deleted file mode 100644 index 058c63ee150..00000000000 --- a/src/slices/search/pages/search-results/SearchResultListItem.tsx +++ /dev/null @@ -1,513 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { chakra, Flex, Grid, Box, Text } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; -import React from 'react'; -import xss from 'xss'; - -import type { AddressFormat } from 'src/slices/address/types/config'; -import type { SearchResultItem } from 'src/slices/search/types/client'; - -import * as AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import { toBech32Address } from 'src/slices/address/utils/bech32'; -import { toAddressModel } from 'src/slices/address/utils/model'; -import * as BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import ContractCertifiedLabel from 'src/slices/contract/components/ContractCertifiedLabel'; -import { saveToRecentKeywords } from 'src/slices/search/utils/recent-search-keywords'; -import type { SearchResultAppItem } from 'src/slices/search/utils/search-categories'; -import { getItemCategory, getSearchCategories } from 'src/slices/search/utils/search-categories'; -import * as TokenEntity from 'src/slices/token/components/entity/TokenEntity'; -import * as TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import * as TacOperationEntity from 'src/features/chain-variants/tac/components/TacOperationEntity'; -import TacOperationStatus from 'src/features/chain-variants/tac/components/TacOperationStatus'; -import * as BlobEntity from 'src/features/data-availability/components/entity/BlobEntity'; -import * as EnsEntity from 'src/features/name-services/domains/components/EnsEntity'; -import * as UserOpEntity from 'src/features/user-ops/components/entity/UserOpEntity'; - -import * as mixpanel from 'src/services/mixpanel'; -import dayjs from 'src/shared/date-and-time/dayjs'; -import Time from 'src/shared/date-and-time/Time'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; -import highlightText from 'src/shared/texts/highlight-text'; -import SpriteIcon from 'src/sprite/SpriteIcon'; - -import { Badge } from 'src/toolkit/chakra/badge'; -import { useColorMode } from 'src/toolkit/chakra/color-mode'; -import { Image } from 'src/toolkit/chakra/image'; -import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Tag } from 'src/toolkit/chakra/tag'; -import { SECOND } from 'src/toolkit/utils/consts'; -import { ADDRESS_REGEXP } from 'src/toolkit/utils/regexp'; - -import SearchResultMetadataTag from './SearchResultMetadataTag'; - -interface Props { - data: SearchResultItem | SearchResultAppItem; - searchTerm: string; - isLoading?: boolean; - addressFormat?: AddressFormat; -} - -const SearchResultListItem = ({ data, searchTerm, isLoading, addressFormat }: Props) => { - - const handleLinkClick = React.useCallback((e: React.MouseEvent<HTMLAnchorElement>) => { - saveToRecentKeywords(searchTerm); - mixpanel.logEvent(mixpanel.EventTypes.SEARCH_QUERY, { - 'Search query': searchTerm, - 'Source page type': 'Search results', - 'Result URL': e.currentTarget.href, - }); - }, [ searchTerm ]); - - const { colorMode } = useColorMode(); - - const firstRow = (() => { - switch (data.type) { - case 'token': { - const name = data.name + (data.symbol ? ` (${ data.symbol })` : ''); - - return ( - <Flex alignItems="center" overflow="hidden"> - <TokenEntity.Icon token={{ ...data, type: data.token_type }} isLoading={ isLoading }/> - <Link - href={ route({ pathname: '/token/[hash]', query: { hash: data.address_hash } }) } - fontWeight={ 700 } - wordBreak="break-all" - loading={ isLoading } - onClick={ handleLinkClick } - overflow="hidden" - > - <Skeleton - loading={ isLoading } - dangerouslySetInnerHTML={{ __html: highlightText(name, searchTerm) }} - whiteSpace="nowrap" - overflow="hidden" - textOverflow="ellipsis" - /> - </Link> - { data.certified && <ContractCertifiedLabel iconSize={ 4 } boxSize={ 4 } ml={ 1 }/> } - { data.is_verified_via_admin_panel && !data.certified && <SpriteIcon name="certified" boxSize={ 4 } ml={ 1 } color="green.500"/> } - { data.reputation && <TokenEntity.Reputation value={ data.reputation }/> } - </Flex> - ); - } - - case 'metadata_tag': - case 'contract': - case 'address': { - const shouldHighlightHash = ADDRESS_REGEXP.test(searchTerm); - const hash = addressFormat === 'bech32' ? toBech32Address(data.address_hash) : data.address_hash; - - const address = toAddressModel({ - hash: data.address_hash, - filecoin: { - robust: data.filecoin_robust_address ?? null, - actor_type: null, - id: null, - }, - is_contract: data.type === 'contract' || data.is_smart_contract_address, - is_verified: data.is_smart_contract_verified, - name: null, - }); - - return ( - <AddressEntity.Container> - <AddressEntity.Icon address={ address }/> - <AddressEntity.Link - address={ address } - onClick={ handleLinkClick } - > - <AddressEntity.Content - asProp={ shouldHighlightHash ? 'mark' : 'span' } - address={{ ...address, hash }} - textStyle="sm" - fontWeight={ 700 } - /> - </AddressEntity.Link> - <AddressEntity.Copy address={{ ...address, hash }}/> - </AddressEntity.Container> - ); - } - - case 'label': { - return ( - <Flex alignItems="center"> - <SpriteIcon name="publictags" boxSize={ 6 } mr={ 2 } color="icon.primary"/> - <Link - href={ route({ pathname: '/address/[hash]', query: { hash: data.address_hash } }) } - fontWeight={ 700 } - wordBreak="break-all" - loading={ isLoading } - onClick={ handleLinkClick } - > - <span dangerouslySetInnerHTML={{ __html: highlightText(data.name, searchTerm) }}/> - </Link> - </Flex> - ); - } - - case 'app': { - const title = <span dangerouslySetInnerHTML={{ __html: highlightText(data.app.title, searchTerm) }}/>; - return ( - <Flex alignItems="center"> - <Image - borderRadius="base" - boxSize={ 6 } - mr={ 2 } - src={ colorMode === 'dark' && data.app.logoDarkMode ? data.app.logoDarkMode : data.app.logo } - alt={ `${ data.app.title } app icon` } - /> - <Link - href={ route({ pathname: '/apps/[id]/info', query: { id: data.app.id } }) } - fontWeight={ 700 } - wordBreak="break-all" - loading={ isLoading } - onClick={ handleLinkClick } - > - { title } - </Link> - </Flex> - ); - } - - case 'block': { - const shouldHighlightHash = data.block_hash.toLowerCase() === searchTerm.toLowerCase(); - const isFutureBlock = data.timestamp === undefined; - const href = isFutureBlock ? - route({ pathname: '/block/countdown/[height]', query: { height: String(data.block_number) } }) : - route({ pathname: '/block/[height_or_hash]', query: { height_or_hash: data.block_hash ?? String(data.block_number) } }); - - return ( - <BlockEntity.Container> - <BlockEntity.Icon isLoading={ isLoading }/> - <BlockEntity.Link - href={ href } - onClick={ handleLinkClick } - isLoading={ isLoading } - > - <BlockEntity.Content - asProp={ shouldHighlightHash ? 'span' : 'mark' } - number={ Number(data.block_number) } - fontSize="sm" - fontWeight={ 700 } - isLoading={ isLoading } - /> - </BlockEntity.Link> - { data.block_type === 'reorg' && !isLoading && <Tag ml={ 2 }>Reorg</Tag> } - { data.block_type === 'uncle' && !isLoading && <Tag ml={ 2 }>Uncle</Tag> } - </BlockEntity.Container> - ); - } - - case 'transaction': { - return ( - <TxEntity.Container> - <TxEntity.Icon/> - <TxEntity.Link - isLoading={ isLoading } - hash={ data.transaction_hash } - onClick={ handleLinkClick } - > - <TxEntity.Content - asProp="mark" - hash={ data.transaction_hash } - textStyle="sm" - fontWeight={ 700 } - /> - </TxEntity.Link> - </TxEntity.Container> - ); - } - - case 'zetaChainCCTX': { - return ( - <TxEntity.Container> - <SpriteIcon name="interop" boxSize={ 5 } marginRight={ 1 } color="text.secondary"/> - <TxEntity.Link - isLoading={ isLoading } - hash={ data.cctx.index } - href={ route({ pathname: '/cc/tx/[hash]', query: { hash: data.cctx.index } }) } - onClick={ handleLinkClick } - > - <TxEntity.Content - asProp={ data.cctx.index === searchTerm ? 'mark' : 'span' } - hash={ data.cctx.index } - textStyle="sm" - fontWeight={ 700 } - /> - </TxEntity.Link> - </TxEntity.Container> - ); - } - - case 'tac_operation': { - return ( - <TacOperationEntity.Container> - <TacOperationEntity.Icon status={ data.tac_operation.status } isLoading={ isLoading }/> - <TacOperationEntity.Link - isLoading={ isLoading } - id={ data.tac_operation.operation_id } - onClick={ handleLinkClick } - > - <TacOperationEntity.Content - asProp="mark" - id={ data.tac_operation.operation_id } - textStyle="sm" - fontWeight={ 700 } - mr={ 2 } - /> - </TacOperationEntity.Link> - <TacOperationStatus - status={ data.tac_operation.status } - type={ data.tac_operation.type } - errorReason={ data.tac_operation.error_reason } - isRollback={ data.tac_operation.rollback } - isLoading={ isLoading } - /> - { data.tac_operation.rollback && <Badge loading={ isLoading }>Rollback</Badge> } - </TacOperationEntity.Container> - ); - } - - case 'blob': { - return ( - <BlobEntity.Container> - <BlobEntity.Icon/> - <BlobEntity.Link - isLoading={ isLoading } - hash={ data.blob_hash } - onClick={ handleLinkClick } - > - <BlobEntity.Content - asProp="mark" - hash={ data.blob_hash } - textStyle="sm" - fontWeight={ 700 } - /> - </BlobEntity.Link> - </BlobEntity.Container> - ); - } - - case 'user_operation': { - return ( - <UserOpEntity.Container> - <UserOpEntity.Icon/> - <UserOpEntity.Link - isLoading={ isLoading } - hash={ data.user_operation_hash } - onClick={ handleLinkClick } - > - <UserOpEntity.Content - asProp="mark" - hash={ data.user_operation_hash } - textStyle="sm" - fontWeight={ 700 } - /> - </UserOpEntity.Link> - </UserOpEntity.Container> - ); - } - - case 'ens_domain': { - return ( - <EnsEntity.Container> - <EnsEntity.Icon - protocol={ data.ens_info.protocol } - protocolDapp={{ - url: data.ens_info.protocol_dapp_url, - logo: data.ens_info.protocol_dapp_logo, - }}/> - <Link - href={ data.address_hash ? - route({ pathname: '/address/[hash]', query: { hash: data.address_hash } }) : - route({ pathname: '/name-services/domains/[name]', query: { name: data.ens_info.name } }) - } - fontWeight={ 700 } - wordBreak="break-all" - loading={ isLoading } - onClick={ handleLinkClick } - overflow="hidden" - > - <Box - dangerouslySetInnerHTML={{ __html: highlightText(data.ens_info.name, searchTerm) }} - whiteSpace="nowrap" - overflow="hidden" - textOverflow="ellipsis" - /> - </Link> - </EnsEntity.Container> - ); - } - } - })(); - - const secondRow = (() => { - switch (data.type) { - case 'token': { - const templateCols = `1fr - ${ (data.token_type === 'ERC-20' && data.exchange_rate) || (data.token_type !== 'ERC-20' && data.total_supply) ? ' auto' : '' }`; - const hash = data.filecoin_robust_address || (addressFormat === 'bech32' ? toBech32Address(data.address_hash) : data.address_hash); - - return ( - <Grid templateColumns={ templateCols } alignItems="center" gap={ 2 }> - <Skeleton loading={ isLoading } overflow="hidden" display="flex" alignItems="center"> - <Text whiteSpace="nowrap" overflow="hidden"> - <HashStringShortenDynamic hash={ hash } noTooltip/> - </Text> - { data.is_smart_contract_verified && <SpriteIcon name="status/success" boxSize="14px" color="green.500" ml={ 1 } flexShrink={ 0 }/> } - </Skeleton> - <Skeleton loading={ isLoading } overflow="hidden" whiteSpace="nowrap" textOverflow="ellipsis" fontWeight={ 700 }> - { data.token_type === 'ERC-20' && data.exchange_rate && `$${ Number(data.exchange_rate).toLocaleString() }` } - { data.token_type !== 'ERC-20' && data.total_supply && `Items ${ Number(data.total_supply).toLocaleString() }` } - </Skeleton> - </Grid> - ); - } - case 'block': { - const shouldHighlightHash = data.block_hash.toLowerCase() === searchTerm.toLowerCase(); - const isFutureBlock = data.timestamp === undefined; - - if (isFutureBlock) { - return <Skeleton loading={ isLoading }>Learn estimated time for this block to be created.</Skeleton>; - } - - return ( - <> - <Skeleton loading={ isLoading } display="block" whiteSpace="nowrap" overflow="hidden" mb={ 1 }> - <HashStringShortenDynamic hash={ data.block_hash } as={ shouldHighlightHash ? 'mark' : 'span' }/> - </Skeleton> - <Skeleton loading={ isLoading } color="text.secondary" mr={ 2 }> - <Time timestamp={ data.timestamp } format="lll_s"/> - </Skeleton> - </> - ); - } - case 'transaction': { - if (!data.timestamp) { - return null; - } - return ( - <Time timestamp={ data.timestamp } color="text.secondary" format="lll_s"/> - ); - } - case 'zetaChainCCTX': { - return ( - <Time timestamp={ Number(data.cctx.last_update_timestamp) * SECOND } color="text.secondary" format="lll_s"/> - ); - } - case 'tac_operation': { - return ( - <Time timestamp={ data.tac_operation.timestamp } color="text.secondary" format="lll_s"/> - ); - } - case 'user_operation': { - if (!data.timestamp) { - return null; - } - - return ( - <Time timestamp={ data.timestamp } color="text.secondary" format="lll_s"/> - ); - } - case 'label': { - const hash = data.filecoin_robust_address || (addressFormat === 'bech32' ? toBech32Address(data.address_hash) : data.address_hash); - - return ( - <Flex alignItems="center"> - <Box overflow="hidden"> - <HashStringShortenDynamic hash={ hash }/> - </Box> - { data.is_smart_contract_verified && <SpriteIcon name="status/success" boxSize="14px" color="green.500" ml={ 1 } flexShrink={ 0 }/> } - </Flex> - ); - } - case 'app': { - return ( - <Text lineClamp={ 3 }> - { data.app.description } - </Text> - ); - } - case 'metadata_tag': - case 'contract': - case 'address': { - const shouldHighlightHash = ADDRESS_REGEXP.test(searchTerm); - const addressName = data.name || data.ens_info?.name; - const expiresText = data.ens_info?.expiry_date ? ` (expires ${ dayjs(data.ens_info.expiry_date).fromNow() })` : ''; - - return (addressName || data.type === 'metadata_tag') ? ( - <Flex alignItems="center" gap={ 2 } justifyContent="space-between" flexWrap="wrap"> - { addressName && ( - <Flex alignItems="center"> - <Text - overflow="hidden" - whiteSpace="nowrap" - textOverflow="ellipsis" - > - <span dangerouslySetInnerHTML={{ __html: shouldHighlightHash ? xss(addressName) : highlightText(addressName, searchTerm) }}/> - { data.ens_info && ( - data.ens_info.names_count > 1 ? - <chakra.span color="text.secondary"> ({ data.ens_info.names_count > 39 ? '40+' : `+${ data.ens_info.names_count - 1 }` })</chakra.span> : - <chakra.span color="text.secondary">{ expiresText }</chakra.span> - ) } - </Text> - { data.certified && <ContractCertifiedLabel iconSize={ 4 } boxSize={ 4 } ml={ 1 }/> } - </Flex> - ) } - { data.type === 'metadata_tag' && ( - <SearchResultMetadataTag metadata={ data.metadata } addressHash={ data.address_hash } searchTerm={ searchTerm }/> - ) } - </Flex> - ) : - null; - } - case 'ens_domain': { - const expiresText = data.ens_info?.expiry_date ? ` expires ${ dayjs(data.ens_info.expiry_date).fromNow() }` : ''; - const hash = data.filecoin_robust_address || (addressFormat === 'bech32' && data.address_hash ? toBech32Address(data.address_hash) : data.address_hash); - - return ( - <Flex alignItems="center" gap={ 3 }> - { hash && ( - <Box overflow="hidden"> - <HashStringShortenDynamic hash={ hash }/> - </Box> - ) } - { - data.ens_info.names_count > 1 ? - <chakra.span color="text.secondary"> ({ data.ens_info.names_count > 39 ? '40+' : `+${ data.ens_info.names_count - 1 }` })</chakra.span> : - <chakra.span color="text.secondary">{ expiresText }</chakra.span> - } - </Flex> - ); - } - - default: - return null; - } - })(); - - const category = React.useMemo(() => getItemCategory(data), [ data ]); - const searchCategories = React.useMemo(() => getSearchCategories(), []); - - return ( - <ListItemMobile py={ 3 } textStyle="sm" rowGap={ 2 }> - <Grid templateColumns="1fr auto" w="100%" overflow="hidden"> - { firstRow } - <Skeleton loading={ isLoading } color="text.secondary" ml={ 8 } textTransform="capitalize"> - <span>{ category ? searchCategories.find(({ id }) => id === category)?.itemTitleShort : '' }</span> - </Skeleton> - </Grid> - { Boolean(secondRow) && ( - <Box w="100%" overflow="hidden" whiteSpace={ data.type !== 'app' ? 'nowrap' : undefined }> - { secondRow } - </Box> - ) } - </ListItemMobile> - ); -}; - -export default SearchResultListItem; diff --git a/src/slices/search/pages/search-results/SearchResultMetadataTag.tsx b/src/slices/search/pages/search-results/SearchResultMetadataTag.tsx index cee3129d8bb..8eae189db9d 100644 --- a/src/slices/search/pages/search-results/SearchResultMetadataTag.tsx +++ b/src/slices/search/pages/search-results/SearchResultMetadataTag.tsx @@ -6,6 +6,7 @@ import type { AddressMetadataTagApi } from 'src/features/address-metadata/types/ import MetadataTagIcon from 'src/features/address-metadata/components/tag/MetadataTagIcon'; import { getTagName } from 'src/features/address-metadata/components/tag/utils'; +import { isHiddenTag } from 'src/features/address-metadata/utils/is-hidden-tag'; import highlightText from 'src/shared/texts/highlight-text'; @@ -19,6 +20,10 @@ interface Props extends TagProps { } const SearchResultMetadataTag = ({ metadata, searchTerm, addressHash, ...rest }: Props) => { + if (isHiddenTag(metadata)) { + return null; + } + const name = getTagName(metadata, addressHash); return ( diff --git a/src/slices/search/pages/search-results/SearchResultTableItem.tsx b/src/slices/search/pages/search-results/SearchResultTableItem.tsx index 6bea88bdbf9..872d63b52c4 100644 --- a/src/slices/search/pages/search-results/SearchResultTableItem.tsx +++ b/src/slices/search/pages/search-results/SearchResultTableItem.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra, Text, Flex, Box } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import xss from 'xss'; import type { AddressFormat } from 'src/slices/address/types/config'; import type { SearchResultItem } from 'src/slices/search/types/client'; +import { isFungibleTokenType } from 'src/slices/token/utils/token-types'; import * as AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import { toBech32Address } from 'src/slices/address/utils/bech32'; @@ -25,10 +25,10 @@ import * as BlobEntity from 'src/features/data-availability/components/entity/Bl import * as EnsEntity from 'src/features/name-services/domains/components/EnsEntity'; import * as UserOpEntity from 'src/features/user-ops/components/entity/UserOpEntity'; -import * as mixpanel from 'src/services/mixpanel'; +import * as analytics from 'src/shared/analytics'; import dayjs from 'src/shared/date-and-time/dayjs'; import Time from 'src/shared/date-and-time/Time'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; +import { route } from 'src/shared/router/routes'; import highlightText from 'src/shared/texts/highlight-text'; import SpriteIcon from 'src/sprite/SpriteIcon'; @@ -39,6 +39,7 @@ import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; import { Tag } from 'src/toolkit/chakra/tag'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import { SECOND } from 'src/toolkit/utils/consts'; import { ADDRESS_REGEXP } from 'src/toolkit/utils/regexp'; @@ -55,7 +56,7 @@ const SearchResultTableItem = ({ data, searchTerm, isLoading, addressFormat }: P const handleLinkClick = React.useCallback((e: React.MouseEvent<HTMLAnchorElement>) => { saveToRecentKeywords(searchTerm); - mixpanel.logEvent(mixpanel.EventTypes.SEARCH_QUERY, { + analytics.logEvent(analytics.EventTypes.SEARCH_QUERY, { 'Search query': searchTerm, 'Source page type': 'Search results', 'Result URL': e.currentTarget.href, @@ -99,7 +100,7 @@ const SearchResultTableItem = ({ data, searchTerm, isLoading, addressFormat }: P <TableCell verticalAlign="middle"> <Skeleton loading={ isLoading } whiteSpace="nowrap" overflow="hidden" display="flex" alignItems="center"> <Box overflow="hidden" whiteSpace="nowrap" w={ data.is_smart_contract_verified ? 'calc(100%-28px)' : 'unset' }> - <HashStringShortenDynamic hash={ hash }/> + <Truncate value={ hash }/> </Box> { data.is_smart_contract_verified && <SpriteIcon name="status/success" boxSize="14px" color="green.500" ml={ 1 } flexShrink={ 0 }/> } </Skeleton> @@ -107,8 +108,8 @@ const SearchResultTableItem = ({ data, searchTerm, isLoading, addressFormat }: P <TableCell verticalAlign="middle" isNumeric> <Skeleton loading={ isLoading } whiteSpace="nowrap" overflow="hidden"> <Text overflow="hidden" whiteSpace="nowrap" textOverflow="ellipsis" fontWeight={ 700 }> - { data.token_type === 'ERC-20' && data.exchange_rate && `$${ Number(data.exchange_rate).toLocaleString() }` } - { data.token_type !== 'ERC-20' && data.total_supply && `Items ${ Number(data.total_supply).toLocaleString() }` } + { isFungibleTokenType(data.token_type) && data.exchange_rate && `$${ Number(data.exchange_rate).toLocaleString() }` } + { !isFungibleTokenType(data.token_type) && data.total_supply && `Items ${ Number(data.total_supply).toLocaleString() }` } </Text> </Skeleton> </TableCell> @@ -206,7 +207,7 @@ const SearchResultTableItem = ({ data, searchTerm, isLoading, addressFormat }: P <TableCell verticalAlign="middle"> <Flex alignItems="center" overflow="hidden"> <Box overflow="hidden" whiteSpace="nowrap" w={ data.is_smart_contract_verified ? 'calc(100%-28px)' : 'unset' }> - <HashStringShortenDynamic hash={ hash }/> + <Truncate value={ hash }/> </Box> { data.is_smart_contract_verified && <SpriteIcon name="status/success" boxSize="14px" color="green.500" ml={ 1 } flexShrink={ 0 }/> } </Flex> @@ -288,7 +289,7 @@ const SearchResultTableItem = ({ data, searchTerm, isLoading, addressFormat }: P { data.block_type === 'reorg' && !isLoading && <Tag flexShrink={ 0 }>Reorg</Tag> } { data.block_type === 'uncle' && !isLoading && <Tag flexShrink={ 0 }>Uncle</Tag> } <Skeleton loading={ isLoading } overflow="hidden" whiteSpace="nowrap" display="block"> - <HashStringShortenDynamic hash={ data.block_hash } as={ shouldHighlightHash ? 'mark' : 'span' }/> + <Truncate value={ data.block_hash } as={ shouldHighlightHash ? 'mark' : 'span' }/> </Skeleton> </Flex> ) } @@ -483,7 +484,7 @@ const SearchResultTableItem = ({ data, searchTerm, isLoading, addressFormat }: P <Flex alignItems="center" overflow="hidden"> { hash && ( <Box overflow="hidden" whiteSpace="nowrap" w={ data.is_smart_contract_verified ? 'calc(100%-28px)' : 'unset' }> - <HashStringShortenDynamic hash={ hash }/> + <Truncate value={ hash }/> </Box> ) } { data.is_smart_contract_verified && <SpriteIcon name="status/success" boxSize="14px" color="green.500" ml={ 1 } flexShrink={ 0 }/> } diff --git a/src/slices/search/pages/search-results/SearchResults.pw.tsx b/src/slices/search/pages/search-results/SearchResults.pw.tsx index 100568be9fc..f3fa47a6495 100644 --- a/src/slices/search/pages/search-results/SearchResults.pw.tsx +++ b/src/slices/search/pages/search-results/SearchResults.pw.tsx @@ -1,6 +1,8 @@ import type { Page } from '@playwright/test'; import React from 'react'; +import * as indexingStatusMock from 'src/slices/chain/indexing-status/mocks'; +import * as chainMock from 'src/slices/chain/mocks'; import * as searchMock from 'src/slices/search/mocks'; import { metatag1, metatag2, metatag3 } from 'src/features/address-metadata/mocks/search'; @@ -10,11 +12,22 @@ import { apps as appsMock } from 'src/features/marketplace/mocks/dapps'; import { domain1 } from 'src/features/name-services/domains/mocks/search'; import { userOp1 } from 'src/features/user-ops/mocks/search'; +import config from 'src/config'; + import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; +import type { TestFnArgs } from 'playwright/lib'; import { test, expect } from 'playwright/lib'; import SearchResults from './SearchResults'; +// The page renders the layout around the results: the footer asks for the backend version and +// indexing status, and the marketplace feature (on by default in .env.pw) for the dapps list +const mockPageChrome = async(mockApiResponse: TestFnArgs['mockApiResponse']) => { + await mockApiResponse('core:homepage_indexing_status', indexingStatusMock.finished); + await mockApiResponse('core:config_backend_version', chainMock.backendVersion); + await mockApiResponse('admin:marketplace_dapps', [], { pathParams: { instanceId: config.apis.admin?.instanceId } }); +}; + // Might not be the best solution but simply scrolling to the top doesn't work async function resetScroll(page: Page) { await page.evaluate(() => window.scrollTo(0, 0)); @@ -42,7 +55,7 @@ async function resetScroll(page: Page) { } test.describe('search by name', () => { - test('+@mobile +@dark-mode', async({ render, mockApiResponse, mockAssetResponse, mockEnvs, page }) => { + test('+@dark-mode', async({ render, mockApiResponse, mockAssetResponse, mockEnvs, page }) => { const hooksConfig = { router: { query: { q: 'o' }, @@ -63,6 +76,7 @@ test.describe('search by name', () => { [ 'NEXT_PUBLIC_MARKETPLACE_ENABLED', 'false' ], ]); await mockApiResponse('core:search', data, { queryParams: { q: 'o' } }); + await mockPageChrome(mockApiResponse); await mockAssetResponse(searchMock.token1.icon_url as string, './playwright/mocks/image_s.jpg'); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); @@ -71,7 +85,7 @@ test.describe('search by name', () => { }); }); -test('search by address hash +@mobile', async({ render, mockApiResponse, page }) => { +test('search by address hash', async({ render, mockApiResponse, page }) => { const hooksConfig = { router: { query: { q: searchMock.address1.address_hash }, @@ -82,6 +96,7 @@ test('search by address hash +@mobile', async({ render, mockApiResponse, page }) next_page_params: null, }; await mockApiResponse('core:search', data, { queryParams: { q: searchMock.address1.address_hash } }); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); @@ -89,7 +104,7 @@ test('search by address hash +@mobile', async({ render, mockApiResponse, page }) await expect(component.locator('main')).toHaveScreenshot(); }); -test('search by meta tag +@mobile', async({ render, mockApiResponse, page }) => { +test('search by meta tag', async({ render, mockApiResponse, page }) => { const hooksConfig = { router: { query: { q: 'utko' }, @@ -100,6 +115,7 @@ test('search by meta tag +@mobile', async({ render, mockApiResponse, page }) => next_page_params: null, }; await mockApiResponse('core:search', data, { queryParams: { q: 'utko' } }); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); @@ -107,7 +123,7 @@ test('search by meta tag +@mobile', async({ render, mockApiResponse, page }) => await expect(component.locator('main')).toHaveScreenshot(); }); -test('search by block number +@mobile', async({ render, mockApiResponse, page }) => { +test('search by block number', async({ render, mockApiResponse, page }) => { const hooksConfig = { router: { query: { q: String(searchMock.block1.block_number) }, @@ -118,13 +134,14 @@ test('search by block number +@mobile', async({ render, mockApiResponse, page }) next_page_params: null, }; await mockApiResponse('core:search', data, { queryParams: { q: searchMock.block1.block_number } }); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); await expect(component.locator('main')).toHaveScreenshot(); }); -test('search by block hash +@mobile', async({ render, mockApiResponse, page }) => { +test('search by block hash', async({ render, mockApiResponse, page }) => { const hooksConfig = { router: { query: { q: searchMock.block1.block_hash }, @@ -135,13 +152,14 @@ test('search by block hash +@mobile', async({ render, mockApiResponse, page }) = next_page_params: null, }; await mockApiResponse('core:search', data, { queryParams: { q: searchMock.block1.block_hash } }); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); await expect(component.locator('main')).toHaveScreenshot(); }); -test('search by tx hash +@mobile', async({ render, mockApiResponse, page }) => { +test('search by tx hash', async({ render, mockApiResponse, page }) => { const hooksConfig = { router: { query: { q: searchMock.tx1.transaction_hash }, @@ -152,13 +170,14 @@ test('search by tx hash +@mobile', async({ render, mockApiResponse, page }) => { next_page_params: null, }; await mockApiResponse('core:search', data, { queryParams: { q: searchMock.tx1.transaction_hash } }); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); await expect(component.locator('main')).toHaveScreenshot(); }); -test('search by tac operation hash +@mobile', async({ render, mockApiResponse, mockEnvs, page }) => { +test('search by tac operation hash', async({ render, mockApiResponse, mockEnvs, page }) => { await mockEnvs(ENVS_MAP.tac); const hooksConfig = { router: { @@ -170,13 +189,14 @@ test('search by tac operation hash +@mobile', async({ render, mockApiResponse, m next_page_params: null, }; await mockApiResponse('core:search', data, { queryParams: { q: tacOperation1.tac_operation.operation_id } }); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); await expect(component.locator('main')).toHaveScreenshot(); }); -test('search by blob hash +@mobile', async({ render, mockApiResponse, mockEnvs, page }) => { +test('search by blob hash', async({ render, mockApiResponse, mockEnvs, page }) => { const hooksConfig = { router: { query: { q: blob1.blob_hash }, @@ -188,13 +208,14 @@ test('search by blob hash +@mobile', async({ render, mockApiResponse, mockEnvs, }; await mockEnvs(ENVS_MAP.dataAvailability); await mockApiResponse('core:search', data, { queryParams: { q: blob1.blob_hash } }); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); await expect(component.locator('main')).toHaveScreenshot(); }); -test('search by domain name +@mobile', async({ render, mockApiResponse, mockEnvs, page }) => { +test('search by domain name', async({ render, mockApiResponse, mockEnvs, page }) => { const hooksConfig = { router: { query: { q: domain1.ens_info.name }, @@ -206,13 +227,14 @@ test('search by domain name +@mobile', async({ render, mockApiResponse, mockEnvs }; await mockEnvs(ENVS_MAP.nameService); await mockApiResponse('core:search', data, { queryParams: { q: domain1.ens_info.name } }); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); await expect(component.locator('main')).toHaveScreenshot(); }); -test('search by user op hash +@mobile', async({ render, mockApiResponse, mockEnvs, page }) => { +test('search by user op hash', async({ render, mockApiResponse, mockEnvs, page }) => { const hooksConfig = { router: { query: { q: userOp1.user_operation_hash }, @@ -224,6 +246,7 @@ test('search by user op hash +@mobile', async({ render, mockApiResponse, mockEnv }; await mockEnvs(ENVS_MAP.userOps); await mockApiResponse('core:search', data, { queryParams: { q: userOp1.user_operation_hash } }); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); @@ -231,7 +254,7 @@ test('search by user op hash +@mobile', async({ render, mockApiResponse, mockEnv }); test.describe('with apps', () => { - test('default view +@mobile', async({ render, mockApiResponse, mockConfigResponse, mockAssetResponse, mockEnvs, page }) => { + test('default view', async({ render, mockApiResponse, mockConfigResponse, mockAssetResponse, mockEnvs, page }) => { const MARKETPLACE_CONFIG_URL = 'https://localhost:4000/marketplace-config.json'; const hooksConfig = { router: { @@ -257,9 +280,11 @@ test.describe('with apps', () => { [ 'NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', MARKETPLACE_CONFIG_URL ], ]); await mockApiResponse('core:search', data, { queryParams: { q: 'o' } }); + await mockPageChrome(mockApiResponse); await mockConfigResponse('NEXT_PUBLIC_MARKETPLACE_CONFIG_URL', MARKETPLACE_CONFIG_URL, appsMock); await mockAssetResponse(appsMock[0].logo, './playwright/mocks/image_s.jpg'); await mockAssetResponse(appsMock[1].logo, './playwright/mocks/image_s.jpg'); + await mockAssetResponse(searchMock.token1.icon_url as string, './playwright/mocks/image_s.jpg'); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); @@ -277,18 +302,21 @@ test.describe('block countdown', () => { test('no results', async({ render, mockApiResponse, page }) => { await mockApiResponse('core:search', { items: [], next_page_params: null }, { queryParams: { q: blockHeight } }); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); await expect(component.locator('main')).toHaveScreenshot(); }); - test('with results +@mobile', async({ render, mockApiResponse, page }) => { + test('with results', async({ render, mockApiResponse, mockAssetResponse, page }) => { + await mockAssetResponse(searchMock.token1.icon_url as string, './playwright/mocks/image_s.jpg'); await mockApiResponse( 'core:search', { items: [ { ...searchMock.token1, name: '1234567890123456789' } ], next_page_params: null }, { queryParams: { q: blockHeight } }, ); + await mockPageChrome(mockApiResponse); const component = await render(<SearchResults/>, { hooksConfig }); await resetScroll(page); diff --git a/src/slices/search/pages/search-results/SearchResults.tsx b/src/slices/search/pages/search-results/SearchResults.tsx index e300ca0a4d0..1103e4b83cc 100644 --- a/src/slices/search/pages/search-results/SearchResults.tsx +++ b/src/slices/search/pages/search-results/SearchResults.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, chakra } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import type { FormEvent } from 'react'; import React from 'react'; @@ -29,13 +28,14 @@ import AppErrorBoundary from 'src/shared/errors/AppErrorBoundary'; import Pagination from 'src/shared/pagination/Pagination'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import removeQueryParam from 'src/shared/router/remove-query-param'; +import { useRouter } from 'src/shared/router/useRouter'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import { ContentLoader } from 'src/toolkit/components/loaders/ContentLoader'; import * as regexp from 'src/toolkit/utils/regexp'; import SearchResultsInput from './SearchResultsInput'; -import SearchResultsList from './SearchResultsList'; import SearchResultsTable from './SearchResultsTable'; const nameServicesFeature = config.features.nameServices; @@ -47,15 +47,15 @@ const SearchResultsPageContent = () => { query, redirectCheckQuery, searchTerm, - debouncedSearchTerm, + appliedSearchTerm, handleSearchTermChange, zetaChainCCTXQuery, externalSearchItem, } = useSearchQuery(withRedirectCheck); - const { data, isError, isPlaceholderData, pagination } = query; + const { data, isError, isInitialLoading, pagination } = query; const [ showContent, setShowContent ] = React.useState(!withRedirectCheck); - const marketplaceApps = useMarketplaceApps(debouncedSearchTerm); + const marketplaceApps = useMarketplaceApps(appliedSearchTerm); const settingsContext = useSettingsContext(); const handleNavigateToResults = React.useCallback((searchTerm: string) => { @@ -67,7 +67,7 @@ const SearchResultsPageContent = () => { return; } - if (!debouncedSearchTerm) { + if (!appliedSearchTerm) { setShowContent(true); return; } @@ -115,13 +115,13 @@ const SearchResultsPageContent = () => { setShowContent(true); removeQueryParam(router, 'redirect'); } - }, [ redirectCheckQuery, router, debouncedSearchTerm, showContent ]); + }, [ redirectCheckQuery, router, appliedSearchTerm, showContent ]); const handleSubmit = React.useCallback((event: FormEvent<HTMLFormElement>) => { event.preventDefault(); }, [ ]); - const isLoading = marketplaceApps.isPlaceholderData || isPlaceholderData; + const isLoading = marketplaceApps.isPlaceholderData || isInitialLoading; const displayedItems: Array<SearchResultItem | SearchResultAppItem> = React.useMemo(() => { const apiData = (data?.items || []).filter((item) => { @@ -143,16 +143,16 @@ const SearchResultsPageContent = () => { return true; }); - const futureBlockItem = !isPlaceholderData && + const futureBlockItem = !isInitialLoading && pagination.page === 1 && !data?.next_page_params && apiData.length > 0 && !apiData.some(({ type }) => type === 'block') && - regexp.BLOCK_HEIGHT.test(debouncedSearchTerm) ? + regexp.BLOCK_HEIGHT.test(appliedSearchTerm) ? { type: 'block' as const, block_type: 'block' as const, - block_number: debouncedSearchTerm, + block_number: appliedSearchTerm, block_hash: '', timestamp: undefined, } : undefined; @@ -171,9 +171,9 @@ const SearchResultsPageContent = () => { }, [ data?.items, data?.next_page_params, - isPlaceholderData, + isInitialLoading, pagination.page, - debouncedSearchTerm, + appliedSearchTerm, marketplaceApps.displayedApps, isLoading, zetaChainCCTXQuery.data, @@ -189,27 +189,16 @@ const SearchResultsPageContent = () => { } return ( - <> - <Box hideFrom="lg"> - <SearchResultsList - items={ displayedItems } - searchTerm={ debouncedSearchTerm } - isLoading={ isLoading } - addressFormat={ settingsContext?.addressFormat } - resetKey={ `${ query.queryHash }:${ debouncedSearchTerm }` } - /> - </Box> - <Box hideBelow="lg"> - <SearchResultsTable - items={ displayedItems } - searchTerm={ debouncedSearchTerm } - isLoading={ isLoading } - addressFormat={ settingsContext?.addressFormat } - top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - resetKey={ `${ query.queryHash }:${ debouncedSearchTerm }` } - /> - </Box> - </> + <TableContainerScrollable> + <SearchResultsTable + items={ displayedItems } + searchTerm={ appliedSearchTerm } + isLoading={ isLoading } + addressFormat={ settingsContext?.addressFormat } + top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + resetKey={ `${ query.queryHash }:${ appliedSearchTerm }` } + /> + </TableContainerScrollable> ); })(); @@ -237,10 +226,10 @@ const SearchResultsPageContent = () => { { resultsCount } </chakra.span> <span> matching result{ (((displayedItems.length || 0) + marketplaceApps.displayedApps.length) > 1) || pagination.page > 1 ? 's' : '' } for </span> - "<chakra.span fontWeight={ 700 }>{ debouncedSearchTerm }</chakra.span>" + "<chakra.span fontWeight={ 700 }>{ appliedSearchTerm }</chakra.span>" </Box> - { resultsCount === 0 && regexp.BLOCK_HEIGHT.test(debouncedSearchTerm) && - <SearchBarSuggestBlockCountdown blockHeight={ debouncedSearchTerm } mt={ -4 }/> } + { resultsCount === 0 && regexp.BLOCK_HEIGHT.test(appliedSearchTerm) && + <SearchBarSuggestBlockCountdown blockHeight={ appliedSearchTerm } mt={ -4 }/> } </> ); })(); diff --git a/src/slices/search/pages/search-results/SearchResultsList.tsx b/src/slices/search/pages/search-results/SearchResultsList.tsx deleted file mode 100644 index 5eaf4a3826a..00000000000 --- a/src/slices/search/pages/search-results/SearchResultsList.tsx +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { AddressFormat } from 'src/slices/address/types/config'; -import type { SearchResultItem } from 'src/slices/search/types/client'; - -import type { SearchResultAppItem } from 'src/slices/search/utils/search-categories'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import SearchResultListItem from './SearchResultListItem'; - -interface Props { - items: Array<SearchResultItem | SearchResultAppItem>; - searchTerm: string; - isLoading?: boolean; - addressFormat?: AddressFormat; - resetKey?: string; -} - -const SearchResultsList = ({ items, searchTerm, isLoading, addressFormat, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { items.slice(0, renderedItemsNum).map((item, index) => ( - <SearchResultListItem - key={ (isLoading ? 'placeholder_' : 'actual_') + index } - data={ item } - searchTerm={ searchTerm } - isLoading={ isLoading } - addressFormat={ addressFormat } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(SearchResultsList); diff --git a/src/slices/search/pages/search-results/SearchResultsTable.tsx b/src/slices/search/pages/search-results/SearchResultsTable.tsx index 63be653e109..9879ebb129e 100644 --- a/src/slices/search/pages/search-results/SearchResultsTable.tsx +++ b/src/slices/search/pages/search-results/SearchResultsTable.tsx @@ -26,7 +26,7 @@ const SearchResultsTable = ({ items, searchTerm, isLoading, addressFormat, top, const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); return ( - <TableRoot fontWeight={ 500 }> + <TableRoot minW="1000px" fontWeight={ 500 }> <TableHeaderSticky top={ top }> <TableRow> <TableColumnHeader width="30%">Search result</TableColumnHeader> diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_dark-color-mode_search-by-name-dark-mode-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_dark-color-mode_search-by-name-dark-mode-1.png new file mode 100644 index 00000000000..0d7c095be54 Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_dark-color-mode_search-by-name-dark-mode-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_dark-color-mode_search-by-name-mobile-dark-mode-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_dark-color-mode_search-by-name-mobile-dark-mode-1.png deleted file mode 100644 index cb1bac34d00..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_dark-color-mode_search-by-name-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_block-countdown-with-results-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_block-countdown-with-results-1.png new file mode 100644 index 00000000000..72059a387db Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_block-countdown-with-results-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_block-countdown-with-results-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_block-countdown-with-results-mobile-1.png deleted file mode 100644 index af248ef70db..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_block-countdown-with-results-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-address-hash-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-address-hash-1.png new file mode 100644 index 00000000000..abf37676d4d Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-address-hash-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-address-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-address-hash-mobile-1.png deleted file mode 100644 index 97b87042b3e..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-address-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-blob-hash-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-blob-hash-1.png new file mode 100644 index 00000000000..35e8e5a060c Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-blob-hash-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-blob-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-blob-hash-mobile-1.png deleted file mode 100644 index ac73a405b63..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-blob-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-hash-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-hash-1.png new file mode 100644 index 00000000000..6b28b3894c1 Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-hash-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-hash-mobile-1.png deleted file mode 100644 index 93865992182..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-number-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-number-1.png new file mode 100644 index 00000000000..690fe6af466 Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-number-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-number-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-number-mobile-1.png deleted file mode 100644 index 9af59ba8300..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-block-number-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-domain-name-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-domain-name-1.png new file mode 100644 index 00000000000..d1d217935e9 Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-domain-name-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-domain-name-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-domain-name-mobile-1.png deleted file mode 100644 index c367d3ee8cc..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-domain-name-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-meta-tag-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-meta-tag-1.png new file mode 100644 index 00000000000..fe5933ca004 Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-meta-tag-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-meta-tag-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-meta-tag-mobile-1.png deleted file mode 100644 index 7374a5ea1d3..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-meta-tag-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-name-dark-mode-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-name-dark-mode-1.png new file mode 100644 index 00000000000..07f04b4f77e Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-name-dark-mode-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-name-mobile-dark-mode-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-name-mobile-dark-mode-1.png deleted file mode 100644 index a0747a00949..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-name-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tac-operation-hash-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tac-operation-hash-1.png new file mode 100644 index 00000000000..b2000134410 Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tac-operation-hash-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tac-operation-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tac-operation-hash-mobile-1.png deleted file mode 100644 index 89300d8d122..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tac-operation-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tx-hash-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tx-hash-1.png new file mode 100644 index 00000000000..9c0e63aba6b Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tx-hash-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tx-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tx-hash-mobile-1.png deleted file mode 100644 index 6120d603f8a..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-tx-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-user-op-hash-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-user-op-hash-1.png new file mode 100644 index 00000000000..b3e53516432 Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-user-op-hash-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-user-op-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-user-op-hash-mobile-1.png deleted file mode 100644 index d940b6b648b..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_search-by-user-op-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_with-apps-default-view-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_with-apps-default-view-1.png new file mode 100644 index 00000000000..c4ddfa57678 Binary files /dev/null and b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_with-apps-default-view-1.png differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_with-apps-default-view-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_with-apps-default-view-mobile-1.png deleted file mode 100644 index 6e08e4f7093..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_default_with-apps-default-view-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_block-countdown-with-results-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_block-countdown-with-results-mobile-1.png deleted file mode 100644 index 2d4092f259f..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_block-countdown-with-results-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-address-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-address-hash-mobile-1.png deleted file mode 100644 index fe0a9e078f1..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-address-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-blob-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-blob-hash-mobile-1.png deleted file mode 100644 index c8202231432..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-blob-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-block-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-block-hash-mobile-1.png deleted file mode 100644 index c89420aab0e..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-block-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-block-number-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-block-number-mobile-1.png deleted file mode 100644 index 4e7c6be93e4..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-block-number-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-domain-name-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-domain-name-mobile-1.png deleted file mode 100644 index bccd80974b4..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-domain-name-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-meta-tag-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-meta-tag-mobile-1.png deleted file mode 100644 index e0e542344a5..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-meta-tag-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-name-mobile-dark-mode-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-name-mobile-dark-mode-1.png deleted file mode 100644 index 2cd7fa85f06..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-name-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-tac-operation-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-tac-operation-hash-mobile-1.png deleted file mode 100644 index e7fae60e55c..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-tac-operation-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-tx-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-tx-hash-mobile-1.png deleted file mode 100644 index 400d63e170e..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-tx-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-user-op-hash-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-user-op-hash-mobile-1.png deleted file mode 100644 index cd920de3553..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_search-by-user-op-hash-mobile-1.png and /dev/null differ diff --git a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_with-apps-default-view-mobile-1.png b/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_with-apps-default-view-mobile-1.png deleted file mode 100644 index fd69d094b11..00000000000 Binary files a/src/slices/search/pages/search-results/__screenshots__/SearchResults.pw.tsx_mobile_with-apps-default-view-mobile-1.png and /dev/null differ diff --git a/src/slices/search/utils/search-categories.spec.ts b/src/slices/search/utils/search-categories.spec.ts new file mode 100644 index 00000000000..e836620d559 --- /dev/null +++ b/src/slices/search/utils/search-categories.spec.ts @@ -0,0 +1,68 @@ +import * as searchMock from 'src/slices/search/mocks'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import type { Category } from './search-categories'; + +const NO_ADDITIONAL_TOKEN_TYPES = undefined; + +function getTokenCategory(tokenType: string, envs: Array<[ string, string ]> | undefined): Promise<Category | undefined> { + return withEnvs(envs, async() => { + const { getItemCategory } = await import('./search-categories'); + return getItemCategory({ ...searchMock.token1, token_type: tokenType }); + }); +} + +describe('getItemCategory', () => { + describe('token', () => { + it.each([ + [ 'ERC-20', 'token' ], + [ 'ERC-721', 'nft' ], + [ 'ERC-1155', 'nft' ], + [ 'ERC-8056', 'nft' ], + [ 'ERC-7984', 'nft' ], + ])('%s with no additional token types → %s', async(tokenType, expected) => { + expect(await getTokenCategory(tokenType, NO_ADDITIONAL_TOKEN_TYPES)).toBe(expected); + }); + + it.each([ + [ 'ERC-20', 'token' ], + [ 'ERC-721', 'nft' ], + [ 'ERC-8056', 'token' ], + [ 'ERC-7984', 'confidential_token' ], + ])('%s with ERC-7984 and ERC-8056 enabled → %s', async(tokenType, expected) => { + expect(await getTokenCategory(tokenType, ENVS_MAP.additionalTokenTypes)).toBe(expected); + }); + }); + + it.each([ + [ searchMock.address1, 'address' ], + [ searchMock.contract1, 'address' ], + [ searchMock.block1, 'block' ], + [ searchMock.label1, 'public_tag' ], + [ searchMock.tx1, 'transaction' ], + ])('$type → $1', async(item, expected) => { + const { getItemCategory } = await import('./search-categories'); + expect(getItemCategory(item)).toBe(expected); + }); +}); + +describe('getSearchCategories', () => { + async function getFungibleTokensTitle(envs: Array<[ string, string ]> | undefined): Promise<string | undefined> { + return withEnvs(envs, async() => { + const { getSearchCategories } = await import('./search-categories'); + return getSearchCategories().find((category) => category.id === 'token')?.title; + }); + } + + it('names only ERC-20 when there are no additional token types', async() => { + expect(await getFungibleTokensTitle(NO_ADDITIONAL_TOKEN_TYPES)).toBe('Tokens (ERC-20)'); + }); + + it('lists the enabled fungible additional types, leaving confidential ones to their own group', async() => { + expect(await getFungibleTokensTitle(ENVS_MAP.additionalTokenTypes)).toBe('Tokens (ERC-20, ERC-8056)'); + }); +}); diff --git a/src/slices/search/utils/search-categories.ts b/src/slices/search/utils/search-categories.ts index a416fafd1f0..bea353da8d2 100644 --- a/src/slices/search/utils/search-categories.ts +++ b/src/slices/search/utils/search-categories.ts @@ -4,7 +4,7 @@ import type { MarketplaceDapp } from '@blockscout/admin-rs-types'; import type { CctxListItem } from '@blockscout/zetachain-cctx-types'; import type { QuickSearchResultItem } from 'src/slices/search/types/client'; import type { TokenType } from 'src/slices/token/types/api'; -import { isConfidentialTokenType } from 'src/slices/token/utils/token-types'; +import { getAdditionalTokenTypes, isConfidentialTokenType, isFungibleTokenType } from 'src/slices/token/utils/token-types'; import config from 'src/config'; import { getFeaturePayload } from 'src/config/utils/features'; @@ -37,6 +37,16 @@ export type SearchResultAppItem = { const hasConfidentialTokenType = (chainsConfig: Array<typeof config> = [ config ]) => chainsConfig.some((chainConfig) => chainConfig.slices.token.additionalTypes.some((item) => isConfidentialTokenType(item.id as TokenType))); +const getFungibleTokensCategoryTitle = (chainsConfig: Array<typeof config>): string => { + const typeNames = [ + `${ config.slices.token.standard }-20`, + ...getAdditionalTokenTypes(chainsConfig) + .filter((item) => !isConfidentialTokenType(item.id as TokenType)) + .map((item) => item.name), + ]; + return `Tokens (${ typeNames.join(', ') })`; +}; + export const getSearchCategories = (chainsConfig: Array<typeof config> = [ config ]): Array<{ id: Category; title: string; tabTitle: string; itemTitle: string; itemTitleShort: string }> => { const nameServicesFeatures = chainsConfig.map((chainConfig) => chainConfig.features.nameServices).filter((feature) => feature?.isEnabled); @@ -75,7 +85,7 @@ export const getSearchCategories = ] : []), { id: 'token', - title: `Tokens (${ config.slices.token.standard }-20)`, + title: getFungibleTokensCategoryTitle(chainsConfig), tabTitle: 'Tokens', itemTitle: 'Token', itemTitleShort: 'Token', @@ -167,12 +177,12 @@ export function getItemCategory(item: QuickSearchResultItem | SearchResultAppIte return 'address'; } case 'token': { - if (item.token_type === 'ERC-20') { - return 'token'; - } if (hasConfidentialTokenType([ chainConfig ]) && isConfidentialTokenType(item.token_type as TokenType)) { return 'confidential_token'; } + if (isFungibleTokenType(item.token_type, chainConfig)) { + return 'token'; + } return 'nft'; } case 'block': { diff --git a/src/slices/token-transfer/components/list/TokenTransferList.pw.tsx b/src/slices/token-transfer/components/list/TokenTransferList.pw.tsx deleted file mode 100644 index 1fe4d694863..00000000000 --- a/src/slices/token-transfer/components/list/TokenTransferList.pw.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import * as tokenTransferMock from 'src/slices/token-transfer/mocks'; -import * as tokenInstanceMock from 'src/slices/token/mocks/instance'; - -import { erc7984 } from 'src/features/fhe-operations/mocks/token-transfer'; - -import { test, expect, devices } from 'playwright/lib'; - -import TokenTransferList from './TokenTransferList'; - -test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - -const data = [ - { - ...tokenTransferMock.erc20, - to: { - ...tokenTransferMock.erc20.to, - hash: tokenTransferMock.erc721.to.hash, - }, - }, - tokenTransferMock.erc721, - tokenTransferMock.erc1155A, - tokenTransferMock.erc1155B, - tokenTransferMock.erc1155C, - tokenTransferMock.erc1155D, - erc7984, -]; - -test('without tx info', async({ render, mockAssetResponse }) => { - await mockAssetResponse(tokenInstanceMock.base.image_url as string, './playwright/mocks/image_s.jpg'); - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <TokenTransferList - data={ data } - showTxInfo={ false } - /> - </Box>, - ); - - await expect(component).toHaveScreenshot(); -}); - -test('with tx info', async({ render, mockAssetResponse }) => { - await mockAssetResponse(tokenInstanceMock.base.image_url as string, './playwright/mocks/image_s.jpg'); - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <TokenTransferList - data={ data } - showTxInfo={ true } - /> - </Box>, - ); - - await expect(component).toHaveScreenshot(); -}); diff --git a/src/slices/token-transfer/components/list/TokenTransferList.tsx b/src/slices/token-transfer/components/list/TokenTransferList.tsx deleted file mode 100644 index 1a9cefd064f..00000000000 --- a/src/slices/token-transfer/components/list/TokenTransferList.tsx +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -// TODO: remove this component once tables in mobile are finalized -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import { useMultichainContext } from 'src/features/multichain/context'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import { getTokenTransferKey } from '../../utils/get-token-transfer-key'; -import TokenTransferListItem from './TokenTransferListItem'; - -interface Props { - data: Array<schemas['TokenTransfer']>; - baseAddress?: string; - showTxInfo?: boolean; - enableTimeIncrement?: boolean; - isLoading?: boolean; - resetKey?: string; -} - -const TokenTransferList = ({ data, baseAddress, showTxInfo, enableTimeIncrement, isLoading, resetKey }: Props) => { - const multichainContext = useMultichainContext(); - const chainData = multichainContext?.chain; - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <TokenTransferListItem - key={ getTokenTransferKey(item) + (isLoading ? index : '') } - data={ item } - baseAddress={ baseAddress } - showTxInfo={ showTxInfo } - enableTimeIncrement={ enableTimeIncrement } - isLoading={ isLoading } - chainData={ chainData } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(TokenTransferList); diff --git a/src/slices/token-transfer/components/list/TokenTransferTable.pw.tsx b/src/slices/token-transfer/components/list/TokenTransferTable.pw.tsx deleted file mode 100644 index f7449f4ea1e..00000000000 --- a/src/slices/token-transfer/components/list/TokenTransferTable.pw.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import * as tokenTransferMock from 'src/slices/token-transfer/mocks'; -import * as tokenInstanceMock from 'src/slices/token/mocks/instance'; - -import { test, expect } from 'playwright/lib'; - -import TokenTransferTable from './TokenTransferTable'; - -test('without tx info', async({ render, mockAssetResponse }) => { - await mockAssetResponse(tokenInstanceMock.base.image_url as string, './playwright/mocks/image_s.jpg'); - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <TokenTransferTable - data={ tokenTransferMock.mixTokens.items } - top={ 0 } - showTxInfo={ false } - /> - </Box>, - ); - - await expect(component).toHaveScreenshot(); -}); - -test('with tx info', async({ render, mockAssetResponse }) => { - await mockAssetResponse(tokenInstanceMock.base.image_url as string, './playwright/mocks/image_s.jpg'); - const component = await render( - <Box pt={{ base: '134px', lg: 6 }}> - <TokenTransferTable - data={ tokenTransferMock.mixTokens.items } - top={ 0 } - showTxInfo={ true } - /> - </Box>, - ); - - await expect(component).toHaveScreenshot(); -}); diff --git a/src/slices/token-transfer/components/list/TokenTransferTable.tsx b/src/slices/token-transfer/components/list/TokenTransferTable.tsx deleted file mode 100644 index c4b62779fd0..00000000000 --- a/src/slices/token-transfer/components/list/TokenTransferTable.tsx +++ /dev/null @@ -1,101 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import * as SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; - -import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; - -import { useMultichainContext } from 'src/features/multichain/context'; - -import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; - -import { getTokenTransferKey } from '../../utils/get-token-transfer-key'; -import TokenTransferTableItem from './TokenTransferTableItem'; - -interface Props { - data: Array<schemas['TokenTransfer']>; - baseAddress?: string; - showTxInfo?: boolean; - top: number; - enableTimeIncrement?: boolean; - showSocketInfo?: boolean; - showSocketErrorAlert?: boolean; - socketInfoNum?: number; - isLoading?: boolean; - resetKey?: string; -} - -const TokenTransferTable = ({ - data, - baseAddress, - showTxInfo, - top, - enableTimeIncrement, - showSocketInfo, - showSocketErrorAlert, - socketInfoNum, - isLoading, - resetKey, -}: Props) => { - const multichainContext = useMultichainContext(); - const chainData = multichainContext?.chain; - - const { cutRef, renderedItemsNum } = useLazyRenderedList({ - list: data, - isEnabled: !isLoading, - resetKey, - }); - - return ( - <AddressHighlightProvider> - <TableRoot minW={ chainData ? '1000px' : '950px' }> - <TableHeaderSticky top={ top }> - <TableRow> - { showTxInfo && <TableColumnHeader width="48px"></TableColumnHeader> } - { chainData && <TableColumnHeader width={ showTxInfo ? '32px' : '38px' }/> } - <TableColumnHeader width="230px">Token</TableColumnHeader> - <TableColumnHeader width="160px">Token ID</TableColumnHeader> - { showTxInfo && ( - <TableColumnHeader width="200px"> - Txn hash - <TimeFormatToggle/> - </TableColumnHeader> - ) } - <TableColumnHeader width="60%">From/To</TableColumnHeader> - <TableColumnHeader width="40%" isNumeric>Value</TableColumnHeader> - </TableRow> - </TableHeaderSticky> - <TableBody> - { showSocketInfo && ( - <SocketNewItemsNotice.Desktop - showErrorAlert={ showSocketErrorAlert } - num={ socketInfoNum } - type="token_transfer" - isLoading={ isLoading } - /> - ) } - { data.slice(0, renderedItemsNum).map((item, index) => ( - <TokenTransferTableItem - key={ getTokenTransferKey(item) + (isLoading ? index : '') } - data={ item } - baseAddress={ baseAddress } - showTxInfo={ showTxInfo } - enableTimeIncrement={ enableTimeIncrement } - isLoading={ isLoading } - chainData={ chainData } - /> - )) } - </TableBody> - </TableRoot> - <div ref={ cutRef }/> - </AddressHighlightProvider> - ); -}; - -export default React.memo(TokenTransferTable); diff --git a/src/slices/token-transfer/components/list/__screenshots__/TokenTransferList.pw.tsx_default_with-tx-info-1.png b/src/slices/token-transfer/components/list/__screenshots__/TokenTransferList.pw.tsx_default_with-tx-info-1.png deleted file mode 100644 index b361e265859..00000000000 Binary files a/src/slices/token-transfer/components/list/__screenshots__/TokenTransferList.pw.tsx_default_with-tx-info-1.png and /dev/null differ diff --git a/src/slices/token-transfer/components/list/__screenshots__/TokenTransferList.pw.tsx_default_without-tx-info-1.png b/src/slices/token-transfer/components/list/__screenshots__/TokenTransferList.pw.tsx_default_without-tx-info-1.png deleted file mode 100644 index fb0d807007b..00000000000 Binary files a/src/slices/token-transfer/components/list/__screenshots__/TokenTransferList.pw.tsx_default_without-tx-info-1.png and /dev/null differ diff --git a/src/slices/token-transfer/components/list/__screenshots__/TokenTransferTable.pw.tsx_default_with-tx-info-1.png b/src/slices/token-transfer/components/list/__screenshots__/TokenTransferTable.pw.tsx_default_with-tx-info-1.png deleted file mode 100644 index 9c395ae6740..00000000000 Binary files a/src/slices/token-transfer/components/list/__screenshots__/TokenTransferTable.pw.tsx_default_with-tx-info-1.png and /dev/null differ diff --git a/src/slices/token-transfer/components/list/__screenshots__/TokenTransferTable.pw.tsx_default_without-tx-info-1.png b/src/slices/token-transfer/components/list/__screenshots__/TokenTransferTable.pw.tsx_default_without-tx-info-1.png deleted file mode 100644 index 4cd8f94a053..00000000000 Binary files a/src/slices/token-transfer/components/list/__screenshots__/TokenTransferTable.pw.tsx_default_without-tx-info-1.png and /dev/null differ diff --git a/src/slices/token-transfer/components/snippet/TokenTransferSnippet.tsx b/src/slices/token-transfer/components/snippet/TokenTransferSnippet.tsx index 2391728fdbb..8ec199662a4 100644 --- a/src/slices/token-transfer/components/snippet/TokenTransferSnippet.tsx +++ b/src/slices/token-transfer/components/snippet/TokenTransferSnippet.tsx @@ -4,9 +4,12 @@ import { Flex } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; -import { isConfidentialTokenType } from 'src/slices/token/utils/token-types'; +import { isConfidentialTokenType, isFungibleTokenType } from 'src/slices/token/utils/token-types'; import AddressFromTo from 'src/slices/address/components/from-to/AddressFromTo'; +import { getTokenTransferUiMultiplier } from 'src/slices/token-transfer/utils/get-token-transfer-ui-multiplier'; + +import { useMultichainContext } from 'src/features/multichain/context'; import ConfidentialTokenValue from 'src/shared/values/entity/ConfidentialTokenValue'; @@ -21,80 +24,95 @@ interface Props { isLoading?: boolean; } -const TokenTransferSnippet = ({ data, isLoading, noAddressIcons = true }: Props) => { - - const content = (() => { - - if (isLoading) { - return <Skeleton loading w="250px" h={ 6 }/>; - } - - if (data.token && isConfidentialTokenType(data.token.type)) { - return <ConfidentialTokenValue token={ data.token } loading={ false }/>; +const renderNftTransfer = (token: schemas['Token'], total: schemas['TokenTransfer']['total']) => { + switch (token.type) { + case 'ERC-721': { + if (total && 'token_id' in total && 'token_instance' in total) { + return ( + <TokenTransferSnippetNft + token={ token } + tokenId={ total.token_id } + instance={ total.token_instance } + value="1" + /> + ); + } + return null; } - switch (data.token?.type) { - case 'ERC-20': { - const total = data.total as schemas['TokenTransferTotalFungible'] | null; - if (total === null || total.value === null) { - return null; - } - return <TokenTransferSnippetFiat token={ data.token } value={ total.value } decimals={ total.decimals }/>; + case 'ERC-1155': { + if (total && 'token_id' in total && 'token_instance' in total && 'value' in total) { + return ( + <TokenTransferSnippetNft + token={ token } + tokenId={ total.token_id } + instance={ total.token_instance } + value={ total.value || '1' } + /> + ); } + return null; + } - case 'ERC-721': { - if (data.total && 'token_id' in data.total && 'token_instance' in data.total) { - return ( - <TokenTransferSnippetNft - token={ data.token } - tokenId={ data.total.token_id } - instance={ data.total.token_instance } - value="1" - /> - ); - } + case 'ERC-404': { + if (total === null) { return null; } - case 'ERC-1155': { - if (data.total && 'token_id' in data.total && 'token_instance' in data.total && 'value' in data.total) { - return ( - <TokenTransferSnippetNft - token={ data.token } - tokenId={ data.total.token_id } - instance={ data.total.token_instance } - value={ data.total.value || '1' } - /> - ); - } - return null; + if ('token_id' in total && total.token_id !== null) { + return ( + <TokenTransferSnippetNft + token={ token } + tokenId={ total.token_id } + value="1" + /> + ); } - case 'ERC-404': { - if (data.total === null) { - return null; - } - - if ('token_id' in data.total && data.total.token_id !== null) { - return ( - <TokenTransferSnippetNft - token={ data.token } - tokenId={ data.total.token_id } - value="1" - /> - ); - } else { - if ('value' in data.total && data.total.value) { - return <TokenTransferSnippetFiat token={ data.token } value={ data.total.value } decimals={ data.total.decimals }/>; - } - return null; - } + if ('value' in total && total.value) { + return <TokenTransferSnippetFiat token={ token } value={ total.value } decimals={ total.decimals }/>; } + return null; + } + + default: { + return null; + } + } +}; + +const TokenTransferSnippet = ({ data, isLoading, noAddressIcons = true }: Props) => { + const chainConfig = useMultichainContext()?.chain.app_config; - default: { + const content = (() => { + if (isLoading) { + return <Skeleton loading w="250px" h={ 6 }/>; + } + + if (!data.token) { + return null; + } + + if (isConfidentialTokenType(data.token.type)) { + return <ConfidentialTokenValue token={ data.token } loading={ false }/>; + } + + if (isFungibleTokenType(data.token.type, chainConfig)) { + const total = data.total as schemas['TokenTransferTotalFungible'] | null; + if (total === null || total.value === null) { return null; } + return ( + <TokenTransferSnippetFiat + token={ data.token } + value={ total.value } + decimals={ total.decimals } + multiplier={ getTokenTransferUiMultiplier(data, chainConfig) } + /> + ); } + + return renderNftTransfer(data.token, data.total); })(); const { tokenHash, tokenSymbol } = (() => { diff --git a/src/slices/token-transfer/components/snippet/TokenTransferSnippetFiat.tsx b/src/slices/token-transfer/components/snippet/TokenTransferSnippetFiat.tsx index 1feaa09d723..5ac1a74a1ba 100644 --- a/src/slices/token-transfer/components/snippet/TokenTransferSnippetFiat.tsx +++ b/src/slices/token-transfer/components/snippet/TokenTransferSnippetFiat.tsx @@ -1,27 +1,38 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; +import type BigNumber from 'bignumber.js'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; +import TokenMultiplierTag from 'src/slices/token/components/ui-multiplier/TokenMultiplierTag'; + import TokenValue from 'src/shared/values/entity/TokenValue'; interface Props { token: schemas['Token']; value: string; decimals: string | null; + multiplier?: BigNumber; } -const FtTokenTransferSnippet = ({ token, value, decimals }: Props) => { + +const TokenTransferSnippetFiat = ({ token, value, decimals, multiplier }: Props) => { return ( <TokenValue amount={ value } token={ token } decimals={ decimals } + multiplier={ multiplier } accuracy={ 0 } - startElement={ <chakra.span color="text.secondary">for </chakra.span> } + startElement={ ( + <> + <chakra.span color="text.secondary">for </chakra.span> + { multiplier && <TokenMultiplierTag multiplier={ multiplier } mr={ 2 }/> } + </> + ) } /> ); }; -export default React.memo(FtTokenTransferSnippet); +export default React.memo(TokenTransferSnippetFiat); diff --git a/src/slices/token-transfer/components/table/TokenTransferCellByColumn.spec.tsx b/src/slices/token-transfer/components/table/TokenTransferCellByColumn.spec.tsx new file mode 100644 index 00000000000..d6adb8f0827 --- /dev/null +++ b/src/slices/token-transfer/components/table/TokenTransferCellByColumn.spec.tsx @@ -0,0 +1,235 @@ +// @vitest-environment jsdom +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { schemas } from '@blockscout/api-types'; + +import { erc7984 } from 'src/features/fhe-operations/mocks/token-transfer'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, render, screen } from 'vitest/lib'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import { erc1155A, erc20, erc404A, erc404B, erc721, erc8056 } from '../../mocks'; +import type { Props } from './TokenTransferCellByColumn'; +import TokenTransferCellByColumn from './TokenTransferCellByColumn'; + +const DEFAULT_PROPS = { + isLoading: false, + chainConfig: undefined, + baseAddress: undefined, + tokenId: undefined, + instance: undefined, + enableTimeIncrement: false, +}; + +const CELL_TEST_ID = 'cell'; + +const renderCell = (item: schemas['TokenTransfer'], column: Props['column'], props: Partial<Props> = {}) => { + render( + <div data-testid={ CELL_TEST_ID }> + <TokenTransferCellByColumn { ...DEFAULT_PROPS } item={ item } column={ column } { ...props }/> + </div>, + ); + return screen.getByTestId(CELL_TEST_ID); +}; + +const renderErc8056Cell = (column: Props['column']) => withEnvs(ENVS_MAP.additionalTokenTypes, async() => { + const { render: renderFresh } = await import('vitest/lib'); + const { 'default': Cell } = await import('./TokenTransferCellByColumn'); + renderFresh(<div data-testid={ CELL_TEST_ID }><Cell { ...DEFAULT_PROPS } item={ erc8056 } column={ column }/></div>); + return screen.getByTestId(CELL_TEST_ID).textContent; +}); + +const getInstanceLink = () => screen.queryAllByRole('link').find((link) => link.getAttribute('href')?.includes('/instance/')); + +const SELF_TRANSFER = { ...erc20, to: { ...erc20.to, hash: erc20.from.hash } }; +// the backend can push a transfer whose token is not catalogued yet; the schema types the field as non-null +const NFT_WITHOUT_TOKEN = { ...erc721, token: null } as unknown as schemas['TokenTransfer']; + +describe('TokenTransferCellByColumn', () => { + afterEach(cleanup); + + describe('in / out', () => { + it('tags a transfer to the base address as incoming', () => { + const cell = renderCell(erc20, 'in_out', { baseAddress: erc20.to.hash }); + + expect(cell.textContent).toBe('In'); + }); + + it('tags a transfer from the base address as outgoing', () => { + const cell = renderCell(erc20, 'in_out', { baseAddress: erc20.from.hash.toLowerCase() }); + + expect(cell.textContent).toBe('Out'); + }); + + it('tags a transfer from the base address to itself as self', () => { + const cell = renderCell(SELF_TRANSFER, 'in_out', { baseAddress: erc20.from.hash }); + + expect(cell.textContent).toBe('Self'); + }); + + it('shows a dash when the base address is neither side', () => { + const cell = renderCell(erc20, 'in_out', { baseAddress: erc721.from.hash }); + + expect(cell.textContent).toBe('-'); + }); + + it('shows a dash without a base address', () => { + const cell = renderCell(erc20, 'in_out'); + + expect(cell.textContent).toBe('-'); + }); + }); + + describe('type', () => { + it('shows the token standard', () => { + const cell = renderCell(erc1155A, 'type'); + + expect(cell.textContent).toBe('ERC-1155'); + }); + }); + + describe('transfer type', () => { + it('shows the mint badge for a minting row', () => { + const cell = renderCell(erc1155A, 'transfer_type'); + + expect(cell.textContent).toBe('Minting'); + }); + }); + + describe('amount', () => { + it('shows the fungible amount without its USD value', () => { + const cell = renderCell(erc20, 'amount'); + + expect(cell.textContent).toBe('0.03156737'); + }); + + it('hides the amount of a confidential token', () => { + const cell = renderCell(erc7984, 'amount'); + + expect(cell.textContent).toBe('•••••'); + }); + + it('shows one for an NFT row without a value', () => { + const cell = renderCell(erc721, 'amount'); + + expect(cell.textContent).toBe('1'); + }); + + it('shows a dash for an NFT row whose token is unknown', () => { + const cell = renderCell(NFT_WITHOUT_TOKEN, 'amount'); + + expect(cell.textContent).toBe('-'); + }); + + it('shows a dash for an NFT row without a total', () => { + const cell = renderCell({ ...erc721, total: null }, 'amount'); + + expect(cell.textContent).toBe('-'); + }); + + it('shows one for an ERC-404 row with a token id and a null value', () => { + const cell = renderCell({ ...erc404B, total: { token_id: '4625304364899952', value: null, decimals: '18', token_instance: null } }, 'amount'); + + expect(cell.textContent).toBe('1'); + }); + + it('shows a dash for an ERC-404 row with neither a value nor a token id', () => { + const cell = renderCell({ ...erc404A, total: { token_id: null, value: null, decimals: '18', token_instance: null } }, 'amount'); + + expect(cell.textContent).toBe('-'); + }); + + it('shows one for an ERC-404 row with a token id', () => { + const cell = renderCell(erc404B, 'amount'); + + expect(cell.textContent).toBe('1'); + }); + + it('shows the value of an ERC-1155 row rather than its token id', () => { + const cell = renderCell(erc1155A, 'amount'); + + expect(cell.textContent).toBe('42'); + }); + + it('shows the fungible amount of an ERC-404 row without a token id', () => { + const cell = renderCell(erc404A, 'amount'); + + expect(cell.textContent).toBe('42,000,000'); + }); + + it('scales the amount by the token multiplier without tagging it', async() => { + const text = await renderErc8056Cell('amount'); + + expect(text).toBe('0.05334886'); + }); + }); + + describe('multiplier', () => { + it('shows the factor in force when an ERC-8056 transfer happened', async() => { + const text = await renderErc8056Cell('multiplier'); + + expect(text).toBe('1.69x'); + }); + + it('shows a dash for a transfer without a multiplier', () => { + const cell = renderCell(erc20, 'multiplier'); + + expect(cell.textContent).toBe('-'); + }); + }); + + describe('value', () => { + it('shows the USD value derived from the exchange rate', () => { + const cell = renderCell(erc20, 'value'); + + expect(cell.textContent).toBe('$1.33'); + }); + + it('shows a dash when the token has no exchange rate', () => { + const cell = renderCell(erc721, 'value'); + + expect(cell.textContent).toBe('-'); + }); + }); + + describe('asset', () => { + it('shows only the token symbol for a fungible row', () => { + const cell = renderCell(erc20, 'asset'); + + expect(cell.textContent).toBe('ARIA'); + expect(getInstanceLink()).toBeUndefined(); + }); + + it('shows the token id of an NFT row as a link to the instance, then the token symbol', () => { + const cell = renderCell(erc721, 'asset'); + + expect(cell.textContent).toBe('875879856AriaSA'); + expect(getInstanceLink()?.textContent).toBe('875879856'); + }); + + it('does not link the token id of the current instance', () => { + const cell = renderCell(erc721, 'asset', { tokenId: '875879856' }); + + expect(cell.textContent).toBe('875879856AriaSA'); + expect(getInstanceLink()).toBeUndefined(); + }); + + it('shows the token id of an ERC-1155 row beside the symbol', () => { + renderCell(erc1155A, 'asset'); + + expect(getInstanceLink()?.textContent).toBe('123'); + }); + + it('shows only the token symbol for an ERC-404 row without a token id', () => { + const cell = renderCell(erc404A, 'asset'); + + expect(cell.textContent).toBe('MY_SYMBOL_IS_VERY_LONG'); + expect(getInstanceLink()).toBeUndefined(); + }); + }); +}); diff --git a/src/slices/token-transfer/components/table/TokenTransferCellByColumn.tsx b/src/slices/token-transfer/components/table/TokenTransferCellByColumn.tsx new file mode 100644 index 00000000000..b5b492cca9d --- /dev/null +++ b/src/slices/token-transfer/components/table/TokenTransferCellByColumn.tsx @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Flex } from '@chakra-ui/react'; +import React from 'react'; + +import type { TokenTransferColumnId } from '../../types/client'; +import type { schemas } from '@blockscout/api-types'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; +import { getTokenTypeName, isConfidentialTokenType, NFT_TOKEN_TYPE_IDS } from 'src/slices/token/utils/token-types'; + +import AddressFromTo from 'src/slices/address/components/from-to/AddressFromTo'; +import AddressFromToTag from 'src/slices/address/components/from-to/AddressFromToTag'; +import { getTxCourseType } from 'src/slices/address/utils/tx'; +import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; +import NftEntity from 'src/slices/token/components/entity/NftEntity'; +import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; +import { formatUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; +import TxEntity from 'src/slices/tx/components/entity/TxEntity'; + +import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import AssetValue from 'src/shared/values/entity/AssetValue'; +import calculateUsdValue from 'src/shared/values/entity/calculateUsdValue'; +import ConfidentialValue from 'src/shared/values/entity/ConfidentialValue'; +import SimpleValue from 'src/shared/values/entity/SimpleValue'; +import { DEFAULT_ACCURACY_USD } from 'src/shared/values/entity/utils'; + +import { Badge } from 'src/toolkit/chakra/badge'; +import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; + +import { getTokenTransferUiMultiplier } from '../../utils/get-token-transfer-ui-multiplier'; +import TokenTransferTypeBadge from '../TokenTransferTypeBadge'; + +export interface Props { + readonly item: schemas['TokenTransfer']; + readonly column: TokenTransferColumnId; + readonly isLoading: boolean | undefined; + readonly chainConfig: ClusterChainConfig['app_config'] | undefined; + readonly baseAddress: string | undefined; + readonly tokenId: string | undefined; + readonly instance: schemas['TokenInstance'] | undefined; + readonly enableTimeIncrement: boolean | undefined; +} + +type CellProps = Omit<Props, 'column'>; + +const Dash = ({ isLoading }: Pick<CellProps, 'isLoading'>) => <Skeleton loading={ isLoading }>-</Skeleton>; + +function getFungibleAmount(item: CellProps['item']): { value: string; decimals: string } | undefined { + if (!item.total || !('value' in item.total) || item.total.value === null) { + return undefined; + } + return { value: item.total.value, decimals: item.total.decimals || '0' }; +} + +function getNftTokenId(item: CellProps['item']): string | undefined { + if (!item.token?.type || !NFT_TOKEN_TYPE_IDS.includes(item.token.type)) { + return undefined; + } + if (!item.total || !('token_id' in item.total) || item.total.token_id === null) { + return undefined; + } + return item.total.token_id; +} + +const InOutCell = ({ item, isLoading, baseAddress }: CellProps) => { + const type = getTxCourseType(item.from.hash, item.to?.hash, baseAddress); + if (type === 'unspecified') { + return <Dash isLoading={ isLoading }/>; + } + return <AddressFromToTag type={ type } isLoading={ isLoading }/>; +}; + +const TxHashCell = ({ item, isLoading }: CellProps) => { + if (!item.transaction_hash) { + return <Dash isLoading={ isLoading }/>; + } + return ( + <TxEntity + hash={ item.transaction_hash } + isLoading={ isLoading } + fontWeight={ 600 } + noIcon + truncation="constant" + /> + ); +}; + +const TypeCell = ({ item, isLoading, chainConfig }: CellProps) => { + if (item.token?.type) { + return <Badge loading={ isLoading }>{ getTokenTypeName(item.token.type, chainConfig) }</Badge>; + } + return <Dash isLoading={ isLoading }/>; +}; + +const TransferTypeCell = ({ item, isLoading }: CellProps) => { + return ( + <TokenTransferTypeBadge + methodType={ item.type } + tokenType={ item.token?.type ?? undefined } + transferTokenType={ item.token_type } + loading={ isLoading } + /> + ); +}; + +const MethodCell = ({ item, isLoading }: CellProps) => { + if (!item.method) { + return null; + } + return <Badge loading={ isLoading } truncated>{ item.method }</Badge>; +}; + +const TimestampCell = ({ item, isLoading, enableTimeIncrement }: CellProps) => ( + <TimeWithTooltip + timestamp={ item.timestamp } + enableIncrement={ enableTimeIncrement } + isLoading={ isLoading } + color="text.secondary" + fontWeight="400" + /> +); + +const BlockCell = ({ item, isLoading }: CellProps) => ( + <BlockEntity number={ item.block_number } isLoading={ isLoading } noIcon/> +); + +const FromToCell = ({ item, isLoading, baseAddress }: CellProps) => ( + <AddressFromTo + plainArrow + from={ item.from } + to={ item.to } + current={ baseAddress } + tokenHash={ item.token?.address_hash } + tokenSymbol={ item.token?.symbol ?? undefined } + isLoading={ isLoading } + mode="long" + /> +); + +const MultiplierCell = ({ item, isLoading, chainConfig }: CellProps) => { + const multiplier = getTokenTransferUiMultiplier(item, chainConfig); + if (!multiplier) { + return <Dash isLoading={ isLoading }/>; + } + return ( + <Truncate + value={ formatUiMultiplier(multiplier) } + loading={ isLoading } + color="text.secondary" + type="end" + maxW="100%" + display="block" + /> + ); +}; + +const AmountCell = ({ item, isLoading, chainConfig }: CellProps) => { + const amount = getFungibleAmount(item); + if (!amount) { + if (getNftTokenId(item) !== undefined) { + return <Skeleton loading={ isLoading }>1</Skeleton>; + } + return item.token && isConfidentialTokenType(item.token.type) ? + <ConfidentialValue loading={ isLoading }/> : + <Dash isLoading={ isLoading }/>; + } + return ( + <AssetValue + amount={ amount.value } + decimals={ amount.decimals } + multiplier={ getTokenTransferUiMultiplier(item, chainConfig) } + loading={ isLoading } + /> + ); +}; + +const AssetCell = ({ item, isLoading, tokenId, instance }: CellProps) => { + if (!item.token) { + return <Dash isLoading={ isLoading }/>; + } + const nftTokenId = getNftTokenId(item); + if (nftTokenId === undefined) { + return <TokenEntity token={ item.token } isLoading={ isLoading } noCopy onlySymbol icon={{ marginRight: 1 }}/>; + } + const rowInstance = item.total && 'token_instance' in item.total ? item.total.token_instance : undefined; + return ( + <Flex alignItems="center" columnGap={ 2 }> + <NftEntity + hash={ item.token.address_hash } + id={ nftTokenId } + instance={ instance ?? rowInstance } + noLink={ tokenId === nftTokenId } + isLoading={ isLoading } + w="auto" + maxW="50%" + /> + <TokenEntity + token={ item.token } + isLoading={ isLoading } + noIcon + noCopy + onlySymbol + w="auto" + maxW="50%" + /> + </Flex> + ); +}; + +const ValueCell = ({ item, isLoading, chainConfig }: CellProps) => { + const amount = getFungibleAmount(item); + const exchangeRate = item.token?.exchange_rate; + if (!amount || !exchangeRate) { + return <Dash isLoading={ isLoading }/>; + } + const { usdBn } = calculateUsdValue({ + amount: amount.value, + decimals: amount.decimals, + exchangeRate, + multiplier: getTokenTransferUiMultiplier(item, chainConfig), + }); + return <SimpleValue value={ usdBn } accuracy={ DEFAULT_ACCURACY_USD } prefix="$" loading={ isLoading }/>; +}; + +const TokenTransferCellByColumn = ({ column, ...rest }: Props) => { + switch (column) { + case 'in_out': + return <InOutCell { ...rest }/>; + case 'tx_hash': + return <TxHashCell { ...rest }/>; + case 'type': + return <TypeCell { ...rest }/>; + case 'transfer_type': + return <TransferTypeCell { ...rest }/>; + case 'method': + return <MethodCell { ...rest }/>; + case 'timestamp': + return <TimestampCell { ...rest }/>; + case 'block': + return <BlockCell { ...rest }/>; + case 'from_to': + return <FromToCell { ...rest }/>; + case 'multiplier': + return <MultiplierCell { ...rest }/>; + case 'amount': + return <AmountCell { ...rest }/>; + case 'asset': + return <AssetCell { ...rest }/>; + case 'value': + return <ValueCell { ...rest }/>; + } +}; + +export default React.memo(TokenTransferCellByColumn); diff --git a/src/slices/token-transfer/components/table/TokenTransfersTable.pw.tsx b/src/slices/token-transfer/components/table/TokenTransfersTable.pw.tsx new file mode 100644 index 00000000000..b678420de19 --- /dev/null +++ b/src/slices/token-transfer/components/table/TokenTransfersTable.pw.tsx @@ -0,0 +1,25 @@ +import * as tokenTransferMock from 'src/slices/token-transfer/mocks'; +import * as tokenInstanceMock from 'src/slices/token/mocks/instance'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { expect, test } from 'playwright/lib'; + +import { TOKEN_TRANSFER_COLUMNS } from '../../utils/columns'; +import TokenTransfersTable from './TokenTransfersTable'; + +test('base view', async({ render, mockAssetResponse, mockEnvs, page }) => { + await mockEnvs(ENVS_MAP.additionalTokenTypes); + await mockAssetResponse(tokenInstanceMock.base.image_url as string, './playwright/mocks/image_s.jpg'); + + const component = await render( + <TokenTransfersTable + items={ tokenTransferMock.mixTokens.items } + columns={ TOKEN_TRANSFER_COLUMNS.map(({ id }) => id).filter((id) => id !== 'in_out') } + />, + ); + + await expect(component).toHaveScreenshot(); + await page.mouse.wheel(1000, 0); + await expect(component).toHaveScreenshot(); +}); diff --git a/src/slices/token-transfer/components/table/TokenTransfersTable.spec.tsx b/src/slices/token-transfer/components/table/TokenTransfersTable.spec.tsx new file mode 100644 index 00000000000..529250ade98 --- /dev/null +++ b/src/slices/token-transfer/components/table/TokenTransfersTable.spec.tsx @@ -0,0 +1,105 @@ +// @vitest-environment jsdom +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { schemas } from '@blockscout/api-types'; + +import { getDefaultColumnIds } from 'src/shared/lists/columns/column-overrides'; + +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, render, screen, within } from 'vitest/lib'; + +import { erc1155A, erc1155B, erc1155C, erc1155D, erc20, erc721 } from '../../mocks'; +import { getSurfaceColumnStates, TOKEN_TRANSFER_COLUMNS } from '../../utils/columns'; +import TokenTransfersTable from './TokenTransfersTable'; + +const BATCH_PAGE = [ erc1155A, erc1155B, erc1155C, erc1155D ]; +const NEXT_PAGE = [ erc20, erc721 ]; +const ALL_COLUMNS = [ 'in_out', 'tx_hash', 'type', 'transfer_type', 'method', 'timestamp', 'block', 'from_to', 'amount', 'asset', 'value' ] as const; +// The backend can push a transfer whose token is not catalogued yet (seen on +// the address Token transfers tab via the websocket feed). The schema types the +// field as non-null, so the mock has to be cast. +const WITHOUT_TOKEN = { ...erc20, token: null } as unknown as schemas['TokenTransfer']; + +const getHeaders = (container: HTMLElement) => Array.from(container.querySelectorAll('thead th')).map((th) => th.textContent); + +describe('TokenTransfersTable', () => { + afterEach(cleanup); + + it('renders every item of a batch transfer', () => { + const { container } = render(<TokenTransfersTable columns={ ALL_COLUMNS } items={ BATCH_PAGE }/>); + + expect(container.querySelectorAll('tbody tr')).toHaveLength(BATCH_PAGE.length); + }); + + it('drops all rows of the previous page when the next page arrives', () => { + const { container, rerender } = render(<TokenTransfersTable columns={ ALL_COLUMNS } items={ BATCH_PAGE }/>); + + rerender(<TokenTransfersTable columns={ ALL_COLUMNS } items={ NEXT_PAGE }/>); + + expect(container.querySelectorAll('tbody tr')).toHaveLength(NEXT_PAGE.length); + expect(container.textContent).not.toContain(erc1155A.transaction_hash?.slice(0, 10)); + }); + + it('renders every column of the vocabulary in order', () => { + const { container } = render(<TokenTransfersTable columns={ ALL_COLUMNS } items={ NEXT_PAGE }/>); + + expect(getHeaders(container)).toEqual( + [ 'In / Out', 'Txn hash', 'Token type', 'Transfer type', 'Method', 'Timestamp', 'Block', 'From / To', 'Amount', 'ID / Asset', 'Value' ], + ); + expect(container.querySelectorAll('tbody tr:first-child td')).toHaveLength(ALL_COLUMNS.length); + }); + + it('renders the columns in the order they are passed in', () => { + const { container } = render(<TokenTransfersTable columns={ [ 'value', 'tx_hash', 'type' ] } items={ NEXT_PAGE }/>); + + expect(getHeaders(container)).toEqual([ 'Value', 'Txn hash', 'Token type' ]); + const [ , txHashCell ] = Array.from(container.querySelectorAll('tbody tr:first-child td')); + expect(txHashCell.textContent).toContain(erc20.transaction_hash?.slice(0, 4)); + }); + + it('renders every column it is given, multiplier included', () => { + const { container } = render(<TokenTransfersTable columns={ [ 'tx_hash', 'multiplier', 'amount' ] } items={ NEXT_PAGE }/>); + + expect(getHeaders(container)).toEqual([ 'Txn hash', 'Multiplier', 'Amount' ]); + }); + + it('puts the time format toggle in the timestamp header', () => { + const { container } = render(<TokenTransfersTable columns={ [ 'tx_hash', 'timestamp' ] } items={ NEXT_PAGE }/>); + const [ txHashHeader, timestampHeader ] = Array.from(container.querySelectorAll('thead th')) as Array<HTMLElement>; + + expect(within(timestampHeader).getByRole('button', { name: 'Toggle time format' })).toBeDefined(); + expect(within(txHashHeader).queryByRole('button')).toBeNull(); + }); + + it('renders no chain column outside a multichain context', () => { + render(<TokenTransfersTable columns={ [ 'tx_hash' ] } items={ NEXT_PAGE }/>); + + expect(screen.getAllByRole('columnheader')).toHaveLength(1); + }); + + it('renders a row without a token instead of crashing', () => { + const { container } = render(<TokenTransfersTable columns={ ALL_COLUMNS } items={ [ WITHOUT_TOKEN ] }/>); + + expect(container.querySelectorAll('tbody tr')).toHaveLength(1); + expect(container.querySelectorAll('tbody tr td')).toHaveLength(ALL_COLUMNS.length); + }); + + it('renders the address surface defaults, In / Out first', () => { + const columns = getDefaultColumnIds(TOKEN_TRANSFER_COLUMNS, getSurfaceColumnStates('address', {})); + const { container } = render(<TokenTransfersTable columns={ columns } items={ NEXT_PAGE } baseAddress={ erc20.to.hash }/>); + + expect(getHeaders(container)).toEqual( + [ 'In / Out', 'Txn hash', 'Token type', 'Timestamp', 'From / To', 'Amount', 'ID / Asset', 'Value' ], + ); + expect(container.querySelector('tbody tr:first-child td')?.textContent).toBe('In'); + }); + + it('renders the token surface defaults', () => { + const columns = getDefaultColumnIds(TOKEN_TRANSFER_COLUMNS, getSurfaceColumnStates('token', {})); + const { container } = render(<TokenTransfersTable columns={ columns } items={ NEXT_PAGE }/>); + + expect(getHeaders(container)).toEqual([ 'Txn hash', 'Timestamp', 'From / To', 'Amount', 'ID / Asset', 'Value' ]); + }); +}); diff --git a/src/slices/token-transfer/components/table/TokenTransfersTable.tsx b/src/slices/token-transfer/components/table/TokenTransfersTable.tsx new file mode 100644 index 00000000000..111bf47f850 --- /dev/null +++ b/src/slices/token-transfer/components/table/TokenTransfersTable.tsx @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { TokenTransferColumnId } from '../../types/client'; +import type { schemas } from '@blockscout/api-types'; + +import * as SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; + +import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; + +import { useMultichainContext } from 'src/features/multichain/context'; + +import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; +import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; + +import { TableBody, TableColumnHeader, TableContainerScrollable, TableHeader, TableRoot, TableRow } from 'src/toolkit/chakra/table'; + +import { TOKEN_TRANSFER_COLUMNS } from '../../utils/columns'; +import { getTokenTransferKey } from '../../utils/get-token-transfer-key'; +import TokenTransfersTableItem from './TokenTransfersTableItem'; + +interface Props { + readonly columns: ReadonlyArray<TokenTransferColumnId>; + readonly items: Array<schemas['TokenTransfer']> | undefined; + readonly isLoading?: boolean; + readonly resetKey?: string; + readonly baseAddress?: string; + readonly tokenId?: string; + readonly instance?: schemas['TokenInstance']; + readonly enableTimeIncrement?: boolean; + readonly showSocketInfo?: boolean; + readonly showSocketErrorAlert?: boolean; + readonly socketInfoNum?: number; +} + +const TokenTransfersTable = ({ + columns, + items, + isLoading, + resetKey, + baseAddress, + tokenId, + instance, + enableTimeIncrement, + showSocketInfo, + showSocketErrorAlert, + socketInfoNum, +}: Props) => { + const multichainContext = useMultichainContext(); + const chainData = multichainContext?.chain; + + const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + + const getBaseKey = React.useCallback((item: schemas['TokenTransfer']) => getTokenTransferKey(item, chainData?.id), [ chainData?.id ]); + const keys = useUniqueKeys(items, getBaseKey); + + const visibleColumns = React.useMemo( + // Stryker disable next-line ConditionalExpression: every column id is in TOKEN_TRANSFER_COLUMNS, so find always hits; the filter narrows away undefined + () => columns.map((id) => TOKEN_TRANSFER_COLUMNS.find((column) => column.id === id)).filter((column) => column !== undefined), + [ columns ], + ); + + return ( + <AddressHighlightProvider> + <TableContainerScrollable onlyMobile={ false }> + + <TableRoot minW={{ lg: '700px' }}> + <TableHeader> + <TableRow> + { chainData && <TableColumnHeader width="38px"/> } + { visibleColumns.map((column) => ( + <TableColumnHeader key={ column.id } isNumeric={ column.isNumeric } whiteSpace="nowrap" w={ column.width }> + { column.name } + { column.id === 'timestamp' && <TimeFormatToggle/> } + </TableColumnHeader> + )) } + </TableRow> + </TableHeader> + <TableBody> + { showSocketInfo && ( + <SocketNewItemsNotice.Desktop + colSpan={ visibleColumns.length + (chainData ? 1 : 0) } + showErrorAlert={ showSocketErrorAlert } + num={ socketInfoNum } + type="token_transfer" + isLoading={ isLoading } + /> + ) } + { items?.slice(0, renderedItemsNum).map((item, index) => ( + <TokenTransfersTableItem + key={ keys[index] } + item={ item } + columns={ visibleColumns } + chainData={ chainData } + isLoading={ isLoading } + baseAddress={ baseAddress } + tokenId={ tokenId } + instance={ instance } + enableTimeIncrement={ enableTimeIncrement } + /> + )) } + </TableBody> + </TableRoot> + <div ref={ cutRef }/> + </TableContainerScrollable> + </AddressHighlightProvider> + ); +}; + +export default React.memo(TokenTransfersTable); diff --git a/src/slices/token-transfer/components/table/TokenTransfersTableItem.tsx b/src/slices/token-transfer/components/table/TokenTransfersTableItem.tsx new file mode 100644 index 00000000000..c7d95c09be2 --- /dev/null +++ b/src/slices/token-transfer/components/table/TokenTransfersTableItem.tsx @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { TokenTransferColumn } from '../../types/client'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +import ChainIcon from 'src/shared/external-chains/ChainIcon'; + +import { TableCell, TableRow } from 'src/toolkit/chakra/table'; + +import type { Props as CellProps } from './TokenTransferCellByColumn'; +import TokenTransferCellByColumn from './TokenTransferCellByColumn'; + +interface Props extends Omit<CellProps, 'column' | 'chainConfig'> { + readonly columns: ReadonlyArray<TokenTransferColumn>; + readonly chainData: ClusterChainConfig | undefined; +} + +const TokenTransfersTableItem = ({ columns, chainData, ...rest }: Props) => { + return ( + <TableRow> + { chainData && ( + <TableCell> + <ChainIcon data={ chainData } isLoading={ rest.isLoading }/> + </TableCell> + ) } + { columns.map((column) => ( + <TableCell key={ column.id } isNumeric={ column.isNumeric } verticalAlign="middle"> + <TokenTransferCellByColumn + column={ column.id } + chainConfig={ chainData?.app_config } + { ...rest } + /> + </TableCell> + )) } + </TableRow> + ); +}; + +export default React.memo(TokenTransfersTableItem); diff --git a/src/slices/token-transfer/components/table/__screenshots__/TokenTransfersTable.pw.tsx_default_base-view-1.png b/src/slices/token-transfer/components/table/__screenshots__/TokenTransfersTable.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..2bfaa601629 Binary files /dev/null and b/src/slices/token-transfer/components/table/__screenshots__/TokenTransfersTable.pw.tsx_default_base-view-1.png differ diff --git a/src/slices/token-transfer/components/table/__screenshots__/TokenTransfersTable.pw.tsx_default_base-view-2.png b/src/slices/token-transfer/components/table/__screenshots__/TokenTransfersTable.pw.tsx_default_base-view-2.png new file mode 100644 index 00000000000..c463eeeb878 Binary files /dev/null and b/src/slices/token-transfer/components/table/__screenshots__/TokenTransfersTable.pw.tsx_default_base-view-2.png differ diff --git a/src/slices/token-transfer/hooks/useTokenTransferColumns.spec.ts b/src/slices/token-transfer/hooks/useTokenTransferColumns.spec.ts new file mode 100644 index 00000000000..13eab766262 --- /dev/null +++ b/src/slices/token-transfer/hooks/useTokenTransferColumns.spec.ts @@ -0,0 +1,206 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import mixpanel from 'mixpanel-browser'; + +import type { TokenTransferSurface } from '../types/client'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +import { chainA } from 'src/features/multichain/mocks/chains'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, renderHook } from 'vitest/lib'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import type { SurfaceColumnStatesParams } from '../utils/columns'; + +vi.mock('mixpanel-browser', () => ({ 'default': { init: vi.fn(), track: vi.fn() } })); + +const withMixpanel = (run: () => Promise<void>) => withEnvs([ [ 'NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN', 'test-mixpanel' ] ], run); + +const chainWithoutErc8056 = chainA.app_config as ClusterChainConfig['app_config']; + +const chainWithErc8056 = { + ...chainWithoutErc8056, + slices: { + ...chainWithoutErc8056.slices, + token: { + ...chainWithoutErc8056.slices.token, + additionalTypes: [ { id: 'ERC-8056', name: 'ERC-8056' } ], + }, + }, +} as ClusterChainConfig['app_config']; + +const NO_PARAMS: SurfaceColumnStatesParams = {}; +const ERC20_FILTER = [ 'ERC-20' ]; + +const renderColumnsHook = async(surface: TokenTransferSurface, params: SurfaceColumnStatesParams = NO_PARAMS) => { + const { init } = await import('src/shared/analytics/queue'); + const { getEnabledProviders } = await import('src/shared/analytics/providers'); + await init(getEnabledProviders().map((provider) => ({ provider, options: { debug: false } })), () => {}); + const { useTokenTransferColumns } = await import('./useTokenTransferColumns'); + return renderHook((props: SurfaceColumnStatesParams) => useTokenTransferColumns(surface, props), { initialProps: params }); +}; + +afterEach(() => { + cleanup(); + window.localStorage.clear(); + vi.clearAllMocks(); +}); + +describe('useTokenTransferColumns', () => { + it('shows the surface defaults and offers only its available columns when nothing is stored', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook('tx'); + + expect(result.current.columns).toEqual([ 'type', 'from_to', 'amount', 'asset', 'value' ]); + expect(result.current.selectableColumns.map(({ id }) => id)).toEqual( + [ 'type', 'transfer_type', 'from_to', 'amount', 'asset', 'value' ], + ); + }); + }); + + it('offers off-by-default columns unchecked', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook('token'); + + expect(result.current.columns).toEqual([ 'tx_hash', 'timestamp', 'from_to', 'amount', 'asset', 'value' ]); + expect(result.current.selectableColumns.map(({ id }) => id)).toContain('block'); + expect(result.current.checkedColumns.block).toBeFalsy(); + }); + }); + + it('shows In / Out first among the address surface defaults', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook('address'); + + expect(result.current.columns).toEqual( + [ 'in_out', 'tx_hash', 'type', 'timestamp', 'from_to', 'amount', 'asset', 'value' ], + ); + }); + }); + + it('puts In / Out back first when the stored order lacks it', async() => { + window.localStorage.setItem( + 'table_columns_token_transfers_address', + JSON.stringify({ order: [ 'value', 'tx_hash', 'type', 'transfer_type', 'method', 'timestamp', 'block', 'from_to', 'amount', 'asset' ] }), + ); + + await withMixpanel(async() => { + const { result } = await renderColumnsHook('address'); + + expect(result.current.columns).toEqual( + [ 'in_out', 'value', 'tx_hash', 'type', 'timestamp', 'from_to', 'amount', 'asset' ], + ); + }); + }); + + it('stores each surface under its own key', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook('index'); + act(() => { + result.current.onColumnsChange({ ...result.current.checkedColumns, block: true }); + }); + + expect(JSON.parse(window.localStorage.getItem('table_columns_token_transfers_index') ?? '')).toEqual({ visibility: { block: true } }); + }); + }); + + it('reads the setting of its own surface only', async() => { + window.localStorage.setItem('table_columns_token_transfers_token', JSON.stringify({ visibility: { block: true } })); + + await withMixpanel(async() => { + const { result: index } = await renderColumnsHook('index'); + const { result: address } = await renderColumnsHook('address'); + const { result: token } = await renderColumnsHook('token'); + + expect(token.current.columns).toContain('block'); + expect(index.current.isCustomized).toBe(false); + expect(address.current.isCustomized).toBe(false); + }); + }); + + it('keeps a stored choice to show an off-by-default column, and a stored hide of it changes nothing', async() => { + window.localStorage.setItem('table_columns_token_transfers_index', JSON.stringify({ visibility: { transfer_type: true, block: false } })); + + await withMixpanel(async() => { + const { result } = await renderColumnsHook('index'); + + expect(result.current.columns).toEqual([ 'tx_hash', 'type', 'transfer_type', 'timestamp', 'from_to', 'amount', 'asset', 'value' ]); + }); + }); + + it('logs the table and the surface with the column id', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook('token'); + act(() => { + result.current.onColumnsChange({ ...result.current.checkedColumns, block: true }); + }); + + expect(mixpanel.track).toHaveBeenCalledTimes(1); + expect(mixpanel.track).toHaveBeenCalledWith( + 'Table columns', + { Table: 'Token transfers', Surface: 'token', Column: 'block', State: 'On' }, + undefined, + ); + }); + }); + + it('shows the multiplier column before amount when the chain enables ERC-8056', async() => { + await withMixpanel(async() => { + const { result } = await renderColumnsHook('index', { chainConfig: chainWithErc8056 }); + + expect(result.current.columns).toEqual( + [ 'tx_hash', 'type', 'timestamp', 'from_to', 'multiplier', 'amount', 'asset', 'value' ], + ); + }); + }); + + it('drops the multiplier column from the table and the selector under a type filter without ERC-8056', async() => { + await withMixpanel(async() => { + const { result, rerender } = await renderColumnsHook('address', { chainConfig: chainWithErc8056 }); + rerender({ chainConfig: chainWithErc8056, typeFilter: ERC20_FILTER }); + + expect(result.current.columns).not.toContain('multiplier'); + expect(result.current.selectableColumns.map(({ id }) => id)).not.toContain('multiplier'); + }); + }); + + it('keeps the multiplier column hidden after it is filtered out and back', async() => { + await withMixpanel(async() => { + const { result, rerender } = await renderColumnsHook('address', { chainConfig: chainWithErc8056 }); + act(() => { + result.current.onColumnsChange({ ...result.current.checkedColumns, multiplier: false }); + }); + rerender({ chainConfig: chainWithErc8056, typeFilter: ERC20_FILTER }); + rerender({ chainConfig: chainWithErc8056 }); + + expect(result.current.columns).not.toContain('multiplier'); + expect(result.current.checkedColumns.multiplier).toBeFalsy(); + expect(result.current.selectableColumns.map(({ id }) => id)).toContain('multiplier'); + }); + }); + + it('brings the multiplier column back before amount after another column moved while it was filtered out', async() => { + await withMixpanel(async() => { + const { result, rerender } = await renderColumnsHook('tx', { chainConfig: chainWithErc8056, typeFilter: ERC20_FILTER }); + act(() => { + result.current.onColumnsReorder([ 'value', 'type', 'transfer_type', 'from_to', 'amount', 'asset' ], 'value'); + }); + rerender({ chainConfig: chainWithErc8056 }); + + expect(result.current.columns).toEqual([ 'value', 'type', 'from_to', 'multiplier', 'amount', 'asset' ]); + }); + }); + + it('offers the multiplier column on the token surface only for an ERC-8056 token', async() => { + await withMixpanel(async() => { + const { result: erc8056 } = await renderColumnsHook('token', { chainConfig: chainWithErc8056, tokenType: 'ERC-8056' }); + const { result: erc20 } = await renderColumnsHook('token', { chainConfig: chainWithErc8056, tokenType: 'ERC-20' }); + + expect(erc8056.current.columns).toContain('multiplier'); + expect(erc8056.current.selectableColumns.filter(({ isNumeric }) => isNumeric).map(({ id }) => id)).toEqual([ 'multiplier', 'amount', 'value' ]); + expect(erc20.current.selectableColumns.map(({ id }) => id)).not.toContain('multiplier'); + }); + }); +}); diff --git a/src/slices/token-transfer/hooks/useTokenTransferColumns.ts b/src/slices/token-transfer/hooks/useTokenTransferColumns.ts new file mode 100644 index 00000000000..a2bf9e3920f --- /dev/null +++ b/src/slices/token-transfer/hooks/useTokenTransferColumns.ts @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { TokenTransferColumn, TokenTransferSurface } from '../types/client'; + +import type { PersistedColumnsState, TableColumnsAnalytics } from 'src/shared/lists/columns/usePersistedColumns'; +import { usePersistedColumns } from 'src/shared/lists/columns/usePersistedColumns'; + +import type { SurfaceColumnStatesParams } from '../utils/columns'; +import { getSurfaceColumnStates, TOKEN_TRANSFER_COLUMNS } from '../utils/columns'; + +export type TokenTransferColumnsState = PersistedColumnsState<TokenTransferColumn>; + +export function useTokenTransferColumns( + surface: TokenTransferSurface, + { chainConfig, typeFilter, tokenType }: SurfaceColumnStatesParams, +): TokenTransferColumnsState { + const states = React.useMemo( + () => getSurfaceColumnStates(surface, { chainConfig, typeFilter, tokenType }), + [ surface, chainConfig, typeFilter, tokenType ], + ); + const analytics = React.useMemo((): TableColumnsAnalytics => ({ Table: 'Token transfers', Surface: surface }), [ surface ]); + + return usePersistedColumns({ + storageKey: `table_columns_token_transfers_${ surface }`, + columns: TOKEN_TRANSFER_COLUMNS, + states, + analytics, + }); +} diff --git a/src/slices/token-transfer/hooks/useTokenTransfersQuery.ts b/src/slices/token-transfer/hooks/useTokenTransfersQuery.ts index fda440ac283..a22158d84a4 100644 --- a/src/slices/token-transfer/hooks/useTokenTransfersQuery.ts +++ b/src/slices/token-transfer/hooks/useTokenTransfersQuery.ts @@ -1,57 +1,42 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; import type { TokenType } from 'src/slices/token/types/api'; import { getTokenTransfersStub } from 'src/slices/token-transfer/stubs'; import { getTokenFilterValue } from 'src/slices/token/utils/list-utils'; -import multichainConfig from 'src/features/multichain/chains-config'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; -import getQueryParamString from 'src/shared/router/get-query-param-string'; - -const getFilters = (query: Record<string, string | Array<string> | undefined>) => { - const chainIdParam = getQueryParamString(query.chain_id); - const typeParam = getQueryParamString(query.type); - const config = multichainConfig(); - - const chainConfig = chainIdParam ? config?.chains.find(chain => chain.id === chainIdParam) : config?.chains[0]; - return getTokenFilterValue(typeParam, chainConfig?.app_config) || []; -}; +const NO_TYPES: Array<TokenType> = []; interface Props { - isMultichain?: boolean; + chain?: ClusterChainConfig; enabled?: boolean; } -export default function useTokenTransfersQuery({ isMultichain, enabled }: Props) { - const router = useRouter(); - const [ typeFilter, setTypeFilter ] = React.useState<Array<TokenType>>(getFilters(router.query)); - - React.useEffect(() => { - if (enabled) { - setTypeFilter(getFilters(router.query)); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ enabled ]); - - const query = useQueryWithPages({ +export default function useTokenTransfersQuery({ chain, enabled }: Props) { + const query = useApiPaginatedQuery({ resourceName: 'core:token_transfers_all', - filters: { type: typeFilter }, options: { placeholderData: getTokenTransfersStub(), enabled, }, - isMultichain, + chain, }); + const typeParam = query.filters.type; + const typeFilter = React.useMemo( + () => getTokenFilterValue(typeParam, chain?.app_config) || NO_TYPES, + [ typeParam, chain?.app_config ], + ); + + const { onFilterChange } = query; const onTokenTypesChange = React.useCallback((value: Array<TokenType>) => { - query.onFilterChange({ type: value }); - setTypeFilter(value); - }, [ query ]); + onFilterChange({ type: value }); + }, [ onFilterChange ]); return React.useMemo(() => ({ query, diff --git a/src/slices/token-transfer/mocks.ts b/src/slices/token-transfer/mocks.ts index 9bb6904ef3f..6e2de86ddc5 100644 --- a/src/slices/token-transfer/mocks.ts +++ b/src/slices/token-transfer/mocks.ts @@ -1,6 +1,7 @@ import type { paths, schemas } from '@blockscout/api-types'; import * as addressParamMock from 'src/slices/address/mocks/address-param'; +import * as tokenInfoMock from 'src/slices/token/mocks/info'; import * as tokenInstanceMock from 'src/slices/token/mocks/instance'; import { toTokenModel } from 'src/slices/token/utils/model'; @@ -202,17 +203,28 @@ export const erc404B: schemas['TokenTransfer'] = { total: { token_id: '4625304364899952', token_instance: null }, }; +export const erc8056: schemas['TokenTransfer'] = { + ...erc20, + token: tokenInfoMock.tokenInfoERC8056, + total: { + decimals: '18', + value: '31567373703130350', + ui_multiplier: '1690000000000000000', + }, + transaction_hash: '0x8b7a2e1d4c6f9a3b5e7d1c2f4a6b8d0e2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c2e', + token_type: 'ERC-8056', + method: 'transfer', +}; + export const mixTokens: paths['/api/v2/token-transfers']['get'] = { items: [ erc20, erc721, - erc1155A, - erc1155B, erc1155C, - erc1155D, erc404A, erc404B, erc7984, + erc8056, ], next_page_params: null, }; diff --git a/src/slices/token-transfer/pages/index/TokenTransfers.pw.tsx b/src/slices/token-transfer/pages/index/TokenTransfers.pw.tsx deleted file mode 100644 index 5cf7e88083e..00000000000 --- a/src/slices/token-transfer/pages/index/TokenTransfers.pw.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import React from 'react'; - -import { mixTokens } from 'src/slices/token-transfer/mocks'; -import * as tokenInstanceMock from 'src/slices/token/mocks/instance'; - -import { test, expect } from 'playwright/lib'; - -import TokenTransfers from './TokenTransfers'; - -// FIXME: test is flaky, screenshot in docker container is different from local -test.skip('base view +@mobile', async({ render, mockTextAd, mockApiResponse, mockAssetResponse }) => { - await mockAssetResponse(tokenInstanceMock.base.image_url as string, './playwright/mocks/image_s.jpg'); - await mockTextAd(); - await mockApiResponse('core:token_transfers_all', mixTokens, { queryParams: { type: [ 'all' ] } }); - const component = await render(<TokenTransfers/>); - await expect(component).toHaveScreenshot(); -}); diff --git a/src/slices/token-transfer/pages/index/TokenTransfersListItem.tsx b/src/slices/token-transfer/pages/index/TokenTransfersListItem.tsx deleted file mode 100644 index 63de669b0ca..00000000000 --- a/src/slices/token-transfer/pages/index/TokenTransfersListItem.tsx +++ /dev/null @@ -1,118 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; -import { hasTokenTransferValue, isConfidentialTokenType, NFT_TOKEN_TYPE_IDS } from 'src/slices/token/utils/token-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import NftEntity from 'src/slices/token/components/entity/NftEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import ConfidentialTokenValue from 'src/shared/values/entity/ConfidentialTokenValue'; -import TokenValue from 'src/shared/values/entity/TokenValue'; - -import { Badge } from 'src/toolkit/chakra/badge'; - -interface Props { - item: schemas['TokenTransfer']; - isLoading: boolean; - chainData?: ClusterChainConfig; -}; - -const TokenTransfersListItem = ({ item, isLoading, chainData }: Props) => { - const isConfidential = item.token ? isConfidentialTokenType(item.token.type) : false; - - return ( - <ListItemMobileGrid.Container> - { item.transaction_hash && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Txn hash</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TxEntity hash={ item.transaction_hash } isLoading={ isLoading } truncation="constant_long" noIcon={ !chainData } chain={ chainData }/> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Age</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TimeWithTooltip - timestamp={ item.timestamp } - enableIncrement - isLoading={ isLoading } - /> - </ListItemMobileGrid.Value> - - { item.method && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Method</ListItemMobileGrid.Label><ListItemMobileGrid.Value> - <Badge loading={ isLoading }>{ item.method }</Badge> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Block</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <BlockEntity number={ item.block_number } isLoading={ isLoading } noIcon/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>From</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity address={ item.from } isLoading={ isLoading } truncation="constant"/> - </ListItemMobileGrid.Value> - - <ListItemMobileGrid.Label isLoading={ isLoading }>To</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntity address={ item.to } isLoading={ isLoading } truncation="constant"/> - </ListItemMobileGrid.Value> - - { item.total && 'token_id' in item.total && item.token && item.token.type && - (NFT_TOKEN_TYPE_IDS.includes(item.token.type)) && item.total.token_id !== null && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Token ID</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value overflow="hidden"> - <NftEntity - hash={ item.token.address_hash } - id={ item.total.token_id } - instance={ item.total.token_instance } - isLoading={ isLoading } - noIcon - /> - </ListItemMobileGrid.Value> - </> - ) } - - { item.token && item.total && 'value' in item.total && item.total.value !== null && (hasTokenTransferValue(item.token.type, chainData?.app_config)) && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Amount</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TokenValue - amount={ item.total.value } - token={ item.token } - decimals={ item.total.decimals || '0' } - loading={ isLoading } - /> - </ListItemMobileGrid.Value> - </> - ) } - - { isConfidential && item.token && (!item.total || !('value' in item.total) || item.total.value === null) && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Amount</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <ConfidentialTokenValue - token={ item.token } - loading={ isLoading } - /> - </ListItemMobileGrid.Value> - </> - ) } - </ListItemMobileGrid.Container> - ); -}; - -export default TokenTransfersListItem; diff --git a/src/slices/token-transfer/pages/index/TokenTransfersLocal.tsx b/src/slices/token-transfer/pages/index/TokenTransfersLocal.tsx index 013eb09ead8..813d4d2e776 100644 --- a/src/slices/token-transfer/pages/index/TokenTransfersLocal.tsx +++ b/src/slices/token-transfer/pages/index/TokenTransfersLocal.tsx @@ -1,53 +1,43 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; +import { HStack } from '@chakra-ui/react'; import React from 'react'; import type { TokenType } from 'src/slices/token/types/api'; -import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; +import ActionBar from 'src/shell/page/action-bar/ActionBar'; import TokenTypeFilter from 'src/slices/token/components/TokenTypeFilter'; import PopoverFilter from 'src/shared/filters/PopoverFilter'; +import ColumnsButton from 'src/shared/lists/columns/ColumnsButton'; import DataList from 'src/shared/lists/DataList'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import Pagination from 'src/shared/pagination/Pagination'; +import TokenTransfersTable from '../../components/table/TokenTransfersTable'; +import { useTokenTransferColumns } from '../../hooks/useTokenTransferColumns'; import useTokenTransfersQuery from '../../hooks/useTokenTransfersQuery'; -import { getTokenTransferKey } from '../../utils/get-token-transfer-key'; -import TokenTransfersListItem from './TokenTransfersListItem'; -import TokenTransfersTable from './TokenTransfersTable'; const TokenTransfersLocal = () => { const { query, typeFilter, onTokenTypesChange } = useTokenTransfersQuery({ enabled: true }); - const { cutRef, renderedItemsNum } = useLazyRenderedList({ - list: query.data?.items, - isEnabled: !query.isPlaceholderData, - resetKey: query.queryHash, - }); + const { + columns, + selectableColumns, + checkedColumns, + isCustomized, + onColumnsChange, + onColumnsReorder, + onColumnsReset, + } = useTokenTransferColumns('index', { typeFilter }); const content = ( - <> - <Box hideFrom="lg"> - { query.data?.items.slice(0, renderedItemsNum).map((item, index) => ( - <TokenTransfersListItem - key={ getTokenTransferKey(item) + (query.isPlaceholderData ? index : '') } - isLoading={ query.isPlaceholderData } - item={ item } - /> - )) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - <Box hideBelow="lg"> - <TokenTransfersTable - items={ query.data?.items } - top={ query.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } - isLoading={ query.isPlaceholderData } - resetKey={ query.queryHash } - /> - </Box> - </> + <TokenTransfersTable + columns={ columns } + items={ query.data?.items } + isLoading={ query.isInitialLoading } + resetKey={ query.queryHash } + enableTimeIncrement + /> ); const filter = ( @@ -58,7 +48,17 @@ const TokenTransfersLocal = () => { const actionBar = ( <ActionBar mt={ -6 }> - { filter } + <HStack gap={ 3 }> + { filter } + <ColumnsButton + tableColumns={ selectableColumns } + columns={ checkedColumns } + onChange={ onColumnsChange } + onOrderChange={ onColumnsReorder } + selected={ isCustomized } + onReset={ onColumnsReset } + /> + </HStack> <Pagination { ...query.pagination }/> </ActionBar> ); @@ -70,6 +70,7 @@ const TokenTransfersLocal = () => { emptyText="There are no token transfers." actionBar={ actionBar } hasActiveFilters={ Boolean(typeFilter.length) } + isTransitioning={ query.isTransitioning } emptyStateProps={{ term: 'token transfer', }} diff --git a/src/slices/token-transfer/pages/index/TokenTransfersTable.spec.tsx b/src/slices/token-transfer/pages/index/TokenTransfersTable.spec.tsx deleted file mode 100644 index 5d021cd31f1..00000000000 --- a/src/slices/token-transfer/pages/index/TokenTransfersTable.spec.tsx +++ /dev/null @@ -1,32 +0,0 @@ -// @vitest-environment jsdom -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import { afterEach, describe, expect, it } from 'vitest'; -import { cleanup, render } from 'vitest/lib'; - -import { erc1155A, erc1155B, erc1155C, erc1155D, erc20, erc721 } from '../../mocks'; -import TokenTransfersTable from './TokenTransfersTable'; - -const BATCH_PAGE = [ erc1155A, erc1155B, erc1155C, erc1155D ]; -const NEXT_PAGE = [ erc20, erc721 ]; - -describe('TokenTransfersTable', () => { - afterEach(cleanup); - - it('renders every item of a batch transfer', () => { - const { container } = render(<TokenTransfersTable items={ BATCH_PAGE } top={ 0 }/>); - - expect(container.querySelectorAll('tbody tr')).toHaveLength(BATCH_PAGE.length); - }); - - it('drops all rows of the previous page when the next page arrives', () => { - const { container, rerender } = render(<TokenTransfersTable items={ BATCH_PAGE } top={ 0 }/>); - - rerender(<TokenTransfersTable items={ NEXT_PAGE } top={ 0 }/>); - - expect(container.querySelectorAll('tbody tr')).toHaveLength(NEXT_PAGE.length); - expect(container.textContent).not.toContain(erc1155A.transaction_hash?.slice(0, 10)); - }); -}); diff --git a/src/slices/token-transfer/pages/index/TokenTransfersTable.tsx b/src/slices/token-transfer/pages/index/TokenTransfersTable.tsx deleted file mode 100644 index afd804fd8db..00000000000 --- a/src/slices/token-transfer/pages/index/TokenTransfersTable.tsx +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; - -import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; - -import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; - -import { getTokenTransferKey } from '../../utils/get-token-transfer-key'; -import TokenTransferTableItem from './TokenTransfersTableItem'; - -interface Props { - items?: Array<schemas['TokenTransfer']>; - top: number; - isLoading?: boolean; - chainData?: ClusterChainConfig; - resetKey?: string; -} - -const TokenTransferTable = ({ items, top, isLoading, chainData, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); - - return ( - <AddressHighlightProvider> - <TableRoot minW="950px" tableLayout="auto"> - <TableHeaderSticky top={ top }> - <TableRow> - { chainData && <TableColumnHeader width="38px"/> } - <TableColumnHeader> - Txn hash - <TimeFormatToggle/> - </TableColumnHeader> - <TableColumnHeader>Method</TableColumnHeader> - <TableColumnHeader>Block</TableColumnHeader> - <TableColumnHeader>From/To</TableColumnHeader> - <TableColumnHeader>Token ID</TableColumnHeader> - <TableColumnHeader isNumeric>Amount</TableColumnHeader> - </TableRow> - </TableHeaderSticky> - <TableBody> - { items?.slice(0, renderedItemsNum).map((item, index) => ( - <TokenTransferTableItem - key={ getTokenTransferKey(item) + (isLoading ? index : '') + (chainData ? chainData.id : '') } - item={ item } - isLoading={ isLoading } - chainData={ chainData } - /> - )) } - </TableBody> - </TableRoot> - <div ref={ cutRef }/> - </AddressHighlightProvider> - ); -}; - -export default React.memo(TokenTransferTable); diff --git a/src/slices/token-transfer/pages/index/TokenTransfersTableItem.tsx b/src/slices/token-transfer/pages/index/TokenTransfersTableItem.tsx deleted file mode 100644 index bc96f260df2..00000000000 --- a/src/slices/token-transfer/pages/index/TokenTransfersTableItem.tsx +++ /dev/null @@ -1,121 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; -import { isConfidentialTokenType, NFT_TOKEN_TYPE_IDS } from 'src/slices/token/utils/token-types'; - -import AddressFromTo from 'src/slices/address/components/from-to/AddressFromTo'; -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import NftEntity from 'src/slices/token/components/entity/NftEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ChainIcon from 'src/shared/external-chains/ChainIcon'; -import ConfidentialTokenValue from 'src/shared/values/entity/ConfidentialTokenValue'; -import TokenValue from 'src/shared/values/entity/TokenValue'; - -import { Badge } from 'src/toolkit/chakra/badge'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TableCell, TableRow } from 'src/toolkit/chakra/table'; - -type Props = { - item: schemas['TokenTransfer']; - isLoading?: boolean; - chainData?: ClusterChainConfig; -}; - -const TokenTransferTableItem = ({ item, isLoading, chainData }: Props) => { - const isConfidential = item.token ? isConfidentialTokenType(item.token.type) : false; - - const renderValue = () => { - if (item.token && item.total && 'value' in item.total && item.total.value !== null) { - return ( - <TokenValue - amount={ item.total.value } - token={ item.token } - decimals={ item.total.decimals || '0' } - layout="vertical" - loading={ isLoading } - /> - ); - } - - if (isConfidential && item.token) { - return ( - <ConfidentialTokenValue - token={ item.token } - loading={ isLoading } - /> - ); - } - - return <Skeleton loading={ isLoading }>-</Skeleton>; - }; - - return ( - <TableRow> - { chainData && ( - <TableCell> - <ChainIcon data={ chainData } isLoading={ isLoading }/> - </TableCell> - ) } - <TableCell> - { item.transaction_hash ? ( - <TxEntity - hash={ item.transaction_hash } - isLoading={ isLoading } - fontWeight={ 600 } - noIcon - truncation="constant_long" - /> - ) : ( - <Skeleton loading={ isLoading }>-</Skeleton> - ) } - <TimeWithTooltip - timestamp={ item.timestamp } - enableIncrement - isLoading={ isLoading } - color="text.secondary" - fontWeight="400" - display="inline-block" - /> - </TableCell> - <TableCell maxW="120px"> - { item.method && <Badge loading={ isLoading }>{ item.method }</Badge> } - </TableCell> - <TableCell> - <BlockEntity number={ item.block_number } isLoading={ isLoading } noIcon/> - </TableCell> - <TableCell> - <AddressFromTo - maxW={{ lg: '220px', xl: '320px' }} - from={ item.from } - to={ item.to } - tokenHash={ item.token?.address_hash } - tokenSymbol={ item.token?.symbol ?? undefined } - isLoading={ isLoading } - mode={{ lg: 'compact', xl: 'long' }} - /> - </TableCell> - <TableCell> - { item.total && 'token_id' in item.total && item.token && item.token.type && - (NFT_TOKEN_TYPE_IDS.includes(item.token.type)) && item.total.token_id !== null ? ( - <NftEntity - hash={ item.token.address_hash } - id={ item.total.token_id } - instance={ item.total.token_instance } - isLoading={ isLoading } - maxW="140px" - /> - ) : <Skeleton loading={ isLoading }>-</Skeleton> } - </TableCell> - <TableCell isNumeric verticalAlign="top"> - { renderValue() } - </TableCell> - </TableRow> - ); -}; - -export default React.memo(TokenTransferTableItem); diff --git a/src/slices/token-transfer/pages/index/__screenshots__/TokenTransfers.pw.tsx_default_base-view-mobile-1.png b/src/slices/token-transfer/pages/index/__screenshots__/TokenTransfers.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index ecbe5e89c62..00000000000 Binary files a/src/slices/token-transfer/pages/index/__screenshots__/TokenTransfers.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/token-transfer/pages/index/__screenshots__/TokenTransfers.pw.tsx_mobile_base-view-mobile-1.png b/src/slices/token-transfer/pages/index/__screenshots__/TokenTransfers.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index 583cbdbeaa0..00000000000 Binary files a/src/slices/token-transfer/pages/index/__screenshots__/TokenTransfers.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/token-transfer/pages/token/TokenTransfer.pw.tsx b/src/slices/token-transfer/pages/token/TokenTransfer.pw.tsx deleted file mode 100644 index 02f197e19fe..00000000000 --- a/src/slices/token-transfer/pages/token/TokenTransfer.pw.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import * as tokenTransferMock from 'src/slices/token-transfer/mocks'; -import { tokenInfoERC20a, tokenInfoERC721a, tokenInfoERC1155a } from 'src/slices/token/mocks/info'; -import * as tokenInstanceMock from 'src/slices/token/mocks/instance'; - -import { test, expect } from 'playwright/lib'; - -import TokenTransfer from './TokenTransfer'; - -test('erc20 +@mobile', async({ render, mockApiResponse }) => { - test.slow(); - await mockApiResponse('core:token_transfers', { - items: [ tokenTransferMock.erc20 ], - next_page_params: { page_token: 1 }, - }, { pathParams: { hash: tokenInfoERC20a.address_hash } }); - - const component = await render( - <Box pt={{ base: '134px', lg: '100px' }}> - <TokenTransfer token={ tokenInfoERC20a }/> - </Box>, - ); - - await expect(component).toHaveScreenshot({ timeout: 10_000 }); -}); - -test('erc721 +@mobile', async({ render, mockAssetResponse, mockApiResponse }) => { - test.slow(); - await mockApiResponse('core:token_transfers', { - items: [ tokenTransferMock.erc721 ], - next_page_params: { page_token: 1 }, - }, { pathParams: { hash: tokenInfoERC721a.address_hash } }); - await mockAssetResponse(tokenInstanceMock.base.image_url as string, './playwright/mocks/image_s.jpg'); - - const component = await render( - <Box pt={{ base: '134px', lg: '100px' }}> - <TokenTransfer token={ tokenInfoERC721a }/> - </Box>, - ); - - await expect(component).toHaveScreenshot({ timeout: 10_000 }); -}); - -test('erc1155 +@mobile', async({ render, mockApiResponse }) => { - test.slow(); - await mockApiResponse('core:token_transfers', { - items: [ tokenTransferMock.erc1155A, tokenTransferMock.erc1155B, tokenTransferMock.erc1155C, tokenTransferMock.erc1155D ], - next_page_params: { page_token: 1 }, - }, { pathParams: { hash: tokenInfoERC1155a.address_hash } }); - - const component = await render( - <Box pt={{ base: '134px', lg: '100px' }}> - <TokenTransfer token={ tokenInfoERC1155a }/> - </Box>, - ); - - await expect(component).toHaveScreenshot({ timeout: 10_000 }); -}); diff --git a/src/slices/token-transfer/pages/token/TokenTransfer.tsx b/src/slices/token-transfer/pages/token/TokenTransfer.tsx index c7562ef57af..42a28ca539a 100644 --- a/src/slices/token-transfer/pages/token/TokenTransfer.tsx +++ b/src/slices/token-transfer/pages/token/TokenTransfer.tsx @@ -1,26 +1,27 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; +import { HStack } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; import type { SocketMessage } from 'src/api/socket/types'; -import * as SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; import useSocketChannel from 'src/api/socket/useSocketChannel'; import useSocketMessage from 'src/api/socket/useSocketMessage'; -import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; +import ActionBar from 'src/shell/page/action-bar/ActionBar'; -import TokenTransferList from 'src/slices/token-transfer/pages/token/TokenTransferList'; -import TokenTransferTable from 'src/slices/token-transfer/pages/token/TokenTransferTable'; +import TokenTransfersTable from 'src/slices/token-transfer/components/table/TokenTransfersTable'; +import { useTokenTransferColumns } from 'src/slices/token-transfer/hooks/useTokenTransferColumns'; import TokenAdvancedFilterLink from 'src/features/advanced-filter/pages/token/TokenAdvancedFilterLink'; +import { useMultichainContext } from 'src/features/multichain/context'; +import ColumnsButton from 'src/shared/lists/columns/ColumnsButton'; import DataList from 'src/shared/lists/DataList'; import useGradualIncrement from 'src/shared/numbers/useGradualIncrement'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { getTokenTransfersStub } from '../../stubs'; @@ -34,13 +35,15 @@ interface Props { const TokenTransfer = ({ tokenId, token, isLoading: isLoadingProp, tokenInstance }: Props) => { const [ newItemsCount, setNewItemsCount ] = useGradualIncrement(0); const [ showSocketErrorAlert, setShowSocketErrorAlert ] = React.useState(false); + const multichainContext = useMultichainContext(); + const columnsState = useTokenTransferColumns('token', { tokenType: token?.type, chainConfig: multichainContext?.chain?.app_config }); // The backend emits `token_transfer` events for the whole token, not per instance, so on the NFT // instance page they produce false "N more transfers" notices. // See https://github.com/blockscout/frontend/issues/3653 const isSocketEnabled = !tokenId; - const transfersQuery = useQueryWithPages({ + const transfersQuery = useApiPaginatedQuery({ resourceName: tokenId ? 'core:token_instance_transfers' : 'core:token_transfers', pathParams: { hash: token?.address_hash, id: tokenId }, options: { @@ -73,47 +76,37 @@ const TokenTransfer = ({ tokenId, token, isLoading: isLoadingProp, tokenInstance handler: handleNewTransfersMessage, }); - const isLoading = transfersQuery.isPlaceholderData || isLoadingProp; + const isLoading = transfersQuery.isInitialLoading || isLoadingProp; const content = transfersQuery.data?.items && token ? ( - <> - <Box display={{ base: 'none', lg: 'block' }}> - <TokenTransferTable - data={ transfersQuery.data?.items } - top={ ACTION_BAR_HEIGHT_DESKTOP } - showSocketInfo={ isSocketEnabled && transfersQuery.pagination.page === 1 } - showSocketErrorAlert={ showSocketErrorAlert } - socketInfoNum={ newItemsCount } - tokenId={ tokenId } - token={ token } - instance={ tokenInstance } - isLoading={ isLoading } - resetKey={ transfersQuery.queryHash } - /> - </Box> - <Box display={{ base: 'block', lg: 'none' }}> - { isSocketEnabled && transfersQuery.pagination.page === 1 && ( - <SocketNewItemsNotice.Mobile - num={ newItemsCount } - showErrorAlert={ showSocketErrorAlert } - type="token_transfer" - isLoading={ isLoading } - /> - ) } - <TokenTransferList - data={ transfersQuery.data?.items } - tokenId={ tokenId } - instance={ tokenInstance } - isLoading={ isLoading } - resetKey={ transfersQuery.queryHash } - /> - </Box> - </> + <TokenTransfersTable + columns={ columnsState.columns } + items={ transfersQuery.data.items } + showSocketInfo={ isSocketEnabled && transfersQuery.pagination.page === 1 } + showSocketErrorAlert={ showSocketErrorAlert } + socketInfoNum={ newItemsCount } + enableTimeIncrement + tokenId={ tokenId } + instance={ tokenInstance } + isLoading={ isLoading } + resetKey={ transfersQuery.queryHash } + /> ) : null; const actionBar = token ? ( <ActionBar mt={ -6 }> - <TokenAdvancedFilterLink token={ token } isLoading={ isLoading } minH={ 8 }/> + <HStack gap={ 3 }> + <ColumnsButton + tableColumns={ columnsState.selectableColumns } + columns={ columnsState.checkedColumns } + onChange={ columnsState.onColumnsChange } + onOrderChange={ columnsState.onColumnsReorder } + selected={ columnsState.isCustomized } + onReset={ columnsState.onColumnsReset } + isLoading={ isLoading } + /> + <TokenAdvancedFilterLink token={ token } isLoading={ isLoading } minH={ 8 }/> + </HStack> { transfersQuery.pagination.isVisible && <Pagination ml="auto" { ...transfersQuery.pagination }/> } </ActionBar> ) : null; @@ -124,6 +117,7 @@ const TokenTransfer = ({ tokenId, token, isLoading: isLoadingProp, tokenInstance itemsNum={ transfersQuery.data?.items.length } emptyText="There are no token transfers." actionBar={ actionBar } + isTransitioning={ transfersQuery.isTransitioning } > { content } </DataList> diff --git a/src/slices/token-transfer/pages/token/TokenTransferList.tsx b/src/slices/token-transfer/pages/token/TokenTransferList.tsx deleted file mode 100644 index d4de228dbe7..00000000000 --- a/src/slices/token-transfer/pages/token/TokenTransferList.tsx +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import TokenTransferListItem from 'src/slices/token-transfer/pages/token/TokenTransferListItem'; - -import { useMultichainContext } from 'src/features/multichain/context'; - -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -interface Props { - data: Array<schemas['TokenTransfer']>; - tokenId?: string; - instance?: schemas['TokenInstance']; - isLoading?: boolean; - resetKey?: string; -} - -const TokenTransferList = ({ data, tokenId, instance, isLoading, resetKey }: Props) => { - const multichainContext = useMultichainContext(); - const chainData = multichainContext?.chain; - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => ( - <TokenTransferListItem - key={ item.transaction_hash + item.block_hash + item.log_index + '_' + index } - data={ item } - tokenId={ tokenId } - instance={ instance } - isLoading={ isLoading } - chainData={ chainData } - /> - )) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> - ); -}; - -export default React.memo(TokenTransferList); diff --git a/src/slices/token-transfer/pages/token/TokenTransferListItem.tsx b/src/slices/token-transfer/pages/token/TokenTransferListItem.tsx deleted file mode 100644 index a4c59adc514..00000000000 --- a/src/slices/token-transfer/pages/token/TokenTransferListItem.tsx +++ /dev/null @@ -1,132 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; -import { hasTokenTransferValue, isConfidentialTokenType, NFT_TOKEN_TYPE_IDS } from 'src/slices/token/utils/token-types'; - -import AddressFromTo from 'src/slices/address/components/from-to/AddressFromTo'; -import NftEntity from 'src/slices/token/components/entity/NftEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import AssetValue from 'src/shared/values/entity/AssetValue'; -import ConfidentialValue from 'src/shared/values/entity/ConfidentialValue'; - -import { Badge } from 'src/toolkit/chakra/badge'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; - -interface Props { - data: schemas['TokenTransfer']; - tokenId?: string; - instance?: schemas['TokenInstance']; - isLoading?: boolean; - chainData?: ClusterChainConfig; -} - -const TokenTransferListItem = ({ - data, - tokenId, - isLoading, - instance, - chainData, -}: Props) => { - return ( - <ListItemMobile rowGap={ 3 }> - <Flex justifyContent="space-between" alignItems="center" lineHeight="24px" width="100%"> - { data.transaction_hash && ( - <TxEntity - isLoading={ isLoading } - hash={ data.transaction_hash } - truncation="constant_long" - fontWeight="700" - chain={ chainData } - /> - ) } - <TimeWithTooltip - timestamp={ data.timestamp } - enableIncrement - isLoading={ isLoading } - color="text.secondary" - fontWeight="400" - fontSize="sm" - display="inline-block" - /> - </Flex> - { data.method && <Badge loading={ isLoading }>{ data.method }</Badge> } - <AddressFromTo - from={ data.from } - to={ data.to } - isLoading={ isLoading } - tokenHash={ data.token?.address_hash } - tokenSymbol={ data.token?.symbol ?? undefined } - w="100%" - fontWeight="500" - /> - { data.total && 'value' in data.total && data.token && - (hasTokenTransferValue(data.token.type, chainData?.app_config)) && !isConfidentialTokenType(data.token.type) && ( - <Flex alignItems="center" columnGap={ 2 } maxW="100%" w="full"> - <Skeleton - display="inline-flex" - alignItems="center" - loading={ isLoading } - flexShrink={ 0 } - fontWeight={ 500 } - maxW="50%" - whiteSpace="pre" - overflow="hidden" - > - <span>Value </span> - { data.token.symbol && <TruncatedText text={ data.token.symbol } loading={ isLoading }/> } - </Skeleton> - <AssetValue - amount={ data.total.value } - decimals={ data.total.decimals || '0' } - exchangeRate={ data.token?.exchange_rate } - loading={ isLoading } - color="text.secondary" - /> - </Flex> - ) } - { data.token && isConfidentialTokenType(data.token.type) && ( - <Flex alignItems="center" columnGap={ 2 } maxW="100%" w="full"> - <Skeleton - display="inline-flex" - alignItems="center" - loading={ isLoading } - flexShrink={ 0 } - fontWeight={ 500 } - maxW="50%" - whiteSpace="pre" - overflow="hidden" - > - <span>Value </span> - { data.token.symbol && <TruncatedText text={ data.token.symbol } loading={ isLoading }/> } - </Skeleton> - <ConfidentialValue - loading={ isLoading } - color="text.secondary" - wordBreak="break-all" - overflow="hidden" - flexGrow={ 1 } - /> - </Flex> - ) } - { data.total && 'token_id' in data.total && data.token?.type && (NFT_TOKEN_TYPE_IDS.includes(data.token.type)) && data.total.token_id !== null && ( - <NftEntity - hash={ data.token.address_hash } - id={ data.total.token_id } - instance={ instance || data.total.token_instance } - noLink={ Boolean(tokenId && tokenId === data.total.token_id) } - isLoading={ isLoading } - /> - ) } - </ListItemMobile> - ); -}; - -export default React.memo(TokenTransferListItem); diff --git a/src/slices/token-transfer/pages/token/TokenTransferTable.tsx b/src/slices/token-transfer/pages/token/TokenTransferTable.tsx deleted file mode 100644 index 700ff7cde19..00000000000 --- a/src/slices/token-transfer/pages/token/TokenTransferTable.tsx +++ /dev/null @@ -1,91 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import { hasTokenIds, hasTokenTransferValue, isConfidentialTokenType, isFungibleTokenType, NFT_TOKEN_TYPE_IDS } from 'src/slices/token/utils/token-types'; - -import * as SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; - -import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; -import TokenTransferTableItem from 'src/slices/token-transfer/pages/token/TokenTransferTableItem'; - -import { useMultichainContext } from 'src/features/multichain/context'; - -import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; - -interface Props { - data: Array<schemas['TokenTransfer']>; - top?: number; - showSocketInfo: boolean; - showSocketErrorAlert?: boolean; - socketInfoNum?: number; - tokenId?: string; - isLoading?: boolean; - token: schemas['Token']; - instance?: schemas['TokenInstance']; - resetKey?: string; -} - -const TokenTransferTable = ({ data, top, showSocketInfo, showSocketErrorAlert, socketInfoNum, tokenId, isLoading, token, instance, resetKey }: Props) => { - const multichainContext = useMultichainContext(); - const chainData = multichainContext?.chain; - const tokenType = token.type; - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); - - return ( - <AddressHighlightProvider> - <TableRoot minW="950px"> - <TableHeaderSticky top={ top }> - <TableRow> - { chainData && <TableColumnHeader width="38px"/> } - <TableColumnHeader width="280px"> - Txn hash - <TimeFormatToggle/> - </TableColumnHeader> - <TableColumnHeader width="200px">Method</TableColumnHeader> - <TableColumnHeader width={{ lg: '224px', xl: '380px' }}>From/To</TableColumnHeader> - { (tokenType && NFT_TOKEN_TYPE_IDS.includes(tokenType)) && - <TableColumnHeader width={ hasTokenIds(tokenType) ? '50%' : '100%' }>Token ID</TableColumnHeader> - } - { hasTokenTransferValue(tokenType, chainData?.app_config) && ( - <TableColumnHeader - width={ (isFungibleTokenType(tokenType, chainData?.app_config) || isConfidentialTokenType(tokenType)) ? '100%' : '50%' } - isNumeric - > - <TruncatedText text={ `Value ${ token?.symbol || '' }` } w="100%" verticalAlign="middle"/> - </TableColumnHeader> - ) } - </TableRow> - </TableHeaderSticky> - <TableBody> - { showSocketInfo && ( - <SocketNewItemsNotice.Desktop - showErrorAlert={ showSocketErrorAlert } - num={ socketInfoNum } - type="token_transfer" - isLoading={ isLoading } - /> - ) } - { data.slice(0, renderedItemsNum).map((item, index) => ( - <TokenTransferTableItem - key={ item.transaction_hash + item.block_hash + item.log_index + '_' + index } - data={ item } - tokenId={ tokenId } - instance={ instance } - isLoading={ isLoading } - chainData={ chainData } - /> - )) } - </TableBody> - </TableRoot> - <div ref={ cutRef }/> - </AddressHighlightProvider> - ); -}; - -export default React.memo(TokenTransferTable); diff --git a/src/slices/token-transfer/pages/token/TokenTransferTableItem.tsx b/src/slices/token-transfer/pages/token/TokenTransferTableItem.tsx deleted file mode 100644 index cc86105c941..00000000000 --- a/src/slices/token-transfer/pages/token/TokenTransferTableItem.tsx +++ /dev/null @@ -1,120 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; -import { hasTokenTransferValue, isConfidentialTokenType, NFT_TOKEN_TYPE_IDS } from 'src/slices/token/utils/token-types'; - -import AddressFromTo from 'src/slices/address/components/from-to/AddressFromTo'; -import NftEntity from 'src/slices/token/components/entity/NftEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; - -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ChainIcon from 'src/shared/external-chains/ChainIcon'; -import AssetValue from 'src/shared/values/entity/AssetValue'; -import ConfidentialValue from 'src/shared/values/entity/ConfidentialValue'; - -import { Badge } from 'src/toolkit/chakra/badge'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TableCell, TableRow } from 'src/toolkit/chakra/table'; - -interface Props { - data: schemas['TokenTransfer']; - tokenId?: string; - isLoading?: boolean; - instance?: schemas['TokenInstance']; - chainData?: ClusterChainConfig; -} - -const TokenTransferTableItem = ({ - data, - tokenId, - isLoading, - instance, - chainData, -}: Props) => { - - return ( - <TableRow alignItems="top"> - { chainData && ( - <TableCell> - <ChainIcon data={ chainData } isLoading={ isLoading } my="5px"/> - </TableCell> - ) } - <TableCell> - <Flex flexDirection="column" alignItems="flex-start" mt="5px" rowGap={ 3 }> - { data.transaction_hash ? ( - <TxEntity - hash={ data.transaction_hash } - isLoading={ isLoading } - fontWeight={ 600 } - noIcon - truncation="constant_long" - /> - ) : <Skeleton loading={ isLoading }>-</Skeleton> } - <TimeWithTooltip - timestamp={ data.timestamp } - enableIncrement - isLoading={ isLoading } - display="inline-block" - color="text.secondary" - fontWeight="400" - /> - </Flex> - </TableCell> - <TableCell> - { data.method ? ( - <Box my="3px"> - <Badge loading={ isLoading } truncated>{ data.method }</Badge> - </Box> - ) : null } - </TableCell> - <TableCell> - <AddressFromTo - from={ data.from } - to={ data.to } - isLoading={ isLoading } - mt="5px" - mode={{ lg: 'compact', xl: 'long' }} - tokenHash={ data.token?.address_hash } - tokenSymbol={ data.token?.symbol ?? undefined } - /> - </TableCell> - { (data.token?.type && NFT_TOKEN_TYPE_IDS.includes(data.token.type)) && ( - <TableCell> - { data.total && 'token_id' in data.total && data.token && data.total.token_id !== null ? ( - <NftEntity - hash={ data.token.address_hash } - id={ data.total.token_id } - instance={ instance || data.total.token_instance } - noLink={ Boolean(tokenId && tokenId === data.total.token_id) } - isLoading={ isLoading } - /> - ) : '' - } - </TableCell> - ) } - { data.token && (hasTokenTransferValue(data.token.type, chainData?.app_config)) && ( - <TableCell isNumeric verticalAlign="top"> - { isConfidentialTokenType(data.token.type) ? ( - <ConfidentialValue loading={ isLoading } mt="7px" wordBreak="break-all"/> - ) : ( - <AssetValue - amount={ data.total && 'value' in data.total ? data.total.value : null } - decimals={ data.total && 'decimals' in data.total ? data.total.decimals || '0' : '0' } - exchangeRate={ data.token?.exchange_rate } - loading={ isLoading } - layout="vertical" - mt="7px" - rowGap="10px" - /> - ) } - </TableCell> - ) } - </TableRow> - ); -}; - -export default React.memo(TokenTransferTableItem); diff --git a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_default_erc1155-mobile-1.png b/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_default_erc1155-mobile-1.png deleted file mode 100644 index 6c49f3949ca..00000000000 Binary files a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_default_erc1155-mobile-1.png and /dev/null differ diff --git a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_default_erc20-mobile-1.png b/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_default_erc20-mobile-1.png deleted file mode 100644 index c0d399631e7..00000000000 Binary files a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_default_erc20-mobile-1.png and /dev/null differ diff --git a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_default_erc721-mobile-1.png b/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_default_erc721-mobile-1.png deleted file mode 100644 index 01951bf5a83..00000000000 Binary files a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_default_erc721-mobile-1.png and /dev/null differ diff --git a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_mobile_erc1155-mobile-1.png b/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_mobile_erc1155-mobile-1.png deleted file mode 100644 index 0420857f9d8..00000000000 Binary files a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_mobile_erc1155-mobile-1.png and /dev/null differ diff --git a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_mobile_erc20-mobile-1.png b/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_mobile_erc20-mobile-1.png deleted file mode 100644 index de9bf5e1ec3..00000000000 Binary files a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_mobile_erc20-mobile-1.png and /dev/null differ diff --git a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_mobile_erc721-mobile-1.png b/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_mobile_erc721-mobile-1.png deleted file mode 100644 index 5e67284836c..00000000000 Binary files a/src/slices/token-transfer/pages/token/__screenshots__/TokenTransfer.pw.tsx_mobile_erc721-mobile-1.png and /dev/null differ diff --git a/src/slices/token-transfer/pages/tx/TxTokenTransfer.tsx b/src/slices/token-transfer/pages/tx/TxTokenTransfer.tsx index a583ca652af..2ac8d4ad618 100644 --- a/src/slices/token-transfer/pages/tx/TxTokenTransfer.tsx +++ b/src/slices/token-transfer/pages/tx/TxTokenTransfer.tsx @@ -1,20 +1,22 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; +import { HStack } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; import type { TokenType } from 'src/slices/token/types/api'; -import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; +import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import TokenTransferFilter from 'src/slices/token-transfer/components/TokenTransferFilter'; +import { useTokenTransferColumns } from 'src/slices/token-transfer/hooks/useTokenTransferColumns'; import { getTokenTransfersStub } from 'src/slices/token-transfer/stubs'; import { getTokenFilterValue } from 'src/slices/token/utils/list-utils'; import TxPendingAlert from 'src/slices/tx/components/TxPendingAlert'; import TxSocketAlert from 'src/slices/tx/components/TxSocketAlert'; import type { TxQuery } from 'src/slices/tx/hooks/useTxQuery'; +import { hasActiveColumnFilters } from 'src/features/cross-chain-txs/components/filters/utils'; import useTxCrossChainTransfersQuery from 'src/features/cross-chain-txs/hooks/useTxCrossChainTransfersQuery'; import TxTokenTransferCrossChain from 'src/features/cross-chain-txs/pages/tx/TxTokenTransferCrossChain'; import { useMultichainContext } from 'src/features/multichain/context'; @@ -22,14 +24,23 @@ import { useMultichainContext } from 'src/features/multichain/context'; import config from 'src/config'; import useIsInitialLoading from 'src/shared/hooks/useIsInitialLoading'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import ColumnsButton from 'src/shared/lists/columns/ColumnsButton'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; import TxTokenTransferLocal from './TxTokenTransferLocal'; +const NO_TYPES: Array<TokenType> = []; + +const LOCAL_TAB_RIGHT_SLOT_PROPS = { + display: 'flex', + widthAllocation: 'available' as const, +}; + interface Props { txQuery: TxQuery; tokenTransferFilter?: (data: schemas['TokenTransfer']) => boolean; @@ -45,20 +56,22 @@ const TxTokenTransfer = ({ txQuery, tokenTransferFilter, noCrossChain }: Props) const areQueriesEnabled = !txQuery.isPlaceholderData && Boolean(txQuery.data?.status && txQuery.data?.hash); const chainConfig = multichainContext?.chain?.app_config ?? config; - const [ typeFilter, setTypeFilter ] = React.useState<Array<TokenType>>( - getTokenFilterValue(router.query.type, multichainContext?.chain?.app_config) || [], - ); - - const localQuery = useQueryWithPages({ + const localQuery = useApiPaginatedQuery({ resourceName: 'core:tx_token_transfers', pathParams: { hash: txQuery.data?.hash.toString() }, options: { enabled: areQueriesEnabled, placeholderData: getTokenTransfersStub(), }, - filters: { type: typeFilter }, }); + const typeParam = localQuery.filters.type; + const typeFilter = React.useMemo( + () => getTokenFilterValue(typeParam, multichainContext?.chain?.app_config) || NO_TYPES, + [ typeParam, multichainContext?.chain?.app_config ], + ); + const columnsState = useTokenTransferColumns('tx', { typeFilter, chainConfig: multichainContext?.chain?.app_config }); + const crossChainQuery = useTxCrossChainTransfersQuery({ hash: String(txQuery.data?.hash), enabled: areQueriesEnabled && !noCrossChain && chainConfig.features.crossChainTxs.isEnabled, @@ -66,11 +79,11 @@ const TxTokenTransfer = ({ txQuery, tokenTransferFilter, noCrossChain }: Props) const hasCrossChainTab = chainConfig.features.crossChainTxs.isEnabled && - Boolean(!crossChainQuery.isPlaceholderData && crossChainQuery.data?.items.length) && + (Boolean(!crossChainQuery.isPlaceholderData && crossChainQuery.data?.items.length) || hasActiveColumnFilters(crossChainQuery.filters)) && !noCrossChain; const isLocalTab = tab === 'token_transfers' || (tab !== 'token_transfers_cross_chain' && !hasCrossChainTab); const isTabsLoading = useIsInitialLoading( - localQuery.isPlaceholderData || + localQuery.isInitialLoading || (chainConfig.features.crossChainTxs.isEnabled && crossChainQuery.isPlaceholderData && !noCrossChain), ); @@ -84,6 +97,7 @@ const TxTokenTransfer = ({ txQuery, tokenTransferFilter, noCrossChain }: Props) tokenTransferFilter={ tokenTransferFilter } tokenTransferQuery={ localQuery } numActiveFilters={ typeFilter.length } + columnsState={ columnsState } /> ), }, @@ -96,24 +110,27 @@ const TxTokenTransfer = ({ txQuery, tokenTransferFilter, noCrossChain }: Props) crossChainQuery={ crossChainQuery } isLoading={ isTabsLoading } tableTop={ ACTION_BAR_HEIGHT_DESKTOP } + actionBar={ isMobile && crossChainQuery.pagination.isVisible && ( + <ActionBar> + <Pagination ml="auto" { ...crossChainQuery.pagination }/> + </ActionBar> + ) } /> ), }, ].filter(Boolean); + const { onFilterChange } = localQuery; const handleTypeFilterChange = React.useCallback((nextValue: Array<TokenType>) => { - localQuery.onFilterChange({ type: nextValue }); - setTypeFilter(nextValue); - }, [ localQuery ]); + onFilterChange({ type: nextValue }); + }, [ onFilterChange ]); const rightSlotProps = React.useMemo(() => { if (tabs.length === 1) { - return { ml: 0 }; + return { ...LOCAL_TAB_RIGHT_SLOT_PROPS, ml: 0 }; } if (isLocalTab) { - return { - ml: 6, - }; + return { ...LOCAL_TAB_RIGHT_SLOT_PROPS, ml: 6 }; } }, [ isLocalTab, tabs.length ]); @@ -137,18 +154,33 @@ const TxTokenTransfer = ({ txQuery, tokenTransferFilter, noCrossChain }: Props) } return ( <> - <TokenTransferFilter - defaultTypeFilters={ typeFilter } - onTypeFilterChange={ handleTypeFilterChange } - appliedFiltersNum={ typeFilter.length } - isLoading={ txQuery.isPlaceholderData || localQuery.isPlaceholderData } - chainConfig={ multichainContext?.chain?.app_config } - /> + <HStack gap={{ base: 2, lg: 3 }}> + <TokenTransferFilter + defaultTypeFilters={ typeFilter } + onTypeFilterChange={ handleTypeFilterChange } + appliedFiltersNum={ typeFilter.length } + isLoading={ txQuery.isPlaceholderData || localQuery.isInitialLoading } + chainConfig={ multichainContext?.chain?.app_config } + /> + <ColumnsButton + tableColumns={ columnsState.selectableColumns } + columns={ columnsState.checkedColumns } + onChange={ columnsState.onColumnsChange } + onOrderChange={ columnsState.onColumnsReorder } + selected={ columnsState.isCustomized } + onReset={ columnsState.onColumnsReset } + isLoading={ txQuery.isPlaceholderData || localQuery.isInitialLoading } + /> + </HStack> <Pagination ml="auto" { ...localQuery.pagination }/> </> ); } + if (isMobile) { + return null; + } + return ( <Pagination ml="auto" { ...crossChainQuery.pagination }/> ); diff --git a/src/slices/token-transfer/pages/tx/TxTokenTransferLocal.tsx b/src/slices/token-transfer/pages/tx/TxTokenTransferLocal.tsx index b0cdecbb61c..87e8cd626d6 100644 --- a/src/slices/token-transfer/pages/tx/TxTokenTransferLocal.tsx +++ b/src/slices/token-transfer/pages/tx/TxTokenTransferLocal.tsx @@ -1,33 +1,31 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; -import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; - -import TokenTransferList from 'src/slices/token-transfer/components/list/TokenTransferList'; -import TokenTransferTable from 'src/slices/token-transfer/components/list/TokenTransferTable'; +import TokenTransfersTable from 'src/slices/token-transfer/components/table/TokenTransfersTable'; +import type { TokenTransferColumnsState } from 'src/slices/token-transfer/hooks/useTokenTransferColumns'; import type { TxQuery } from 'src/slices/tx/hooks/useTxQuery'; import DataList from 'src/shared/lists/DataList'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; interface Props { txQuery: TxQuery; - tokenTransferQuery: QueryWithPagesResult<'core:tx_token_transfers'>; + tokenTransferQuery: ApiPaginatedQueryResult<'core:tx_token_transfers'>; tokenTransferFilter?: (data: schemas['TokenTransfer']) => boolean; numActiveFilters: number; - tableTop?: number; + columnsState: TokenTransferColumnsState; } -const TxTokenTransferLocal = ({ txQuery, tokenTransferQuery, tokenTransferFilter, numActiveFilters, tableTop }: Props) => { +const TxTokenTransferLocal = ({ txQuery, tokenTransferQuery, tokenTransferFilter, numActiveFilters, columnsState }: Props) => { + const { isInitialLoading, isTransitioning } = tokenTransferQuery; let items: Array<schemas['TokenTransfer']> = []; if (tokenTransferQuery.data?.items) { - if (tokenTransferQuery.isPlaceholderData) { + if (isInitialLoading) { items = tokenTransferQuery.data?.items; } else { items = tokenTransferFilter ? tokenTransferQuery.data.items.filter(tokenTransferFilter) : tokenTransferQuery.data.items; @@ -35,19 +33,12 @@ const TxTokenTransferLocal = ({ txQuery, tokenTransferQuery, tokenTransferFilter } const content = tokenTransferQuery.data?.items ? ( - <> - <Box hideBelow="lg"> - <TokenTransferTable - data={ items } - top={ tableTop ?? ACTION_BAR_HEIGHT_DESKTOP } - isLoading={ tokenTransferQuery.isPlaceholderData } - resetKey={ tokenTransferQuery.queryHash } - /> - </Box> - <Box hideFrom="lg"> - <TokenTransferList data={ items } isLoading={ tokenTransferQuery.isPlaceholderData } resetKey={ tokenTransferQuery.queryHash }/> - </Box> - </> + <TokenTransfersTable + columns={ columnsState.columns } + items={ items } + isLoading={ isInitialLoading } + resetKey={ tokenTransferQuery.queryHash } + /> ) : null; return ( @@ -56,6 +47,7 @@ const TxTokenTransferLocal = ({ txQuery, tokenTransferQuery, tokenTransferFilter itemsNum={ items.length } emptyText="There are no token transfers." hasActiveFilters={ Boolean(numActiveFilters) } + isTransitioning={ isTransitioning } emptyStateProps={{ term: 'token transfer', }} diff --git a/src/slices/token-transfer/types/client.ts b/src/slices/token-transfer/types/client.ts new file mode 100644 index 00000000000..670df0a0258 --- /dev/null +++ b/src/slices/token-transfer/types/client.ts @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +export type TokenTransferSurface = 'index' | 'address' | 'token' | 'tx'; + +export type TokenTransferColumnId = + 'in_out' | + 'tx_hash' | + 'type' | + 'transfer_type' | + 'method' | + 'timestamp' | + 'block' | + 'from_to' | + 'multiplier' | + 'amount' | + 'asset' | + 'value'; + +export interface TokenTransferColumn { + readonly id: TokenTransferColumnId; + readonly name: string; + readonly isNumeric?: boolean; + readonly width: string; +} diff --git a/src/slices/token-transfer/utils/columns.spec.ts b/src/slices/token-transfer/utils/columns.spec.ts new file mode 100644 index 00000000000..b383fd40770 --- /dev/null +++ b/src/slices/token-transfer/utils/columns.spec.ts @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +import { chainA } from 'src/features/multichain/mocks/chains'; + +import { getAvailableColumns, getDefaultColumnIds } from 'src/shared/lists/columns/column-overrides'; + +import { describe, expect, it } from 'vitest'; + +import type { SurfaceColumnStatesParams } from './columns'; +import { getSurfaceColumnStates, TOKEN_TRANSFER_COLUMNS } from './columns'; + +const chainWithoutErc8056 = chainA.app_config as ClusterChainConfig['app_config']; + +const chainWithErc8056 = { + ...chainWithoutErc8056, + slices: { + ...chainWithoutErc8056.slices, + token: { + ...chainWithoutErc8056.slices.token, + additionalTypes: [ { id: 'ERC-8056', name: 'ERC-8056' } ], + }, + }, +} as ClusterChainConfig['app_config']; + +const ALL_COLUMNS = [ 'in_out', 'tx_hash', 'type', 'transfer_type', 'method', 'timestamp', 'block', 'from_to', 'multiplier', 'amount', 'asset', 'value' ]; +const WITHOUT_IN_OUT = ALL_COLUMNS.filter((id) => id !== 'in_out'); +const WITHOUT_IN_OUT_AND_MULTIPLIER = WITHOUT_IN_OUT.filter((id) => id !== 'multiplier'); +const MULTIPLIER_ENABLED: SurfaceColumnStatesParams = { chainConfig: chainWithErc8056 }; + +const getAvailableIds = (...args: Parameters<typeof getSurfaceColumnStates>) => + getAvailableColumns(TOKEN_TRANSFER_COLUMNS, getSurfaceColumnStates(...args)).map(({ id }) => id); +const getDefaultIds = (...args: Parameters<typeof getSurfaceColumnStates>) => + getDefaultColumnIds(TOKEN_TRANSFER_COLUMNS, getSurfaceColumnStates(...args)); + +describe('TOKEN_TRANSFER_COLUMNS', () => { + it('names the columns for display, in vocabulary order', () => { + expect(TOKEN_TRANSFER_COLUMNS.map(({ name }) => name)).toEqual( + [ 'In / Out', 'Txn hash', 'Token type', 'Transfer type', 'Method', 'Timestamp', 'Block', 'From / To', 'Multiplier', 'Amount', 'ID / Asset', 'Value' ], + ); + }); + + it('marks only multiplier, amount and value as numeric', () => { + expect(TOKEN_TRANSFER_COLUMNS.filter(({ isNumeric }) => isNumeric).map(({ id }) => id)).toEqual([ 'multiplier', 'amount', 'value' ]); + }); +}); + +describe('getSurfaceColumnStates', () => { + it('offers the whole vocabulary in order on the address surface, In / Out first', () => { + expect(getAvailableIds('address', MULTIPLIER_ENABLED)).toEqual(ALL_COLUMNS); + }); + + it('offers every column but In / Out on the index surface', () => { + expect(getAvailableIds('index', MULTIPLIER_ENABLED)).toEqual(WITHOUT_IN_OUT); + }); + + it('offers every column but In / Out on the token surface of an ERC-8056 token', () => { + expect(getAvailableIds('token', { ...MULTIPLIER_ENABLED, tokenType: 'ERC-8056' })).toEqual(WITHOUT_IN_OUT); + }); + + it('does not offer In / Out on the index, token and tx surfaces', () => { + expect(getSurfaceColumnStates('index', MULTIPLIER_ENABLED).in_out).toBe('unavailable'); + expect(getSurfaceColumnStates('token', MULTIPLIER_ENABLED).in_out).toBe('unavailable'); + expect(getSurfaceColumnStates('tx', MULTIPLIER_ENABLED).in_out).toBe('unavailable'); + }); + + it('does not offer the hash, method, timestamp and block columns on the tx surface', () => { + expect(getAvailableIds('tx', MULTIPLIER_ENABLED)).toEqual( + [ 'type', 'transfer_type', 'from_to', 'multiplier', 'amount', 'asset', 'value' ], + ); + }); + + it('hides Transfer type, Method and Block by default on the index and address surfaces', () => { + expect(getDefaultIds('index', MULTIPLIER_ENABLED)).toEqual( + [ 'tx_hash', 'type', 'timestamp', 'from_to', 'multiplier', 'amount', 'asset', 'value' ], + ); + expect(getDefaultIds('address', MULTIPLIER_ENABLED)).toEqual( + [ 'in_out', 'tx_hash', 'type', 'timestamp', 'from_to', 'multiplier', 'amount', 'asset', 'value' ], + ); + }); + + it('hides the type columns, method and block by default on the token surface', () => { + expect(getDefaultIds('token', { ...MULTIPLIER_ENABLED, tokenType: 'ERC-8056' })).toEqual( + [ 'tx_hash', 'timestamp', 'from_to', 'multiplier', 'amount', 'asset', 'value' ], + ); + }); + + it('hides Transfer type by default on the tx surface', () => { + expect(getDefaultIds('tx', MULTIPLIER_ENABLED)).toEqual( + [ 'type', 'from_to', 'multiplier', 'amount', 'asset', 'value' ], + ); + }); + + describe('multiplier', () => { + it('is on when the chain enables ERC-8056 and nothing narrows it', () => { + expect(getSurfaceColumnStates('index', MULTIPLIER_ENABLED).multiplier).toBe('on'); + }); + + it('is unavailable when the chain does not enable ERC-8056', () => { + expect(getSurfaceColumnStates('index', { chainConfig: chainWithoutErc8056 }).multiplier).toBe('unavailable'); + }); + + it('follows the instance config when no chain config is given', () => { + expect(getSurfaceColumnStates('index', {}).multiplier).toBe('unavailable'); + }); + + it('is on when the type filter includes ERC-8056', () => { + expect(getSurfaceColumnStates('address', { ...MULTIPLIER_ENABLED, typeFilter: [ 'ERC-20', 'ERC-8056' ] }).multiplier).toBe('on'); + }); + + it('is on when the type filter is empty', () => { + expect(getSurfaceColumnStates('address', { ...MULTIPLIER_ENABLED, typeFilter: [] }).multiplier).toBe('on'); + }); + + it('is unavailable when the type filter is set without ERC-8056', () => { + expect(getSurfaceColumnStates('address', { ...MULTIPLIER_ENABLED, typeFilter: [ 'ERC-20' ] }).multiplier).toBe('unavailable'); + }); + + it('ignores the token type outside the token surface', () => { + expect(getSurfaceColumnStates('tx', { ...MULTIPLIER_ENABLED, tokenType: 'ERC-20' }).multiplier).toBe('on'); + }); + + it('is unavailable on the token surface of a token of another type', () => { + expect(getSurfaceColumnStates('token', { ...MULTIPLIER_ENABLED, tokenType: 'ERC-20' }).multiplier).toBe('unavailable'); + }); + + it('is unavailable on the token surface while the token is unknown', () => { + expect(getSurfaceColumnStates('token', MULTIPLIER_ENABLED).multiplier).toBe('unavailable'); + }); + + it('leaves the other columns unchanged when unavailable', () => { + expect(getAvailableIds('index', { chainConfig: chainWithoutErc8056 })).toEqual(WITHOUT_IN_OUT_AND_MULTIPLIER); + expect(getDefaultIds('index', { chainConfig: chainWithoutErc8056 })).toEqual( + [ 'tx_hash', 'type', 'timestamp', 'from_to', 'amount', 'asset', 'value' ], + ); + }); + }); +}); diff --git a/src/slices/token-transfer/utils/columns.ts b/src/slices/token-transfer/utils/columns.ts new file mode 100644 index 00000000000..091a4eec57e --- /dev/null +++ b/src/slices/token-transfer/utils/columns.ts @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { TokenTransferColumn, TokenTransferColumnId, TokenTransferSurface } from '../types/client'; +import type { ColumnState, ColumnStates } from 'src/shared/lists/columns/types'; +import type { TokenType } from 'src/slices/token/types/api'; +import type { ChainConfig } from 'src/slices/token/types/client'; + +import { isTokenMultiplierEnabled, UI_MULTIPLIER_TOKEN_TYPE } from 'src/slices/token/utils/ui-multiplier'; + +export const TOKEN_TRANSFER_COLUMNS: ReadonlyArray<TokenTransferColumn> = [ + { id: 'in_out', name: 'In / Out', width: '70px' }, + { id: 'tx_hash', name: 'Txn hash', width: '135px' }, + { id: 'type', name: 'Token type', width: '95px' }, + { id: 'transfer_type', name: 'Transfer type', width: '145px' }, + { id: 'method', name: 'Method', width: '120px' }, + { id: 'timestamp', name: 'Timestamp', width: '170px' }, + { id: 'block', name: 'Block', width: '100px' }, + { id: 'from_to', name: 'From / To', width: '350px' }, + { id: 'multiplier', name: 'Multiplier', isNumeric: true, width: '90px' }, + { id: 'amount', name: 'Amount', isNumeric: true, width: '130px' }, + { id: 'asset', name: 'ID / Asset', width: '240px' }, + { id: 'value', name: 'Value', isNumeric: true, width: '120px' }, +]; + +const SURFACE_COLUMN_STATES: Readonly<Record<TokenTransferSurface, ColumnStates<Exclude<TokenTransferColumnId, 'multiplier'>>>> = { + index: { + in_out: 'unavailable', + tx_hash: 'on', + type: 'on', + transfer_type: 'off', + method: 'off', + timestamp: 'on', + block: 'off', + from_to: 'on', + amount: 'on', + asset: 'on', + value: 'on', + }, + address: { + in_out: 'on', + tx_hash: 'on', + type: 'on', + transfer_type: 'off', + method: 'off', + timestamp: 'on', + block: 'off', + from_to: 'on', + amount: 'on', + asset: 'on', + value: 'on', + }, + token: { + in_out: 'unavailable', + tx_hash: 'on', + type: 'off', + transfer_type: 'off', + method: 'off', + timestamp: 'on', + block: 'off', + from_to: 'on', + amount: 'on', + asset: 'on', + value: 'on', + }, + // the transaction endpoint returns method and timestamp as null, and the hash and block are the same for every row + tx: { + in_out: 'unavailable', + tx_hash: 'unavailable', + type: 'on', + transfer_type: 'off', + method: 'unavailable', + timestamp: 'unavailable', + block: 'unavailable', + from_to: 'on', + amount: 'on', + asset: 'on', + value: 'on', + }, +}; + +export interface SurfaceColumnStatesParams { + readonly chainConfig?: ChainConfig; + readonly typeFilter?: ReadonlyArray<TokenType>; + readonly tokenType?: TokenType | null; +} + +function getMultiplierState(surface: TokenTransferSurface, { chainConfig, typeFilter, tokenType }: SurfaceColumnStatesParams): ColumnState { + if (!isTokenMultiplierEnabled(chainConfig)) { + return 'unavailable'; + } + + if (typeFilter && typeFilter.length > 0 && !typeFilter.includes(UI_MULTIPLIER_TOKEN_TYPE)) { + return 'unavailable'; + } + + if (surface === 'token' && tokenType !== UI_MULTIPLIER_TOKEN_TYPE) { + return 'unavailable'; + } + + return 'on'; +} + +export function getSurfaceColumnStates(surface: TokenTransferSurface, params: SurfaceColumnStatesParams): ColumnStates<TokenTransferColumnId> { + return { ...SURFACE_COLUMN_STATES[surface], multiplier: getMultiplierState(surface, params) }; +} diff --git a/src/slices/token-transfer/utils/get-token-transfer-key.spec.ts b/src/slices/token-transfer/utils/get-token-transfer-key.spec.ts index aa82605bc90..a074173c695 100644 --- a/src/slices/token-transfer/utils/get-token-transfer-key.spec.ts +++ b/src/slices/token-transfer/utils/get-token-transfer-key.spec.ts @@ -1,5 +1,7 @@ // SPDX-License-Identifier: LicenseRef-Blockscout +import type { schemas } from '@blockscout/api-types'; + import { describe, expect, it } from 'vitest'; import { erc1155A, erc1155B, erc1155C, erc1155D, erc20 } from '../mocks'; @@ -9,20 +11,30 @@ describe('getTokenTransferKey', () => { it('tells apart the items of a single ERC-1155 batch transfer', () => { const batch = [ erc1155A, erc1155B, erc1155C, erc1155D ]; - expect(new Set(batch.map(getTokenTransferKey)).size).toBe(4); + expect(new Set(batch.map((item) => getTokenTransferKey(item, undefined))).size).toBe(4); }); it('tells apart transfers from the same block that differ only in log index', () => { - const first = getTokenTransferKey(erc1155A); - const second = getTokenTransferKey({ ...erc1155A, log_index: erc1155A.log_index + 1 }); + const first = getTokenTransferKey(erc1155A, undefined); + const second = getTokenTransferKey({ ...erc1155A, log_index: erc1155A.log_index + 1 }, undefined); expect(first).not.toBe(second); }); it('tells apart transfers that carry no token id', () => { - const fungible = getTokenTransferKey(erc20); + const fungible = getTokenTransferKey(erc20, undefined); + + expect(fungible).not.toBe(getTokenTransferKey({ ...erc20, transaction_hash: '0xdeadbeef' }, undefined)); + expect(fungible).not.toBe(getTokenTransferKey(erc1155A, undefined)); + }); + + it('keys a transfer without a total like one whose total has no token id', () => { + const withoutTotal = { ...erc20, total: null } as unknown as schemas['TokenTransfer']; + + expect(getTokenTransferKey(withoutTotal, undefined)).toBe(getTokenTransferKey(erc20, undefined)); + }); - expect(fungible).not.toBe(getTokenTransferKey({ ...erc20, transaction_hash: '0xdeadbeef' })); - expect(fungible).not.toBe(getTokenTransferKey(erc1155A)); + it('tells apart the same transfer on different chains', () => { + expect(getTokenTransferKey(erc20, '1')).not.toBe(getTokenTransferKey(erc20, '10')); }); }); diff --git a/src/slices/token-transfer/utils/get-token-transfer-key.ts b/src/slices/token-transfer/utils/get-token-transfer-key.ts index 73538aeb85b..e882720c201 100644 --- a/src/slices/token-transfer/utils/get-token-transfer-key.ts +++ b/src/slices/token-transfer/utils/get-token-transfer-key.ts @@ -2,16 +2,8 @@ import type { schemas } from '@blockscout/api-types'; -// An ERC-1155 batch transfer reaches the API as a single log, which the API flattens into one item -// per transferred token id — so those items share a (transaction_hash, block_hash, log_index) triple -// and only the token id tells them apart. -// -// Equal keys are not merely untidy here: React tracks pending removals in a key -> fiber map, where -// duplicates overwrite each other, and the shadowed fibers are then never unmounted. Their rows stay -// in the DOM through pagination, stacked above the rows of every page that follows. -// https://github.com/blockscout/frontend/issues/3628 -export function getTokenTransferKey(item: schemas['TokenTransfer']): string { +export function getTokenTransferKey(item: schemas['TokenTransfer'], chainId: string | undefined): string { const tokenId = item.total && 'token_id' in item.total ? item.total.token_id : null; - return [ item.transaction_hash, item.block_hash, item.log_index, tokenId ].join('_'); + return [ item.transaction_hash, item.block_hash, item.log_index, tokenId, chainId ].join('_'); } diff --git a/src/slices/token-transfer/utils/get-token-transfer-ui-multiplier.spec.ts b/src/slices/token-transfer/utils/get-token-transfer-ui-multiplier.spec.ts new file mode 100644 index 00000000000..7779c6eebb3 --- /dev/null +++ b/src/slices/token-transfer/utils/get-token-transfer-ui-multiplier.spec.ts @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { schemas } from '@blockscout/api-types'; + +import * as advancedFilterMock from 'src/features/advanced-filter/mocks'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import { erc20, erc721, erc8056 } from '../mocks'; + +const CURRENT_TOKEN_FACTOR = '2000000000000000000'; + +const erc8056WithChangedTokenFactor: schemas['TokenTransfer'] = { + ...erc8056, + token: { ...erc8056.token!, ui_multiplier: CURRENT_TOKEN_FACTOR }, +}; + +function resolveWithTypeEnabled(data: schemas['TokenTransfer']) { + return withEnvs(ENVS_MAP.additionalTokenTypes, async() => { + const { getTokenTransferUiMultiplier } = await import('./get-token-transfer-ui-multiplier'); + return getTokenTransferUiMultiplier(data); + }); +} + +describe('getTokenTransferUiMultiplier', () => { + it('resolves the factor that applied to the transfer', async() => { + const result = await resolveWithTypeEnabled(erc8056); + expect(result?.toFixed()).toBe('1.69'); + }); + + it('resolves the factor of an advanced filter item', async() => { + const item = advancedFilterMock.baseResponse.items.find(({ type }) => type === 'ERC-8056'); + const result = await withEnvs(ENVS_MAP.additionalTokenTypes, async() => { + const { getTokenTransferUiMultiplier } = await import('./get-token-transfer-ui-multiplier'); + return getTokenTransferUiMultiplier(item!); + }); + expect(result?.toFixed()).toBe('1.69'); + }); + + it('ignores the token current factor', async() => { + const result = await resolveWithTypeEnabled(erc8056WithChangedTokenFactor); + expect(result?.toFixed()).toBe('1.69'); + }); + + it('resolves to nothing when the transfer factor is null, with no fallback to the token', async() => { + const result = await resolveWithTypeEnabled({ + ...erc8056WithChangedTokenFactor, + total: { ...erc8056.total as schemas['TokenTransferTotalFungible'], ui_multiplier: null }, + }); + expect(result).toBeUndefined(); + }); + + it('resolves to nothing for a transfer of another fungible type', async() => { + expect(await resolveWithTypeEnabled(erc20)).toBeUndefined(); + }); + + it('resolves to nothing for an NFT transfer', async() => { + expect(await resolveWithTypeEnabled(erc721)).toBeUndefined(); + }); + + it('resolves to nothing when the transfer has no total', async() => { + expect(await resolveWithTypeEnabled({ ...erc8056, total: null })).toBeUndefined(); + }); + + it('resolves to nothing when ERC-8056 is not among the instance additional token types', async() => { + const { getTokenTransferUiMultiplier } = await import('./get-token-transfer-ui-multiplier'); + expect(getTokenTransferUiMultiplier(erc8056)).toBeUndefined(); + }); +}); diff --git a/src/slices/token-transfer/utils/get-token-transfer-ui-multiplier.ts b/src/slices/token-transfer/utils/get-token-transfer-ui-multiplier.ts new file mode 100644 index 00000000000..e259772ab25 --- /dev/null +++ b/src/slices/token-transfer/utils/get-token-transfer-ui-multiplier.ts @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type BigNumber from 'bignumber.js'; + +import type { schemas } from '@blockscout/api-types'; +import type { ChainConfig } from 'src/slices/token/types/client'; + +import { getUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; + +type TransferLike = Pick<schemas['TokenTransfer'] | schemas['AdvancedFilterItem'], 'token' | 'total'>; + +// A transfer is scaled by the factor in force when it happened (total.ui_multiplier), +// never by the token's current factor (token.ui_multiplier), which may have changed since. +export function getTokenTransferUiMultiplier(data: TransferLike, chainConfig?: ChainConfig): BigNumber | undefined { + if (!data.token || !data.total || !('ui_multiplier' in data.total)) { + return undefined; + } + + return getUiMultiplier({ type: data.token.type, ui_multiplier: data.total.ui_multiplier }, chainConfig); +} diff --git a/src/slices/token/components/entity/TokenEntity.tsx b/src/slices/token/components/entity/TokenEntity.tsx index aaf4a116511..cb50d223a91 100644 --- a/src/slices/token/components/entity/TokenEntity.tsx +++ b/src/slices/token/components/entity/TokenEntity.tsx @@ -20,7 +20,7 @@ import SpriteIcon from 'src/sprite/SpriteIcon'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; import { Tooltip } from 'src/toolkit/chakra/tooltip'; -import { TruncatedTextTooltip } from 'src/toolkit/components/truncation/TruncatedTextTooltip'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; type LinkProps = EntityBase.LinkBaseProps & Pick<EntityProps, 'token'>; @@ -113,17 +113,7 @@ const Symbol = (props: SymbolProps) => { color="text.secondary" > <div>(</div> - <TruncatedTextTooltip label={ symbol }> - <chakra.span - display="inline-block" - whiteSpace="nowrap" - overflow="hidden" - textOverflow="ellipsis" - height="fit-content" - > - { symbol } - </chakra.span> - </TruncatedTextTooltip> + <Truncate value={ symbol } type="end"/> <div>)</div> </Skeleton> ); diff --git a/src/slices/token/components/entity/TokenEntityWithAddressFilter.tsx b/src/slices/token/components/entity/TokenEntityWithAddressFilter.tsx index 6a4f863101e..a8a9d06a1db 100644 --- a/src/slices/token/components/entity/TokenEntityWithAddressFilter.tsx +++ b/src/slices/token/components/entity/TokenEntityWithAddressFilter.tsx @@ -1,12 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { chakra } from '@chakra-ui/react'; -import { route } from 'nextjs-routes'; import React from 'react'; import * as TokenEntity from 'src/slices/token/components/entity/TokenEntity'; import config from 'src/config'; +import { route } from 'src/shared/router/routes'; interface Props extends TokenEntity.EntityProps { addressHash: string; diff --git a/src/slices/token/components/entity/__screenshots__/NftEntity.pw.tsx_default_loading-1.png b/src/slices/token/components/entity/__screenshots__/NftEntity.pw.tsx_default_loading-1.png index e4f5956d237..f59eafa48b2 100644 Binary files a/src/slices/token/components/entity/__screenshots__/NftEntity.pw.tsx_default_loading-1.png and b/src/slices/token/components/entity/__screenshots__/NftEntity.pw.tsx_default_loading-1.png differ diff --git a/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_customization-1.png b/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_customization-1.png index e66f919f66d..c299e5ba182 100644 Binary files a/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_customization-1.png and b/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_customization-1.png differ diff --git a/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_loading-1.png b/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_loading-1.png index 3087d7b62b8..9e780228dcb 100644 Binary files a/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_loading-1.png and b/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_loading-1.png differ diff --git a/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_variant-content-1.png b/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_variant-content-1.png index 8b5cbac5eac..5b1cefefe03 100644 Binary files a/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_variant-content-1.png and b/src/slices/token/components/entity/__screenshots__/TokenEntity.pw.tsx_default_variant-content-1.png differ diff --git a/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_dark-color-mode_image-fullscreen-dark-mode-mobile-1.png b/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_dark-color-mode_image-fullscreen-dark-mode-mobile-1.png index 59f81a37e76..3f82b698f18 100644 Binary files a/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_dark-color-mode_image-fullscreen-dark-mode-mobile-1.png and b/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_dark-color-mode_image-fullscreen-dark-mode-mobile-1.png differ diff --git a/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_dark-color-mode_no-url-preview-dark-mode-1.png b/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_dark-color-mode_no-url-preview-dark-mode-1.png index 249c60b9152..829f7325861 100644 Binary files a/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_dark-color-mode_no-url-preview-dark-mode-1.png and b/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_dark-color-mode_no-url-preview-dark-mode-1.png differ diff --git a/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_default_image-fullscreen-dark-mode-mobile-1.png b/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_default_image-fullscreen-dark-mode-mobile-1.png index 6a736a55e63..87c9f701633 100644 Binary files a/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_default_image-fullscreen-dark-mode-mobile-1.png and b/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_default_image-fullscreen-dark-mode-mobile-1.png differ diff --git a/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_default_no-url-preview-dark-mode-1.png b/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_default_no-url-preview-dark-mode-1.png index 2249710f665..f2d0648503a 100644 Binary files a/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_default_no-url-preview-dark-mode-1.png and b/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_default_no-url-preview-dark-mode-1.png differ diff --git a/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_mobile_image-fullscreen-dark-mode-mobile-1.png b/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_mobile_image-fullscreen-dark-mode-mobile-1.png index 9c85df14982..d9f9b8e4d6f 100644 Binary files a/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_mobile_image-fullscreen-dark-mode-mobile-1.png and b/src/slices/token/components/nft-media/__screenshots__/NftMedia.pw.tsx_mobile_image-fullscreen-dark-mode-mobile-1.png differ diff --git a/src/slices/token/components/nft-media/useLoadImageViaIpfs.ts b/src/slices/token/components/nft-media/useLoadImageViaIpfs.ts new file mode 100644 index 00000000000..50358e558fc --- /dev/null +++ b/src/slices/token/components/nft-media/useLoadImageViaIpfs.ts @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { withHTTP } from '@helia/http'; +import type { VerifiedFetch } from '@helia/verified-fetch'; +import { createVerifiedFetchWithHelia } from '@helia/verified-fetch'; +import { createHeliaLight } from 'helia'; +import React from 'react'; + +import { VERIFIED_FETCH_GATEWAYS } from 'src/slices/token/utils/verified-fetch'; + +import { SECOND } from 'src/toolkit/utils/consts'; + +// a block the gateways have to look up first can stall for minutes; past this the image falls back to HTTP +const LOAD_TIMEOUT = 30 * SECOND; + +const EMPTY_ROUTER = { + name: 'empty-router', + async *findProviders() {}, +}; + +let verifiedFetchPromise: Promise<VerifiedFetch> | undefined; + +// The default verified-fetch node discovers providers through delegated routing and connects to them directly, +// but those hosts are unknown in advance and cannot be allowed by the CSP, so only the fixed gateways are used. +function getVerifiedFetch(): Promise<VerifiedFetch> { + verifiedFetchPromise ??= (async() => { + const helia = withHTTP(createHeliaLight(), { + delegatedRouters: [], + recursiveGateways: VERIFIED_FETCH_GATEWAYS, + }); + // Helia waits forever for providers when it has no regular router, and never falls back to the gateways + helia.addRouter(EMPTY_ROUTER); + await helia.start(); + return createVerifiedFetchWithHelia(helia); + })().catch((error: unknown) => { + verifiedFetchPromise = undefined; + throw error; + }); + + return verifiedFetchPromise; +} + +export default function useLoadImageViaIpfs() { + const objectUrlRef = React.useRef<string>(undefined); + const generationRef = React.useRef(0); + + React.useEffect(() => { + return () => { + generationRef.current += 1; + objectUrlRef.current && URL.revokeObjectURL(objectUrlRef.current); + objectUrlRef.current = undefined; + }; + }, []); + + return React.useCallback(async(url: string): Promise<string | undefined> => { + generationRef.current += 1; + const generation = generationRef.current; + + const verifiedFetch = await getVerifiedFetch(); + const response = await verifiedFetch(url, { signal: AbortSignal.timeout(LOAD_TIMEOUT) }); + + if (response.status !== 200) { + throw new Error('Failed to load image'); + } + + const blob = await response.blob(); + // react-doctor-disable-next-line react-doctor/no-create-object-url-without-revoke -- revoked when superseded, stale or unmounted; rule wants a sync revoke + const src = URL.createObjectURL(blob); + + if (generation !== generationRef.current) { + URL.revokeObjectURL(src); + return undefined; + } + + objectUrlRef.current && URL.revokeObjectURL(objectUrlRef.current); + objectUrlRef.current = src; + + return src; + }, [ ]); +} diff --git a/src/slices/token/components/nft-media/useLoadImageViaIpfs.tsx b/src/slices/token/components/nft-media/useLoadImageViaIpfs.tsx deleted file mode 100644 index 5acca756b5a..00000000000 --- a/src/slices/token/components/nft-media/useLoadImageViaIpfs.tsx +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { verifiedFetch } from '@helia/verified-fetch'; -import React from 'react'; - -export default function useLoadImageViaIpfs() { - return React.useCallback(async(url: string) => { - const response = await verifiedFetch(url); - - if (response.status !== 200) { - throw new Error('Failed to load image'); - } - - const blob = await response.blob(); - const src = URL.createObjectURL(blob); - return src; - }, [ ]); -} diff --git a/src/slices/token/components/nft-media/useNftMediaInfo.ts b/src/slices/token/components/nft-media/useNftMediaInfo.ts new file mode 100644 index 00000000000..8972210504b --- /dev/null +++ b/src/slices/token/components/nft-media/useNftMediaInfo.ts @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { UseQueryResult } from '@tanstack/react-query'; +import { useQuery } from '@tanstack/react-query'; + +import type { schemas } from '@blockscout/api-types'; + +import config from 'src/config'; +import type { DynamicRoute } from 'src/shared/router/routes'; +import { route } from 'src/shared/router/routes'; + +import type { MediaType, Size, TransportType } from './utils'; +import { getIpfsUri, getPreliminaryMediaType } from './utils'; + +interface Params { + data: schemas['TokenInstance'] | schemas['TokenInstanceInTokenInstancesList']; + addressHash: string; + size: Size; + allowedTypes?: Array<MediaType>; + field: 'animation_url' | 'image_url'; + isEnabled: boolean; +} + +interface MediaInfo { + src: string; + srcSet?: string; + mediaType: MediaType; + transport: TransportType; +} + +export default function useNftMediaInfo({ data, addressHash, size, allowedTypes, field, isEnabled }: Params): UseQueryResult<Array<MediaInfo> | null> { + const url = data[field]; + const query = useQuery({ + queryKey: [ 'nft-media-info', addressHash, data.id, url, size, ...(allowedTypes ? allowedTypes : []) ], + queryFn: async() => { + const metadataField = field === 'animation_url' ? 'animation_url' : 'image'; + const mediaType = await getMediaType(data, addressHash, field); + + if (!mediaType || (allowedTypes ? !allowedTypes.includes(mediaType) : false)) { + return null; + } + + const cdnData = getCdnData(data, size, mediaType); + const ipfsData = getIpfsData(data.metadata?.[metadataField], mediaType); + + return [ + cdnData, + ipfsData, + url ? { src: url, mediaType, transport: 'http' as const } : undefined, + ].filter(Boolean); + }, + enabled: isEnabled, + }); + + return query; +} + +async function getMediaType( + data: schemas['TokenInstance'] | schemas['TokenInstanceInTokenInstancesList'], + addressHash: string, + field: Params['field'], +): Promise<MediaType | undefined> { + const url = data[field]; + + if (!url) { + return; + } + + // If the media_url is the same as the url, we can use the media_type field to determine the media type. + if (url === data.media_url) { + const mediaType = castMimeTypeToMediaType(data.media_type || undefined); + if (mediaType) { + return mediaType; + } + } + + // Media can be an image, video, or HTML page. + // We pre-fetch the resources to determine their content type. + // We must do this via Node.js due to strict CSP for connect-src. + // To avoid overloading our server, we first check the file URL extension. + // If it is valid, we will trust it and display the corresponding media component. + + const preliminaryType = getPreliminaryMediaType(url); + + if (preliminaryType) { + return preliminaryType; + } + + try { + const mediaTypeResourceUrl = route({ + // eslint-disable-next-line max-len + pathname: '/node-api/tokens/[hash]/instances/[id]/media-type' as DynamicRoute<'/api/tokens/[hash]/instances/[id]/media-type', { hash: string; id: string }>['pathname'], + query: { + hash: addressHash, + id: data.id, + field, + }, + }); + const response = await fetch(mediaTypeResourceUrl); + const payload = await response.json() as { type: MediaType | undefined }; + + return payload.type; + } catch (error) { + return; + } +} + +function castMimeTypeToMediaType(mimeType: string | undefined): MediaType | undefined { + if (!mimeType) { + return; + } + + if (mimeType.startsWith('image/')) { + return 'image'; + } + + if (mimeType.startsWith('video/')) { + return 'video'; + } +} + +function getCdnData(data: schemas['TokenInstance'] | schemas['TokenInstanceInTokenInstancesList'], size: Size, mediaType: MediaType): MediaInfo | undefined { + // CDN is only used for images + if (mediaType !== 'image') { + return; + } + + if (!data.thumbnails) { + return; + } + + switch (size) { + case 'sm': { + return { + src: data.thumbnails['60x60'] || data.thumbnails['250x250'] || data.thumbnails['500x500'] || data.thumbnails['original'], + // the smallest thumbnail is already greater than sm size by two times + // so there is no need to pass srcSet + srcSet: undefined, + mediaType: 'image', + transport: 'http', + }; + } + case 'md': { + const srcSet = data.thumbnails['250x250'] && data.thumbnails['500x500'] ? `${ data.thumbnails['500x500'] } 2x` : undefined; + const src = (srcSet ? data.thumbnails['250x250'] : undefined) || data.thumbnails['500x500'] || data.thumbnails.original; + + return { + src, + srcSet, + mediaType: 'image', + transport: 'http', + }; + } + default: { + if (data.thumbnails.original) { + return { + src: data.thumbnails.original, + mediaType: 'image', + transport: 'http', + }; + } + } + } +} + +function getIpfsData(url: unknown, mediaType: MediaType): MediaInfo | undefined { + if (!config.slices.token.nft.verifiedFetch.isEnabled) { + return; + } + + // Currently we only load images via IPFS + if (mediaType !== 'image') { + return; + } + + if (typeof url !== 'string') { + return; + } + + const ipfsUri = getIpfsUri(url); + if (!ipfsUri) { + return; + } + + return { + src: ipfsUri, + mediaType, + transport: 'ipfs', + }; +} diff --git a/src/slices/token/components/nft-media/useNftMediaInfo.tsx b/src/slices/token/components/nft-media/useNftMediaInfo.tsx deleted file mode 100644 index c659b577e46..00000000000 --- a/src/slices/token/components/nft-media/useNftMediaInfo.tsx +++ /dev/null @@ -1,189 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import type { UseQueryResult } from '@tanstack/react-query'; -import { useQuery } from '@tanstack/react-query'; -import type { DynamicRoute } from 'nextjs-routes'; -import { route } from 'nextjs-routes'; - -import type { schemas } from '@blockscout/api-types'; - -import config from 'src/config'; - -import type { MediaType, Size, TransportType } from './utils'; -import { getPreliminaryMediaType } from './utils'; - -interface Params { - data: schemas['TokenInstance'] | schemas['TokenInstanceInTokenInstancesList']; - addressHash: string; - size: Size; - allowedTypes?: Array<MediaType>; - field: 'animation_url' | 'image_url'; - isEnabled: boolean; -} - -interface MediaInfo { - src: string; - srcSet?: string; - mediaType: MediaType; - transport: TransportType; -} - -export default function useNftMediaInfo({ data, addressHash, size, allowedTypes, field, isEnabled }: Params): UseQueryResult<Array<MediaInfo> | null> { - const url = data[field]; - const query = useQuery({ - queryKey: [ 'nft-media-info', addressHash, data.id, url, size, ...(allowedTypes ? allowedTypes : []) ], - queryFn: async() => { - const metadataField = field === 'animation_url' ? 'animation_url' : 'image'; - const mediaType = await getMediaType(data, addressHash, field); - - if (!mediaType || (allowedTypes ? !allowedTypes.includes(mediaType) : false)) { - return null; - } - - const cdnData = getCdnData(data, size, mediaType); - const ipfsData = getIpfsData(data.metadata?.[metadataField], mediaType); - - return [ - cdnData, - ipfsData, - url ? { src: url, mediaType, transport: 'http' as const } : undefined, - ].filter(Boolean); - }, - enabled: isEnabled, - }); - - return query; -} - -async function getMediaType( - data: schemas['TokenInstance'] | schemas['TokenInstanceInTokenInstancesList'], - addressHash: string, - field: Params['field'], -): Promise<MediaType | undefined> { - const url = data[field]; - - if (!url) { - return; - } - - // If the media_url is the same as the url, we can use the media_type field to determine the media type. - if (url === data.media_url) { - const mediaType = castMimeTypeToMediaType(data.media_type || undefined); - if (mediaType) { - return mediaType; - } - } - - // Media can be an image, video, or HTML page. - // We pre-fetch the resources to determine their content type. - // We must do this via Node.js due to strict CSP for connect-src. - // To avoid overloading our server, we first check the file URL extension. - // If it is valid, we will trust it and display the corresponding media component. - - const preliminaryType = getPreliminaryMediaType(url); - - if (preliminaryType) { - return preliminaryType; - } - - try { - const mediaTypeResourceUrl = route({ - // eslint-disable-next-line max-len - pathname: '/node-api/tokens/[hash]/instances/[id]/media-type' as DynamicRoute<'/api/tokens/[hash]/instances/[id]/media-type', { hash: string; id: string }>['pathname'], - query: { - hash: addressHash, - id: data.id, - field, - }, - }); - const response = await fetch(mediaTypeResourceUrl); - const payload = await response.json() as { type: MediaType | undefined }; - - return payload.type; - } catch (error) { - return; - } -} - -function castMimeTypeToMediaType(mimeType: string | undefined): MediaType | undefined { - if (!mimeType) { - return; - } - - if (mimeType.startsWith('image/')) { - return 'image'; - } - - if (mimeType.startsWith('video/')) { - return 'video'; - } -} - -function getCdnData(data: schemas['TokenInstance'] | schemas['TokenInstanceInTokenInstancesList'], size: Size, mediaType: MediaType): MediaInfo | undefined { - // CDN is only used for images - if (mediaType !== 'image') { - return; - } - - if (!data.thumbnails) { - return; - } - - switch (size) { - case 'sm': { - return { - src: data.thumbnails['60x60'] || data.thumbnails['250x250'] || data.thumbnails['500x500'] || data.thumbnails['original'], - // the smallest thumbnail is already greater than sm size by two times - // so there is no need to pass srcSet - srcSet: undefined, - mediaType: 'image', - transport: 'http', - }; - } - case 'md': { - const srcSet = data.thumbnails['250x250'] && data.thumbnails['500x500'] ? `${ data.thumbnails['500x500'] } 2x` : undefined; - const src = (srcSet ? data.thumbnails['250x250'] : undefined) || data.thumbnails['500x500'] || data.thumbnails.original; - - return { - src, - srcSet, - mediaType: 'image', - transport: 'http', - }; - } - default: { - if (data.thumbnails.original) { - return { - src: data.thumbnails.original, - mediaType: 'image', - transport: 'http', - }; - } - } - } -} - -function getIpfsData(url: unknown, mediaType: MediaType): MediaInfo | undefined { - if (!config.slices.token.nft.verifiedFetch.isEnabled) { - return; - } - - // Currently we only load images via IPFS - if (mediaType !== 'image') { - return; - } - - if (typeof url !== 'string') { - return; - } - - if (!url.includes('ipfs')) { - return; - } - - return { - src: url, - mediaType, - transport: 'ipfs', - }; -} diff --git a/src/slices/token/components/nft-media/utils.spec.ts b/src/slices/token/components/nft-media/utils.spec.ts new file mode 100644 index 00000000000..5a348c569c0 --- /dev/null +++ b/src/slices/token/components/nft-media/utils.spec.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest'; + +import { getIpfsUri } from './utils'; + +const CID = 'bafybeigdyrztx7ls4mrwlwyfm2p3zjnyxyuhx2qrcdxjr2bnqh6qhvcfsy'; + +describe('getIpfsUri', () => { + it.each([ + [ 'ipfs://' + CID + '/1.png', 'ipfs://' + CID + '/1.png' ], + [ 'ipfs://ipfs/' + CID + '/1.png', 'ipfs://' + CID + '/1.png' ], + ])('keeps a native URI addressing the content: %s', (url, expected) => { + expect(getIpfsUri(url)).toBe(expected); + }); + + it.each([ + [ 'https://ipfs.io/ipfs/' + CID, 'ipfs://' + CID ], + [ 'https://ipfs.io/ipfs/' + CID + '/', 'ipfs://' + CID ], + [ 'https://gateway.pinata.cloud/ipfs/' + CID + '/images/1.png?filename=1.png', 'ipfs://' + CID + '/images/1.png?filename=1.png' ], + [ 'http://localhost:8080/ipfs/' + CID + '/1.png', 'ipfs://' + CID + '/1.png' ], + [ 'https://ipfs.io/ipfs/ipfs/' + CID + '/1.png', 'ipfs://' + CID + '/1.png' ], + [ 'https://gateway.ipfs.io/ipfs/' + CID + '/1.png', 'ipfs://' + CID + '/1.png' ], + ])('converts a path gateway URL: %s', (url, expected) => { + expect(getIpfsUri(url)).toBe(expected); + }); + + it.each([ + [ 'https://' + CID + '.ipfs.dweb.link', 'ipfs://' + CID ], + [ 'https://' + CID + '.ipfs.w3s.link/images/1.png', 'ipfs://' + CID + '/images/1.png' ], + [ 'https://' + CID + '.ipfs.dweb.link/1.png?v=2', 'ipfs://' + CID + '/1.png?v=2' ], + [ 'https://' + CID + '.ipfs.dweb.link/ipfs/1.png', 'ipfs://' + CID + '/ipfs/1.png' ], + ])('converts a subdomain gateway URL: %s', (url, expected) => { + expect(getIpfsUri(url)).toBe(expected); + }); + + it.each([ + 'ipns://example.eth/1.png', + 'https://ipfs.io/ipns/example.eth/1.png', + 'https://example-eth.ipns.dweb.link/1.png', + ])('leaves an IPNS name to the HTTP transport: %s', (url) => { + expect(getIpfsUri(url)).toBeUndefined(); + }); + + it.each([ + 'https://example.com/images/ipfs.png', + 'https://ipfs.io/', + 'https://ipfs.io/ipfs/', + 'https://' + CID + '.ipfs/1.png', + 'https://' + CID + '.example.com/1.png', + 'ftp://ipfs.io/ipfs/' + CID, + 'ar://some-arweave-id', + 'not a url ipfs', + ])('rejects a URL that does not address IPFS content: %s', (url) => { + expect(getIpfsUri(url)).toBeUndefined(); + }); +}); diff --git a/src/slices/token/components/nft-media/utils.ts b/src/slices/token/components/nft-media/utils.ts index 448bd432846..4cd7e8562ec 100644 --- a/src/slices/token/components/nft-media/utils.ts +++ b/src/slices/token/components/nft-media/utils.ts @@ -1,6 +1,7 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { HTMLChakraProps } from '@chakra-ui/react'; +import { CID } from 'multiformats/cid'; import type React from 'react'; export type MediaType = 'image' | 'video' | 'html'; @@ -51,6 +52,50 @@ export function getPreliminaryMediaType(url: string): MediaType | undefined { } } +const NATIVE_IPFS_URI_REGEX = /^ipfs:\/\/(?:ipfs\/)?(.+)$/; +const GATEWAY_PATH_REGEX = /^\/ipfs\/(?:ipfs\/)?([^/]+)(\/.*)?$/; + +function buildIpfsUri(cid: string, path: string, search: string): string { + return `ipfs://${ cid }${ path === '/' ? '' : path }${ search }`; +} + +function isCid(value: string): boolean { + try { + CID.parse(value); + return true; + } catch { + return false; + } +} + +// verified-fetch accepts only native URIs, but NFT metadata often links to the content through an HTTP gateway. +// IPNS names are left to the HTTP transport: resolving them needs delegated routing, which the CSP does not allow. +export function getIpfsUri(url: string): string | undefined { + const nativeMatch = url.match(NATIVE_IPFS_URI_REGEX); + if (nativeMatch) { + return `ipfs://${ nativeMatch[1] }`; + } + + if (!URL.canParse(url)) { + return; + } + + const { protocol, hostname, pathname, search } = new URL(url); + if (protocol !== 'https:' && protocol !== 'http:') { + return; + } + + const [ subdomainCid, subdomainNamespace, ...gatewayHost ] = hostname.split('.'); + if (subdomainNamespace === 'ipfs' && gatewayHost.length > 0 && isCid(subdomainCid)) { + return buildIpfsUri(subdomainCid, pathname, search); + } + + const pathMatch = pathname.match(GATEWAY_PATH_REGEX); + if (pathMatch) { + return buildIpfsUri(pathMatch[1], pathMatch[2] ?? '', search); + } +} + export const mediaStyleProps = { transitionProperty: 'transform', transitionDuration: 'normal', diff --git a/src/slices/token/components/ui-multiplier/TokenMultiplierChangeStatusTag.tsx b/src/slices/token/components/ui-multiplier/TokenMultiplierChangeStatusTag.tsx new file mode 100644 index 00000000000..f4402db08bb --- /dev/null +++ b/src/slices/token/components/ui-multiplier/TokenMultiplierChangeStatusTag.tsx @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { UiMultiplierChangeStatus } from 'src/slices/token/utils/ui-multiplier'; + +import type { BadgeProps } from 'src/toolkit/chakra/badge'; +import { Badge } from 'src/toolkit/chakra/badge'; + +interface Props { + status: UiMultiplierChangeStatus; + isLoading?: boolean; +} + +const STATUS_LABELS: Record<UiMultiplierChangeStatus, string> = { + active: 'Active', + inactive: 'Inactive', + scheduled: 'Scheduled', +}; + +const STATUS_COLORS: Record<UiMultiplierChangeStatus, BadgeProps['colorPalette']> = { + active: 'green', + inactive: 'gray', + scheduled: 'gray', +}; + +const TokenMultiplierChangeStatusTag = ({ status, isLoading }: Props) => { + return ( + <Badge colorPalette={ STATUS_COLORS[status] } loading={ isLoading }> + { STATUS_LABELS[status] } + </Badge> + ); +}; + +export default React.memo(TokenMultiplierChangeStatusTag); diff --git a/src/slices/token/components/ui-multiplier/TokenMultiplierChangeValue.tsx b/src/slices/token/components/ui-multiplier/TokenMultiplierChangeValue.tsx new file mode 100644 index 00000000000..22351f33556 --- /dev/null +++ b/src/slices/token/components/ui-multiplier/TokenMultiplierChangeValue.tsx @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { HStack } from '@chakra-ui/react'; +import React from 'react'; + +import { formatUiMultiplier, parseUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; + +import SpriteIcon from 'src/sprite/SpriteIcon'; + +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; + +interface Props { + oldMultiplier: string; + newMultiplier: string; + isLoading?: boolean; +} + +const TokenMultiplierChangeValue = ({ oldMultiplier, newMultiplier, isLoading }: Props) => { + return ( + <HStack> + <Truncate + value={ formatUiMultiplier(parseUiMultiplier(oldMultiplier)) } + type="end" + loading={ isLoading } + color="text.secondary" + maxW="calc(50% - 18px)" + /> + <SpriteIcon + name="arrows/east" + isLoading={ isLoading } + boxSize={ 5 } + flexShrink={ 0 } + color="icon.primary" + /> + <Truncate + value={ formatUiMultiplier(parseUiMultiplier(newMultiplier)) } + type="end" + loading={ isLoading } + color="text.secondary" + maxW="calc(50% - 18px)" + /> + </HStack> + ); +}; + +export default React.memo(TokenMultiplierChangeValue); diff --git a/src/slices/token/components/ui-multiplier/TokenMultiplierTag.tsx b/src/slices/token/components/ui-multiplier/TokenMultiplierTag.tsx new file mode 100644 index 00000000000..dfc81476cd4 --- /dev/null +++ b/src/slices/token/components/ui-multiplier/TokenMultiplierTag.tsx @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type BigNumber from 'bignumber.js'; +import React from 'react'; + +import { formatUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; + +import { Tag, type TagProps } from 'src/toolkit/chakra/tag'; +import { Tooltip } from 'src/toolkit/chakra/tooltip'; + +interface Props extends TagProps { + multiplier: BigNumber; +} + +const TokenMultiplierTag = ({ multiplier, ...rest }: Props) => { + return ( + <Tooltip content="Token amounts shown are scaled by this factor compared to the raw ERC-20 token amount"> + <Tag { ...rest }>{ formatUiMultiplier(multiplier) }</Tag> + </Tooltip> + ); +}; + +export default React.memo(TokenMultiplierTag); diff --git a/src/slices/token/hooks/useTokensQuery.ts b/src/slices/token/hooks/useTokensQuery.ts index fcb5ac77c28..388bef7c641 100644 --- a/src/slices/token/hooks/useTokensQuery.ts +++ b/src/slices/token/hooks/useTokensQuery.ts @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TokenType, TokensSortingValue, TokensSortingField, TokensSorting } from 'src/slices/token/types/api'; @@ -8,8 +7,8 @@ import type { TokenType, TokensSortingValue, TokensSortingField, TokensSorting } import { TOKEN_INFO_ERC_20 } from 'src/slices/token/stubs'; import { getTokenFilterValue, SORT_OPTIONS } from 'src/slices/token/utils/list-utils'; -import useDebounce from 'src/shared/hooks/useDebounce'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { useDebouncedFilterChange } from 'src/shared/pagination/useDebouncedFilterChange'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; @@ -22,20 +21,8 @@ interface Props { } export default function useTokensQuery({ enabled }: Props) { - const router = useRouter(); - - const q = getQueryParamString(router.query.q); - - const [ searchTerm, setSearchTerm ] = React.useState<string>(q ?? ''); - const [ tokenTypes, setTokenTypes ] = React.useState<Array<TokenType> | undefined>(getTokenFilterValue(router.query.type)); - const [ sort, setSort ] = React.useState<TokensSortingValue>(getSortValueFromQuery<TokensSortingValue>(router.query, SORT_OPTIONS) ?? 'default'); - - const debouncedSearchTerm = useDebounce(searchTerm, 300); - - const query = useQueryWithPages({ + const query = useApiPaginatedQuery({ resourceName: 'core:tokens', - filters: { q: debouncedSearchTerm, type: tokenTypes }, - sorting: getSortParamsFromValue<TokensSortingValue, TokensSortingField, TokensSorting['order']>(sort), options: { enabled, placeholderData: generateListStub<'core:tokens'>( @@ -46,21 +33,22 @@ export default function useTokensQuery({ enabled }: Props) { }, }); - const onSearchTermChange = React.useCallback((value: string) => { - query.onFilterChange({ q: value, type: tokenTypes }); - setSearchTerm(value); - }, [ tokenTypes, query ]); + const searchTerm = getQueryParamString(query.filters.q); + const typeParam = query.filters.type; + const tokenTypes = React.useMemo(() => getTokenFilterValue(typeParam), [ typeParam ]); + const sort = getSortValueFromQuery<TokensSortingValue>({ ...query.sorting }, SORT_OPTIONS) ?? 'default'; + + const { onFilterChange, onSortingChange } = query; + + const onSearchTermChange = useDebouncedFilterChange((value) => onFilterChange({ q: value, type: tokenTypes })); const onTokenTypesChange = React.useCallback((value: Array<TokenType>) => { - query.onFilterChange({ q: debouncedSearchTerm, type: value }); - setTokenTypes(value); - }, [ debouncedSearchTerm, query ]); + onFilterChange({ q: searchTerm, type: value }); + }, [ searchTerm, onFilterChange ]); const onSortChange: OnValueChangeHandler = React.useCallback(({ value }) => { - const sortValue = value[0] as TokensSortingValue; - setSort(sortValue); - query.onSortingChange(getSortParamsFromValue(sortValue)); - }, [ query ]); + onSortingChange(getSortParamsFromValue<TokensSortingValue, TokensSortingField, TokensSorting['order']>(value[0] as TokensSortingValue)); + }, [ onSortingChange ]); return React.useMemo(() => ({ query, diff --git a/src/slices/token/mocks/address-tokens.ts b/src/slices/token/mocks/address-tokens.ts index e49857a9fa4..ec237470037 100644 --- a/src/slices/token/mocks/address-tokens.ts +++ b/src/slices/token/mocks/address-tokens.ts @@ -49,6 +49,16 @@ export const erc20BigAmount: schemas['TokenBalance'] = { token_instance: null, }; +export const erc8056: schemas['TokenBalance'] = { + token: { + ...tokens.tokenInfoERC8056, + exchange_rate: '0.5', + }, + token_id: null, + value: '1000000000000000000000', + token_instance: null, +}; + export const erc721a: schemas['TokenBalance'] = { token: tokens.tokenInfoERC721a, token_id: null, @@ -154,6 +164,13 @@ export const erc404List: paths['/api/v2/addresses/{address_hash_param}/tokens'][ next_page_params: null, }; +export const erc8056List: paths['/api/v2/addresses/{address_hash_param}/tokens']['get'] = { + items: [ + erc8056, + ], + next_page_params: null, +}; + export const nfts: paths['/api/v2/addresses/{address_hash_param}/nft']['get'] = { items: [ { diff --git a/src/slices/token/mocks/info.ts b/src/slices/token/mocks/info.ts index 9c366a8ea3f..e48859ee802 100644 --- a/src/slices/token/mocks/info.ts +++ b/src/slices/token/mocks/info.ts @@ -20,6 +20,7 @@ export const tokenInfo = toTokenModel({ export const tokenCounters: schemas['TokenCountersResponse'] = { token_holders_count: '8838883', transfers_count: '88282281', + ui_multiplier_changes_count: '0', }; export const tokenInfoERC20a = toTokenModel({ @@ -92,6 +93,23 @@ export const tokenInfoERC20LongSymbol = toTokenModel({ reputation: 'ok', }); +export const tokenInfoERC8056 = toTokenModel({ + address_hash: '0x6D50E6CBca0e390BbCF82bEA80B31F4c2694395e', + circulating_market_cap: null, + decimals: '18', + exchange_rate: null, + holders_count: '2', + name: 'EMPTY PROMISES', + symbol: 'IOU', + total_supply: '1000000000000000000000000', + type: 'ERC-8056', + icon_url: null, + reputation: 'ok', + ui_multiplier: '1690000000000000000', + new_ui_multiplier: '1690000000000000000', + ui_multiplier_effective_at: '2026-09-07T14:27:48.000000Z', +}); + export const tokenInfoERC721a = toTokenModel({ address_hash: '0xDe7cAc71E072FCBd4453E5FB3558C2684d1F88A0', circulating_market_cap: null, diff --git a/src/slices/token/mocks/ui-multiplier.ts b/src/slices/token/mocks/ui-multiplier.ts new file mode 100644 index 00000000000..966e0f9b86a --- /dev/null +++ b/src/slices/token/mocks/ui-multiplier.ts @@ -0,0 +1,46 @@ +import type { paths } from '@blockscout/api-types'; + +export const tokenUiMultiplierChanges: paths['/api/v2/tokens/{address_hash_param}/ui-multiplier-changes']['get'] = { + items: [ + { + block_hash: '0x7c8bcc1ace3fc67b97acb73d0fd861f2834e4361c0589843682ee55f3fd991d3', + block_number: 11387790, + effective_at: '2022-11-20T00:00:00.000000Z', + log_index: 12, + new_multiplier: '12587469837638463968346836434630963098', + old_multiplier: '1040000000000000000', + timestamp: '2022-11-11T10:00:00.000000Z', + transaction_hash: '0x62d597ebcf3e8d60096dd0363bc2f0f5e2df27ba1dacd696c51aa7c9409f3193', + }, + { + block_hash: '0x7c8bcc1ace3fc67b97acb73d0fd861f2834e4361c0589843682ee55f3fd991d3', + block_number: 11387767, + effective_at: '2022-11-10T08:47:48.000000Z', + log_index: 738, + new_multiplier: '1040000000000000000', + old_multiplier: '105345398325738457923847598539', + timestamp: '2022-11-10T06:48:36.000000Z', + transaction_hash: '0x95cbc393f1e43ee417383c56c921e40106f09c77c3657ff024c8c2db6f35f1a4', + }, + { + block_hash: '0x7c8bcc1ace3fc67b97acb73d0fd861f2834e4361c0589843682ee55f3fd991d3', + block_number: 11387767, + effective_at: '2022-11-10T06:48:36.000000Z', + log_index: 737, + new_multiplier: '105345398325738457923847598539', + old_multiplier: '1000000000000000000', + timestamp: '2022-11-10T06:48:36.000000Z', + transaction_hash: null, + }, + ], + next_page_params: null, +}; + +export const tokenUiMultiplierChangesOverflow: paths['/api/v2/tokens/{address_hash_param}/ui-multiplier-changes']['get'] = { + items: Array.from({ length: 7 }, (_, index) => ({ + ...tokenUiMultiplierChanges.items[1], + block_number: tokenUiMultiplierChanges.items[1].block_number - index, + log_index: index, + })), + next_page_params: null, +}; diff --git a/src/slices/token/pages/address/AddressTokenBalances.tsx b/src/slices/token/pages/address/AddressTokenBalances.tsx index 74a0ea83b9c..bbbe87c5e60 100644 --- a/src/slices/token/pages/address/AddressTokenBalances.tsx +++ b/src/slices/token/pages/address/AddressTokenBalances.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -11,6 +10,7 @@ import NativeTokenIcon from 'src/slices/token/components/icon/TokenIconNative'; import config from 'src/config'; import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; +import { useRouter } from 'src/shared/router/useRouter'; import calculateUsdValue from 'src/shared/values/entity/calculateUsdValue'; import SpriteIcon from 'src/sprite/SpriteIcon'; diff --git a/src/slices/token/pages/address/fungible/AddressFungibleTokens.tsx b/src/slices/token/pages/address/fungible/AddressFungibleTokens.tsx index b38e15cd6cb..294b3f3b6f2 100644 --- a/src/slices/token/pages/address/fungible/AddressFungibleTokens.tsx +++ b/src/slices/token/pages/address/fungible/AddressFungibleTokens.tsx @@ -22,6 +22,7 @@ import AddressFungibleTokensTable from './AddressFungibleTokensTable'; type Props = { items: Array<Pick<schemas['TokenBalance'], 'token' | 'value'>> | undefined; isLoading: boolean; + isTransitioning?: boolean; pagination: PaginationParams; isError: boolean; top?: number; @@ -30,7 +31,7 @@ type Props = { resetKey?: string; }; -const AddressFungibleTokens = ({ items, isLoading, pagination, isError, top, tokenTypes, onTokenTypesChange, resetKey }: Props) => { +const AddressFungibleTokens = ({ items, isLoading, isTransitioning, pagination, isError, top, tokenTypes, onTokenTypesChange, resetKey }: Props) => { const isMobile = useIsMobile(); const hasAdditionalTokenTypes = config.slices.token.additionalTypes.length > 0; @@ -59,6 +60,7 @@ const AddressFungibleTokens = ({ items, isLoading, pagination, isError, top, tok itemsNum={ items?.length } emptyText="There are no tokens of selected type." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/slices/token/pages/address/fungible/AddressFungibleTokensListItem.tsx b/src/slices/token/pages/address/fungible/AddressFungibleTokensListItem.tsx deleted file mode 100644 index 6ef65ba4f87..00000000000 --- a/src/slices/token/pages/address/fungible/AddressFungibleTokensListItem.tsx +++ /dev/null @@ -1,118 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, HStack } from '@chakra-ui/react'; -import { BigNumber } from 'bignumber.js'; -import React from 'react'; - -import type { AddressFungibleTokensItem } from '../types'; -import { getTokenTypeName, isConfidentialTokenType } from 'src/slices/token/utils/token-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; -import NativeTokenTag from 'src/slices/token/components/NativeTokenTag'; - -import TokenAddToWallet from 'src/features/web3-wallet/components/TokenAddToWallet'; - -import config from 'src/config'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import calculateUsdValue from 'src/shared/values/entity/calculateUsdValue'; -import ConfidentialValue from 'src/shared/values/entity/ConfidentialValue'; -import SimpleValue from 'src/shared/values/entity/SimpleValue'; -import { DEFAULT_ACCURACY_USD } from 'src/shared/values/entity/utils'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Tag } from 'src/toolkit/chakra/tag'; - -type Props = AddressFungibleTokensItem & { isLoading: boolean; hasAdditionalTokenTypes?: boolean }; - -const AddressFungibleTokensListItem = ({ - token, - value, - isLoading, - hasAdditionalTokenTypes, -}: Props) => { - - if (!token) { - return null; - } - - const { - valueBn: tokenQuantity, - usdBn: tokenValue, - } = calculateUsdValue({ amount: value, exchangeRate: token.exchange_rate, decimals: token.decimals }); - - const isNativeToken = config.slices.address.nativeTokenAddress && - token.address_hash.toLowerCase() === config.slices.address.nativeTokenAddress.toLowerCase(); - - return ( - <ListItemMobile rowGap={ 2 }> - <Flex alignItems="center" width="100%" columnGap={ 2 }> - <TokenEntity - token={ token } - isLoading={ isLoading } - noCopy - jointSymbol - fontWeight="700" - width="auto" - /> - { isNativeToken && <NativeTokenTag/> } - { hasAdditionalTokenTypes && <Tag loading={ isLoading }>{ getTokenTypeName(token.type) }</Tag> } - </Flex> - <Flex alignItems="center" pl={ 8 }> - <AddressEntity - address={{ hash: token.address_hash }} - isLoading={ isLoading } - truncation="constant" - noIcon - /> - <TokenAddToWallet token={ token } ml={ 2 } isLoading={ isLoading }/> - </Flex> - { token.exchange_rate !== undefined && token.exchange_rate !== null && ( - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 }>Price</Skeleton> - <SimpleValue - value={ BigNumber(token.exchange_rate) } - loading={ isLoading } - prefix="$" - fontSize="sm" - color="text.secondary" - /> - </HStack> - ) } - <HStack gap={ 3 } alignItems="baseline"> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 }>Quantity</Skeleton> - { isConfidentialTokenType(token.type) ? ( - <ConfidentialValue loading={ isLoading }/> - ) : ( - <SimpleValue - value={ tokenQuantity } - loading={ isLoading } - fontSize="sm" - color="text.secondary" - /> - ) } - </HStack> - { isConfidentialTokenType(token.type) && ( - <HStack gap={ 3 } alignItems="baseline"> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 }>Value</Skeleton> - <ConfidentialValue loading={ isLoading }/> - </HStack> - ) } - { !isConfidentialTokenType(token.type) && token.exchange_rate && ( - <HStack gap={ 3 } alignItems="baseline"> - <Skeleton loading={ isLoading } fontSize="sm" fontWeight={ 500 }>Value</Skeleton> - <SimpleValue - value={ tokenValue } - prefix="$" - loading={ isLoading } - accuracy={ DEFAULT_ACCURACY_USD } - fontSize="sm" - color="text.secondary" - /> - </HStack> - ) } - </ListItemMobile> - ); -}; - -export default AddressFungibleTokensListItem; diff --git a/src/slices/token/pages/address/fungible/AddressFungibleTokensTable.tsx b/src/slices/token/pages/address/fungible/AddressFungibleTokensTable.tsx index 91ee3bedb2a..e4cb411fd65 100644 --- a/src/slices/token/pages/address/fungible/AddressFungibleTokensTable.tsx +++ b/src/slices/token/pages/address/fungible/AddressFungibleTokensTable.tsx @@ -4,6 +4,9 @@ import React from 'react'; import type { schemas } from '@blockscout/api-types'; +import { useMultichainContext } from 'src/features/multichain/context'; + +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -18,8 +21,12 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: Pick<schemas['TokenBalance'], 'token' | 'value'>): string => item.token?.address_hash ?? ''; + const AddressFungibleTokensTable = ({ data, top, isLoading, hasAdditionalTokenTypes, resetKey }: Props) => { + const chainData = useMultichainContext()?.chain; const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); return ( <TableRoot minW="900px"> @@ -35,8 +42,9 @@ const AddressFungibleTokensTable = ({ data, top, isLoading, hasAdditionalTokenTy <TableBody> { data.slice(0, renderedItemsNum).map((item, index) => ( <AddressFungibleTokensTableItem - key={ (item.token?.address_hash ?? '') + (isLoading ? index : '') } + key={ keys[index] } { ...item } + chainData={ chainData } isLoading={ isLoading } hasAdditionalTokenTypes={ hasAdditionalTokenTypes } /> diff --git a/src/slices/token/pages/address/fungible/AddressFungibleTokensTableItem.tsx b/src/slices/token/pages/address/fungible/AddressFungibleTokensTableItem.tsx index 88b71acff71..d9d228048b3 100644 --- a/src/slices/token/pages/address/fungible/AddressFungibleTokensTableItem.tsx +++ b/src/slices/token/pages/address/fungible/AddressFungibleTokensTableItem.tsx @@ -5,11 +5,14 @@ import { BigNumber } from 'bignumber.js'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; import { getTokenTypeName, isConfidentialTokenType } from 'src/slices/token/utils/token-types'; import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; import NativeTokenTag from 'src/slices/token/components/NativeTokenTag'; +import TokenMultiplierTag from 'src/slices/token/components/ui-multiplier/TokenMultiplierTag'; +import { getUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; import TokenAddToWallet from 'src/features/web3-wallet/components/TokenAddToWallet'; @@ -22,23 +25,26 @@ import { DEFAULT_ACCURACY_USD } from 'src/shared/values/entity/utils'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; import { Tag } from 'src/toolkit/chakra/tag'; -type Props = Pick<schemas['TokenBalance'], 'token' | 'value'> & { isLoading: boolean; hasAdditionalTokenTypes?: boolean }; +type Props = Pick<schemas['TokenBalance'], 'token' | 'value'> & { chainData?: ClusterChainConfig; isLoading: boolean; hasAdditionalTokenTypes?: boolean }; const AddressFungibleTokensTableItem = ({ token, value, + chainData, isLoading, hasAdditionalTokenTypes, }: Props) => { - if (!token) { return null; } + const multiplier = getUiMultiplier(token, chainData?.app_config); + const { valueBn: tokenQuantity, + rawValueBn: tokenRawQuantity, usdBn: tokenValue, - } = calculateUsdValue({ amount: value, exchangeRate: token.exchange_rate, decimals: token.decimals }); + } = calculateUsdValue({ amount: value, exchangeRate: token.exchange_rate, decimals: token.decimals, multiplier }); const isNativeToken = config.slices.address.nativeTokenAddress && token.address_hash.toLowerCase() === config.slices.address.nativeTokenAddress.toLowerCase(); @@ -88,6 +94,9 @@ const AddressFungibleTokensTableItem = ({ ) : ( <SimpleValue value={ tokenQuantity } + rawValue={ tokenRawQuantity } + multiplier={ multiplier } + startElement={ multiplier && <TokenMultiplierTag multiplier={ multiplier } loading={ isLoading } mr={ 2 }/> } color={ isNativeToken ? 'text.secondary' : undefined } loading={ isLoading } /> diff --git a/src/slices/token/pages/address/nfts/AddressNfts.tsx b/src/slices/token/pages/address/nfts/AddressNfts.tsx index 4add53de132..e9824955ef2 100644 --- a/src/slices/token/pages/address/nfts/AddressNfts.tsx +++ b/src/slices/token/pages/address/nfts/AddressNfts.tsx @@ -13,7 +13,7 @@ import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import Pagination from 'src/shared/pagination/Pagination'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; import AddressNftItem from './AddressNftItem'; import AddressNftTypeFilter from './AddressNftTypeFilter'; @@ -22,7 +22,7 @@ import AddressNftTypeFilter from './AddressNftTypeFilter'; const INITIAL_RENDERED_ITEMS_NUM = 30; type Props = { - tokensQuery: QueryWithPagesResult<'core:address_nfts'>; + tokensQuery: ApiPaginatedQueryResult<'core:address_nfts'>; tokenTypes: Array<NftTokenType> | undefined; onTokenTypesChange: (value: Array<NftTokenType>) => void; }; @@ -31,11 +31,11 @@ const AddressNfts = ({ tokensQuery, tokenTypes, onTokenTypesChange }: Props) => const isMobile = useIsMobile(); const multichainContext = useMultichainContext(); - const { isError, isPlaceholderData, data, pagination } = tokensQuery; + const { isError, isInitialLoading, isTransitioning, data, pagination } = tokensQuery; const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data?.items, - isEnabled: !isPlaceholderData, + isEnabled: !isInitialLoading, minItemsNum: INITIAL_RENDERED_ITEMS_NUM, resetKey: tokensQuery.queryHash, }); @@ -58,14 +58,14 @@ const AddressNfts = ({ tokensQuery, tokenTypes, onTokenTypesChange }: Props) => gridTemplateColumns={{ base: 'repeat(2, calc((100% - 12px)/2))', lg: 'repeat(auto-fill, minmax(210px, 1fr))' }} > { data.items.slice(0, renderedItemsNum).map((item, index) => { - const key = item.token?.address_hash + '_' + (item.id && !isPlaceholderData ? `id_${ item.id }` : `index_${ index }`); + const key = item.token?.address_hash + '_' + (item.id && !isInitialLoading ? `id_${ item.id }` : `index_${ index }`); return ( <AddressNftItem key={ key } instance={ item } token={ item.token ?? undefined } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } withTokenLink chain={ multichainContext?.chain } /> @@ -86,6 +86,7 @@ const AddressNfts = ({ tokensQuery, tokenTypes, onTokenTypesChange }: Props) => emptyStateProps={{ term: 'token', }} + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/slices/token/pages/address/nfts/AddressNftsCollections.tsx b/src/slices/token/pages/address/nfts/AddressNftsCollections.tsx index 95e5b5febbd..3a04b3661b5 100644 --- a/src/slices/token/pages/address/nfts/AddressNftsCollections.tsx +++ b/src/slices/token/pages/address/nfts/AddressNftsCollections.tsx @@ -16,7 +16,7 @@ import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import Pagination from 'src/shared/pagination/Pagination'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; @@ -31,7 +31,7 @@ import AddressNftTypeFilter from './AddressNftTypeFilter'; const INITIAL_RENDERED_COLLECTIONS_NUM = 10; type Props = { - collectionsQuery: QueryWithPagesResult<'core:address_collections'>; + collectionsQuery: ApiPaginatedQueryResult<'core:address_collections'>; address: string; tokenTypes: Array<NftTokenType> | undefined; onTokenTypesChange: (value: Array<NftTokenType>) => void; @@ -41,12 +41,12 @@ const AddressNftsCollections = ({ collectionsQuery, address, tokenTypes, onToken const isMobile = useIsMobile(); const multichainContext = useMultichainContext(); - const { isError, isPlaceholderData, data, pagination } = collectionsQuery; + const { isError, isInitialLoading, isTransitioning, data, pagination } = collectionsQuery; const items = data?.items?.filter((item) => item.token_instances.length > 0); const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, - isEnabled: !isPlaceholderData, + isEnabled: !isInitialLoading, minItemsNum: INITIAL_RENDERED_COLLECTIONS_NUM, resetKey: collectionsQuery.queryHash, }); @@ -71,21 +71,21 @@ const AddressNftsCollections = ({ collectionsQuery, address, tokenTypes, onToken }, { chain: multichainContext?.chain }); const hasOverload = Number(item.amount) > item.token_instances.length; return ( - <Box key={ item.token.address_hash + index } mb={ 6 }> + <Box key={ item.token.address_hash + (isInitialLoading ? index : '') } mb={ 6 }> <Flex mb={ 3 } flexWrap="wrap" lineHeight="30px"> <TokenEntity width="auto" noSymbol token={ item.token } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } noCopy fontWeight="600" chain={ multichainContext?.chain } /> - <Skeleton loading={ isPlaceholderData } mr={ 3 }> + <Skeleton loading={ isInitialLoading } mr={ 3 }> <Text color="text.secondary" whiteSpace="pre">{ ` - ${ Number(item.amount).toLocaleString() } item${ Number(item.amount) > 1 ? 's' : '' }` }</Text> </Skeleton> - <Link href={ collectionUrl } loading={ isPlaceholderData }> + <Link href={ collectionUrl } loading={ isInitialLoading }> View in collection </Link> </Flex> @@ -97,14 +97,14 @@ const AddressNftsCollections = ({ collectionsQuery, address, tokenTypes, onToken gridTemplateColumns={{ base: 'repeat(2, calc((100% - 12px)/2))', lg: 'repeat(auto-fill, minmax(210px, 1fr))' }} > { item.token_instances.map((instance, index) => { - const key = item.token.address_hash + '_' + (instance.id && !isPlaceholderData ? `id_${ instance.id }` : `index_${ index }`); + const key = item.token.address_hash + '_' + (instance.id && !isInitialLoading ? `id_${ instance.id }` : `index_${ index }`); return ( <AddressNftItem key={ key } instance={ instance } token={ item.token } - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } chain={ multichainContext?.chain } /> ); @@ -143,6 +143,7 @@ const AddressNftsCollections = ({ collectionsQuery, address, tokenTypes, onToken emptyStateProps={{ term: 'token', }} + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/slices/token/pages/address/useAddressFungibleTokensQuery.ts b/src/slices/token/pages/address/useAddressFungibleTokensQuery.ts index 1a44a5aeb8c..4d9da2c1476 100644 --- a/src/slices/token/pages/address/useAddressFungibleTokensQuery.ts +++ b/src/slices/token/pages/address/useAddressFungibleTokensQuery.ts @@ -1,13 +1,13 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TokenType } from '../../types/api'; import { ADDRESS_TOKEN_BALANCE_ERC_20 } from 'src/slices/address/stubs/address'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { usePaginationParams } from 'src/shared/pagination/usePaginationParams'; import { generateListStub } from 'src/shared/pagination/utils'; import getFilterValuesFromQuery from 'src/shared/router/get-filter-values-from-query'; @@ -23,14 +23,13 @@ interface Props { } export default function useAddressFungibleTokensQuery({ scrollRef, enabled, addressHash }: Props) { - const router = useRouter(); + const typeParam = usePaginationParams('core:address_tokens').filters.type; + const tokenTypes = React.useMemo(() => getTokenFilterValue(typeParam) || FUNGIBLE_TOKEN_TYPES, [ typeParam ]); - const [ tokenTypes, setTokenTypes ] = React.useState<Array<TokenType>>(getTokenFilterValue(router.query.type) || FUNGIBLE_TOKEN_TYPES); - - const query = useQueryWithPages({ + const query = useApiPaginatedQuery({ resourceName: 'core:address_tokens', pathParams: { hash: addressHash }, - filters: { type: tokenTypes }, + queryParams: { type: tokenTypes }, scrollRef, options: { enabled, @@ -39,16 +38,14 @@ export default function useAddressFungibleTokensQuery({ scrollRef, enabled, addr }, }); + const { onFilterChange } = query; const onTokenTypesChange = React.useCallback((value: Array<TokenType>) => { - query.onFilterChange({ type: value }); - setTokenTypes(value); - }, [ query ]); - - return React.useMemo(() => { - return { - query, - tokenTypes, - onTokenTypesChange, - }; - }, [ query, tokenTypes, onTokenTypesChange ]); + onFilterChange({ type: value }); + }, [ onFilterChange ]); + + return React.useMemo(() => ({ + query, + tokenTypes, + onTokenTypesChange, + }), [ query, tokenTypes, onTokenTypesChange ]); } diff --git a/src/slices/token/pages/address/useAddressNftQuery.ts b/src/slices/token/pages/address/useAddressNftQuery.ts index 9e5b44c1ad0..234e3bac6a1 100644 --- a/src/slices/token/pages/address/useAddressNftQuery.ts +++ b/src/slices/token/pages/address/useAddressNftQuery.ts @@ -1,8 +1,8 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; +import type { ExternalChainExtended } from 'src/shared/external-chains/types'; import type { NftTokenType } from 'src/slices/token/types/api'; import { NFT_TOKEN_TYPE_IDS } from 'src/slices/token/utils/token-types'; @@ -10,7 +10,7 @@ import { useAppContext } from 'src/shell/app/context'; import { ADDRESS_COLLECTION, ADDRESS_NFT_1155 } from 'src/slices/address/stubs/address'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getFilterValuesFromQuery from 'src/shared/router/get-filter-values-from-query'; import * as cookies from 'src/shared/storage/cookies'; @@ -18,24 +18,22 @@ import * as cookies from 'src/shared/storage/cookies'; const getTokenFilterValue: (type: string | Array<string> | undefined) => Array<NftTokenType> | undefined = (getFilterValuesFromQuery<NftTokenType>).bind(null, NFT_TOKEN_TYPE_IDS); +const NO_TYPES: Array<NftTokenType> = []; + export type TNftDisplayType = 'collection' | 'list'; interface Props { scrollRef: React.RefObject<HTMLDivElement | null>; enabled?: boolean; addressHash: string; - isMultichain?: boolean; - chainIds?: Array<string>; + chain?: ExternalChainExtended; } -export default function useAddressNftQuery({ scrollRef, enabled = true, addressHash, isMultichain, chainIds }: Props) { - const router = useRouter(); - +export default function useAddressNftQuery({ scrollRef, enabled = true, addressHash, chain }: Props) { const displayTypeCookie = cookies.get(cookies.NAMES.ADDRESS_NFT_DISPLAY_TYPE, useAppContext().cookies); const [ displayType, setDisplayType ] = React.useState<TNftDisplayType>(displayTypeCookie === 'list' ? 'list' : 'collection'); - const [ tokenTypes, setTokenTypes ] = React.useState<Array<NftTokenType> | undefined>(getTokenFilterValue(router.query.type) || []); - const collectionsQuery = useQueryWithPages({ + const collectionsQuery = useApiPaginatedQuery({ resourceName: 'core:address_collections', pathParams: { hash: addressHash }, scrollRef, @@ -43,12 +41,10 @@ export default function useAddressNftQuery({ scrollRef, enabled = true, addressH enabled: enabled && displayType === 'collection', placeholderData: generateListStub<'core:address_collections'>(ADDRESS_COLLECTION, 10, { next_page_params: null }), }, - filters: { type: tokenTypes }, - isMultichain, - chainIds, + chain, }); - const nftsQuery = useQueryWithPages({ + const nftsQuery = useApiPaginatedQuery({ resourceName: 'core:address_nfts', pathParams: { hash: addressHash }, scrollRef, @@ -56,21 +52,21 @@ export default function useAddressNftQuery({ scrollRef, enabled = true, addressH enabled: enabled && displayType === 'list', placeholderData: generateListStub<'core:address_nfts'>(ADDRESS_NFT_1155, 10, { next_page_params: null }), }, - filters: { type: tokenTypes }, - isMultichain, - chainIds, + chain, }); + const typeParam = nftsQuery.filters.type; + const tokenTypes = React.useMemo(() => getTokenFilterValue(typeParam) || NO_TYPES, [ typeParam ]); + const onDisplayTypeChange = React.useCallback((val: string) => { cookies.set(cookies.NAMES.ADDRESS_NFT_DISPLAY_TYPE, val); setDisplayType(val as TNftDisplayType); }, []); + const { onFilterChange } = nftsQuery; const onTokenTypesChange = React.useCallback((value: Array<NftTokenType>) => { - nftsQuery.onFilterChange({ type: value }); - collectionsQuery.onFilterChange({ type: value }); - setTokenTypes(value); - }, [ nftsQuery, collectionsQuery ]); + onFilterChange({ type: value }); + }, [ onFilterChange ]); return React.useMemo(() => ({ nftsQuery, diff --git a/src/slices/token/pages/address/useFetchTokens.ts b/src/slices/token/pages/address/useFetchTokens.ts index 3c7cc6dd598..346bf5988ee 100644 --- a/src/slices/token/pages/address/useFetchTokens.ts +++ b/src/slices/token/pages/address/useFetchTokens.ts @@ -21,7 +21,7 @@ import config from 'src/config'; import * as cookies from 'src/shared/storage/cookies'; import type { TokenEnhancedData } from './utils'; -import { calculateUsdValue } from './utils'; +import { addUsdValue } from './utils'; interface Props { hash?: string; @@ -216,7 +216,7 @@ export default function useFetchTokens({ hash, enabled }: Props) { const additionalGroups = additionalTypes.reduce((result, item, index) => { const query = additionalTokenQueries[index]; result[item.id] = { - items: query?.data?.items.map(calculateUsdValue) || [], + items: query?.data?.items.map((item) => addUsdValue(item, chain?.app_config)) || [], isOverflow: Boolean(query?.data?.next_page_params), }; return result; @@ -224,24 +224,24 @@ export default function useFetchTokens({ hash, enabled }: Props) { return { 'ERC-20': { - items: erc20query.data?.items.map(calculateUsdValue) || [], + items: erc20query.data?.items.map((item) => addUsdValue(item, chain?.app_config)) || [], isOverflow: Boolean(erc20query.data?.next_page_params), }, 'ERC-721': { - items: erc721query.data?.items.map(calculateUsdValue) || [], + items: erc721query.data?.items.map((item) => addUsdValue(item, chain?.app_config)) || [], isOverflow: Boolean(erc721query.data?.next_page_params), }, 'ERC-1155': { - items: erc1155query.data?.items.map(calculateUsdValue) || [], + items: erc1155query.data?.items.map((item) => addUsdValue(item, chain?.app_config)) || [], isOverflow: Boolean(erc1155query.data?.next_page_params), }, 'ERC-404': { - items: erc404query.data?.items.map(calculateUsdValue) || [], + items: erc404query.data?.items.map((item) => addUsdValue(item, chain?.app_config)) || [], isOverflow: Boolean(erc404query.data?.next_page_params), }, ...additionalGroups, }; - }, [ additionalTokenQueries, erc1155query.data, erc20query.data, erc721query.data, erc404query.data ]); + }, [ additionalTokenQueries, erc1155query.data, erc20query.data, erc721query.data, erc404query.data, chain?.app_config ]); const isPending = erc20query.isPending || diff --git a/src/slices/token/pages/address/utils.spec.ts b/src/slices/token/pages/address/utils.spec.ts new file mode 100644 index 00000000000..b257a731c3a --- /dev/null +++ b/src/slices/token/pages/address/utils.spec.ts @@ -0,0 +1,47 @@ +import type { schemas } from '@blockscout/api-types'; + +import * as tokensMock from 'src/slices/token/mocks/address-tokens'; +import { tokenInfoERC20a } from 'src/slices/token/mocks/info'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import { addUsdValue } from './utils'; + +const ERC20_BALANCE_WITH_RATE: schemas['TokenBalance'] = { + ...tokensMock.erc20a, + token: { ...tokenInfoERC20a, exchange_rate: '2' }, + value: '1500000000000000000', +}; +const ERC20_USD = '3'; + +const ERC8056_USD_FROM_SCALED = '845'; + +describe('addUsdValue', () => { + it('leaves a non-fungible balance untouched', () => { + expect(addUsdValue(tokensMock.erc721a)).toBe(tokensMock.erc721a); + }); + + it('leaves a fungible balance without an exchange rate untouched', () => { + expect(addUsdValue(tokensMock.erc20a)).toBe(tokensMock.erc20a); + }); + + it('computes usd from the balance, decimals and exchange rate', () => { + const result = addUsdValue(ERC20_BALANCE_WITH_RATE); + expect(result.usd?.toFixed()).toBe(ERC20_USD); + }); + + it('leaves an ERC-8056 balance untouched when the type is not enabled', () => { + expect(addUsdValue(tokensMock.erc8056)).toBe(tokensMock.erc8056); + }); + + it('computes usd from the scaled ERC-8056 balance when the type is enabled', async() => { + const result = await withEnvs(ENVS_MAP.additionalTokenTypes, async() => { + const { addUsdValue } = await import('./utils'); + return addUsdValue(tokensMock.erc8056); + }); + expect(result.usd?.toFixed()).toBe(ERC8056_USD_FROM_SCALED); + }); +}); diff --git a/src/slices/token/pages/address/utils.ts b/src/slices/token/pages/address/utils.ts index 74d98c78454..77c5dc01b65 100644 --- a/src/slices/token/pages/address/utils.ts +++ b/src/slices/token/pages/address/utils.ts @@ -3,11 +3,15 @@ import BigNumber from 'bignumber.js'; import type { schemas } from '@blockscout/api-types'; +import type { ChainConfig } from 'src/slices/token/types/client'; import { getTokenTypes, isFungibleTokenType } from 'src/slices/token/utils/token-types'; +import { getUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; + import config from 'src/config'; import sumBnReducer from 'src/shared/numbers/sumBnReducer'; import { collator } from 'src/shared/texts/collator'; +import calculateUsdValue from 'src/shared/values/entity/calculateUsdValue'; import { ZERO } from 'src/toolkit/utils/consts'; @@ -109,7 +113,9 @@ export const filterTokens = (searchTerm: string) => ({ token }: schemas['TokenBa return token.name?.toLowerCase().includes(searchTerm); }; -export const calculateUsdValue = (data: schemas['TokenBalance']): TokenEnhancedData => { +const DEFAULT_FUNGIBLE_DECIMALS = '18'; + +export const addUsdValue = (data: schemas['TokenBalance'], chainConfig?: ChainConfig): TokenEnhancedData => { const isFungibleToken = isFungibleTokenType(data.token?.type); if (!isFungibleToken) { @@ -121,11 +127,14 @@ export const calculateUsdValue = (data: schemas['TokenBalance']): TokenEnhancedD return data; } - const decimals = Number(data.token?.decimals || '18'); - return { - ...data, - usd: BigNumber(data.value ?? '0').div(BigNumber(10 ** decimals)).multipliedBy(BigNumber(exchangeRate)), - }; + const { usdBn } = calculateUsdValue({ + amount: data.value, + decimals: data.token?.decimals || DEFAULT_FUNGIBLE_DECIMALS, + exchangeRate, + multiplier: getUiMultiplier(data.token, chainConfig), + }); + + return { ...data, usd: usdBn }; }; export interface TokensTotalInfo { diff --git a/src/slices/token/pages/details/Token.pw.tsx b/src/slices/token/pages/details/Token.pw.tsx index 846e5dd58a6..88617b22458 100644 --- a/src/slices/token/pages/details/Token.pw.tsx +++ b/src/slices/token/pages/details/Token.pw.tsx @@ -9,6 +9,7 @@ import config from 'src/config'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; import * as socketServer from 'playwright/fixtures/socketServer'; +import type { TestFnArgs } from 'playwright/lib'; import { test, expect, devices } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; @@ -19,23 +20,45 @@ const hash = tokenInfo.address_hash; const hooksConfig = { router: { query: { hash }, - isReady: true, }, }; +const addressMetadataQueryParams = { + addresses: [ hash ], + chainId: config.chain.id, + tagsLimit: '20', +}; + // FIXME // test cases which use socket cannot run in parallel since the socket server always run on the same port test.describe.configure({ mode: 'serial' }); -test.beforeEach(async({ mockApiResponse, mockTextAd }) => { +const mockTokenData = async(mockApiResponse: TestFnArgs['mockApiResponse']) => { await mockApiResponse('core:token', tokenInfo, { pathParams: { hash } }); await mockApiResponse('core:address', contract, { pathParams: { hash } }); await mockApiResponse('core:token_counters', tokenCounters, { pathParams: { hash } }); await mockApiResponse('core:token_transfers', { items: [], next_page_params: null }, { pathParams: { hash } }); + // the metadata service is down, so the page shows no tags + await mockApiResponse('metadata:info', null as never, { queryParams: addressMetadataQueryParams, status: 500 }); +}; + +// the other optional services are down too, so the page shows neither verified info nor the token icon +const mockOptionalServicesDown = async(mockApiResponse: TestFnArgs['mockApiResponse'], page: TestFnArgs['page']) => { + await mockApiResponse( + 'contractInfo:token_verified_info', + null as never, + { pathParams: { instanceId: config.apis.contractInfo?.instanceId, hash }, status: 500 }, + ); + await page.route(tokenInfo.icon_url as string, (route) => route.fulfill({ status: 404 })); +}; + +test.beforeEach(async({ mockTextAd }) => { await mockTextAd(); }); -test('base view', async({ render, page, createSocket }) => { +test('base view', async({ render, page, createSocket, mockApiResponse }) => { + await mockTokenData(mockApiResponse); + await mockOptionalServicesDown(mockApiResponse, page); const component = await render(<Token/>, { hooksConfig }, { withSocket: true }); const socket = await createSocket(); @@ -49,6 +72,7 @@ test('base view', async({ render, page, createSocket }) => { test('with verified info', async({ render, page, createSocket, mockApiResponse, mockAssetResponse }) => { test.slow(); + await mockTokenData(mockApiResponse); await mockApiResponse( 'contractInfo:token_verified_info', verifiedAddressesMocks.TOKEN_INFO, @@ -84,6 +108,7 @@ test('bridged token', async({ render, page, createSocket, mockApiResponse, mockA await mockApiResponse('core:address', contract, { pathParams: { hash } }); await mockApiResponse('core:token_counters', tokenCounters, { pathParams: { hash } }); await mockApiResponse('core:token_transfers', { items: [], next_page_params: null }, { pathParams: { hash } }); + await mockApiResponse('metadata:info', null as never, { queryParams: { ...addressMetadataQueryParams, addresses: [ hash ] }, status: 500 }); await mockApiResponse( 'contractInfo:token_verified_info', verifiedAddressesMocks.TOKEN_INFO, @@ -106,6 +131,8 @@ test('scam token', async({ render, page, createSocket, mockApiResponse, mockEnvs await mockEnvs([ [ 'NEXT_PUBLIC_VIEWS_TOKEN_SCAM_TOGGLE_ENABLED', 'true' ], ]); + await mockTokenData(mockApiResponse); + await mockOptionalServicesDown(mockApiResponse, page); await mockApiResponse('core:token', { ...tokenInfo, reputation: 'scam' }, { pathParams: { hash } }); const component = await render(<Token/>, { hooksConfig }, { withSocket: true }); @@ -121,8 +148,10 @@ test('scam token', async({ render, page, createSocket, mockApiResponse, mockEnvs test.describe('mobile', () => { test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - test('base view', async({ render, page, createSocket }) => { + test('base view', async({ render, page, createSocket, mockApiResponse }) => { test.slow(); + await mockTokenData(mockApiResponse); + await mockOptionalServicesDown(mockApiResponse, page); const component = await render(<Token/>, { hooksConfig }, { withSocket: true }); const socket = await createSocket(); const channel = await socketServer.joinChannel(socket, `tokens:${ hash }`); @@ -137,6 +166,7 @@ test.describe('mobile', () => { test('with verified info', async({ render, page, createSocket, mockApiResponse, mockAssetResponse }) => { test.slow(); + await mockTokenData(mockApiResponse); await mockApiResponse( 'contractInfo:token_verified_info', verifiedAddressesMocks.TOKEN_INFO, diff --git a/src/slices/token/pages/details/Token.tsx b/src/slices/token/pages/details/Token.tsx index 5570f7a7b87..2dbf3fefb3d 100644 --- a/src/slices/token/pages/details/Token.tsx +++ b/src/slices/token/pages/details/Token.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React, { useEffect } from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -20,32 +19,35 @@ import Contract from 'src/slices/contract/pages/details/Contract'; import { CONTRACT_TAB_IDS } from 'src/slices/contract/utils/tabs'; import TokenTransfer from 'src/slices/token-transfer/pages/token/TokenTransfer'; import useTokenQuery from 'src/slices/token/hooks/useTokenQuery'; -import TokenHolders from 'src/slices/token/pages/details/holders/TokenHolders'; +import TokenHolders, { TOKEN_HOLDERS_TAB_IDS } from 'src/slices/token/pages/details/holders/TokenHolders'; import TokenDetails from 'src/slices/token/pages/details/info/TokenDetails'; import TokenInventory from 'src/slices/token/pages/details/inventory/TokenInventory'; +import TokenMultiplierHistory from 'src/slices/token/pages/details/multiplier-history/TokenMultiplierHistory'; import TokenPageTitle from 'src/slices/token/pages/details/TokenPageTitle'; import { TOKEN_COUNTERS } from 'src/slices/token/stubs'; +import { isTokenMultiplierEnabled, UI_MULTIPLIER_TOKEN_TYPE } from 'src/slices/token/utils/ui-multiplier'; import Address3rdPartyWidgets from 'src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgets'; import useAddress3rdPartyWidgets from 'src/features/address-3rd-party-widgets/pages/address/useAddress3rdPartyWidgets'; import TextAd from 'src/features/ads/text/components/TextAd'; +import { useMultichainContext } from 'src/features/multichain/context'; import config from 'src/config'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import useEtherscanRedirects from 'src/shared/router/useEtherscanRedirects'; +import { useRouter } from 'src/shared/router/useRouter'; import SpriteIcon from 'src/sprite/SpriteIcon'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; -export type TokenTabs = 'token_transfers' | 'holders' | 'inventory'; +export type TokenTabs = 'token_transfers' | 'holders' | 'holders_bubblemaps' | 'inventory' | 'multiplier_history'; const TokenPageContent = () => { const [ totalSupplySocket, setTotalSupplySocket ] = React.useState<number>(); const router = useRouter(); const hashString = getQueryParamString(router.query.hash); - const ownerFilter = getQueryParamString(router.query.holder_address_hash) || undefined; useEtherscanRedirects(); const queryClient = useQueryClient(); @@ -64,6 +66,8 @@ const TokenPageContent = () => { }, }); + const multichainContext = useMultichainContext(); + React.useEffect(() => { if (tokenQuery.data && totalSupplySocket) { queryClient.setQueryData(getResourceKey('core:token', { pathParams: { hash: hashString } }), (prevData: schemas['Token'] | undefined) => { @@ -116,6 +120,7 @@ const TokenPageContent = () => { }, [ tokenQuery.data, tokenQuery.isPlaceholderData, verifiedInfoQuery.isPlaceholderData, verifiedInfoQuery.data ]); const hasInventoryTab = tokenQuery.data?.type && NFT_TOKEN_TYPE_IDS.includes(tokenQuery.data.type); + const hasMultiplierHistoryTab = tokenQuery.data?.type === UI_MULTIPLIER_TOKEN_TYPE && isTokenMultiplierEnabled(multichainContext?.chain?.app_config); const tokenCountersQuery = useApiQuery('core:token_counters', { pathParams: { hash: hashString }, @@ -135,6 +140,9 @@ const TokenPageContent = () => { const holdersCount = !tokenCountersQuery.isPlaceholderData && tokenCountersQuery.data?.token_holders_count ? Number(tokenCountersQuery.data.token_holders_count) : undefined; + const multiplierChangesCount = !tokenCountersQuery.isPlaceholderData && tokenCountersQuery.data?.ui_multiplier_changes_count ? + Number(tokenCountersQuery.data.ui_multiplier_changes_count) : + undefined; const tabs: Array<TabItemRegular> = [ { @@ -167,7 +175,7 @@ const TokenPageContent = () => { hasInventoryTab ? { id: 'inventory', title: 'Inventory', - component: <TokenInventory hash={ hashString } token={ tokenQuery.data } isLoading={ isMainDataLoading } ownerFilter={ ownerFilter }/>, + component: <TokenInventory hash={ hashString } token={ tokenQuery.data } isLoading={ isMainDataLoading }/>, } : undefined, { id: 'token_transfers', @@ -180,7 +188,14 @@ const TokenPageContent = () => { title: 'Holders', count: holdersCount, component: <TokenHolders token={ tokenQuery.data } isLoading={ isMainDataLoading }/>, + subTabs: TOKEN_HOLDERS_TAB_IDS, }, + hasMultiplierHistoryTab ? { + id: 'multiplier_history', + title: 'Multiplier history', + count: multiplierChangesCount, + component: <TokenMultiplierHistory token={ tokenQuery.data } isLoading={ isMainDataLoading }/>, + } : undefined, (address3rdPartyWidgets.isEnabled && address3rdPartyWidgets.items.length > 0) ? { id: 'widgets', title: 'Widgets', diff --git a/src/slices/token/pages/details/TokenPageTitle.pw.tsx b/src/slices/token/pages/details/TokenPageTitle.pw.tsx index 37ead0a4a95..683106e8302 100644 --- a/src/slices/token/pages/details/TokenPageTitle.pw.tsx +++ b/src/slices/token/pages/details/TokenPageTitle.pw.tsx @@ -8,11 +8,19 @@ import type { ResourceError } from 'src/api/resources'; import { tokenInfo } from 'src/slices/token/mocks/info'; +<<<<<<< HEAD +======= +import { generateAddressMetadataInfo, hiddenProtocolTagWithMeta } from 'src/features/address-metadata/mocks/tags'; + +import config from 'src/config'; + +>>>>>>> v2.13.0 import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; import { test, expect } from 'playwright/lib'; import TokenPageTitle from './TokenPageTitle'; +<<<<<<< HEAD test('with action button +@dark-mode +@mobile', async({ render, mockEnvs }) => { const tokenQuery = { @@ -26,14 +34,71 @@ test('with action button +@dark-mode +@mobile', async({ render, mockEnvs }) => { const addressQuery = {} as UseQueryResult<schemas['Address'], ResourceError<unknown>>; await mockEnvs(ENVS_MAP.tokenActionButton); +======= +const hash = tokenInfo.address_hash; + +const tokenQuery = { + data: tokenInfo, +} as UseQueryResult<schemas['Token'], ResourceError<unknown>>; + +const verifiedInfoQuery = { + data: {}, +} as UseQueryResult<contractsInfo.TokenInfo, ResourceError<unknown>>; + +const addressQuery = {} as UseQueryResult<schemas['Address'], ResourceError<unknown>>; + +const addressMetadataQueryParams = { + addresses: [ hash ], + chainId: config.chain.id, + tagsLimit: '20', +}; + +test('with action button +@dark-mode +@mobile', async({ render, mockApiResponse, mockAssetResponse }) => { + await mockApiResponse('metadata:info', generateAddressMetadataInfo(hash, hiddenProtocolTagWithMeta), { queryParams: addressMetadataQueryParams }); + await mockAssetResponse(hiddenProtocolTagWithMeta.meta?.appLogoURL as string, './playwright/mocks/image_s.jpg'); + await mockAssetResponse(tokenInfo.icon_url as string, './playwright/mocks/image_s.jpg'); +>>>>>>> v2.13.0 const component = await render( <TokenPageTitle tokenQuery={ tokenQuery } +<<<<<<< HEAD hash={ tokenInfo.address_hash } +======= + hash={ hash } +>>>>>>> v2.13.0 + addressQuery={ addressQuery } + verifiedInfoQuery={ verifiedInfoQuery } + />); + +<<<<<<< HEAD +======= + await expect(component.getByRole('link', { name: /Buy on Duck portal/ })).toHaveAttribute( + 'href', + `https://portal.duck.io/swap?chainId=${ config.chain.id }&token=${ hash.toLowerCase() }&utm_source=blockscout&utm_medium=token`, + ); + await expect(component.getByText('Buy on Duck portal', { exact: true })).toHaveCount(1); + await expect(component).toHaveScreenshot(); +}); + +test('with env action button +@dark-mode +@mobile', async({ render, mockApiResponse, mockAssetResponse, mockEnvs }) => { + await mockEnvs(ENVS_MAP.tokenActionButton); + await mockApiResponse('metadata:info', generateAddressMetadataInfo(hash, hiddenProtocolTagWithMeta), { queryParams: addressMetadataQueryParams }); + await mockAssetResponse(tokenInfo.icon_url as string, './playwright/mocks/image_s.jpg'); + + const component = await render( + <TokenPageTitle + tokenQuery={ tokenQuery } + hash={ hash } addressQuery={ addressQuery } verifiedInfoQuery={ verifiedInfoQuery } />); + await expect(component.getByRole('link', { name: /Buy on Duck Portal/ })).toHaveAttribute( + 'href', + `https://portal.duck.io/swap?chainId=1&token=${ hash.toLowerCase() }&utm_source=blockscout&utm_medium=token`, + ); + await expect(component.getByText('Buy on Duck portal', { exact: true })).toHaveCount(0); +>>>>>>> v2.13.0 await expect(component).toHaveScreenshot(); }); diff --git a/src/slices/token/pages/details/TokenPageTitle.spec.tsx b/src/slices/token/pages/details/TokenPageTitle.spec.tsx new file mode 100644 index 00000000000..8ea599f9242 --- /dev/null +++ b/src/slices/token/pages/details/TokenPageTitle.spec.tsx @@ -0,0 +1,207 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout +// @vitest-environment jsdom + +import type { UseQueryResult } from '@tanstack/react-query'; +import React from 'react'; + +import type { schemas } from '@blockscout/api-types'; +import type * as contractsInfo from '@blockscout/contracts-info-types'; +import type { AddressMetadataInfo, AddressMetadataTagApi } from 'src/features/address-metadata/types/api'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +import type { ResourceError } from 'src/api/resources'; + +import { tokenInfo } from 'src/slices/token/mocks/info'; + +import { hiddenProtocolTagWithMeta, protocolTag, tokenActionButtonHiddenServiceTag } from 'src/features/address-metadata/mocks/tags'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { cleanup, screen, waitFor } from 'vitest/lib'; +import withEnvs from 'vitest/utils/mockEnvs'; + +const ENV_BUTTON_TEXT = 'Buy on Duck Portal'; +const METADATA_BUTTON_TEXT = hiddenProtocolTagWithMeta.meta?.appActionButtonText as string; + +const envs: Array<[ string, string ]> = [ + ...ENVS_MAP.tokenActionButton, + [ 'NEXT_PUBLIC_METADATA_SERVICE_API_HOST', 'https://localhost:3007' ], +]; + +const tokenQuery = { data: tokenInfo } as UseQueryResult<schemas['Token'], ResourceError<unknown>>; +const verifiedInfoQuery = { data: {} } as UseQueryResult<contractsInfo.TokenInfo, ResourceError<unknown>>; +const addressQuery = {} as UseQueryResult<schemas['Address'], ResourceError<unknown>>; + +function metadataInfo(tags: Array<AddressMetadataTagApi>): AddressMetadataInfo { + return { + addresses: { + [ tokenInfo.address_hash.toLowerCase() ]: { + tags: tags.map((tag) => ({ ...tag, meta: tag.meta ? JSON.stringify(tag.meta) : null })), + reputation: null, + }, + }, + }; +} + +function mockMetadata(tags: Array<AddressMetadataTagApi>): void { + fetchMock.mockResponse((request) => request.url.includes('/metadata') ? + { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(metadataInfo(tags)) } : + { status: 404, body: '{}' }, + ); +} + +async function renderTitle(query = tokenQuery): Promise<void> { + const { render } = await import('vitest/lib'); + const { 'default': TokenPageTitle } = await import('./TokenPageTitle'); + render( + <TokenPageTitle + tokenQuery={ query } + addressQuery={ addressQuery } + verifiedInfoQuery={ verifiedInfoQuery } + hash={ tokenInfo.address_hash } + />, + ); + await waitFor(() => expect(fetchMock.mock.calls.length).toBeGreaterThan(0)); +} + +type AppConfig = ClusterChainConfig['app_config']; + +async function renderTitleOnChain(getAppConfig: (rootConfig: AppConfig) => AppConfig): Promise<void> { + const { render } = await import('vitest/lib'); + const { 'default': TokenPageTitle } = await import('./TokenPageTitle'); + const { MultichainContext } = await import('src/features/multichain/context'); + const { 'default': config } = await import('src/config'); + + const chain: ClusterChainConfig = { + id: config.chain.id ?? '1', + name: 'Cluster chain', + slug: 'cluster-chain', + app_config: getAppConfig(config), + }; + + render( + <MultichainContext.Provider value={{ chain }}> + <TokenPageTitle + tokenQuery={ tokenQuery } + addressQuery={ addressQuery } + verifiedInfoQuery={ verifiedInfoQuery } + hash={ tokenInfo.address_hash } + /> + </MultichainContext.Provider>, + ); +} + +const withChainMetadataOff = (rootConfig: AppConfig): AppConfig => ({ + ...rootConfig, + features: { + ...rootConfig.features, + addressMetadata: { title: rootConfig.features.addressMetadata.title, isEnabled: false }, + }, +}); + +const withChainMetadataOn = (rootConfig: AppConfig): AppConfig => ({ + ...rootConfig, + chain: { ...rootConfig.chain, id: rootConfig.chain.id || '1' }, + apis: { ...rootConfig.apis, metadata: { endpoint: 'https://localhost:3007' } }, + features: { + ...rootConfig.features, + addressMetadata: { + title: rootConfig.features.addressMetadata.title, + isEnabled: true, + isTagsUpdateEnabled: false, + isTagSubmitionEnabled: false, + }, + }, +}); + +beforeEach(() => { + fetchMock.resetMocks(); +}); + +afterEach(() => { + cleanup(); +}); + +describe('token action button', () => { + it('shows the configured button on an ERC-20 token without the blacklist tag', async() => { + await withEnvs(envs, async() => { + mockMetadata([ protocolTag ]); + await renderTitle(); + + expect(await screen.findByText(ENV_BUTTON_TEXT)).toBeTruthy(); + expect(screen.getByText(protocolTag.name)).toBeTruthy(); + }); + }); + + it('hides the configured button on a non-ERC-20 token', async() => { + await withEnvs(envs, async() => { + mockMetadata([ protocolTag ]); + const erc721Query = { data: { ...tokenInfo, type: 'ERC-721' } } as UseQueryResult<schemas['Token'], ResourceError<unknown>>; + await renderTitle(erc721Query); + + expect(await screen.findByText(protocolTag.name)).toBeTruthy(); + expect(screen.queryByText(ENV_BUTTON_TEXT)).toBeNull(); + }); + }); + + it('hides the configured button when the address carries the service blacklist tag, and never shows the tag', async() => { + await withEnvs(envs, async() => { + mockMetadata([ protocolTag, tokenActionButtonHiddenServiceTag ]); + await renderTitle(); + + expect(await screen.findByText(protocolTag.name)).toBeTruthy(); + expect(screen.queryByText(ENV_BUTTON_TEXT)).toBeNull(); + expect(screen.queryByText(tokenActionButtonHiddenServiceTag.name)).toBeNull(); + }); + }); + + it('takes precedence over the metadata-driven button', async() => { + await withEnvs(envs, async() => { + mockMetadata([ hiddenProtocolTagWithMeta ]); + await renderTitle(); + + expect(await screen.findByText(ENV_BUTTON_TEXT)).toBeTruthy(); + expect(screen.queryByText(METADATA_BUTTON_TEXT)).toBeNull(); + }); + }); + + it('falls back to the metadata-driven button when the configured one is blacklisted', async() => { + await withEnvs(envs, async() => { + mockMetadata([ hiddenProtocolTagWithMeta, tokenActionButtonHiddenServiceTag ]); + await renderTitle(); + + expect(await screen.findByText(METADATA_BUTTON_TEXT)).toBeTruthy(); + expect(screen.queryByText(ENV_BUTTON_TEXT)).toBeNull(); + }); + }); + + it('shows the configured button on a cluster chain whose metadata service is off', async() => { + await withEnvs(envs, async() => { + await renderTitleOnChain(withChainMetadataOff); + + expect(await screen.findByText(ENV_BUTTON_TEXT)).toBeTruthy(); + }); + }); + + it('waits for the metadata of a cluster chain whose metadata service is on while the root one is off', async() => { + await withEnvs(ENVS_MAP.tokenActionButton, async() => { + let respondWithMetadata: ((body: string) => void) | undefined; + fetchMock.mockResponse((request) => request.url.includes('/metadata') ? + new Promise<string>((resolve) => { + respondWithMetadata = resolve; + }) : + { status: 404, body: '{}' }, + ); + + await renderTitleOnChain(withChainMetadataOn); + await waitFor(() => expect(respondWithMetadata).toBeDefined()); + + expect(screen.queryByText(ENV_BUTTON_TEXT)).toBeNull(); + + respondWithMetadata?.(JSON.stringify(metadataInfo([ protocolTag ]))); + + expect(await screen.findByText(ENV_BUTTON_TEXT)).toBeTruthy(); + }); + }); +}); diff --git a/src/slices/token/pages/details/TokenPageTitle.tsx b/src/slices/token/pages/details/TokenPageTitle.tsx index 367b2751f49..ee4b2a72902 100644 --- a/src/slices/token/pages/details/TokenPageTitle.tsx +++ b/src/slices/token/pages/details/TokenPageTitle.tsx @@ -7,7 +7,7 @@ import React from 'react'; import type { schemas } from '@blockscout/api-types'; import type * as contractsInfo from '@blockscout/contracts-info-types'; import type { MetadataTag } from 'src/features/address-metadata/components/tag/types'; -import { getTokenTypeName } from 'src/slices/token/utils/token-types'; +import { getTokenTypeName, isFungibleTokenType } from 'src/slices/token/utils/token-types'; import type { ResourceError } from 'src/api/resources'; @@ -19,13 +19,19 @@ import AddressAlerts from 'src/slices/address/pages/details/info/AddressAlerts'; import AddressQrCode from 'src/slices/address/pages/details/info/AddressQrCode'; import * as TokenEntity from 'src/slices/token/components/entity/TokenEntity'; +import AppActionButton from 'src/features/address-metadata/components/AppActionButton'; import formatAccountTags from 'src/features/address-metadata/components/tag/format-account-tags'; import MetadataTags from 'src/features/address-metadata/components/tag/MetadataTags'; import sortMetadataTags from 'src/features/address-metadata/components/tag/sort'; import useAddressMetadataInfoQuery from 'src/features/address-metadata/hooks/useAddressMetadataInfoQuery'; +import { getAppActionData } from 'src/features/address-metadata/utils/get-app-action-data'; import AlternativeExplorers from 'src/features/alternative-explorers/components/AlternativeExplorers'; import { useMultichainContext } from 'src/features/multichain/context'; import TokenActionButton from 'src/features/token-action-button/components/TokenActionButton'; +<<<<<<< HEAD +======= +import { isTokenActionButtonHidden } from 'src/features/token-action-button/utils/is-token-action-button-hidden'; +>>>>>>> v2.13.0 import TokenVerifiedInfo from 'src/features/verified-tokens/pages/token/TokenVerifiedInfo'; import TokenAddToWallet from 'src/features/web3-wallet/components/TokenAddToWallet'; @@ -49,6 +55,13 @@ const TokenPageTitle = ({ tokenQuery, addressQuery, verifiedInfoQuery, hash }: P const addressesForMetadataQuery = React.useMemo(() => ([ hash ].filter(Boolean)), [ hash ]); const addressMetadataQuery = useAddressMetadataInfoQuery(addressesForMetadataQuery); + const addressMetadataTags = addressMetadataQuery.data?.addresses?.[hash.toLowerCase()]?.tags; + const appActionData = getAppActionData(addressMetadataTags); + + const hasTokenActionButton = config.features.tokenActionButton.isEnabled && + tokenQuery.data?.type === 'ERC-20' && + !addressMetadataQuery.isLoading && + !isTokenActionButtonHidden(addressMetadataTags); const tokenSymbolText = tokenQuery.data?.symbol ? ` (${ tokenQuery.data.symbol })` : ''; @@ -77,16 +90,15 @@ const TokenPageTitle = ({ tokenQuery, addressQuery, verifiedInfoQuery, hash }: P verifiedInfoQuery.data?.projectSector ? { slug: verifiedInfoQuery.data.projectSector, name: verifiedInfoQuery.data.projectSector, tagType: 'custom' as const, ordinal: -30, meta: null } : undefined, - ...(addressMetadataQuery.data?.addresses?.[hash.toLowerCase()]?.tags.filter(tag => tag.tagType !== 'note') || []), + ...(addressMetadataTags?.filter(tag => tag.tagType !== 'note') || []), ].filter(Boolean).sort(sortMetadataTags); }, [ - addressMetadataQuery.data?.addresses, + addressMetadataTags, addressQuery.data, bridgedTokenTagBgColor, bridgedTokenTagTextColor, tokenQuery.data, verifiedInfoQuery.data?.projectSector, - hash, multichainContext?.chain?.app_config, ]); @@ -113,6 +125,7 @@ const TokenPageTitle = ({ tokenQuery, addressQuery, verifiedInfoQuery, hash }: P <SpriteIcon name="certified" color="green.500" boxSize={ 6 } cursor="pointer"/> </Tooltip> ) } +<<<<<<< HEAD <MetadataTags isLoading={ isTagsLoading } tags={ tags } @@ -124,6 +137,29 @@ const TokenPageTitle = ({ tokenQuery, addressQuery, verifiedInfoQuery, hash }: P tokenType={ tokenQuery.data?.type } isLoading={ tokenQuery.isPlaceholderData } /> +======= + <Flex alignItems="center" justifyContent="space-between" flexGrow={ 1 } flexWrap="wrap" gap={ 3 }> + <MetadataTags + isLoading={ isTagsLoading } + tags={ tags } + addressHash={ addressQuery.data?.hash } + flexGrow={ 1 } + /> + { hasTokenActionButton && ( + <TokenActionButton + tokenHash={ hash } + isLoading={ tokenQuery.isPlaceholderData } + /> + ) } + { !hasTokenActionButton && appActionData && ( + <AppActionButton + data={ appActionData } + addressHash={ hash } + source={ isFungibleTokenType(tokenQuery.data?.type, multichainContext?.chain?.app_config) ? 'Token' : 'NFT collection' } + /> + ) } + </Flex> +>>>>>>> v2.13.0 </> ); @@ -169,7 +205,7 @@ const TokenPageTitle = ({ tokenQuery, addressQuery, verifiedInfoQuery, hash }: P /> { !addressMetadataQuery.isPending && ( <AddressAlerts - tags={ addressMetadataQuery.data?.addresses?.[hash.toLowerCase()]?.tags } + tags={ addressMetadataTags } isScamToken={ tokenQuery.data?.reputation === 'scam' } /> ) } diff --git a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_base-view-1.png b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_base-view-1.png index fcee5595ebe..b7cd2ae27ae 100644 Binary files a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_base-view-1.png and b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_base-view-1.png differ diff --git a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_bridged-token-1.png b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_bridged-token-1.png index 0512517a408..b45fb4433cb 100644 Binary files a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_bridged-token-1.png and b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_bridged-token-1.png differ diff --git a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_mobile-base-view-1.png b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_mobile-base-view-1.png index da1d78f74ed..782018ae7b4 100644 Binary files a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_mobile-base-view-1.png and b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_mobile-base-view-1.png differ diff --git a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_mobile-with-verified-info-1.png b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_mobile-with-verified-info-1.png index ecca3a441d0..123878ba2c4 100644 Binary files a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_mobile-with-verified-info-1.png and b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_mobile-with-verified-info-1.png differ diff --git a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_scam-token-1.png b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_scam-token-1.png index b8d930905fa..63a138e240b 100644 Binary files a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_scam-token-1.png and b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_scam-token-1.png differ diff --git a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_with-verified-info-1.png b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_with-verified-info-1.png index 5e196100216..07848127d7c 100644 Binary files a/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_with-verified-info-1.png and b/src/slices/token/pages/details/__screenshots__/Token.pw.tsx_default_with-verified-info-1.png differ diff --git a/src/slices/token/pages/details/__screenshots__/TokenPageTitle.pw.tsx_dark-color-mode_with-env-action-button-dark-mode-mobile-1.png b/src/slices/token/pages/details/__screenshots__/TokenPageTitle.pw.tsx_dark-color-mode_with-env-action-button-dark-mode-mobile-1.png new file mode 100644 index 00000000000..03c248db0d0 Binary files /dev/null and b/src/slices/token/pages/details/__screenshots__/TokenPageTitle.pw.tsx_dark-color-mode_with-env-action-button-dark-mode-mobile-1.png differ diff --git a/src/slices/token/pages/details/__screenshots__/TokenPageTitle.pw.tsx_default_with-env-action-button-dark-mode-mobile-1.png b/src/slices/token/pages/details/__screenshots__/TokenPageTitle.pw.tsx_default_with-env-action-button-dark-mode-mobile-1.png new file mode 100644 index 00000000000..e89044566f0 Binary files /dev/null and b/src/slices/token/pages/details/__screenshots__/TokenPageTitle.pw.tsx_default_with-env-action-button-dark-mode-mobile-1.png differ diff --git a/src/slices/token/pages/details/__screenshots__/TokenPageTitle.pw.tsx_mobile_with-env-action-button-dark-mode-mobile-1.png b/src/slices/token/pages/details/__screenshots__/TokenPageTitle.pw.tsx_mobile_with-env-action-button-dark-mode-mobile-1.png new file mode 100644 index 00000000000..82ec57cdcc5 Binary files /dev/null and b/src/slices/token/pages/details/__screenshots__/TokenPageTitle.pw.tsx_mobile_with-env-action-button-dark-mode-mobile-1.png differ diff --git a/src/slices/token/pages/details/holders/TokenHolders.tsx b/src/slices/token/pages/details/holders/TokenHolders.tsx index 0b646ec58db..5aebf3a7774 100644 --- a/src/slices/token/pages/details/holders/TokenHolders.tsx +++ b/src/slices/token/pages/details/holders/TokenHolders.tsx @@ -1,47 +1,52 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; -import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; - -import { getTokenHoldersStub } from 'src/slices/token/stubs'; +import ActionBar from 'src/shell/page/action-bar/ActionBar'; +import BubblemapsMap from 'src/features/bubblemaps/components/BubblemapsMap'; import CsvExport from 'src/features/csv-export/components/CsvExport'; -import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; -import DataList from 'src/shared/lists/DataList'; +import config from 'src/config'; +import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; + +import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; import TokenHoldersList from './TokenHoldersList'; -import TokenHoldersTable from './TokenHoldersTable'; +import { useTokenHoldersQuery } from './useTokenHoldersQuery'; + +export const TOKEN_HOLDERS_TAB_IDS = [ 'holders_address' as const, 'holders_bubblemaps' as const ]; + +const TAB_LIST_PROPS = { + marginBottom: 0, + pt: 6, + pb: 3, + marginTop: -6, +}; interface Props { token: schemas['Token'] | undefined; - tokenId?: string; isLoading: boolean; -}; + tokenId?: string; +} -const TokenHolders = ({ token, tokenId, isLoading }: Props) => { +const TokenHolders = ({ token, isLoading, tokenId }: Props) => { + const router = useRouter(); + const isMobile = useIsMobile(); + const tab = getQueryParamString(router.query.tab); - const holdersQuery = useQueryWithPages({ - resourceName: tokenId ? 'core:token_instance_holders' : 'core:token_holders', - pathParams: { hash: token?.address_hash, id: tokenId }, - options: { - enabled: Boolean(token?.address_hash) && !isLoading, - placeholderData: getTokenHoldersStub(token?.type, null), - }, - }); + const hasBubblemapsTab = config.features.bubblemaps.isEnabled && (isLoading || token?.type === 'ERC-20'); + const isAddressTab = !hasBubblemapsTab || tab === 'holders_address' || tab === 'holders'; - if (holdersQuery.isError) { - return <ApiFetchAlert/>; - } + const holdersQuery = useTokenHoldersQuery({ token, tokenId, enabled: !isLoading && isAddressTab }); - const actionBar = ( - <ActionBar mt={ -6 }> + const controls = ( + <> { token && ( <CsvExport type="token_holders" @@ -53,43 +58,49 @@ const TokenHolders = ({ token, tokenId, isLoading }: Props) => { /> ) } { holdersQuery.pagination.isVisible && <Pagination ml="auto" { ...holdersQuery.pagination }/> } - </ActionBar> + </> ); - const items = holdersQuery.data?.items; - - const content = items && token ? ( - <> - <Box display={{ base: 'none', lg: 'block' }}> - <TokenHoldersTable - data={ items } - token={ token } - top={ ACTION_BAR_HEIGHT_DESKTOP } - isLoading={ holdersQuery.isPlaceholderData } - resetKey={ holdersQuery.queryHash } - /> - </Box> - <Box display={{ base: 'block', lg: 'none' }}> - <TokenHoldersList - data={ items } - token={ token } - isLoading={ holdersQuery.isPlaceholderData } - resetKey={ holdersQuery.queryHash } - /> - </Box> - </> + const addressActionBar = isMobile ? ( + <ActionBar> + { controls } + </ActionBar> ) : null; + const tabs = [ + { + id: 'holders_address', + title: 'Address', + component: <TokenHoldersList token={ token } query={ holdersQuery } actionBar={ addressActionBar }/>, + }, + hasBubblemapsTab ? { + id: 'holders_bubblemaps', + title: 'Bubblemaps', + component: token ? <BubblemapsMap key={ token.address_hash } hash={ token.address_hash } isLoading={ isLoading }/> : null, + } : null, + ].filter(Boolean); + + const rightSlot = isAddressTab && !isMobile ? controls : null; + + const rightSlotProps = { + display: 'flex', + justifyContent: 'space-between', + ml: { base: 0, lg: hasBubblemapsTab ? 4 : 0 }, + widthAllocation: 'available' as const, + }; + return ( - <DataList - isError={ holdersQuery.isError } - itemsNum={ holdersQuery.data?.items.length } - emptyText="There are no holders for this token." - actionBar={ actionBar } - > - { content } - </DataList> + <RoutedTabs + variant="secondary" + isLoading={ isLoading } + size="sm" + tabs={ tabs } + rightSlot={ rightSlot } + rightSlotProps={ rightSlotProps } + listProps={ isMobile ? undefined : TAB_LIST_PROPS } + stickyEnabled={ !isMobile && isAddressTab } + /> ); }; -export default TokenHolders; +export default React.memo(TokenHolders); diff --git a/src/slices/token/pages/details/holders/TokenHoldersList.pw.tsx b/src/slices/token/pages/details/holders/TokenHoldersList.pw.tsx deleted file mode 100644 index 6c6902aa00a..00000000000 --- a/src/slices/token/pages/details/holders/TokenHoldersList.pw.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import React from 'react'; - -import { tokenHoldersERC20, tokenHoldersERC1155 } from 'src/slices/token/mocks/holders'; -import { tokenInfo, tokenInfoERC1155a } from 'src/slices/token/mocks/info'; - -import { test, expect, devices } from 'playwright/lib'; - -import TokenHoldersList from './TokenHoldersList'; - -test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - -test('base view without IDs', async({ render }) => { - const component = await render(<TokenHoldersList data={ tokenHoldersERC20.items } token={ tokenInfo }/>); - await expect(component).toHaveScreenshot(); -}); - -test('base view with IDs', async({ render }) => { - const component = await render(<TokenHoldersList data={ tokenHoldersERC1155.items } token={ tokenInfoERC1155a }/>); - await expect(component).toHaveScreenshot(); -}); diff --git a/src/slices/token/pages/details/holders/TokenHoldersList.tsx b/src/slices/token/pages/details/holders/TokenHoldersList.tsx index 84cd29d3e47..a247763e4ae 100644 --- a/src/slices/token/pages/details/holders/TokenHoldersList.tsx +++ b/src/slices/token/pages/details/holders/TokenHoldersList.tsx @@ -1,42 +1,53 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; +import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; -import TokenHoldersListItem from './TokenHoldersListItem'; +import DataList from 'src/shared/lists/DataList'; + +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; + +import TokenHoldersTable from './TokenHoldersTable'; +import type { TokenHoldersQuery } from './useTokenHoldersQuery'; interface Props { - data: Array<schemas['TokenHolderResponse']>; - token: schemas['Token']; - isLoading?: boolean; - resetKey?: string; + token: schemas['Token'] | undefined; + query: TokenHoldersQuery; + actionBar: React.ReactNode; } -const TokenHoldersList = ({ data, token, isLoading, resetKey }: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); +const TokenHoldersList = ({ token, query, actionBar }: Props) => { + + const items = query.data?.items; + + const content = items && token ? ( + <TableContainerScrollable> + <TokenHoldersTable + data={ items } + token={ token } + top={ ACTION_BAR_HEIGHT_DESKTOP } + isLoading={ query.isInitialLoading } + resetKey={ query.queryHash } + /> + </TableContainerScrollable> + ) : null; return ( - <> - <Box> - { data.slice(0, renderedItemsNum).map((item, index) => { - const tokenId = 'token_id' in item ? item.token_id : null; - return ( - <TokenHoldersListItem - key={ item.address.hash + tokenId + (isLoading ? index : '') } - token={ token } - holder={ item } - isLoading={ isLoading } - /> - ); - }) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </> + <DataList + isError={ query.isError } + itemsNum={ query.data?.items.length } + emptyText="There are no holders for this token." + actionBar={ actionBar } + isTransitioning={ query.isTransitioning } + showActionBarIfEmpty + showActionBarIfError + > + { content } + </DataList> ); }; -export default TokenHoldersList; +export default React.memo(TokenHoldersList); diff --git a/src/slices/token/pages/details/holders/TokenHoldersListItem.tsx b/src/slices/token/pages/details/holders/TokenHoldersListItem.tsx deleted file mode 100644 index 68d963bd693..00000000000 --- a/src/slices/token/pages/details/holders/TokenHoldersListItem.tsx +++ /dev/null @@ -1,79 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import BigNumber from 'bignumber.js'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import { hasTokenIds, isConfidentialTokenType } from 'src/slices/token/utils/token-types'; - -import AddressEntityWithTokenFilter from 'src/slices/address/components/entity/AddressEntityWithTokenFilter'; - -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; -import AssetValue from 'src/shared/values/entity/AssetValue'; -import ConfidentialValue from 'src/shared/values/entity/ConfidentialValue'; -import Utilization from 'src/shared/values/utilization/Utilization'; - -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; - -interface Props { - holder: schemas['TokenHolderResponse']; - token: schemas['Token']; - isLoading?: boolean; -} - -const TokenHoldersListItem = ({ holder, token, isLoading }: Props) => { - return ( - <ListItemMobileGrid.Container> - <ListItemMobileGrid.Label isLoading={ isLoading }>Address</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <AddressEntityWithTokenFilter - address={ holder.address } - tokenHash={ token.address_hash } - tokenSymbol={ token.symbol ?? undefined } - isLoading={ isLoading } - fontWeight="700" - maxW="100%" - /> - </ListItemMobileGrid.Value> - - { (hasTokenIds(token.type)) && 'token_id' in holder && holder.token_id !== null && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>ID#</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <TruncatedText text={ holder.token_id } loading={ isLoading } w="100%"/> - </ListItemMobileGrid.Value> - </> - ) } - - <ListItemMobileGrid.Label isLoading={ isLoading }>Quantity</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - { isConfidentialTokenType(token.type) ? ( - <ConfidentialValue loading={ isLoading }/> - ) : ( - <AssetValue - amount={ holder.value } - decimals={ token.decimals ?? '0' } - loading={ isLoading } - /> - ) } - </ListItemMobileGrid.Value> - - { token.total_supply && token.type !== 'ERC-404' && !isConfidentialTokenType(token.type) && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Percentage</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value> - <Utilization - value={ BigNumber(holder.value ?? '0').div(BigNumber(token.total_supply)).dp(4).toNumber() } - colorScheme="green" - isLoading={ isLoading } - display="inline-flex" - /> - </ListItemMobileGrid.Value> - </> - ) } - - </ListItemMobileGrid.Container> - ); -}; - -export default TokenHoldersListItem; diff --git a/src/slices/token/pages/details/holders/TokenHoldersTable.pw.tsx b/src/slices/token/pages/details/holders/TokenHoldersTable.pw.tsx index 6bdafa36a26..91dd19c4890 100644 --- a/src/slices/token/pages/details/holders/TokenHoldersTable.pw.tsx +++ b/src/slices/token/pages/details/holders/TokenHoldersTable.pw.tsx @@ -1,17 +1,19 @@ import { Box } from '@chakra-ui/react'; -import React from 'react'; -import { tokenHoldersERC20, tokenHoldersERC1155 } from 'src/slices/token/mocks/holders'; -import { tokenInfo, tokenInfoERC1155a } from 'src/slices/token/mocks/info'; +import { tokenHoldersERC1155, tokenHoldersERC20 } from 'src/slices/token/mocks/holders'; +import { tokenInfoERC1155a, tokenInfoERC8056 } from 'src/slices/token/mocks/info'; -import { test, expect } from 'playwright/lib'; +import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; +import { expect, test } from 'playwright/lib'; import TokenHoldersTable from './TokenHoldersTable'; -test('base view without IDs', async({ render }) => { +test('base view without IDs', async({ render, mockEnvs }) => { + await mockEnvs(ENVS_MAP.additionalTokenTypes); + const component = await render( <Box pt="128px"> - <TokenHoldersTable data={ tokenHoldersERC20.items } token={ tokenInfo } top={ 88 }/> + <TokenHoldersTable data={ tokenHoldersERC20.items } token={ tokenInfoERC8056 } top={ 88 }/> </Box>, ); diff --git a/src/slices/token/pages/details/holders/TokenHoldersTable.tsx b/src/slices/token/pages/details/holders/TokenHoldersTable.tsx index 668b65159ff..85528a7c51a 100644 --- a/src/slices/token/pages/details/holders/TokenHoldersTable.tsx +++ b/src/slices/token/pages/details/holders/TokenHoldersTable.tsx @@ -7,6 +7,9 @@ import { hasTokenIds, isConfidentialTokenType } from 'src/slices/token/utils/tok import TokenHoldersTableItem from 'src/slices/token/pages/details/holders/TokenHoldersTableItem'; +import { useMultichainContext } from 'src/features/multichain/context'; + +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; @@ -19,11 +22,19 @@ interface Props { resetKey?: string; } +const getBaseKey = (item: schemas['TokenHolderResponse']): string => { + const tokenId = 'token_id' in item ? item.token_id : null; + + return item.address.hash + tokenId; +}; + const TokenHoldersTable = ({ data, token, top, isLoading, resetKey }: Props) => { + const chainData = useMultichainContext()?.chain; const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(data, getBaseKey); return ( - <TableRoot> + <TableRoot minW="800px"> <TableHeaderSticky top={ top }> <TableRow> <TableColumnHeader w="70%">Holder</TableColumnHeader> @@ -35,12 +46,15 @@ const TokenHoldersTable = ({ data, token, top, isLoading, resetKey }: Props) => </TableRow> </TableHeaderSticky> <TableBody> - { data.slice(0, renderedItemsNum).map((item, index) => { - const tokenId = 'token_id' in item ? item.token_id : null; - return ( - <TokenHoldersTableItem key={ item.address.hash + tokenId + (isLoading ? index : '') } holder={ item } token={ token } isLoading={ isLoading }/> - ); - }) } + { data.slice(0, renderedItemsNum).map((item, index) => ( + <TokenHoldersTableItem + key={ keys[index] } + holder={ item } + token={ token } + chainData={ chainData } + isLoading={ isLoading } + /> + )) } <TableRow ref={ cutRef }/> </TableBody> </TableRoot> diff --git a/src/slices/token/pages/details/holders/TokenHoldersTableItem.tsx b/src/slices/token/pages/details/holders/TokenHoldersTableItem.tsx index 914d7fad73a..e6ee3c9db0f 100644 --- a/src/slices/token/pages/details/holders/TokenHoldersTableItem.tsx +++ b/src/slices/token/pages/details/holders/TokenHoldersTableItem.tsx @@ -4,24 +4,30 @@ import BigNumber from 'bignumber.js'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; import { hasTokenIds, isConfidentialTokenType } from 'src/slices/token/utils/token-types'; import AddressEntityWithTokenFilter from 'src/slices/address/components/entity/AddressEntityWithTokenFilter'; +import TokenMultiplierTag from 'src/slices/token/components/ui-multiplier/TokenMultiplierTag'; +import { getUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; import AssetValue from 'src/shared/values/entity/AssetValue'; import ConfidentialValue from 'src/shared/values/entity/ConfidentialValue'; import Utilization from 'src/shared/values/utilization/Utilization'; import { TableCell, TableRow } from 'src/toolkit/chakra/table'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props { holder: schemas['TokenHolderResponse']; token: schemas['Token']; + chainData?: ClusterChainConfig; isLoading?: boolean; }; -const TokenTransferTableItem = ({ holder, token, isLoading }: Props) => { +const TokenTransferTableItem = ({ holder, token, chainData, isLoading }: Props) => { + const multiplier = getUiMultiplier(token, chainData?.app_config); + return ( <TableRow> <TableCell verticalAlign="middle"> @@ -36,7 +42,7 @@ const TokenTransferTableItem = ({ holder, token, isLoading }: Props) => { </TableCell> { (hasTokenIds(token.type)) && 'token_id' in holder && holder.token_id !== null && ( <TableCell verticalAlign="middle"> - <TruncatedText text={ holder.token_id } loading={ isLoading } w="100%"/> + <Truncate value={ holder.token_id } type="end" loading={ isLoading } w="100%"/> </TableCell> ) } <TableCell verticalAlign="middle" isNumeric> @@ -46,6 +52,8 @@ const TokenTransferTableItem = ({ holder, token, isLoading }: Props) => { <AssetValue amount={ holder.value } decimals={ token.decimals ?? '0' } + multiplier={ multiplier } + startElement={ multiplier && <TokenMultiplierTag multiplier={ multiplier } loading={ isLoading } mr={ 2 }/> } loading={ isLoading } /> ) } diff --git a/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersList.pw.tsx_default_base-view-with-IDs-1.png b/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersList.pw.tsx_default_base-view-with-IDs-1.png deleted file mode 100644 index ac762b9220a..00000000000 Binary files a/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersList.pw.tsx_default_base-view-with-IDs-1.png and /dev/null differ diff --git a/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersList.pw.tsx_default_base-view-without-IDs-1.png b/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersList.pw.tsx_default_base-view-without-IDs-1.png deleted file mode 100644 index f68c51990f9..00000000000 Binary files a/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersList.pw.tsx_default_base-view-without-IDs-1.png and /dev/null differ diff --git a/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersTable.pw.tsx_default_base-view-with-IDs-1.png b/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersTable.pw.tsx_default_base-view-with-IDs-1.png index 41366cf7e96..8cf0a3a0baa 100644 Binary files a/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersTable.pw.tsx_default_base-view-with-IDs-1.png and b/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersTable.pw.tsx_default_base-view-with-IDs-1.png differ diff --git a/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersTable.pw.tsx_default_base-view-without-IDs-1.png b/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersTable.pw.tsx_default_base-view-without-IDs-1.png index 38556cbb8b8..66fb20795d7 100644 Binary files a/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersTable.pw.tsx_default_base-view-without-IDs-1.png and b/src/slices/token/pages/details/holders/__screenshots__/TokenHoldersTable.pw.tsx_default_base-view-without-IDs-1.png differ diff --git a/src/slices/token/pages/details/holders/useTokenHoldersQuery.ts b/src/slices/token/pages/details/holders/useTokenHoldersQuery.ts new file mode 100644 index 00000000000..e06ba36e4ab --- /dev/null +++ b/src/slices/token/pages/details/holders/useTokenHoldersQuery.ts @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { schemas } from '@blockscout/api-types'; + +import { getTokenHoldersStub } from 'src/slices/token/stubs'; + +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; + +interface Params { + token: schemas['Token'] | undefined; + tokenId: string | undefined; + enabled: boolean; +} + +export const useTokenHoldersQuery = ({ token, tokenId, enabled }: Params) => { + return useApiPaginatedQuery({ + resourceName: tokenId ? 'core:token_instance_holders' : 'core:token_holders', + pathParams: { hash: token?.address_hash, id: tokenId }, + options: { + enabled: Boolean(token?.address_hash) && enabled, + placeholderData: getTokenHoldersStub(token?.type, null), + }, + }); +}; + +export type TokenHoldersQuery = ReturnType<typeof useTokenHoldersQuery>; diff --git a/src/slices/token/pages/details/info/TokenDetails.tsx b/src/slices/token/pages/details/info/TokenDetails.tsx index 45e47f174fb..3d2cb103d81 100644 --- a/src/slices/token/pages/details/info/TokenDetails.tsx +++ b/src/slices/token/pages/details/info/TokenDetails.tsx @@ -2,29 +2,28 @@ import { chakra } from '@chakra-ui/react'; import BigNumber from 'bignumber.js'; -import { useRouter } from 'next/router'; import React, { useCallback } from 'react'; import type { schemas } from '@blockscout/api-types'; -import { isConfidentialTokenType } from 'src/slices/token/utils/token-types'; +import { isConfidentialTokenType, isFungibleTokenType } from 'src/slices/token/utils/token-types'; import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import type { TokenTabs } from 'src/slices/token/pages/details/Token'; +import { formatUiMultiplier, getUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; import Address3rdPartyWidgets from 'src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgets'; -import AppActionButton from 'src/features/address-metadata/components/AppActionButton'; -import useAppActionData from 'src/features/address-metadata/hooks/useAppActionData'; import { useMultichainContext } from 'src/features/multichain/context'; -import config from 'src/config'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import DetailedInfoSponsoredItem from 'src/shared/detailed-info/DetailedInfoSponsoredItem'; import useIsMounted from 'src/shared/hooks/useIsMounted'; +import { useRouter } from 'src/shared/router/useRouter'; import AssetValue from 'src/shared/values/entity/AssetValue'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import TokenMultiplierHistoryInline from './TokenMultiplierHistoryInline'; import TokenNftMarketplaces from './TokenNftMarketplaces'; interface Props { @@ -44,14 +43,11 @@ const TokenDetails = ({ data, counters, isLoading, isLoadingCounters, address3rd const multichainContext = useMultichainContext(); const chainSlug = multichainContext?.chain?.slug; - const appActionData = useAppActionData(hash); - const changeTab = useCallback((tab: TokenTabs) => () => { router.push( chainSlug ? { pathname: '/chain/[chain_slug_or_id]/token/[hash]', query: { hash: hash || '', tab, chain_slug_or_id: chainSlug } } : { pathname: '/token/[hash]', query: { hash: hash || '', tab } }, - undefined, { shallow: true }, ); }, [ chainSlug, hash, router ]); @@ -89,6 +85,9 @@ const TokenDetails = ({ data, counters, isLoading, isLoadingCounters, address3rd zilliqa, } = data || {}; + const multiplier = getUiMultiplier(data, multichainContext?.chain?.app_config); + const multiplierChangesCount = isLoadingCounters ? 0 : Number(counters?.ui_multiplier_changes_count ?? 0); + return ( <DetailedInfo.Container> { zilliqa?.zrc2_address_hash && ( @@ -123,6 +122,25 @@ const TokenDetails = ({ data, counters, isLoading, isLoadingCounters, address3rd </> ) } + { multiplier && ( + <> + <DetailedInfo.ItemLabel + hint="Token amounts shown are scaled by this factor compared to the raw ERC-20 token" + isLoading={ isLoading } + > + Multiplier + </DetailedInfo.ItemLabel> + <DetailedInfo.ItemValue multiRow> + <Skeleton loading={ isLoading } display="inline-block"> + <span>{ formatUiMultiplier(multiplier) }</span> + </Skeleton> + { hash && !isLoading && multiplierChangesCount > 0 && ( + <TokenMultiplierHistoryInline hash={ hash } changesCount={ multiplierChangesCount }/> + ) } + </DetailedInfo.ItemValue> + </> + ) } + { marketCap && ( <> <DetailedInfo.ItemLabel @@ -182,6 +200,7 @@ const TokenDetails = ({ data, counters, isLoading, isLoadingCounters, address3rd asset={ <chakra.span maxW="50%" overflow="hidden" textOverflow="ellipsis"> { symbol }</chakra.span> } accuracy={ 3 } decimals={ decimals ?? '0' } + multiplier={ multiplier } loading={ isLoading } w="100%" /> @@ -229,30 +248,13 @@ const TokenDetails = ({ data, counters, isLoading, isLoadingCounters, address3rd </> ) } - { type !== 'ERC-20' && ( + { !isFungibleTokenType(type) && ( <TokenNftMarketplaces hash={ hash } isLoading={ isLoading } - appActionData={ appActionData } - source="NFT collection" /> ) } - { (type !== 'ERC-20' && config.slices.token.nft.marketplaces.length === 0 && appActionData) && ( - <> - <DetailedInfo.ItemLabel - hint="Link to the dapp" - > - Dapp - </DetailedInfo.ItemLabel> - <DetailedInfo.ItemValue - py="1px" - > - <AppActionButton data={ appActionData } height="30px" source="NFT collection"/> - </DetailedInfo.ItemValue> - </> - ) } - <DetailedInfoSponsoredItem isLoading={ isLoading }/> { ((address3rdPartyWidgets ?? []).length > 0) && ( diff --git a/src/slices/token/pages/details/info/TokenMultiplierHistoryInline.pw.tsx b/src/slices/token/pages/details/info/TokenMultiplierHistoryInline.pw.tsx new file mode 100644 index 00000000000..cea10e6e9a1 --- /dev/null +++ b/src/slices/token/pages/details/info/TokenMultiplierHistoryInline.pw.tsx @@ -0,0 +1,27 @@ +import { tokenInfoERC8056 } from 'src/slices/token/mocks/info'; +import { tokenUiMultiplierChangesOverflow } from 'src/slices/token/mocks/ui-multiplier'; + +import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; +import { expect, test } from 'playwright/lib'; + +import TokenMultiplierHistoryInline from './TokenMultiplierHistoryInline'; + +const hash = tokenInfoERC8056.address_hash; + +test('base view +@mobile', async({ render, mockApiResponse, mockEnvs }) => { + await mockEnvs(ENVS_MAP.additionalTokenTypes); + await mockApiResponse( + 'core:token_ui_multiplier_changes', + tokenUiMultiplierChangesOverflow, + { pathParams: { hash } }, + ); + + const component = await render( + <TokenMultiplierHistoryInline hash={ hash } changesCount={ 7 }/>, + ); + + await component.getByText('View history').click(); + await expect(component.getByRole('link', { name: 'View all' })).toBeVisible(); + + await expect(component).toHaveScreenshot(); +}); diff --git a/src/slices/token/pages/details/info/TokenMultiplierHistoryInline.tsx b/src/slices/token/pages/details/info/TokenMultiplierHistoryInline.tsx new file mode 100644 index 00000000000..3e28af044ce --- /dev/null +++ b/src/slices/token/pages/details/info/TokenMultiplierHistoryInline.tsx @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Box, Grid, GridItem, Text } from '@chakra-ui/react'; +import React from 'react'; + +import useApiQuery from 'src/api/hooks/useApiQuery'; + +import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; +import TokenMultiplierChangeStatusTag from 'src/slices/token/components/ui-multiplier/TokenMultiplierChangeStatusTag'; +import TokenMultiplierChangeValue from 'src/slices/token/components/ui-multiplier/TokenMultiplierChangeValue'; +import { TOKEN_UI_MULTIPLIER_CHANGE } from 'src/slices/token/stubs'; +import { getUiMultiplierChangeStatuses } from 'src/slices/token/utils/ui-multiplier'; +import TxEntity from 'src/slices/tx/components/entity/TxEntity'; + +import { useMultichainContext } from 'src/features/multichain/context'; + +import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; +import { generateListStub } from 'src/shared/pagination/utils'; +import { route } from 'src/shared/router/routes'; + +import { CollapsibleDetails } from 'src/toolkit/chakra/collapsible'; +import { Link } from 'src/toolkit/chakra/link'; +import { Skeleton } from 'src/toolkit/chakra/skeleton'; + +export const INLINE_HISTORY_MAX_ITEMS = 5; + +interface Props { + hash: string; + changesCount: number; +} + +const TokenMultiplierHistoryInline = ({ hash, changesCount }: Props) => { + const multichainContext = useMultichainContext(); + // latched on the first expand, so collapsing and re-expanding reuses the cached page instead of refetching it + const [ isEnabled, setIsEnabled ] = React.useState(false); + + const handleToggle = React.useCallback(() => { + setIsEnabled(true); + }, []); + + const query = useApiQuery('core:token_ui_multiplier_changes', { + pathParams: { hash }, + queryOptions: { + enabled: isEnabled, + placeholderData: generateListStub<'core:token_ui_multiplier_changes'>( + TOKEN_UI_MULTIPLIER_CHANGE, + Math.min(changesCount, INLINE_HISTORY_MAX_ITEMS), + { next_page_params: null }, + ), + }, + }); + + const viewAllUrl = route({ + pathname: '/token/[hash]', + query: { hash, tab: 'multiplier_history' }, + }, { chain: multichainContext?.chain }); + + const items = query.data?.items.slice(0, INLINE_HISTORY_MAX_ITEMS); + const isLoading = query.isPlaceholderData; + const statuses = items ? getUiMultiplierChangeStatuses(items, 1) : []; + + const content = (() => { + if (query.isError) { + return <Text textStyle="sm" color="text.secondary" mt={ 2 } w="100%">Unable to load the multiplier history.</Text>; + } + + if (!items || items.length === 0) { + return <Text textStyle="sm" color="text.secondary" mt={ 2 } w="100%">No multiplier changes found.</Text>; + } + + return ( + <Box + w="100%" + maxW={{ base: '100%', lg: undefined }} + overflowX={{ base: 'scroll', lg: 'unset' }} + > + <Grid + gridTemplateColumns="120px 100px 180px 170px 80px" + alignItems="center" + textStyle="sm" + bgColor={{ _light: 'blackAlpha.50', _dark: 'whiteAlpha.50' }} + p={{ base: 3, lg: 4 }} + mt={ 1 } + columnGap={ 5 } + rowGap={ 4 } + borderBottomRightRadius="base" + borderBottomLeftRadius="base" + w="fit-content" + > + <GridItem fontWeight={ 600 }>Txn hash</GridItem> + <GridItem fontWeight={ 600 }>Block</GridItem> + <GridItem fontWeight={ 600 }>Multiplier</GridItem> + <GridItem fontWeight={ 600 }> + Activation date + <TimeFormatToggle/> + </GridItem> + <GridItem fontWeight={ 600 }>Status</GridItem> + { items.map((item, index) => { + const status = statuses[index]; + return ( + <React.Fragment key={ `${ item.block_number }-${ item.log_index }` + (isLoading ? String(index) : '') }> + { item.transaction_hash ? ( + <TxEntity + hash={ item.transaction_hash } + isLoading={ isLoading } + noIcon + truncation="constant" + /> + ) : ( + <Skeleton loading={ isLoading } display="inline-block" color="text.secondary">N/A</Skeleton> + ) } + <BlockEntity number={ item.block_number } isLoading={ isLoading } noIcon/> + <TokenMultiplierChangeValue + oldMultiplier={ item.old_multiplier } + newMultiplier={ item.new_multiplier } + isLoading={ isLoading } + /> + <TimeWithTooltip + timestamp={ item.effective_at } + enableIncrement + isLoading={ isLoading } + color="text.secondary" + display="inline-block" + /> + { status ? + <TokenMultiplierChangeStatusTag status={ status } isLoading={ isLoading }/> : + <Skeleton loading={ isLoading } display="inline-block" color="text.secondary">N/A</Skeleton> } + </React.Fragment> + ); + }) } + </Grid> + { changesCount > INLINE_HISTORY_MAX_ITEMS && ( + <Link href={ viewAllUrl } textStyle="sm" variant="secondary" mt={ 2.5 } loading={ query.isPlaceholderData }> + View all + </Link> + ) } + </Box> + ); + })(); + + return ( + <CollapsibleDetails + noScroll + text={ [ 'View history', 'Hide history' ] } + onClick={ handleToggle } + variant="secondary" + display="block" + ml={ 3 } + > + { content } + </CollapsibleDetails> + ); +}; + +export default React.memo(TokenMultiplierHistoryInline); diff --git a/src/slices/token/pages/details/info/TokenNftMarketplaces.tsx b/src/slices/token/pages/details/info/TokenNftMarketplaces.tsx index d0e0728837c..18fd280544e 100644 --- a/src/slices/token/pages/details/info/TokenNftMarketplaces.tsx +++ b/src/slices/token/pages/details/info/TokenNftMarketplaces.tsx @@ -3,13 +3,8 @@ import { HStack } from '@chakra-ui/react'; import React from 'react'; -import type { AddressMetadataTagFormatted } from 'src/features/address-metadata/types/client'; - -import AppActionButton from 'src/features/address-metadata/components/AppActionButton'; - import config from 'src/config'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; -import TextSeparator from 'src/shared/texts/TextSeparator'; import { Image } from 'src/toolkit/chakra/image'; import { Link } from 'src/toolkit/chakra/link'; @@ -20,11 +15,9 @@ interface Props { hash: string | undefined; id?: string; isLoading?: boolean; - appActionData?: AddressMetadataTagFormatted['meta']; - source: 'NFT collection' | 'NFT item'; } -const TokenNftMarketplaces = ({ hash, id, isLoading, appActionData, source }: Props) => { +const TokenNftMarketplaces = ({ hash, id, isLoading }: Props) => { if (!hash || config.slices.token.nft.marketplaces.length === 0) { return null; } @@ -61,9 +54,7 @@ const TokenNftMarketplaces = ({ hash, id, isLoading, appActionData, source }: Pr > Marketplaces </DetailedInfo.ItemLabel> - <DetailedInfo.ItemValue - py={ appActionData ? '1px' : '6px' } - > + <DetailedInfo.ItemValue py="6px"> <Skeleton loading={ isLoading } display="flex" flexWrap="wrap" alignItems="center"> <HStack gap={ 3 }> { items.map((item) => { @@ -81,12 +72,6 @@ const TokenNftMarketplaces = ({ hash, id, isLoading, appActionData, source }: Pr ); }) } </HStack> - { appActionData && ( - <> - <TextSeparator/> - <AppActionButton data={ appActionData } height="30px" source={ source }/> - </> - ) } </Skeleton> </DetailedInfo.ItemValue> </> diff --git a/src/slices/token/pages/details/info/__screenshots__/TokenMultiplierHistoryInline.pw.tsx_default_base-view-mobile-1.png b/src/slices/token/pages/details/info/__screenshots__/TokenMultiplierHistoryInline.pw.tsx_default_base-view-mobile-1.png new file mode 100644 index 00000000000..4be14cc9531 Binary files /dev/null and b/src/slices/token/pages/details/info/__screenshots__/TokenMultiplierHistoryInline.pw.tsx_default_base-view-mobile-1.png differ diff --git a/src/slices/token/pages/details/info/__screenshots__/TokenMultiplierHistoryInline.pw.tsx_mobile_base-view-mobile-1.png b/src/slices/token/pages/details/info/__screenshots__/TokenMultiplierHistoryInline.pw.tsx_mobile_base-view-mobile-1.png new file mode 100644 index 00000000000..5a7d88bb5a2 Binary files /dev/null and b/src/slices/token/pages/details/info/__screenshots__/TokenMultiplierHistoryInline.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/slices/token/pages/details/inventory/TokenInventory.pw.tsx b/src/slices/token/pages/details/inventory/TokenInventory.pw.tsx index 2b236bea135..07213291c3a 100644 --- a/src/slices/token/pages/details/inventory/TokenInventory.pw.tsx +++ b/src/slices/token/pages/details/inventory/TokenInventory.pw.tsx @@ -22,12 +22,18 @@ test('base view +@mobile', async({ render, mockAssetResponse, mockApiResponse }) }); await mockAssetResponse(tokenInstance.image_url as string, './playwright/mocks/image_s.jpg'); + const hooksConfig = { + router: { + query: { hash: tokenInfoERC721a.address_hash, holder_address_hash: tokenInfoERC721a.address_hash }, + }, + }; + const component = await render( <TokenInventory hash={ tokenInfoERC721a.address_hash } token={ tokenInfoERC721a } - ownerFilter={ tokenInfoERC721a.address_hash } />, + { hooksConfig }, ); await expect(component).toHaveScreenshot(); diff --git a/src/slices/token/pages/details/inventory/TokenInventory.tsx b/src/slices/token/pages/details/inventory/TokenInventory.tsx index f4a2f916dbe..970bf585982 100644 --- a/src/slices/token/pages/details/inventory/TokenInventory.tsx +++ b/src/slices/token/pages/details/inventory/TokenInventory.tsx @@ -16,8 +16,9 @@ import useIsMobile from 'src/shared/hooks/useIsMobile'; import DataList from 'src/shared/lists/DataList'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; +import getQueryParamString from 'src/shared/router/get-query-param-string'; import TokenInventoryItem from './TokenInventoryItem'; @@ -28,22 +29,21 @@ interface Props { hash: string; token: schemas['Token'] | undefined; isLoading?: boolean; - ownerFilter?: string; }; -const TokenInventory = ({ hash, token, isLoading: isLoadingProp, ownerFilter }: Props) => { +const TokenInventory = ({ hash, token, isLoading: isLoadingProp }: Props) => { const isMobile = useIsMobile(); - const inventoryQuery = useQueryWithPages({ + const inventoryQuery = useApiPaginatedQuery({ resourceName: 'core:token_inventory', pathParams: { hash }, - filters: ownerFilter ? { holder_address_hash: ownerFilter } : {}, options: { placeholderData: generateListStub<'core:token_inventory'>(TOKEN_INSTANCE_ITEM, 50, { next_page_params: { unique_token: 1 } }), }, }); - const isLoading = isLoadingProp || Boolean(inventoryQuery.isPlaceholderData); + const ownerFilter = getQueryParamString(inventoryQuery.filters.holder_address_hash) || undefined; + const isLoading = isLoadingProp || inventoryQuery.isInitialLoading; const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: inventoryQuery.data?.items, @@ -52,9 +52,10 @@ const TokenInventory = ({ hash, token, isLoading: isLoadingProp, ownerFilter }: resetKey: inventoryQuery.queryHash, }); + const { onFilterChange } = inventoryQuery; const resetOwnerFilter = React.useCallback(() => { - inventoryQuery.onFilterChange({}); - }, [ inventoryQuery ]); + onFilterChange({}); + }, [ onFilterChange ]); const ownerFilterComponent = ownerFilter && ( <Flex @@ -91,7 +92,7 @@ const TokenInventory = ({ hash, token, isLoading: isLoadingProp, ownerFilter }: > { items.slice(0, renderedItemsNum).map((item, index) => ( <TokenInventoryItem - key={ item.id + '_' + index + (inventoryQuery.isPlaceholderData ? '_' + 'placeholder' : '') } + key={ item.id + (isLoading ? '_' + index : '') } item={ item } isLoading={ isLoading } token={ token } @@ -112,6 +113,7 @@ const TokenInventory = ({ hash, token, isLoading: isLoadingProp, ownerFilter }: description: 'No tokens found for the selected owner.', }} actionBar={ actionBar } + isTransitioning={ inventoryQuery.isTransitioning } > { isMobile && ownerFilterComponent } { content } diff --git a/src/slices/token/pages/details/inventory/TokenInventoryItem.tsx b/src/slices/token/pages/details/inventory/TokenInventoryItem.tsx index 6b4a244d98f..8c70ba1959a 100644 --- a/src/slices/token/pages/details/inventory/TokenInventoryItem.tsx +++ b/src/slices/token/pages/details/inventory/TokenInventoryItem.tsx @@ -14,8 +14,7 @@ import useIsMobile from 'src/shared/hooks/useIsMobile'; import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedTextTooltip } from 'src/toolkit/components/truncation/TruncatedTextTooltip'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; interface Props { item: schemas['TokenInstanceInTokenInstancesList']; @@ -57,20 +56,15 @@ const TokenInventoryItem = ({ item, token, isLoading }: Props) => { { item.id && ( <Flex mb={ 2 } ml={ 1 }> <Text whiteSpace="pre" color="text.secondary">ID# </Text> - <TruncatedTextTooltip label={ item.id }> - <Skeleton loading={ isLoading } overflow="hidden"> - <Link - overflow="hidden" - textOverflow="ellipsis" - whiteSpace="nowrap" - display="block" - loading={ isLoading } - href={ url } - > - { item.id } - </Link> - </Skeleton> - </TruncatedTextTooltip> + <Link + href={ url } + loading={ isLoading } + display="block" + overflow="hidden" + minW={ 0 } + > + <Truncate value={ item.id } type="end" display="block" w="100%"/> + </Link> </Flex> ) } { item.owner && ( diff --git a/src/slices/token/pages/details/inventory/__screenshots__/TokenInventory.pw.tsx_default_base-view-mobile-1.png b/src/slices/token/pages/details/inventory/__screenshots__/TokenInventory.pw.tsx_default_base-view-mobile-1.png index 99e875fbc7d..702624947a8 100644 Binary files a/src/slices/token/pages/details/inventory/__screenshots__/TokenInventory.pw.tsx_default_base-view-mobile-1.png and b/src/slices/token/pages/details/inventory/__screenshots__/TokenInventory.pw.tsx_default_base-view-mobile-1.png differ diff --git a/src/slices/token/pages/details/inventory/__screenshots__/TokenInventory.pw.tsx_mobile_base-view-mobile-1.png b/src/slices/token/pages/details/inventory/__screenshots__/TokenInventory.pw.tsx_mobile_base-view-mobile-1.png index 8cbf1035b70..290b3b4c969 100644 Binary files a/src/slices/token/pages/details/inventory/__screenshots__/TokenInventory.pw.tsx_mobile_base-view-mobile-1.png and b/src/slices/token/pages/details/inventory/__screenshots__/TokenInventory.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistory.tsx b/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistory.tsx new file mode 100644 index 00000000000..92b54267d72 --- /dev/null +++ b/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistory.tsx @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { schemas } from '@blockscout/api-types'; + +import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; + +import { TOKEN_UI_MULTIPLIER_CHANGE } from 'src/slices/token/stubs'; + +import DataList from 'src/shared/lists/DataList'; +import Pagination from 'src/shared/pagination/Pagination'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; +import { generateListStub } from 'src/shared/pagination/utils'; + +import TokenMultiplierHistoryTable from './TokenMultiplierHistoryTable'; + +interface Props { + token: schemas['Token'] | undefined; + isLoading: boolean; +} + +const TokenMultiplierHistory = ({ token, isLoading }: Props) => { + const query = useApiPaginatedQuery({ + resourceName: 'core:token_ui_multiplier_changes', + pathParams: { hash: token?.address_hash }, + options: { + enabled: Boolean(token?.address_hash) && !isLoading, + placeholderData: generateListStub<'core:token_ui_multiplier_changes'>(TOKEN_UI_MULTIPLIER_CHANGE, 50, { next_page_params: null }), + }, + }); + + const actionBar = query.pagination.isVisible ? ( + <ActionBar mt={ -6 }> + <Pagination ml="auto" { ...query.pagination }/> + </ActionBar> + ) : null; + + const content = query.data?.items ? ( + <TokenMultiplierHistoryTable + data={ query.data.items } + page={ query.pagination.page } + top={ query.pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 } + isLoading={ query.isInitialLoading } + resetKey={ query.queryHash } + /> + ) : null; + + return ( + <DataList + isError={ query.isError } + itemsNum={ query.data?.items.length } + emptyText="There are no multiplier changes for this token." + actionBar={ actionBar } + isTransitioning={ query.isTransitioning } + > + { content } + </DataList> + ); +}; + +export default TokenMultiplierHistory; diff --git a/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistoryTable.pw.tsx b/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistoryTable.pw.tsx new file mode 100644 index 00000000000..704c4676b40 --- /dev/null +++ b/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistoryTable.pw.tsx @@ -0,0 +1,16 @@ +import { tokenUiMultiplierChanges } from 'src/slices/token/mocks/ui-multiplier'; + +import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; +import { expect, test } from 'playwright/lib'; + +import TokenMultiplierHistoryTable from './TokenMultiplierHistoryTable'; + +test('base view', async({ render, mockEnvs }) => { + await mockEnvs(ENVS_MAP.additionalTokenTypes); + + const component = await render( + <TokenMultiplierHistoryTable data={ tokenUiMultiplierChanges.items } page={ 1 }/>, + ); + + await expect(component).toHaveScreenshot(); +}); diff --git a/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistoryTable.tsx b/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistoryTable.tsx new file mode 100644 index 00000000000..ee0f374f192 --- /dev/null +++ b/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistoryTable.tsx @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import { Box } from '@chakra-ui/react'; +import React from 'react'; + +import type { schemas } from '@blockscout/api-types'; + +import { getUiMultiplierChangeStatuses } from 'src/slices/token/utils/ui-multiplier'; + +import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; +import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; + +import { TableBody, TableColumnHeader, TableContainerScrollable, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; + +import TokenMultiplierHistoryTableItem from './TokenMultiplierHistoryTableItem'; + +interface Props { + data: Array<schemas['TokenUIMultiplierChange']>; + page: number; + top?: number; + isLoading?: boolean; + resetKey?: string; +} + +const TokenMultiplierHistoryTable = ({ data, page, top, isLoading, resetKey }: Props) => { + const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data, isEnabled: !isLoading, resetKey }); + const statuses = React.useMemo(() => getUiMultiplierChangeStatuses(data, page), [ data, page ]); + + return ( + <> + <TableContainerScrollable> + <TableRoot minW="1000px"> + <TableHeaderSticky top={ top }> + <TableRow> + <TableColumnHeader width="20%">Txn hash</TableColumnHeader> + <TableColumnHeader width="16%"> + Timestamp + <TimeFormatToggle/> + </TableColumnHeader> + <TableColumnHeader width="14%">Block</TableColumnHeader> + <TableColumnHeader width="18%">Multiplier</TableColumnHeader> + <TableColumnHeader width="20%"> + Activation date + <TimeFormatToggle/> + </TableColumnHeader> + <TableColumnHeader width="12%">Status</TableColumnHeader> + </TableRow> + </TableHeaderSticky> + <TableBody> + { data.slice(0, renderedItemsNum).map((item, index) => ( + <TokenMultiplierHistoryTableItem + key={ `${ item.block_number }-${ item.log_index }` + (isLoading ? String(index) : '') } + data={ item } + status={ statuses[index] } + page={ page } + isLoading={ isLoading } + /> + )) } + </TableBody> + </TableRoot> + </TableContainerScrollable> + <Box ref={ cutRef } h={ 0 }/> + </> + ); +}; + +export default React.memo(TokenMultiplierHistoryTable); diff --git a/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistoryTableItem.tsx b/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistoryTableItem.tsx new file mode 100644 index 00000000000..d267e289bc8 --- /dev/null +++ b/src/slices/token/pages/details/multiplier-history/TokenMultiplierHistoryTableItem.tsx @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { schemas } from '@blockscout/api-types'; + +import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; +import TokenMultiplierChangeStatusTag from 'src/slices/token/components/ui-multiplier/TokenMultiplierChangeStatusTag'; +import TokenMultiplierChangeValue from 'src/slices/token/components/ui-multiplier/TokenMultiplierChangeValue'; +import type { UiMultiplierChangeStatus } from 'src/slices/token/utils/ui-multiplier'; +import TxEntity from 'src/slices/tx/components/entity/TxEntity'; + +import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; + +import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { TableCell, TableRow } from 'src/toolkit/chakra/table'; + +interface Props { + data: schemas['TokenUIMultiplierChange']; + status: UiMultiplierChangeStatus; + page: number; + isLoading?: boolean; +} + +const TokenMultiplierHistoryTableItem = ({ data, status, page, isLoading }: Props) => { + return ( + <TableRow> + <TableCell verticalAlign="middle"> + { data.transaction_hash ? ( + <TxEntity + hash={ data.transaction_hash } + isLoading={ isLoading } + noIcon + fontWeight={ 700 } + truncation="constant_long" + /> + ) : ( + <Skeleton loading={ isLoading } display="inline-block" color="text.secondary">N/A</Skeleton> + ) } + </TableCell> + <TableCell verticalAlign="middle"> + <TimeWithTooltip + timestamp={ data.timestamp } + enableIncrement={ page === 1 } + isLoading={ isLoading } + color="text.secondary" + display="inline-block" + /> + </TableCell> + <TableCell verticalAlign="middle"> + <BlockEntity + number={ data.block_number } + isLoading={ isLoading } + noIcon + /> + </TableCell> + <TableCell verticalAlign="middle"> + <TokenMultiplierChangeValue + oldMultiplier={ data.old_multiplier } + newMultiplier={ data.new_multiplier } + isLoading={ isLoading } + /> + </TableCell> + <TableCell verticalAlign="middle"> + <TimeWithTooltip + timestamp={ data.effective_at } + enableIncrement={ page === 1 } + isLoading={ isLoading } + color="text.secondary" + display="inline-block" + /> + </TableCell> + <TableCell verticalAlign="middle"> + <TokenMultiplierChangeStatusTag status={ status } isLoading={ isLoading }/> + </TableCell> + </TableRow> + ); +}; + +export default React.memo(TokenMultiplierHistoryTableItem); diff --git a/src/slices/token/pages/details/multiplier-history/__screenshots__/TokenMultiplierHistoryTable.pw.tsx_default_base-view-1.png b/src/slices/token/pages/details/multiplier-history/__screenshots__/TokenMultiplierHistoryTable.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..72490af00f1 Binary files /dev/null and b/src/slices/token/pages/details/multiplier-history/__screenshots__/TokenMultiplierHistoryTable.pw.tsx_default_base-view-1.png differ diff --git a/src/slices/token/pages/index/Tokens.pw.tsx b/src/slices/token/pages/index/Tokens.pw.tsx index 59743d00f6f..8cd422ee7da 100644 --- a/src/slices/token/pages/index/Tokens.pw.tsx +++ b/src/slices/token/pages/index/Tokens.pw.tsx @@ -1,10 +1,9 @@ import { Box } from '@chakra-ui/react'; -import React from 'react'; import * as tokens from 'src/slices/token/mocks/info'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; -import { test, expect } from 'playwright/lib'; +import { expect, test } from 'playwright/lib'; import Tokens from './Tokens'; @@ -28,7 +27,7 @@ const allTokens = { }; // FIXME: test is flaky, screenshot in docker container is different from local -test.skip('base view +@mobile +@dark-mode', async({ render, mockApiResponse }) => { +test.skip('base view +@dark-mode', async({ render, mockApiResponse }) => { await mockApiResponse('core:tokens', allTokens); @@ -42,7 +41,7 @@ test.skip('base view +@mobile +@dark-mode', async({ render, mockApiResponse }) = await expect(component).toHaveScreenshot(); }); -test('with search +@mobile +@dark-mode', async({ page, render, mockApiResponse }) => { +test('with search +@dark-mode', async({ page, render, mockApiResponse }) => { const filteredTokens = { items: [ tokens.tokenInfoERC20a, tokens.tokenInfoERC20b, tokens.tokenInfoERC20c, @@ -50,7 +49,12 @@ test('with search +@mobile +@dark-mode', async({ page, render, mockApiResponse } next_page_params: null, }; - await mockApiResponse('core:tokens', allTokens); + const hooksConfig = { + router: { + query: { q: 'foo' }, + }, + }; + const filteredTokensApiUrl = await mockApiResponse('core:tokens', filteredTokens, { queryParams: { q: 'foo' } }); const component = await render( @@ -58,14 +62,10 @@ test('with search +@mobile +@dark-mode', async({ page, render, mockApiResponse } <Box h={{ base: '134px', lg: 6 }}/> <Tokens/> </div>, + { hooksConfig }, ); - const requestPromise = page.waitForRequest(filteredTokensApiUrl); - await component.getByRole('textbox', { name: 'Token name, address or symbol' }).focus(); - await component.getByRole('textbox', { name: 'Token name, address or symbol' }).fill('foo'); - await component.getByRole('textbox', { name: 'Token name, address or symbol' }).blur(); - - await requestPromise; + await page.waitForResponse(filteredTokensApiUrl); await expect(component).toHaveScreenshot({ maxDiffPixels: 20 }); }); @@ -83,22 +83,15 @@ test.describe('bridged tokens', () => { market_cap: null, }, }; - const bridgedFilteredTokens = { - items: [ - tokens.bridgedTokenC, - ], - next_page_params: null, - }; const hooksConfig = { router: { query: { tab: 'bridged' }, }, }; - test('base view', async({ render, page, mockApiResponse, mockEnvs }) => { + test('base view', async({ render, mockApiResponse, mockEnvs }) => { await mockEnvs(ENVS_MAP.bridgedTokens); await mockApiResponse('core:tokens_bridged', bridgedTokens); - const bridgedFilteredTokensApiUrl = await mockApiResponse('core:tokens_bridged', bridgedFilteredTokens, { queryParams: { chain_ids: '99' } }); const component = await render( <div> @@ -109,14 +102,5 @@ test.describe('bridged tokens', () => { ); await expect(component).toHaveScreenshot(); - - await component.getByRole('button', { name: /filter/i }).click(); - const requestPromise = page.waitForRequest(bridgedFilteredTokensApiUrl); - await page.locator('label').filter({ hasText: /poa/i }).click(); - await page.click('body'); - - await requestPromise; - - await expect(component).toHaveScreenshot(); }); }); diff --git a/src/slices/token/pages/index/Tokens.tsx b/src/slices/token/pages/index/Tokens.tsx index ca643ad7d24..93d19ae1741 100644 --- a/src/slices/token/pages/index/Tokens.tsx +++ b/src/slices/token/pages/index/Tokens.tsx @@ -1,13 +1,12 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Box, HStack } from '@chakra-ui/react'; -import { useRouter } from 'next/router'; import React from 'react'; import type { TokenType } from 'src/slices/token/types/api'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; -import ActionBar from 'src/shell/page/action-bar/ActionBar'; +import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; import PageTitle from 'src/shell/page/title/PageTitle'; import TokenTypeFilter from 'src/slices/token/components/TokenTypeFilter'; @@ -26,26 +25,12 @@ import PopoverFilter from 'src/shared/filters/PopoverFilter'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import Sort from 'src/shared/sort/Sort'; -import type { SlotProps } from 'src/toolkit/components/AdaptiveTabs/AdaptiveTabsList'; import { FilterInput } from 'src/toolkit/components/filters/FilterInput'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; -const TAB_LIST_PROPS = { - marginBottom: 0, - pt: 6, - pb: 6, - marginTop: -5, - alignItems: 'center', -}; -const TABS_HEIGHT = 88; - -const TABS_RIGHT_SLOT_PROPS: SlotProps = { - ml: 8, - widthAllocation: 'available', -}; - const bridgedTokensFeature = config.features.bridgedTokens; const crossChainTxsFeature = config.features.crossChainTxs; @@ -67,8 +52,6 @@ const Tokens = () => { enabled: tab === 'bridged' && crossChainTxsFeature.isEnabled, }); - const hasMultipleTabs = bridgedTokensFeature.isEnabled || crossChainTxsFeature.isEnabled; - const pagination = (() => { if (tab === 'bridged') { if (crossChainTxsFeature.isEnabled) { @@ -193,10 +176,6 @@ const Tokens = () => { ); } - if (hasMultipleTabs) { - return null; - } - return ( <ActionBar> <HStack gap={ 3 }> @@ -208,21 +187,6 @@ const Tokens = () => { ); })(); - const tabsRightSlot = (() => { - if (hasMultipleTabs && !isMobile) { - return ( - <HStack justifyContent="space-between"> - <HStack gap={ 3 }> - { filter } - { searchInput } - </HStack> - <Pagination { ...pagination }/> - </HStack> - ); - } - return null; - })(); - const description = (() => { if (!bridgedTokensFeature.isEnabled) { return null; @@ -233,7 +197,7 @@ const Tokens = () => { }); return ( - <Box fontSize="sm" mb={ 4 } mt={ 1 } whiteSpace="pre-wrap" flexWrap="wrap"> + <Box fontSize="sm" mb={ 6 } whiteSpace="pre-wrap" flexWrap="wrap"> List of the tokens bridged through { bridgesListText } extensions </Box> ); @@ -250,7 +214,6 @@ const Tokens = () => { onSortChange={ allTokensQuery.onSortChange } actionBar={ actionBar } hasActiveFilters={ Boolean(allTokensQuery.searchTerm || allTokensQuery.tokenTypes) } - tableTop={ hasMultipleTabs ? TABS_HEIGHT : undefined } /> ), }, @@ -258,15 +221,16 @@ const Tokens = () => { id: 'bridged', title: 'Bridged', component: ( - <TokensList - query={ bridgedTokensQuery.query } - sort={ bridgedTokensQuery.sort } - onSortChange={ bridgedTokensQuery.onSortChange } - actionBar={ actionBar } - hasActiveFilters={ Boolean(bridgedTokensQuery.searchTerm || bridgedTokensQuery.bridgeChains) } - description={ description } - tableTop={ TABS_HEIGHT } - /> + <> + { description } + <TokensList + query={ bridgedTokensQuery.query } + sort={ bridgedTokensQuery.sort } + onSortChange={ bridgedTokensQuery.onSortChange } + actionBar={ actionBar } + hasActiveFilters={ Boolean(bridgedTokensQuery.searchTerm || bridgedTokensQuery.bridgeChains) } + /> + </> ), } : undefined, crossChainTxsFeature.isEnabled ? { @@ -279,7 +243,7 @@ const Tokens = () => { onSortChange={ bridgedTokensQueryCrossChain.onSortChange } actionBar={ actionBar } hasActiveFilters={ Boolean(bridgedTokensQueryCrossChain.searchTerm) } - tableTop={ TABS_HEIGHT } + tableTop={ ACTION_BAR_HEIGHT_DESKTOP } /> ), } : undefined, @@ -291,13 +255,7 @@ const Tokens = () => { title="Tokens" withTextAd /> - <RoutedTabs - tabs={ tabs } - listProps={ isMobile ? undefined : TAB_LIST_PROPS } - rightSlot={ tabsRightSlot } - rightSlotProps={ tabsRightSlot ? TABS_RIGHT_SLOT_PROPS : undefined } - stickyEnabled={ !isMobile } - /> + <RoutedTabs tabs={ tabs }/> </> ); }; diff --git a/src/slices/token/pages/index/TokensList.tsx b/src/slices/token/pages/index/TokensList.tsx index 14e148873c4..cf6931486aa 100644 --- a/src/slices/token/pages/index/TokensList.tsx +++ b/src/slices/token/pages/index/TokensList.tsx @@ -1,78 +1,45 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box } from '@chakra-ui/react'; import React from 'react'; import type { TokensSortingValue } from 'src/slices/token/types/api'; import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; import DataList from 'src/shared/lists/DataList'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; import type { OnValueChangeHandler } from 'src/toolkit/chakra/select'; +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import TokensListItem from './TokensListItem'; import TokensTable from './TokensTable'; interface Props { - query: QueryWithPagesResult<'core:tokens'> | QueryWithPagesResult<'core:tokens_bridged'> | QueryWithPagesResult<'multichainAggregator:tokens'>; + query: ApiPaginatedQueryResult<'core:tokens'> | ApiPaginatedQueryResult<'core:tokens_bridged'> | ApiPaginatedQueryResult<'multichainAggregator:tokens'>; onSortChange?: OnValueChangeHandler; sort?: TokensSortingValue; actionBar?: React.ReactNode; hasActiveFilters: boolean; - description?: React.ReactNode; - tableTop?: number; } -const Tokens = ({ query, onSortChange, sort, actionBar, description, hasActiveFilters, tableTop }: Props) => { +const Tokens = ({ query, onSortChange, sort, actionBar, hasActiveFilters }: Props) => { - const { isError, isPlaceholderData, data, pagination } = query; - - const { cutRef, renderedItemsNum } = useLazyRenderedList({ - list: data?.items, - isEnabled: !isPlaceholderData, - resetKey: query.queryHash, - }); + const { isError, isInitialLoading, isTransitioning, data, pagination } = query; if (isError) { return <ApiFetchAlert/>; } const content = data?.items ? ( - <> - <Box hideFrom="lg"> - { description } - <Box> - { data.items.slice(0, renderedItemsNum).map((item, index) => { - const chainIds = 'chain_infos' in item ? Object.keys(item.chain_infos).join(',') : undefined; - - return ( - <TokensListItem - key={ item.address_hash + (isPlaceholderData ? index : '') + (chainIds ? chainIds : '') } - token={ item } - index={ index } - page={ pagination.page } - isLoading={ isPlaceholderData } - /> - ); - }) } - </Box> - <Box ref={ cutRef } h={ 0 }/> - </Box> - <Box hideBelow="lg"> - { description } - <TokensTable - items={ data.items } - page={ pagination.page } - isLoading={ isPlaceholderData } - setSorting={ onSortChange } - sorting={ sort } - top={ tableTop } - resetKey={ query.queryHash } - /> - </Box> - </> + <TableContainerScrollable> + <TokensTable + items={ data.items } + page={ pagination.page } + isLoading={ isInitialLoading } + setSorting={ onSortChange } + sorting={ sort } + resetKey={ query.queryHash } + /> + </TableContainerScrollable> ) : null; return ( @@ -85,6 +52,7 @@ const Tokens = ({ query, onSortChange, sort, actionBar, description, hasActiveFi term: 'token', }} actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/slices/token/pages/index/TokensListItem.tsx b/src/slices/token/pages/index/TokensListItem.tsx deleted file mode 100644 index 43e6d77e651..00000000000 --- a/src/slices/token/pages/index/TokensListItem.tsx +++ /dev/null @@ -1,144 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Flex, HStack, Grid, GridItem } from '@chakra-ui/react'; -import BigNumber from 'bignumber.js'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { AggregatedTokenInfo } from 'src/features/multichain/types/client'; -import { getTokenTypeName } from 'src/slices/token/utils/token-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; -import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; - -import multichainConfig from 'src/features/multichain/chains-config'; -import TokenAddToWallet from 'src/features/web3-wallet/components/TokenAddToWallet'; - -import config from 'src/config'; -import getItemIndex from 'src/shared/lists/get-item-index'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import SimpleValue from 'src/shared/values/entity/SimpleValue'; -import { DEFAULT_ACCURACY_USD } from 'src/shared/values/entity/utils'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { Tag } from 'src/toolkit/chakra/tag'; - -type Props = { - token: schemas['Token'] | AggregatedTokenInfo; - index: number; - page: number; - isLoading?: boolean; -}; - -const bridgedTokensFeature = config.features.bridgedTokens; - -const TokensListItem = ({ - token, - page, - index, - isLoading, -}: Props) => { - - const { - address_hash: addressHash, - exchange_rate: exchangeRate, - type, - holders_count: holdersCount, - circulating_market_cap: marketCap, - } = token; - - const originalChainId = 'origin_chain_id' in token ? token.origin_chain_id : undefined; - const chainInfos = 'chain_infos' in token ? token.chain_infos : undefined; - - const bridgedChainTag = bridgedTokensFeature.isEnabled ? - bridgedTokensFeature.chains.find(({ id }) => id === originalChainId)?.short_title : - undefined; - - const filecoinRobustAddress = 'filecoin_robust_address' in token ? token.filecoin_robust_address : undefined; - - const chainInfo = React.useMemo(() => { - if (!chainInfos) { - return; - } - - const chainId = Object.keys(chainInfos)[0]; - const chain = multichainConfig()?.chains.find((chain) => chain.id === chainId); - return chain; - }, [ chainInfos ]); - - return ( - <ListItemMobile rowGap={ 3 }> - <Grid - width="100%" - gridTemplateColumns="minmax(0, 1fr)" - > - <GridItem display="flex"> - <TokenEntity - token={ token } - chain={ chainInfo } - isLoading={ isLoading } - jointSymbol - noCopy - w="auto" - textStyle="sm" - fontWeight="700" - noLink={ type === 'NATIVE' } - /> - <Flex ml={ 3 } flexShrink={ 0 } columnGap={ 1 }> - <Tag loading={ isLoading }>{ getTokenTypeName(type, chainInfo?.app_config) }</Tag> - { bridgedChainTag && <Tag loading={ isLoading }>{ bridgedChainTag }</Tag> } - </Flex> - <Skeleton loading={ isLoading } textStyle="sm" ml="auto" color="text.secondary" minW="24px" textAlign="right"> - <span>{ getItemIndex(index, page) }</span> - </Skeleton> - </GridItem> - </Grid> - { type !== 'NATIVE' && ( - <Flex justifyContent="space-between" alignItems="center" width="150px" ml={ 7 } mt={ -2 }> - <AddressEntity - address={{ hash: addressHash, filecoin: { robust: filecoinRobustAddress ?? null, actor_type: null, id: null } }} - isLoading={ isLoading } - truncation="constant" - link={{ variant: 'secondary' }} - noIcon - /> - <TokenAddToWallet token={ token } isLoading={ isLoading }/> - </Flex> - ) } - { exchangeRate && ( - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } textStyle="sm" fontWeight={ 500 }>Price</Skeleton> - <SimpleValue - value={ BigNumber(exchangeRate) } - loading={ isLoading } - accuracy={ 4 } - prefix="$" - textStyle="sm" - color="text.secondary" - /> - </HStack> - ) } - { marketCap && ( - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } textStyle="sm" fontWeight={ 500 }>On-chain market cap</Skeleton> - <SimpleValue - value={ BigNumber(marketCap) } - loading={ isLoading } - prefix="$" - accuracy={ DEFAULT_ACCURACY_USD } - textStyle="sm" - color="text.secondary" - /> - </HStack> - ) } - { holdersCount && ( - <HStack gap={ 3 }> - <Skeleton loading={ isLoading } textStyle="sm" fontWeight={ 500 }>Holders</Skeleton> - <Skeleton loading={ isLoading } textStyle="sm" color="text.secondary"><span>{ Number(holdersCount).toLocaleString() }</span></Skeleton> - </HStack> - ) } - </ListItemMobile> - ); -}; - -export default TokensListItem; diff --git a/src/slices/token/pages/index/TokensTable.tsx b/src/slices/token/pages/index/TokensTable.tsx index 86cce96bf66..cbe627dcf91 100644 --- a/src/slices/token/pages/index/TokensTable.tsx +++ b/src/slices/token/pages/index/TokensTable.tsx @@ -8,6 +8,7 @@ import type { TokensSortingField, TokensSortingValue } from 'src/slices/token/ty import { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import { default as getNextSortValueShared } from 'src/shared/sort/get-next-sort-value'; @@ -24,8 +25,16 @@ const SORT_SEQUENCE: Record<TokensSortingField, Array<TokensSortingValue>> = { const getNextSortValue = (getNextSortValueShared<TokensSortingField, TokensSortingValue>).bind(undefined, SORT_SEQUENCE); +type Item = schemas['Token'] | AggregatedTokenInfo; + +const getBaseKey = (item: Item): string => { + const chainIds = 'chain_infos' in item ? Object.keys(item.chain_infos).join(',') : undefined; + + return item.address_hash + (chainIds ? chainIds : ''); +}; + type Props = { - items: Array<schemas['Token']> | Array<AggregatedTokenInfo>; + items: Array<Item>; page: number; sorting?: TokensSortingValue; setSorting?: OnValueChangeHandler; @@ -38,6 +47,7 @@ const TokensTable = ({ items, page, isLoading, sorting, setSorting, top, resetKe const hasSorting = setSorting && sorting; const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: items, isEnabled: !isLoading, resetKey }); + const keys = useUniqueKeys(items, getBaseKey); const sort = React.useCallback((field: TokensSortingField) => { if (!hasSorting) { @@ -48,7 +58,7 @@ const TokensTable = ({ items, page, isLoading, sorting, setSorting, top, resetKe }, [ sorting, setSorting, hasSorting ]); return ( - <TableRoot> + <TableRoot minW="900px"> <TableHeaderSticky top={ top ?? ACTION_BAR_HEIGHT_DESKTOP }> <TableRow> <TableColumnHeader w="50%">Token</TableColumnHeader> @@ -100,19 +110,15 @@ const TokensTable = ({ items, page, isLoading, sorting, setSorting, top, resetKe </TableRow> </TableHeaderSticky> <TableBody> - { items.slice(0, renderedItemsNum).map((item, index) => { - const chainIds = 'chain_infos' in item ? Object.keys(item.chain_infos).join(',') : undefined; - - return ( - <TokensTableItem - key={ item.address_hash + (isLoading ? index : '') + (chainIds ? chainIds : '') } - token={ item } - index={ index } - page={ page } - isLoading={ isLoading } - /> - ); - }) } + { items.slice(0, renderedItemsNum).map((item, index) => ( + <TokensTableItem + key={ keys[index] } + token={ item } + index={ index } + page={ page } + isLoading={ isLoading } + /> + )) } <TableRow ref={ cutRef }/> </TableBody> </TableRoot> diff --git a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_dark-color-mode_with-search-dark-mode-1.png b/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_dark-color-mode_with-search-dark-mode-1.png new file mode 100644 index 00000000000..6c4df2b8efa Binary files /dev/null and b/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_dark-color-mode_with-search-dark-mode-1.png differ diff --git a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_dark-color-mode_with-search-mobile-dark-mode-1.png b/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_dark-color-mode_with-search-mobile-dark-mode-1.png deleted file mode 100644 index be47e1437fc..00000000000 Binary files a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_dark-color-mode_with-search-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_bridged-tokens-base-view-1.png b/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_bridged-tokens-base-view-1.png index 2fbdfdb6db1..c25ece0ff13 100644 Binary files a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_bridged-tokens-base-view-1.png and b/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_bridged-tokens-base-view-1.png differ diff --git a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_bridged-tokens-base-view-2.png b/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_bridged-tokens-base-view-2.png deleted file mode 100644 index aed20b59fec..00000000000 Binary files a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_bridged-tokens-base-view-2.png and /dev/null differ diff --git a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_with-search-dark-mode-1.png b/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_with-search-dark-mode-1.png new file mode 100644 index 00000000000..83dcc8b66b0 Binary files /dev/null and b/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_with-search-dark-mode-1.png differ diff --git a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_with-search-mobile-dark-mode-1.png b/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_with-search-mobile-dark-mode-1.png deleted file mode 100644 index cb526e260ca..00000000000 Binary files a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_default_with-search-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_mobile_with-search-mobile-dark-mode-1.png b/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_mobile_with-search-mobile-dark-mode-1.png deleted file mode 100644 index d1362da7fc8..00000000000 Binary files a/src/slices/token/pages/index/__screenshots__/Tokens.pw.tsx_mobile_with-search-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/token/pages/instance/TokenInstance.tsx b/src/slices/token/pages/instance/TokenInstance.tsx index 2df0221d395..cb2c6145985 100644 --- a/src/slices/token/pages/instance/TokenInstance.tsx +++ b/src/slices/token/pages/instance/TokenInstance.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -25,6 +24,7 @@ import TextAd from 'src/features/ads/text/components/TextAd'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; diff --git a/src/slices/token/pages/instance/TokenInstancePageTitle.pw.tsx b/src/slices/token/pages/instance/TokenInstancePageTitle.pw.tsx new file mode 100644 index 00000000000..7343d5b47fb --- /dev/null +++ b/src/slices/token/pages/instance/TokenInstancePageTitle.pw.tsx @@ -0,0 +1,40 @@ +import React from 'react'; + +import { tokenInfoERC721a } from 'src/slices/token/mocks/info'; +import * as tokenInstanceMock from 'src/slices/token/mocks/instance'; + +import { generateAddressMetadataInfo, hiddenProtocolTagWithMeta } from 'src/features/address-metadata/mocks/tags'; + +import config from 'src/config'; + +import { test, expect } from 'playwright/lib'; + +import TokenInstancePageTitle from './TokenInstancePageTitle'; + +const hash = tokenInfoERC721a.address_hash; + +const addressMetadataQueryParams = { + addresses: [ hash ], + chainId: config.chain.id, + tagsLimit: '20', +}; + +test('with action button +@dark-mode +@mobile', async({ render, mockApiResponse, mockAssetResponse }) => { + await mockApiResponse('metadata:info', generateAddressMetadataInfo(hash, hiddenProtocolTagWithMeta), { queryParams: addressMetadataQueryParams }); + await mockAssetResponse(hiddenProtocolTagWithMeta.meta?.appLogoURL as string, './playwright/mocks/image_s.jpg'); + + const component = await render( + <TokenInstancePageTitle + isLoading={ false } + token={ tokenInfoERC721a } + instance={ tokenInstanceMock.unique } + hash={ hash } + />, + ); + + await expect(component.getByRole('link', { name: /Buy on Duck portal/ })).toHaveAttribute( + 'href', + `https://portal.duck.io/swap?chainId=${ config.chain.id }&token=${ hash.toLowerCase() }&utm_source=blockscout&utm_medium=token`, + ); + await expect(component).toHaveScreenshot(); +}); diff --git a/src/slices/token/pages/instance/TokenInstancePageTitle.tsx b/src/slices/token/pages/instance/TokenInstancePageTitle.tsx index 8a3a43984cc..782b4d81124 100644 --- a/src/slices/token/pages/instance/TokenInstancePageTitle.tsx +++ b/src/slices/token/pages/instance/TokenInstancePageTitle.tsx @@ -12,6 +12,8 @@ import PageTitle from 'src/shell/page/title/PageTitle'; import AddressQrCode from 'src/slices/address/pages/details/info/AddressQrCode'; import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; +import AppActionButton from 'src/features/address-metadata/components/AppActionButton'; +import useAppActionData from 'src/features/address-metadata/hooks/useAppActionData'; import { useMultichainContext } from 'src/features/multichain/context'; import TokenAddToWallet from 'src/features/web3-wallet/components/TokenAddToWallet'; @@ -28,6 +30,7 @@ interface Props { const TokenInstancePageTitle = ({ isLoading, token, instance, hash }: Props) => { const multichainContext = useMultichainContext(); + const appActionData = useAppActionData(token?.address_hash, !isLoading); const title = (() => { if (typeof instance?.metadata?.name === 'string') { @@ -45,7 +48,18 @@ const TokenInstancePageTitle = ({ isLoading, token, instance, hash }: Props) => return `ID ${ instance.id }`; })(); - const tokenTag = token ? <Tag loading={ isLoading }>{ getTokenTypeName(token.type) }</Tag> : null; + const contentAfter = ( + <Flex alignItems="center" justifyContent="space-between" flexGrow={ 1 } flexWrap="wrap" gap={ 3 }> + { token && <Tag loading={ isLoading }>{ getTokenTypeName(token.type) }</Tag> } + { appActionData && ( + <AppActionButton + data={ appActionData } + addressHash={ token?.address_hash } + source="NFT item" + /> + ) } + </Flex> + ); const appLink = (() => { if (!instance?.external_app_url) { @@ -104,7 +118,7 @@ const TokenInstancePageTitle = ({ isLoading, token, instance, hash }: Props) => return ( <PageTitle title={ title } - contentAfter={ tokenTag } + contentAfter={ contentAfter } secondRow={ titleSecondRow } isLoading={ isLoading } /> diff --git a/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_base-view-1.png b/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_base-view-1.png index 2d65bc6f2bb..0e0ca334cf3 100644 Binary files a/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_base-view-1.png and b/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_base-view-1.png differ diff --git a/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-1.png b/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-1.png index d27e16b3f3f..a54b6002dcc 100644 Binary files a/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-1.png and b/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-1.png differ diff --git a/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-2.png b/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-2.png index e1d362d2191..da03141163c 100644 Binary files a/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-2.png and b/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-2.png differ diff --git a/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-3.png b/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-3.png index 1419e13bad9..4970ed56877 100644 Binary files a/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-3.png and b/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-3.png differ diff --git a/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-failed-1.png b/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-failed-1.png index 6a06c4558d5..1e5b90a5539 100644 Binary files a/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-failed-1.png and b/src/slices/token/pages/instance/__screenshots__/TokenInstance.pw.tsx_default_metadata-update-failed-1.png differ diff --git a/src/slices/token/pages/instance/__screenshots__/TokenInstancePageTitle.pw.tsx_dark-color-mode_with-action-button-dark-mode-mobile-1.png b/src/slices/token/pages/instance/__screenshots__/TokenInstancePageTitle.pw.tsx_dark-color-mode_with-action-button-dark-mode-mobile-1.png new file mode 100644 index 00000000000..dd95bb54f21 Binary files /dev/null and b/src/slices/token/pages/instance/__screenshots__/TokenInstancePageTitle.pw.tsx_dark-color-mode_with-action-button-dark-mode-mobile-1.png differ diff --git a/src/slices/token/pages/instance/__screenshots__/TokenInstancePageTitle.pw.tsx_default_with-action-button-dark-mode-mobile-1.png b/src/slices/token/pages/instance/__screenshots__/TokenInstancePageTitle.pw.tsx_default_with-action-button-dark-mode-mobile-1.png new file mode 100644 index 00000000000..28a3d44848a Binary files /dev/null and b/src/slices/token/pages/instance/__screenshots__/TokenInstancePageTitle.pw.tsx_default_with-action-button-dark-mode-mobile-1.png differ diff --git a/src/slices/token/pages/instance/__screenshots__/TokenInstancePageTitle.pw.tsx_mobile_with-action-button-dark-mode-mobile-1.png b/src/slices/token/pages/instance/__screenshots__/TokenInstancePageTitle.pw.tsx_mobile_with-action-button-dark-mode-mobile-1.png new file mode 100644 index 00000000000..5e6c0b6e5f7 Binary files /dev/null and b/src/slices/token/pages/instance/__screenshots__/TokenInstancePageTitle.pw.tsx_mobile_with-action-button-dark-mode-mobile-1.png differ diff --git a/src/slices/token/pages/instance/info/TokenInstanceDetails.pw.tsx b/src/slices/token/pages/instance/info/TokenInstanceDetails.pw.tsx index 1d0db1d5526..3e968b8d0f8 100644 --- a/src/slices/token/pages/instance/info/TokenInstanceDetails.pw.tsx +++ b/src/slices/token/pages/instance/info/TokenInstanceDetails.pw.tsx @@ -1,18 +1,10 @@ import React from 'react'; -import type { schemas } from '@blockscout/api-types'; -import type { AddressMetadataInfo } from 'src/features/address-metadata/types/api'; - import * as addressMock from 'src/slices/address/mocks/address'; import { tokenInfoERC721a } from 'src/slices/token/mocks/info'; import * as tokenInstanceMock from 'src/slices/token/mocks/instance'; import { MetadataUpdateProvider } from 'src/slices/token/pages/instance/metadata-update-context'; -import { protocolTagWithMeta } from 'src/features/address-metadata/mocks/tags'; - -import config from 'src/config'; - -import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; import { test, expect, devices } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; @@ -20,25 +12,6 @@ import TokenInstanceDetails from './TokenInstanceDetails'; const hash = tokenInfoERC721a.address_hash; -const addressMetadataQueryParams = { - addresses: [ hash ], - chainId: config.chain.id, - tagsLimit: '20', -}; - -function generateAddressMetadataResponse(tag: schemas['MetadataTag']) { - return { - addresses: { - [ hash.toLowerCase() as string ]: { - tags: [ { - ...tag, - meta: JSON.stringify(tag.meta), - } ], - }, - }, - } as AddressMetadataInfo; -} - test.beforeEach(async({ mockApiResponse, mockAssetResponse }) => { await mockApiResponse('core:address', addressMock.contract, { pathParams: { hash } }); await mockApiResponse('core:token_instance_transfers_count', { transfers_count: 42 }, { pathParams: { id: tokenInstanceMock.unique.id, hash } }); @@ -58,40 +31,6 @@ test('base view +@dark-mode', async({ render, page }) => { }); }); -test.describe('action button', () => { - test.beforeEach(async({ mockApiResponse, mockAssetResponse }) => { - const meta = { ...protocolTagWithMeta.meta, appMarketplaceURL: undefined }; - const metadataResponse = generateAddressMetadataResponse({ ...protocolTagWithMeta, meta }); - await mockApiResponse('metadata:info', metadataResponse, { queryParams: addressMetadataQueryParams }); - await mockAssetResponse(protocolTagWithMeta?.meta?.appLogoURL as string, './playwright/mocks/image_s.jpg'); - }); - - test('base view +@dark-mode', async({ render, page }) => { - const component = await render( - <MetadataUpdateProvider> - <TokenInstanceDetails data={ tokenInstanceMock.unique } token={ tokenInfoERC721a }/> - </MetadataUpdateProvider>, - ); - await expect(component).toHaveScreenshot({ - mask: [ page.locator(pwConfig.adsBannerSelector) ], - maskColor: pwConfig.maskColor, - }); - }); - - test('without marketplaces +@dark-mode', async({ render, page, mockEnvs }) => { - mockEnvs(ENVS_MAP.noNftMarketplaces); - const component = await render( - <MetadataUpdateProvider> - <TokenInstanceDetails data={ tokenInstanceMock.unique } token={ tokenInfoERC721a }/> - </MetadataUpdateProvider>, - ); - await expect(component).toHaveScreenshot({ - mask: [ page.locator(pwConfig.adsBannerSelector) ], - maskColor: pwConfig.maskColor, - }); - }); -}); - test.describe('mobile', () => { test.use({ viewport: devices['iPhone 13 Pro'].viewport }); diff --git a/src/slices/token/pages/instance/info/TokenInstanceDetails.tsx b/src/slices/token/pages/instance/info/TokenInstanceDetails.tsx index a066875c436..4063a23462e 100644 --- a/src/slices/token/pages/instance/info/TokenInstanceDetails.tsx +++ b/src/slices/token/pages/instance/info/TokenInstanceDetails.tsx @@ -9,17 +9,13 @@ import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; import NftMedia from 'src/slices/token/components/nft-media/NftMedia'; import TokenNftMarketplaces from 'src/slices/token/pages/details/info/TokenNftMarketplaces'; -import AppActionButton from 'src/features/address-metadata/components/AppActionButton'; -import useAppActionData from 'src/features/address-metadata/hooks/useAppActionData'; - -import config from 'src/config'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import DetailedInfoSponsoredItem from 'src/shared/detailed-info/DetailedInfoSponsoredItem'; import useIsMounted from 'src/shared/hooks/useIsMounted'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import TokenInstanceCreatorAddress from './TokenInstanceCreatorAddress'; import TokenInstanceMetadataInfo from './TokenInstanceMetadataInfo'; @@ -32,7 +28,6 @@ interface Props { } const TokenInstanceDetails = ({ data, token, isLoading }: Props) => { - const appActionData = useAppActionData(token?.address_hash, !isLoading); const isMounted = useIsMounted(); if (!data || !token || !isMounted) { @@ -74,7 +69,7 @@ const TokenInstanceDetails = ({ data, token, isLoading }: Props) => { <DetailedInfo.ItemValue> <Flex alignItems="center" overflow="hidden"> <Skeleton loading={ isLoading } overflow="hidden" display="inline-block" w="100%"> - <HashStringShortenDynamic hash={ data.id }/> + <Truncate value={ data.id }/> </Skeleton> <CopyToClipboard text={ data.id } isLoading={ isLoading }/> </Flex> @@ -86,22 +81,7 @@ const TokenInstanceDetails = ({ data, token, isLoading }: Props) => { isLoading={ isLoading } hash={ token.address_hash } id={ data.id } - appActionData={ appActionData } - source="NFT item" /> - - { (config.slices.token.nft.marketplaces.length === 0 && appActionData) && ( - <> - <DetailedInfo.ItemLabel - hint="Link to the dapp" - > - Dapp - </DetailedInfo.ItemLabel> - <DetailedInfo.ItemValue py="1px"> - <AppActionButton data={ appActionData } height="30px" source="NFT item"/> - </DetailedInfo.ItemValue> - </> - ) } </DetailedInfo.Container> <NftMedia data={ data } diff --git a/src/slices/token/pages/instance/info/TokenInstanceMetadataInfo.tsx b/src/slices/token/pages/instance/info/TokenInstanceMetadataInfo.tsx index 5be9f29ef0d..ff3690611b8 100644 --- a/src/slices/token/pages/instance/info/TokenInstanceMetadataInfo.tsx +++ b/src/slices/token/pages/instance/info/TokenInstanceMetadataInfo.tsx @@ -12,7 +12,7 @@ import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; -import { TruncatedText } from 'src/toolkit/components/truncation/TruncatedText'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; import { useMetadataUpdateContext } from '../metadata-update-context'; @@ -41,12 +41,12 @@ const Item = ({ data, isLoading }: ItemProps) => { textStyle="sm" loading={ isLoading } > - <TruncatedText text={ data.value } w="calc(100% - 16px)" loading={ isLoading }/> + <Truncate value={ data.value } type="end" w="calc(100% - 16px)" loading={ isLoading }/> </Link> ); } - return <TruncatedText text={ data.value } fontSize="sm" w="100%" loading={ isLoading }/>; + return <Truncate value={ data.value } type="end" fontSize="sm" w="100%" loading={ isLoading }/>; })(); return ( @@ -59,15 +59,12 @@ const Item = ({ data, isLoading }: ItemProps) => { flexDir="column" alignItems="flex-start" > - <TruncatedText - text={ data.trait_type } - textStyle="xs" + <Truncate value={ data.trait_type } type="end" textStyle="xs" w="100%" color="text.secondary" fontWeight={ 500 } mb={ 1 } - loading={ isLoading } - /> + loading={ isLoading }/> { value } </GridItem> ); diff --git a/src/slices/token/pages/instance/info/TokenInstanceTransfersCount.tsx b/src/slices/token/pages/instance/info/TokenInstanceTransfersCount.tsx index 8bf79902efd..93156df6122 100644 --- a/src/slices/token/pages/instance/info/TokenInstanceTransfersCount.tsx +++ b/src/slices/token/pages/instance/info/TokenInstanceTransfersCount.tsx @@ -1,11 +1,11 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { route } from 'nextjs-routes'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; +import { route } from 'src/shared/router/routes'; import { Link } from 'src/toolkit/chakra/link'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; diff --git a/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_dark-color-mode_action-button-base-view-dark-mode-1.png b/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_dark-color-mode_action-button-base-view-dark-mode-1.png deleted file mode 100644 index e1985f44617..00000000000 Binary files a/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_dark-color-mode_action-button-base-view-dark-mode-1.png and /dev/null differ diff --git a/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_dark-color-mode_action-button-without-marketplaces-dark-mode-1.png b/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_dark-color-mode_action-button-without-marketplaces-dark-mode-1.png deleted file mode 100644 index 16c332a0264..00000000000 Binary files a/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_dark-color-mode_action-button-without-marketplaces-dark-mode-1.png and /dev/null differ diff --git a/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_default_action-button-base-view-dark-mode-1.png b/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_default_action-button-base-view-dark-mode-1.png deleted file mode 100644 index 4ff9a0b6681..00000000000 Binary files a/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_default_action-button-base-view-dark-mode-1.png and /dev/null differ diff --git a/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_default_action-button-without-marketplaces-dark-mode-1.png b/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_default_action-button-without-marketplaces-dark-mode-1.png deleted file mode 100644 index 690328c3e1a..00000000000 Binary files a/src/slices/token/pages/instance/info/__screenshots__/TokenInstanceDetails.pw.tsx_default_action-button-without-marketplaces-dark-mode-1.png and /dev/null differ diff --git a/src/slices/token/pages/instance/metadata/__screenshots__/TokenInstanceMetadata.pw.tsx_mobile_base-view-mobile-1.png b/src/slices/token/pages/instance/metadata/__screenshots__/TokenInstanceMetadata.pw.tsx_mobile_base-view-mobile-1.png index 33b5d3d1cf7..457511dd60f 100644 Binary files a/src/slices/token/pages/instance/metadata/__screenshots__/TokenInstanceMetadata.pw.tsx_mobile_base-view-mobile-1.png and b/src/slices/token/pages/instance/metadata/__screenshots__/TokenInstanceMetadata.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/slices/token/stubs.ts b/src/slices/token/stubs.ts index b5c57576671..c106e421890 100644 --- a/src/slices/token/stubs.ts +++ b/src/slices/token/stubs.ts @@ -7,6 +7,8 @@ import { ADDRESS_PARAMS, ADDRESS_HASH } from 'src/slices/address/stubs/address-p import { generateListStub } from 'src/shared/pagination/utils'; +import { TX_HASH } from '../tx/stubs/tx'; + export const BLOCK_HASH = '0x8fa7b9e5e5e79deeb62d608db22ba9a5cb45388c7ebb9223ae77331c6080dc70'; export const TOKEN_INFO_ERC_20: schemas['Token'] = { @@ -24,6 +26,9 @@ export const TOKEN_INFO_ERC_20: schemas['Token'] = { circulating_supply: null, volume_24h: null, is_bridged: false, + ui_multiplier: null, + new_ui_multiplier: null, + ui_multiplier_effective_at: null, }; export const TOKEN_INFO_ERC_721: schemas['Token'] = { @@ -47,6 +52,18 @@ export const TOKEN_INFO_ERC_404: schemas['Token'] = { export const TOKEN_COUNTERS: schemas['TokenCountersResponse'] = { token_holders_count: '123456', transfers_count: '123456', + ui_multiplier_changes_count: '0', +}; + +export const TOKEN_UI_MULTIPLIER_CHANGE: schemas['TokenUIMultiplierChange'] = { + block_hash: BLOCK_HASH, + block_number: 11387767, + effective_at: '2026-07-31T08:47:48.000000Z', + log_index: 738, + new_multiplier: '1040000000000000000', + old_multiplier: '1050000000000000000', + timestamp: '2026-07-31T06:48:36.000000Z', + transaction_hash: TX_HASH, }; export const TOKEN_HOLDER_ERC_20: schemas['TokenHolderResponse'] = { diff --git a/src/slices/token/types/client.ts b/src/slices/token/types/client.ts index 0e5b9116656..053c4db9274 100644 --- a/src/slices/token/types/client.ts +++ b/src/slices/token/types/client.ts @@ -1,5 +1,9 @@ // SPDX-License-Identifier: LicenseRef-Blockscout +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; + +export type ChainConfig = Array<ClusterChainConfig['app_config']> | ClusterChainConfig['app_config']; + export interface Metadata { name?: string; description?: string; diff --git a/src/slices/token/utils/model.ts b/src/slices/token/utils/model.ts index 59c130a7aad..5df6855f8cc 100644 --- a/src/slices/token/utils/model.ts +++ b/src/slices/token/utils/model.ts @@ -19,6 +19,9 @@ export function toTokenModel(fields: Partial<schemas['Token']>): schemas['Token' reputation: fields.reputation ?? null, volume_24h: fields.volume_24h ?? null, is_bridged: fields.is_bridged ?? false, + ui_multiplier: fields.ui_multiplier ?? null, + new_ui_multiplier: fields.new_ui_multiplier ?? null, + ui_multiplier_effective_at: fields.ui_multiplier_effective_at ?? null, }; } diff --git a/src/slices/token/utils/token-types.ts b/src/slices/token/utils/token-types.ts index e8ef1003c22..7ee00aac9da 100644 --- a/src/slices/token/utils/token-types.ts +++ b/src/slices/token/utils/token-types.ts @@ -2,15 +2,13 @@ import { uniqBy } from 'es-toolkit'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; import type { NftTokenType, TokenType } from 'src/slices/token/types/api'; +import type { ChainConfig } from 'src/slices/token/types/client'; import config from 'src/config'; const tokenStandardName = config.slices.token.standard; -type ChainConfig = Array<ClusterChainConfig['app_config']> | ClusterChainConfig['app_config']; - type TokenCategory = 'all' | 'nft' | 'fungible'; export const NFT_TOKEN_TYPES: Record<NftTokenType, string> = { diff --git a/src/slices/token/utils/ui-multiplier.spec.ts b/src/slices/token/utils/ui-multiplier.spec.ts new file mode 100644 index 00000000000..d71884ce620 --- /dev/null +++ b/src/slices/token/utils/ui-multiplier.spec.ts @@ -0,0 +1,101 @@ +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { thinsp } from 'src/toolkit/utils/htmlEntities'; + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import type { UiMultiplierSource } from './ui-multiplier'; +import { getUiMultiplierChangeStatuses } from './ui-multiplier'; + +const ONE = '1000000000000000000'; +const ONE_POINT_SIX_NINE = '1690000000000000000'; +const ONE_POINT_ZERO_ZERO_TWO_FIVE = '1002500000000000000'; +const BELOW_SMALLEST_REPRESENTABLE = '100000000000'; + +const NOW = new Date('2026-08-01T12:00:00Z').getTime(); +const FUTURE = '2026-08-02T00:00:00.000000Z'; +const EXACTLY_NOW = '2026-08-01T12:00:00.000000Z'; +const PAST = '2026-07-31T08:47:48.000000Z'; +const EARLIER_PAST = '2026-07-31T06:48:36.000000Z'; + +const erc8056Token: UiMultiplierSource = { type: 'ERC-8056', ui_multiplier: ONE_POINT_SIX_NINE }; + +function getUiMultiplierWithTypeEnabled(token: UiMultiplierSource | null | undefined) { + return withEnvs(ENVS_MAP.additionalTokenTypes, async() => { + const { getUiMultiplier } = await import('./ui-multiplier'); + return getUiMultiplier(token); + }); +} + +describe('getUiMultiplier', () => { + it('resolves the factor divided by 10^18 when the type is enabled and the field is set', async() => { + const result = await getUiMultiplierWithTypeEnabled(erc8056Token); + expect(result?.toFixed()).toBe('1.69'); + }); + + it('resolves exactly 1', async() => { + const result = await getUiMultiplierWithTypeEnabled({ ...erc8056Token, ui_multiplier: ONE }); + expect(result?.isEqualTo(1)).toBe(true); + }); + + it('resolves to nothing when ERC-8056 is not among the instance additional token types', async() => { + const { getUiMultiplier } = await import('./ui-multiplier'); + expect(getUiMultiplier(erc8056Token)).toBeUndefined(); + }); + + it('resolves to nothing for a token of another type', async() => { + expect(await getUiMultiplierWithTypeEnabled({ ...erc8056Token, type: 'ERC-20' })).toBeUndefined(); + }); + + it('resolves to nothing when the field is null', async() => { + expect(await getUiMultiplierWithTypeEnabled({ ...erc8056Token, ui_multiplier: null })).toBeUndefined(); + }); + + it('resolves to nothing when there is no token', async() => { + expect(await getUiMultiplierWithTypeEnabled(null)).toBeUndefined(); + }); +}); + +describe('formatUiMultiplier', () => { + it.each([ + [ ONE, '1x' ], + [ ONE_POINT_SIX_NINE, '1.69x' ], + [ ONE_POINT_ZERO_ZERO_TWO_FIVE, '1.0025x' ], + [ BELOW_SMALLEST_REPRESENTABLE, `<${ thinsp }0.000001x` ], + ])('%s → %s', async(rawValue, expected) => { + const { formatUiMultiplier, parseUiMultiplier } = await import('./ui-multiplier'); + expect(formatUiMultiplier(parseUiMultiplier(rawValue))).toBe(expected); + }); +}); + +describe('getUiMultiplierChangeStatuses', () => { + it('marks the newest change already in effect as active and the older ones as inactive', () => { + const items = [ { effective_at: PAST }, { effective_at: EARLIER_PAST } ]; + expect(getUiMultiplierChangeStatuses(items, 1, NOW)).toEqual([ 'active', 'inactive' ]); + }); + + it('marks a change scheduled for the future as scheduled and activates the first one in effect below it', () => { + const items = [ { effective_at: FUTURE }, { effective_at: PAST }, { effective_at: EARLIER_PAST } ]; + expect(getUiMultiplierChangeStatuses(items, 1, NOW)).toEqual([ 'scheduled', 'active', 'inactive' ]); + }); + + it('treats a change taking effect exactly now as active', () => { + const items = [ { effective_at: EXACTLY_NOW }, { effective_at: PAST } ]; + expect(getUiMultiplierChangeStatuses(items, 1, NOW)).toEqual([ 'active', 'inactive' ]); + }); + + it('marks nothing active when every change on the first page is scheduled for the future', () => { + const items = [ { effective_at: FUTURE }, { effective_at: FUTURE } ]; + expect(getUiMultiplierChangeStatuses(items, 1, NOW)).toEqual([ 'scheduled', 'scheduled' ]); + }); + + it('marks nothing active on pages after the first, but still marks future changes scheduled', () => { + const items = [ { effective_at: FUTURE }, { effective_at: PAST }, { effective_at: EARLIER_PAST } ]; + expect(getUiMultiplierChangeStatuses(items, 2, NOW)).toEqual([ 'scheduled', 'inactive', 'inactive' ]); + }); + + it('returns no statuses for an empty list', () => { + expect(getUiMultiplierChangeStatuses([], 1, NOW)).toEqual([]); + }); +}); diff --git a/src/slices/token/utils/ui-multiplier.ts b/src/slices/token/utils/ui-multiplier.ts new file mode 100644 index 00000000000..103cbb1c3dd --- /dev/null +++ b/src/slices/token/utils/ui-multiplier.ts @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import BigNumber from 'bignumber.js'; + +import type { schemas } from '@blockscout/api-types'; +import type { TokenType } from 'src/slices/token/types/api'; +import type { ChainConfig } from 'src/slices/token/types/client'; +import { getAdditionalTokenTypes } from 'src/slices/token/utils/token-types'; + +import { formatBnValue } from 'src/shared/values/entity/utils'; + +export const UI_MULTIPLIER_TOKEN_TYPE = 'ERC-8056'; + +// Fixed by ERC-8056 itself: uiMultiplier() is a uint256 where 1e18 means 1.0, regardless of the token's own decimals. +const UI_MULTIPLIER_DECIMALS = 18; +const UI_MULTIPLIER_ACCURACY = 6; + +export interface UiMultiplierSource { + type: TokenType | null | undefined; + ui_multiplier: string | null | undefined; +} + +export function isTokenMultiplierEnabled(chainConfig?: ChainConfig): boolean { + return getAdditionalTokenTypes(chainConfig).some((item) => item.id === UI_MULTIPLIER_TOKEN_TYPE); +} + +export function getUiMultiplier(token: UiMultiplierSource | null | undefined, chainConfig?: ChainConfig): BigNumber | undefined { + if (!token || token.type !== UI_MULTIPLIER_TOKEN_TYPE || !token.ui_multiplier) { + return undefined; + } + + if (!isTokenMultiplierEnabled(chainConfig)) { + return undefined; + } + + const multiplier = parseUiMultiplier(token.ui_multiplier); + return multiplier.isNaN() ? undefined : multiplier; +} + +export function parseUiMultiplier(rawValue: string): BigNumber { + return new BigNumber(rawValue).shiftedBy(-UI_MULTIPLIER_DECIMALS); +} + +export function formatUiMultiplier(value: BigNumber, postfix = 'x'): string { + return formatBnValue({ value, accuracy: UI_MULTIPLIER_ACCURACY, postfix }); +} + +export type UiMultiplierChangeStatus = 'active' | 'inactive' | 'scheduled'; + +type UiMultiplierChange = Pick<schemas['TokenUIMultiplierChange'], 'effective_at'>; + +function isScheduled(item: UiMultiplierChange, now: number): boolean { + return new Date(item.effective_at).getTime() > now; +} + +export function getUiMultiplierChangeStatuses( + items: Array<UiMultiplierChange>, + page: number, + now: number = Date.now(), +): Array<UiMultiplierChangeStatus> { + const activeIndex = page === 1 ? items.findIndex((item) => !isScheduled(item, now)) : -1; + return items.map((item, index) => { + if (isScheduled(item, now)) { + return 'scheduled'; + } + return index === activeIndex ? 'active' : 'inactive'; + }); +} diff --git a/src/slices/token/utils/verified-fetch.ts b/src/slices/token/utils/verified-fetch.ts new file mode 100644 index 00000000000..b898c0f71cb --- /dev/null +++ b/src/slices/token/utils/verified-fetch.ts @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +// Recursive trustless gateways from independent operators, so one outage does not break IPFS loading. +// Both must answer `?format=raw` block requests with CORS headers and without redirecting to another host, +// since every host the client reaches has to be allowed in the CSP connect-src. +export const VERIFIED_FETCH_GATEWAYS = [ + 'https://trustless-gateway.link', + 'https://ipfs.filebase.io', +]; diff --git a/src/slices/tx/components/TxType.spec.tsx b/src/slices/tx/components/TxType.spec.tsx index f17169a9beb..9f883875d98 100644 --- a/src/slices/tx/components/TxType.spec.tsx +++ b/src/slices/tx/components/TxType.spec.tsx @@ -11,6 +11,15 @@ import TxType from './TxType'; describe('TxType', () => { afterEach(cleanup); + it.each([ + [ 'op_stack_l1_attributes_transaction' as const, 'L1 attr tx' ], + [ 'op_stack_post_exec_transaction' as const, 'Post exec tx' ], + ])('renders the label for %s', (type, label) => { + render(<TxType types={ [ type ] }/>); + + expect(screen.queryByText(label)).not.toBeNull(); + }); + it('prefers a more informative type over sponsored_transaction', () => { render(<TxType types={ [ 'sponsored_transaction', 'contract_call' ] }/>); diff --git a/src/slices/tx/components/TxType.tsx b/src/slices/tx/components/TxType.tsx index 2ce14cc0698..7db03cf612e 100644 --- a/src/slices/tx/components/TxType.tsx +++ b/src/slices/tx/components/TxType.tsx @@ -13,6 +13,8 @@ export interface Props extends BadgeProps { } const TYPES_ORDER: schemas['Transaction']['transaction_types'] = [ + 'op_stack_l1_attributes_transaction', + 'op_stack_post_exec_transaction', 'blob_transaction', 'rootstock_remasc', 'rootstock_bridge', @@ -28,7 +30,7 @@ const TYPES_ORDER: schemas['Transaction']['transaction_types'] = [ ]; const TxType = ({ types, isLoading, ...rest }: Props) => { - const typeToShow = types.sort((t1, t2) => TYPES_ORDER.indexOf(t1) - TYPES_ORDER.indexOf(t2))[0]; + const typeToShow = types.slice().sort((t1, t2) => TYPES_ORDER.indexOf(t1) - TYPES_ORDER.indexOf(t2))[0]; let label; let colorPalette: BadgeProps['colorPalette']; @@ -58,6 +60,14 @@ const TxType = ({ types, isLoading, ...rest }: Props) => { label = 'Coin transfer'; colorPalette = 'orange'; break; + case 'op_stack_l1_attributes_transaction': + label = 'L1 attr tx'; + colorPalette = 'green'; + break; + case 'op_stack_post_exec_transaction': + label = 'Post exec tx'; + colorPalette = 'green'; + break; case 'rootstock_remasc': label = 'REMASC'; colorPalette = 'blue'; diff --git a/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_dark-color-mode_regular-transaction-dark-mode-1.png b/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_dark-color-mode_regular-transaction-dark-mode-1.png index 312d04ac5e9..ad7151cf02e 100644 Binary files a/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_dark-color-mode_regular-transaction-dark-mode-1.png and b/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_dark-color-mode_regular-transaction-dark-mode-1.png differ diff --git a/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_default_blob-transaction-1.png b/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_default_blob-transaction-1.png index 7fec3ff91f8..9c2d66dc9d6 100644 Binary files a/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_default_blob-transaction-1.png and b/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_default_blob-transaction-1.png differ diff --git a/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_default_regular-transaction-dark-mode-1.png b/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_default_regular-transaction-dark-mode-1.png index cf0df3ddb27..9677cb4e8b6 100644 Binary files a/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_default_regular-transaction-dark-mode-1.png and b/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_default_regular-transaction-dark-mode-1.png differ diff --git a/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_mobile_regular-transaction-mobile---default-1.png b/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_mobile_regular-transaction-mobile---default-1.png index ef62ceff77c..c6c9ab95ce4 100644 Binary files a/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_mobile_regular-transaction-mobile---default-1.png and b/src/slices/tx/components/__screenshots__/TxAdditionalInfo.pw.tsx_mobile_regular-transaction-mobile---default-1.png differ diff --git a/src/slices/tx/components/entity/__screenshots__/TxEntity.pw.tsx_default_loading-1.png b/src/slices/tx/components/entity/__screenshots__/TxEntity.pw.tsx_default_loading-1.png index fc48d621cea..f06fa010cc3 100644 Binary files a/src/slices/tx/components/entity/__screenshots__/TxEntity.pw.tsx_default_loading-1.png and b/src/slices/tx/components/entity/__screenshots__/TxEntity.pw.tsx_default_loading-1.png differ diff --git a/src/slices/tx/hooks/useTxQuery.spec.ts b/src/slices/tx/hooks/useTxQuery.spec.ts new file mode 100644 index 00000000000..05275cf956a --- /dev/null +++ b/src/slices/tx/hooks/useTxQuery.spec.ts @@ -0,0 +1,140 @@ +// @vitest-environment jsdom + +import { rpcBlockBase } from 'src/slices/block/mocks/rpc'; +import { rpcTx, rpcTxReceipt } from 'src/slices/tx/mocks/rpc'; +import { TX, TX_HASH } from 'src/slices/tx/stubs/tx'; + +import { SECOND } from 'src/toolkit/utils/consts'; + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { renderHook, cleanup, waitFor } from 'vitest/lib'; +import { mockApiAndRpc, rpcRequests, apiRequests } from 'vitest/utils/mockJsonRpc'; +import { routerStandIn } from 'vitest/utils/routerStandIn'; + +import useTxQuery from './useTxQuery'; + +const API_TX = { status: 200, body: JSON.stringify(TX) }; +const API_NOT_FOUND = { status: 404, body: JSON.stringify({ message: 'Not found' }) }; +const API_INVALID_HASH = { status: 422, body: JSON.stringify({ message: 'Invalid hash' }) }; + +const TX_BLOCK_NUMBER = '0x64'; +const LATEST_BLOCK_NUMBER = '0x6e'; +const EXPECTED_CONFIRMATIONS = 11; + +const RPC_NODE_WITH_TX = { + eth_getTransactionByHash: rpcTx, + eth_getTransactionReceipt: { ...rpcTxReceipt, status: '0x1' }, + eth_getBlockByHash: { ...rpcBlockBase, number: TX_BLOCK_NUMBER }, + eth_getBlockByNumber: { ...rpcBlockBase, number: LATEST_BLOCK_NUMBER }, +}; + +const RPC_RETRY_DELAY = 5 * SECOND; +const API_POLL_INTERVAL = 15 * SECOND; + +beforeEach(() => { + fetchMock.resetMocks(); + vi.useFakeTimers({ shouldAdvanceTime: true }); + routerStandIn.reset({ pathname: '/tx/[hash]', query: { hash: TX_HASH } }); +}); + +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +describe('useTxQuery', () => { + it('serves the API transaction and never asks the RPC node', async() => { + mockApiAndRpc({ api: () => API_TX }); + + const { result } = renderHook(() => useTxQuery(), { wrapper: routerStandIn.appWrapper }); + await waitFor(() => expect(result.current.isPlaceholderData).toBe(false)); + + expect(result.current.data?.hash).toBe(TX_HASH); + expect(result.current.isDegradedData).toBe(false); + expect(result.current.apiError).toBeNull(); + expect(rpcRequests()).toEqual([]); + }); + + it('reports a malformed hash straight away without asking the RPC node', async() => { + mockApiAndRpc({ api: () => API_INVALID_HASH, rpc: RPC_NODE_WITH_TX }); + + const { result } = renderHook(() => useTxQuery(), { wrapper: routerStandIn.appWrapper }); + await waitFor(() => expect(result.current.isError).toBe(true)); + + expect(result.current.error?.status).toBe(422); + expect(result.current.isDegradedData).toBe(false); + expect(rpcRequests()).toEqual([]); + }); + + it('reports the API 404 once the RPC node does not know the transaction either', async() => { + mockApiAndRpc({ api: () => API_NOT_FOUND }); + + const { result } = renderHook(() => useTxQuery(), { wrapper: routerStandIn.appWrapper }); + + await waitFor(() => expect(rpcRequests()).toEqual([ 'eth_getTransactionByHash' ])); + expect(result.current.isDegradedData).toBe(true); + expect(result.current.isPlaceholderData).toBe(true); + expect(result.current.isError).toBe(false); + + // a slow indexer and a lagging node may both miss a fresh transaction, so the node is re-asked twice + await vi.advanceTimersByTimeAsync(RPC_RETRY_DELAY); + await vi.advanceTimersByTimeAsync(RPC_RETRY_DELAY); + + await waitFor(() => expect(result.current.isError).toBe(true)); + expect(result.current.error?.status).toBe(404); + expect(result.current.isDegradedData).toBe(false); + + await vi.advanceTimersByTimeAsync(API_POLL_INTERVAL); + expect(apiRequests()).toHaveLength(1); + }); + + it('serves a pending RPC transaction with no confirmations when the node has no receipt or block for it', async() => { + mockApiAndRpc({ + api: () => API_NOT_FOUND, + rpc: { eth_getTransactionByHash: rpcTx, eth_getBlockByNumber: RPC_NODE_WITH_TX.eth_getBlockByNumber }, + }); + + const { result } = renderHook(() => useTxQuery(), { wrapper: routerStandIn.appWrapper }); + await waitFor(() => expect(result.current.isPlaceholderData).toBe(false)); + + expect(result.current.isDegradedData).toBe(true); + expect(result.current.data?.hash).toBe(TX_HASH); + expect(result.current.data?.status).toBeNull(); + expect(result.current.data?.confirmations).toBe(0); + }); + + it('serves the RPC transaction on an API 404 and polls the API until it catches up', async() => { + let apiResponse: typeof API_TX | Promise<typeof API_TX> = API_NOT_FOUND; + mockApiAndRpc({ api: () => apiResponse, rpc: RPC_NODE_WITH_TX }); + + const { result } = renderHook(() => useTxQuery(), { wrapper: routerStandIn.appWrapper }); + await waitFor(() => expect(result.current.isPlaceholderData).toBe(false)); + + expect(result.current.isDegradedData).toBe(true); + expect(result.current.isError).toBe(false); + expect(result.current.data?.hash).toBe(TX_HASH); + expect(result.current.data?.from.hash).toBe(rpcTx.from); + expect(result.current.data?.status).toBe('ok'); + expect(result.current.data?.confirmations).toBe(EXPECTED_CONFIRMATIONS); + expect(result.current.apiError?.status).toBe(404); + expect(apiRequests()).toHaveLength(1); + + const { promise: pendingPoll, resolve: resolveApi } = Promise.withResolvers<typeof API_TX>(); + apiResponse = pendingPoll; + await vi.advanceTimersByTimeAsync(API_POLL_INTERVAL); + + // the RPC data and the 404 verdict stay on screen while the poll is in flight + expect(apiRequests()).toHaveLength(2); + expect(result.current.isDegradedData).toBe(true); + expect(result.current.data?.hash).toBe(TX_HASH); + expect(result.current.apiError?.status).toBe(404); + + resolveApi(API_TX); + await waitFor(() => expect(result.current.isDegradedData).toBe(false)); + expect(result.current.apiError).toBeNull(); + expect(result.current.data).toEqual(TX); + + await vi.advanceTimersByTimeAsync(API_POLL_INTERVAL); + expect(apiRequests()).toHaveLength(2); + }); +}); diff --git a/src/slices/tx/hooks/useTxQuery.ts b/src/slices/tx/hooks/useTxQuery.ts index 7d4e663884d..5b56e47dfb8 100644 --- a/src/slices/tx/hooks/useTxQuery.ts +++ b/src/slices/tx/hooks/useTxQuery.ts @@ -1,9 +1,9 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { UseQueryResult } from '@tanstack/react-query'; -import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; import React from 'react'; +import type { Chain, GetBlockReturnType, GetTransactionReturnType, TransactionReceipt } from 'viem'; import type { schemas } from '@blockscout/api-types'; import type { SocketMessage } from 'src/api/socket/types'; @@ -14,16 +14,32 @@ import type { ResourceError } from 'src/api/resources'; import useSocketChannel from 'src/api/socket/useSocketChannel'; import useSocketMessage from 'src/api/socket/useSocketMessage'; +import { GET_BLOCK } from 'src/slices/block/stubs/rpc'; +import { GET_TRANSACTION, GET_TRANSACTION_CONFIRMATIONS, GET_TRANSACTION_RECEIPT } from 'src/slices/tx/stubs/rpc'; import { TX } from 'src/slices/tx/stubs/tx'; +import { formatTxDetailsRpcData } from 'src/slices/tx/utils/format-rpc-data'; + +import { getPublicClient, isPublicClientAvailable } from 'src/features/connect-wallet/utils/public-client'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import delay from 'src/shared/utils/delay'; import { SECOND } from 'src/toolkit/utils/consts'; -export type TxQuery = UseQueryResult<schemas['TransactionResponse'], ResourceError<{ status: number }>> & { +type RpcResponseType = [ + GetTransactionReturnType<Chain, 'latest'>, + TransactionReceipt | null, + bigint | null, + GetBlockReturnType<Chain, false, 'latest'> | null, +]; + +type TxError = ResourceError<{ status: number }>; + +export type TxQuery = UseQueryResult<schemas['TransactionResponse'], TxError> & { socketStatus: 'close' | 'error' | undefined; - setRefetchEnabled: (value: boolean) => void; + isDegradedData: boolean; + apiError: TxError | null; }; interface Params { @@ -40,7 +56,7 @@ export default function useTxQuery(params?: Params): TxQuery { const hash = params?.hash ?? getQueryParamString(router.query.hash); - const queryResult = useApiQuery<'core:tx', { status: number }>('core:tx', { + const apiQuery = useApiQuery<'core:tx', { status: number }>('core:tx', { pathParams: { hash }, queryOptions: { enabled: Boolean(hash) && params?.isEnabled !== false, @@ -58,7 +74,64 @@ export default function useTxQuery(params?: Params): TxQuery { }, }, }); - const { data, isError, isPlaceholderData, isPending } = queryResult; + const { data, isError, isPlaceholderData, isPending, errorUpdateCount } = apiQuery; + + // a poll of a failed query clears its error while in flight (the placeholder shows meanwhile); + // the last verdict must outlive that window + const [ apiError, setApiError ] = React.useState<TxError | null>(null); + if (!isPending && !isPlaceholderData && apiQuery.error !== apiError) { + setApiError(apiQuery.error); + } + + // the API could not serve the transaction (anything but a malformed hash), so the RPC node is asked instead; + // a 404 is included on purpose: a slow indexer may not have caught a fresh transaction yet + const isRpcFallbackNeeded = isPublicClientAvailable && ((isError && apiQuery.error.status !== 422) || isPlaceholderData) && errorUpdateCount > 0; + + const rpcQuery = useQuery<RpcResponseType, unknown, schemas['TransactionResponse'] | null>({ + queryKey: [ 'RPC', 'tx', { hash } ], + queryFn: async() => { + const publicClient = await getPublicClient(); + // Stryker disable next-line ConditionalExpression: undefined only without an RPC URL, which `enabled` already rules out; the guard narrows the type + if (!publicClient) { + throw new Error('No public RPC client'); + } + + const tx = await publicClient.getTransaction({ hash: hash as `0x${ string }` }); + + const txReceipt = await publicClient.getTransactionReceipt({ hash: hash as `0x${ string }` }).catch(() => null); + const block = await publicClient.getBlock({ blockHash: tx.blockHash }).catch(() => null); + const latestBlock = await publicClient.getBlock().catch(() => null); + const confirmations = latestBlock && block ? latestBlock.number - block.number + BigInt(1) : null; + + return [ + tx, + txReceipt, + confirmations, + block, + ]; + }, + select: (response) => { + const [ tx, receipt, confirmations, block ] = response; + + return formatTxDetailsRpcData({ tx, receipt, confirmations, block }); + }, + placeholderData: [ + GET_TRANSACTION, + GET_TRANSACTION_RECEIPT, + GET_TRANSACTION_CONFIRMATIONS, + GET_BLOCK, + ], + enabled: isRpcFallbackNeeded, + retry: 2, + retryDelay: 5 * SECOND, + }); + + const isDegradedData = isRpcFallbackNeeded && Boolean(rpcQuery.data); + + // the API is polled while the node serves the transaction, so the page recovers once the indexer catches up + React.useEffect(() => { + setRefetchEnabled(isDegradedData); + }, [ isDegradedData ]); const handleStatusUpdateMessage: SocketMessage.TxStatusUpdate['handler'] = React.useCallback(async() => { await delay(5 * SECOND); @@ -87,9 +160,14 @@ export default function useTxQuery(params?: Params): TxQuery { handler: handleStatusUpdateMessage, }); - return React.useMemo(() => ({ - ...queryResult, - socketStatus, - setRefetchEnabled, - }), [ queryResult, socketStatus, setRefetchEnabled ]); + return React.useMemo(() => { + const query = isDegradedData ? rpcQuery as UseQueryResult<schemas['TransactionResponse'], TxError> : apiQuery; + + return { + ...query, + socketStatus, + isDegradedData, + apiError, + }; + }, [ apiQuery, rpcQuery, isDegradedData, socketStatus, apiError ]); } diff --git a/src/slices/tx/hooks/useTxsSocketTypeAddress.ts b/src/slices/tx/hooks/useTxsSocketTypeAddress.ts index 0787f082195..cb541ec88e4 100644 --- a/src/slices/tx/hooks/useTxsSocketTypeAddress.ts +++ b/src/slices/tx/hooks/useTxsSocketTypeAddress.ts @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { useQueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/router'; import React from 'react'; import type { operations, schemas } from '@blockscout/api-types'; @@ -17,6 +16,7 @@ import { useMultichainContext } from 'src/features/multichain/context'; import config from 'src/config'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import getSortValueFromQuery from 'src/shared/sort/get-sort-value-from-query'; import { sortTxsFromSocket } from '../utils/sort-txs'; @@ -73,12 +73,13 @@ export default function useTxsSocketTypeAddress({ isLoading }: Params) { const newItems: Array<schemas['Transaction']> = []; let newCount = 0; let hasUpdatedItems = false; + const prevItems = [ ...prevData.items ]; payload.transactions.forEach(tx => { - const currIndex = prevData.items.findIndex((item) => item.hash === tx.hash); + const currIndex = prevItems.findIndex((item) => item.hash === tx.hash); if (currIndex > -1) { - prevData.items[currIndex] = tx; + prevItems[currIndex] = tx; hasUpdatedItems = true; } else { const isMatch = matchFilter(filterValue as AddressFromToFilter, tx, currentAddress); @@ -107,7 +108,7 @@ export default function useTxsSocketTypeAddress({ isLoading }: Params) { ...prevData, items: [ ...newItems, - ...prevData.items, + ...prevItems, ].sort(sortTxsFromSocket(sort)), }; }); diff --git a/src/slices/tx/hooks/useTxsSocketTypeAll.ts b/src/slices/tx/hooks/useTxsSocketTypeAll.ts index 1ad378c64a0..ad567371c82 100644 --- a/src/slices/tx/hooks/useTxsSocketTypeAll.ts +++ b/src/slices/tx/hooks/useTxsSocketTypeAll.ts @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { TxsSocketType } from '../types/socket'; @@ -10,6 +9,7 @@ import useSocketMessage from 'src/api/socket/useSocketMessage'; import useGradualIncrement from 'src/shared/numbers/useGradualIncrement'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; function getSocketParams(type: TxsSocketType, page: string) { diff --git a/src/slices/tx/hooks/useTxsSort.spec.ts b/src/slices/tx/hooks/useTxsSort.spec.ts new file mode 100644 index 00000000000..b9a2f5b03b2 --- /dev/null +++ b/src/slices/tx/hooks/useTxsSort.spec.ts @@ -0,0 +1,71 @@ +// @vitest-environment jsdom + +import type { UseQueryResult } from '@tanstack/react-query'; +import Cookies from 'js-cookie'; + +import type { operations } from '@blockscout/api-types'; + +import type { ResourceError } from 'src/api/resources'; + +import { describe, it, expect, afterEach } from 'vitest'; +import { renderHook, act, cleanup } from 'vitest/lib'; + +import useTxsSort from './useTxsSort'; + +type QueryResult = UseQueryResult<operations['TransactionController.transactions']['json'], ResourceError<unknown>>; + +const pendingQuery = { isPending: true, isError: false } as QueryResult; + +afterEach(() => { + cleanup(); + Cookies.remove('txs_sort'); +}); + +describe('useTxsSort', () => { + it('restores the saved block number sort when block sort is available', () => { + Cookies.set('txs_sort', 'block_number-asc'); + + const { result } = renderHook(() => useTxsSort(pendingQuery)); + + expect(result.current.sorting).toBe('block_number-asc'); + }); + + it('falls back to default for a saved block number sort when block sort is unavailable', () => { + Cookies.set('txs_sort', 'block_number-asc'); + + const { result } = renderHook(() => useTxsSort(pendingQuery, false)); + + expect(result.current.sorting).toBe('default'); + }); + + it('restores a saved value sort when block sort is unavailable', () => { + Cookies.set('txs_sort', 'value-desc'); + + const { result } = renderHook(() => useTxsSort(pendingQuery, false)); + + expect(result.current.sorting).toBe('value-desc'); + }); + + it('falls back to default for an unknown saved sort', () => { + Cookies.set('txs_sort', 'foo-asc'); + + const { result } = renderHook(() => useTxsSort(pendingQuery)); + + expect(result.current.sorting).toBe('default'); + }); + + it('sorts the loaded page by the chosen field and saves the choice', () => { + const query = { + isPending: false, + isError: false, + data: { items: [ { value: '11' }, { value: '42' }, { value: '24' } ], next_page_params: null }, + // the hook only reads the status flags and data.items, so a partial success result is enough + } as unknown as QueryResult; + + const { result } = renderHook(() => useTxsSort(query, false)); + act(() => result.current.setSortByValue('value-desc')); + + expect(result.current.data?.items.map(({ value }) => value)).toEqual([ '42', '24', '11' ]); + expect(Cookies.get('txs_sort')).toBe('value-desc'); + }); +}); diff --git a/src/slices/tx/hooks/useTxsSort.ts b/src/slices/tx/hooks/useTxsSort.ts index b9357434bc7..437671ae0f6 100644 --- a/src/slices/tx/hooks/useTxsSort.ts +++ b/src/slices/tx/hooks/useTxsSort.ts @@ -23,8 +23,17 @@ export const SORT_OPTIONS: Array<SelectOption<TransactionsSortingValue>> = [ { label: 'Block number ascending', value: 'block_number-asc' }, ]; +export const SORT_OPTIONS_WITHOUT_BLOCK: Array<SelectOption<TransactionsSortingValue>> = + SORT_OPTIONS.filter(({ value }) => !value.startsWith('block_number')); + type SortingValue = TransactionsSortingValue; +function getInitialSorting(withBlockSort: boolean): SortingValue { + const value = cookies.get(cookies.NAMES.TXS_SORT); + const options = withBlockSort ? SORT_OPTIONS : SORT_OPTIONS_WITHOUT_BLOCK; + return options.find((option) => option.value === value)?.value ?? 'default'; +} + type HookResult = UseQueryResult<operations['TransactionController.transactions']['json'], ResourceError<unknown>> & { sorting: SortingValue; setSortByValue: (value: SortingValue) => void; @@ -32,20 +41,16 @@ type HookResult = UseQueryResult<operations['TransactionController.transactions' export default function useTxsSort( queryResult: UseQueryResult<operations['TransactionController.transactions']['json'], ResourceError<unknown>>, + withBlockSort = true, ): HookResult { - const [ sorting, setSorting ] = React.useState<SortingValue>((cookies.get(cookies.NAMES.TXS_SORT) as SortingValue | undefined) ?? 'default'); + const [ sorting, setSorting ] = React.useState<SortingValue>(() => getInitialSorting(withBlockSort)); const setSortByValue = React.useCallback((value: SortingValue) => { - setSorting((prevVal: SortingValue) => { - let newVal: SortingValue = 'default'; - if (value !== prevVal) { - newVal = value as SortingValue; - } - cookies.set(cookies.NAMES.TXS_SORT, newVal ? newVal : ''); - return newVal; - }); - }, []); + const newVal: SortingValue = value !== sorting ? value : 'default'; + cookies.set(cookies.NAMES.TXS_SORT, newVal); + setSorting(newVal); + }, [ sorting ]); return React.useMemo(() => { if (queryResult.isError || queryResult.isPending) { diff --git a/src/slices/tx/mocks/details.ts b/src/slices/tx/mocks/details.ts index af25c7cdda4..3cfb5415cbc 100644 --- a/src/slices/tx/mocks/details.ts +++ b/src/slices/tx/mocks/details.ts @@ -150,9 +150,9 @@ export const withTokenTransfer: schemas['TransactionResponse'] = { }, token_transfers: [ tokenTransferMock.erc20, + tokenTransferMock.erc8056, tokenTransferMock.erc721, tokenTransferMock.erc1155A, - tokenTransferMock.erc1155B, tokenTransferMock.erc1155C, tokenTransferMock.erc1155D, tokenTransferMock.erc404A, diff --git a/src/slices/tx/mocks/rpc.ts b/src/slices/tx/mocks/rpc.ts index 1c9fcfd71b5..6640c065712 100644 --- a/src/slices/tx/mocks/rpc.ts +++ b/src/slices/tx/mocks/rpc.ts @@ -1,4 +1,25 @@ -import type { RpcTransactionReceipt } from 'viem'; +import type { RpcTransaction, RpcTransactionReceipt } from 'viem'; + +import { TX_HASH } from 'src/slices/tx/stubs/tx'; + +export const rpcTx: RpcTransaction = { + blockHash: '0xa737203aac9f38b5355c716f46b84ff1031335d1a99b2366900378c9e4c837a5', + blockNumber: '0x171f82b', + from: '0x21dc71ddd3558cd7536bb5fa422303fb5559ea63', + gas: '0xc3500', + gasPrice: '0x793b22f4', + hash: TX_HASH, + input: '0x', + nonce: '0x1', + to: '0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e', + transactionIndex: '0x2', + value: '0x2a', + type: '0x0', + chainId: '0x1', + v: '0x25', + r: '0x2c5022ff7f78a22f1a99afbd568f75cb52812189ed8c264c8310e0b8dba2c8a8', + s: '0x50938f87c92b9eeb9777507ca8f7397840232d00d1dbac3edac6c115b4656763', +}; export const rpcTxReceipt: RpcTransactionReceipt = { blockHash: '0xa737203aac9f38b5355c716f46b84ff1031335d1a99b2366900378c9e4c837a5', @@ -11,7 +32,7 @@ export const rpcTxReceipt: RpcTransactionReceipt = { logs: [], // eslint-disable-next-line max-len logsBloom: '0x00400040000000000000000000000000000000000000000010000000000000000000000020000000001000000000010400000000000000000000000000000000000400000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010100000000000002801000000000000000000000000000000000000000000000000100000000004000000000000000080100000000000000000000000000000000000000000000802000000000000000000000000000000400000000000000000000000000000000000000000000000000000000004000000800000000000004000000000', - status: 'success' as RpcTransactionReceipt['status'], + status: '0x1', to: '0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e', transactionHash: '0xc39cf2777f03346deba8659b3ff652bbcf3dcbd4fcf846a248a171e45cac94b2', transactionIndex: '0x2', diff --git a/src/slices/tx/mocks/state-changes.ts b/src/slices/tx/mocks/state-changes.ts index 6dc82afba1e..c08fd123429 100644 --- a/src/slices/tx/mocks/state-changes.ts +++ b/src/slices/tx/mocks/state-changes.ts @@ -1,6 +1,7 @@ import type { paths, schemas } from '@blockscout/api-types'; import * as addressParamMock from 'src/slices/address/mocks/address-param'; +import * as tokenInfoMock from 'src/slices/token/mocks/info'; import { toTokenModel } from 'src/slices/token/utils/model'; export const mintToken: schemas['StateChange'] = { @@ -27,6 +28,7 @@ export const mintToken: schemas['StateChange'] = { reputation: 'ok', }), type: 'token' as const, + ui_multiplier: null, }; export const receiveMintedToken: schemas['StateChange'] = { @@ -53,6 +55,7 @@ export const receiveMintedToken: schemas['StateChange'] = { reputation: 'ok', }), type: 'token' as const, + ui_multiplier: null, }; export const transfer1155Token: schemas['StateChange'] = { @@ -79,6 +82,7 @@ export const transfer1155Token: schemas['StateChange'] = { }), token_id: '1', type: 'token' as const, + ui_multiplier: null, }; export const receiveCoin: schemas['StateChange'] = { @@ -92,6 +96,7 @@ export const receiveCoin: schemas['StateChange'] = { is_miner: true, token: null, type: 'coin' as const, + ui_multiplier: null, }; export const sendCoin: schemas['StateChange'] = { @@ -105,6 +110,7 @@ export const sendCoin: schemas['StateChange'] = { is_miner: false, token: null, type: 'coin' as const, + ui_multiplier: null, }; export const sendERC20Token: schemas['StateChange'] = { @@ -130,6 +136,21 @@ export const sendERC20Token: schemas['StateChange'] = { reputation: 'ok', }), type: 'token' as const, + ui_multiplier: null, +}; + +export const sendERC8056Token: schemas['StateChange'] = { + address: { + ...addressParamMock.withoutName, + hash: '0xA955675Dac496eB2c384D2d288e6C07fDb2234AF', + }, + balance_after: '999900000000000000000000', + balance_before: '1000000000000000000000000', + change: '-100000000000000000000', + is_miner: false, + token: tokenInfoMock.tokenInfoERC8056, + type: 'token' as const, + ui_multiplier: '1690000000000000000', }; export const baseResponse: paths['/api/v2/transactions/{transaction_hash_param}/state-changes']['get'] = { @@ -140,6 +161,7 @@ export const baseResponse: paths['/api/v2/transactions/{transaction_hash_param}/ receiveCoin, transfer1155Token, sendERC20Token, + sendERC8056Token, ], next_page_params: { items_count: 50, diff --git a/src/slices/tx/pages/details/Transaction.spec.tsx b/src/slices/tx/pages/details/Transaction.spec.tsx new file mode 100644 index 00000000000..3957c4a1bd9 --- /dev/null +++ b/src/slices/tx/pages/details/Transaction.spec.tsx @@ -0,0 +1,68 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import { rpcTx } from 'src/slices/tx/mocks/rpc'; +import { TX_HASH } from 'src/slices/tx/stubs/tx'; + +import AppErrorBoundary from 'src/shared/errors/AppErrorBoundary'; + +import { SECOND } from 'src/toolkit/utils/consts'; + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { render, screen, cleanup, waitFor } from 'vitest/lib'; +import { mockApiAndRpc, rpcRequests, apiRequests } from 'vitest/utils/mockJsonRpc'; +import { routerStandIn, RouterStandInProvider } from 'vitest/utils/routerStandIn'; + +import Transaction from './Transaction'; + +const API_NOT_FOUND = { status: 404, body: JSON.stringify({ message: 'Not found' }) }; + +const TX_NOT_FOUND_TITLE = 'Sorry, we are unable to locate this transaction hash'; +const DATA_SYNC_ALERT = /Data sync in progress/; +const GENERIC_ERROR_ALERT = /Something went wrong/; + +const RPC_RETRY_DELAY = 5 * SECOND; + +beforeEach(() => { + fetchMock.resetMocks(); + vi.useFakeTimers({ shouldAdvanceTime: true }); + // the boundary re-throws the page error to the console; keep the run readable + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +afterEach(() => { + cleanup(); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +function renderPage(tab: string) { + routerStandIn.reset({ pathname: '/tx/[hash]', query: { hash: TX_HASH, tab } }); + return render(<RouterStandInProvider><AppErrorBoundary><Transaction/></AppErrorBoundary></RouterStandInProvider>); +} + +describe('tx page on an API 404', () => { + it('shows the not-found screen on a non-details tab once the RPC node does not know the transaction', async() => { + mockApiAndRpc({ api: () => API_NOT_FOUND }); + renderPage('token_transfers'); + + await waitFor(() => expect(rpcRequests()).toEqual([ 'eth_getTransactionByHash' ])); + await vi.advanceTimersByTimeAsync(RPC_RETRY_DELAY); + await vi.advanceTimersByTimeAsync(RPC_RETRY_DELAY); + + expect(await screen.findByText(TX_NOT_FOUND_TITLE)).toBeTruthy(); + expect(screen.queryByText(GENERIC_ERROR_ALERT)).toBeNull(); + expect(apiRequests().some((url) => url.includes('/token-transfers'))).toBe(false); + }); + + it('shows the data-sync alert on a non-details tab while the RPC node serves the transaction', async() => { + mockApiAndRpc({ api: () => API_NOT_FOUND, rpc: { eth_getTransactionByHash: rpcTx } }); + renderPage('logs'); + + expect(await screen.findByText(DATA_SYNC_ALERT)).toBeTruthy(); + expect(screen.queryByText(TX_NOT_FOUND_TITLE)).toBeNull(); + expect(screen.queryByText(GENERIC_ERROR_ALERT)).toBeNull(); + expect(apiRequests().some((url) => url.includes('/logs'))).toBe(false); + }); +}); diff --git a/src/slices/tx/pages/details/Transaction.tsx b/src/slices/tx/pages/details/Transaction.tsx index 2a14a6dc8eb..2a30cf60993 100644 --- a/src/slices/tx/pages/details/Transaction.tsx +++ b/src/slices/tx/pages/details/Transaction.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; +import { Flex } from '@chakra-ui/react'; import React from 'react'; import type { MetadataTag as TMetadataTag } from 'src/features/address-metadata/components/tag/types'; @@ -13,10 +13,12 @@ import TxInternals from 'src/slices/internal-tx/pages/tx/TxInternals'; import TxTokenTransfer from 'src/slices/token-transfer/pages/tx/TxTokenTransfer'; import useTxQuery from 'src/slices/tx/hooks/useTxQuery'; +import AppActionButton from 'src/features/address-metadata/components/AppActionButton'; import MetadataTags from 'src/features/address-metadata/components/tag/MetadataTags'; +import useAppActionData from 'src/features/address-metadata/hooks/useAppActionData'; +import { getVisibleProtocolTags } from 'src/features/address-metadata/utils/get-visible-protocol-tags'; import TextAd from 'src/features/ads/text/components/TextAd'; import TxDetailsWrapped from 'src/features/chain-variants/suave/pages/tx/TxDetailsWrapped'; -import { isPublicClientAvailable } from 'src/features/connect-wallet/utils/public-client'; import TxBlobs from 'src/features/data-availability/pages/tx/TxBlobs'; import TxFheOperations from 'src/features/fhe-operations/pages/tx/TxFheOperations'; import TxAuthorizations from 'src/features/tx-authorization/pages/tx/TxAuthorizations'; @@ -24,10 +26,12 @@ import TxAssetFlows from 'src/features/tx-interpretation/noves/pages/tx-asset-fl import TxUserOps from 'src/features/user-ops/pages/tx/TxUserOps'; import config from 'src/config'; +import ApiDegradationAlert from 'src/shared/api-degradation/ApiDegradationAlert'; import isCustomAppError from 'src/shared/errors/is-custom-app-error'; import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; import getQueryParamString from 'src/shared/router/get-query-param-string'; import useEtherscanRedirects from 'src/shared/router/useEtherscanRedirects'; +import { useRouter } from 'src/shared/router/useRouter'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -50,16 +54,14 @@ const TransactionPageContent = () => { const txQuery = useTxQuery(); - const { data, isPlaceholderData, isError, error, errorUpdateCount } = txQuery; - - const showDegradedView = isPublicClientAvailable && ((isError && error.status !== 422) || isPlaceholderData) && errorUpdateCount > 0; + const { data, isError, error, isDegradedData } = txQuery; const tabs: Array<TabItemRegular> = (() => { - const detailsComponent = showDegradedView ? - <TxDetailsRpc hash={ hash } txQuery={ txQuery }/> : + const detailsComponent = isDegradedData ? + <TxDetailsRpc txQuery={ txQuery }/> : <TxDetailsApi txQuery={ txQuery }/>; - return [ + const allTabs: Array<TabItemRegular | undefined> = [ { id: 'index', title: config.features.suave.isEnabled && data?.wrapped ? 'Confidential compute tx details' : 'Details', @@ -93,9 +95,19 @@ const TransactionPageContent = () => { txQuery.data?.authorization_list?.length ? { id: 'authorizations', title: 'Authorizations', component: <TxAuthorizations txQuery={ txQuery }/> } : undefined, - ].filter(Boolean); + ]; + + // the RPC node knows nothing beyond the details, so every other tab waits for the API to catch up + return allTabs + .filter(Boolean) + .map((tab) => tab.id === 'index' || !isDegradedData ? + tab : + { ...tab, component: <ApiDegradationAlert isLoading={ txQuery.isPlaceholderData }/> }, + ); })(); + const appActionData = useAppActionData(txQuery.data?.to?.hash, !txQuery.isPlaceholderData); + const txTags: Array<TMetadataTag> = data?.transaction_tag ? [ { slug: data.transaction_tag, name: data.transaction_tag, tagType: 'private_tag' as const, ordinal: 1 } ] : []; @@ -112,26 +124,26 @@ const TransactionPageContent = () => { txTags.push({ slug: 'sponsored', name: 'Sponsored', tagType: 'custom' as const, ordinal: 0 }); } - const protocolTags = data?.to?.metadata?.tags?.filter(tag => tag.tagType === 'protocol'); - if (protocolTags && protocolTags.length > 0) { - txTags.push(...protocolTags); - } + txTags.push(...getVisibleProtocolTags(data?.to?.metadata?.tags)); const isTabsLoading = txQuery.isPlaceholderData && !txQuery.errorUpdateCount; - const tags = ( - <MetadataTags - isLoading={ isTabsLoading } - tags={ txTags } - /> + const contentAfter = ( + <Flex alignItems="center" justifyContent="space-between" flexGrow={ 1 } flexWrap="wrap" gap={ 3 }> + <MetadataTags + isLoading={ isTabsLoading } + tags={ txTags } + /> + { appActionData && ( + <AppActionButton data={ appActionData } addressHash={ txQuery.data?.to?.hash } txHash={ hash } source="Txn"/> + ) } + </Flex> ); const titleSecondRow = <TxSubHeading hash={ hash } hasTag={ Boolean(data?.transaction_tag) } txQuery={ txQuery }/>; - if (isError && !showDegradedView) { - if (isCustomAppError(error)) { - throwOnResourceLoadError({ resource: 'core:tx', error, isError: true }); - } + if (isError && isCustomAppError(error)) { + throwOnResourceLoadError({ resource: 'core:tx', error, isError: true }); } return ( @@ -139,7 +151,7 @@ const TransactionPageContent = () => { <TextAd mb={ 6 }/> <PageTitle title="Transaction details" - contentAfter={ tags } + contentAfter={ contentAfter } secondRow={ titleSecondRow } /> <RoutedTabs tabs={ tabs } isLoading={ isTabsLoading }/> diff --git a/src/slices/tx/pages/details/TxSubHeading.pw.tsx b/src/slices/tx/pages/details/TxSubHeading.pw.tsx index 7f5658f4a87..8eb13d7e5f9 100644 --- a/src/slices/tx/pages/details/TxSubHeading.pw.tsx +++ b/src/slices/tx/pages/details/TxSubHeading.pw.tsx @@ -1,12 +1,9 @@ import React from 'react'; -import type { AddressMetadataInfo, AddressMetadataTagApi } from 'src/features/address-metadata/types/api'; - -import * as addressParamMock from 'src/slices/address/mocks/address-param'; import type { TxQuery } from 'src/slices/tx/hooks/useTxQuery'; import * as txMock from 'src/slices/tx/mocks/details'; -import { protocolTagWithMeta } from 'src/features/address-metadata/mocks/tags'; +import { generateAddressMetadataInfo, protocolTag } from 'src/features/address-metadata/mocks/tags'; import { txInterpretation } from 'src/features/tx-interpretation/blockscout/mocks'; import { transaction as novesTransaction } from 'src/features/tx-interpretation/noves/mocks'; @@ -25,25 +22,14 @@ const txQuery = { isError: false, } as TxQuery; +const recipientHash = txMock.base.to?.hash as string; + const addressMetadataQueryParams = { - addresses: [ txMock.base.to?.hash as string ], + addresses: [ recipientHash ], chainId: config.chain.id, tagsLimit: '20', }; -function generateAddressMetadataResponse(tag: AddressMetadataTagApi) { - return { - addresses: { - [ txMock.base.to?.hash?.toLowerCase() as string ]: { - tags: [ { - ...tag, - meta: JSON.stringify(tag.meta), - } ], - }, - }, - } as AddressMetadataInfo; -} - test('no interpretation +@mobile', async({ render }) => { const component = await render(<TxSubHeading hash={ hash } hasTag={ false } txQuery={ txQuery }/>); await expect(component).toHaveScreenshot(); @@ -60,16 +46,6 @@ test.describe('blockscout provider', () => { await expect(component).toHaveScreenshot(); }); - test('with interpretation and action button +@mobile +@dark-mode', async({ render, mockApiResponse, mockAssetResponse }) => { - const meta = { ...protocolTagWithMeta.meta, appMarketplaceURL: undefined }; - const metadataResponse = generateAddressMetadataResponse({ ...protocolTagWithMeta, meta }); - await mockApiResponse('metadata:info', metadataResponse, { queryParams: addressMetadataQueryParams }); - await mockAssetResponse(protocolTagWithMeta?.meta?.appLogoURL as string, './playwright/mocks/image_s.jpg'); - await mockApiResponse('core:tx_interpretation', txInterpretation, { pathParams: { hash } }); - const component = await render(<TxSubHeading hash={ hash } hasTag={ false } txQuery={ txQuery }/>); - await expect(component).toHaveScreenshot(); - }); - test('with interpretation and recipient name +@mobile', async({ render, mockApiResponse }) => { const newTxQuery = { ...txQuery, data: txMock.withRecipientName } as TxQuery; await mockApiResponse('core:tx_interpretation', txInterpretation, { pathParams: { hash } }); @@ -101,42 +77,16 @@ test.describe('blockscout provider', () => { await expect(component).toHaveScreenshot(); }); - test('with interpretation and view all link, and action button (external link) +@mobile', async({ - render, mockApiResponse, mockAssetResponse, - }) => { - const metadataResponse = generateAddressMetadataResponse(protocolTagWithMeta); - await mockApiResponse('metadata:info', metadataResponse, { queryParams: addressMetadataQueryParams }); - await mockAssetResponse(protocolTagWithMeta?.meta?.appLogoURL as string, './playwright/mocks/image_s.jpg'); - await mockApiResponse( - 'core:tx_interpretation', - { data: { summaries: [ ...txInterpretation.data.summaries, ...txInterpretation.data.summaries ] } }, - { pathParams: { hash } }, - ); - const component = await render(<TxSubHeading hash={ hash } hasTag={ false } txQuery={ txQuery }/>); - await expect(component).toHaveScreenshot(); - }); - - test('no interpretation, has method called', async({ render, mockApiResponse, mockAssetResponse }) => { + test('no interpretation, has method called', async({ render, mockApiResponse }) => { const newTxQuery = { ...txQuery, data: { ...txMock.withRecipientContract, status: 'error' } } as TxQuery; - const metadataResponse = generateAddressMetadataResponse(protocolTagWithMeta); + const metadataResponse = generateAddressMetadataInfo(recipientHash, protocolTag); await mockApiResponse('metadata:info', metadataResponse, { queryParams: addressMetadataQueryParams }); - await mockAssetResponse(protocolTagWithMeta?.meta?.appLogoURL as string, './playwright/mocks/image_s.jpg'); await mockApiResponse('core:tx_interpretation', { data: { summaries: [] } }, { pathParams: { hash } }); const component = await render(<TxSubHeading hash={ hash } hasTag={ false } txQuery={ newTxQuery }/>); await expect(component).toHaveScreenshot(); }); - test('no interpretation, with action button', async({ render, mockApiResponse, mockAssetResponse }) => { - const metadataResponse = generateAddressMetadataResponse(protocolTagWithMeta); - await mockApiResponse('metadata:info', metadataResponse, { queryParams: addressMetadataQueryParams }); - await mockAssetResponse(protocolTagWithMeta?.meta?.appLogoURL as string, './playwright/mocks/image_s.jpg'); - - const newTxQuery = { ...txQuery, data: { ...txMock.pending, to: addressParamMock.contract } } as TxQuery; - const component = await render(<TxSubHeading hash={ hash } hasTag={ false } txQuery={ newTxQuery }/>); - await expect(component).toHaveScreenshot(); - }); - test('no interpretation (pending)', async({ render, mockApiResponse }) => { const txPendingQuery = { data: txMock.pending, diff --git a/src/slices/tx/pages/details/TxSubHeading.tsx b/src/slices/tx/pages/details/TxSubHeading.tsx index f5bd6abd327..2061608ad59 100644 --- a/src/slices/tx/pages/details/TxSubHeading.tsx +++ b/src/slices/tx/pages/details/TxSubHeading.tsx @@ -12,8 +12,6 @@ import ActionsMenu from 'src/shell/page/actions-menu/ActionsMenu'; import TxEntity from 'src/slices/tx/components/entity/TxEntity'; import type { TxQuery } from 'src/slices/tx/hooks/useTxQuery'; -import AppActionButton from 'src/features/address-metadata/components/AppActionButton'; -import useAppActionData from 'src/features/address-metadata/hooks/useAppActionData'; import AlternativeExplorers from 'src/features/alternative-explorers/components/AlternativeExplorers'; import { useMultichainContext } from 'src/features/multichain/context'; import { TX_INTERPRETATION } from 'src/features/tx-interpretation/blockscout/stubs'; @@ -39,8 +37,6 @@ const TxSubHeading = ({ hash, hasTag, txQuery }: Props) => { const hasInterpretationFeature = feature.isEnabled; const isNovesInterpretation = hasInterpretationFeature && feature.provider === 'noves'; - const appActionData = useAppActionData(txQuery.data?.to?.hash, !txQuery.isPlaceholderData); - const txInterpretationQuery = useApiQuery('core:tx_interpretation', { pathParams: { hash }, queryOptions: { @@ -157,9 +153,6 @@ const TxSubHeading = ({ hash, hasTag, txQuery }: Props) => { mt={{ base: 3, lg: 0 }} > { !hasTag && <ActionsMenu isLoading={ isLoading }/> } - { appActionData && ( - <AppActionButton data={ appActionData } txHash={ hash } source="Txn"/> - ) } <AlternativeExplorers type="tx" pathParam={ hash } ml="auto"/> </Flex> </Box> diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_dark-color-mode_blockscout-provider-with-interpretation-and-action-button-mobile-dark-mode-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_dark-color-mode_blockscout-provider-with-interpretation-and-action-button-mobile-dark-mode-1.png deleted file mode 100644 index d6a8b6c803d..00000000000 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_dark-color-mode_blockscout-provider-with-interpretation-and-action-button-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-no-interpretation-has-method-called-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-no-interpretation-has-method-called-1.png index ef47be73417..a103a65dbd2 100644 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-no-interpretation-has-method-called-1.png and b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-no-interpretation-has-method-called-1.png differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-no-interpretation-with-action-button-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-no-interpretation-with-action-button-1.png deleted file mode 100644 index 1f16b4d7d9f..00000000000 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-no-interpretation-with-action-button-1.png and /dev/null differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-with-interpretation-and-action-button-mobile-dark-mode-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-with-interpretation-and-action-button-mobile-dark-mode-1.png deleted file mode 100644 index 3b8c1cbc3f0..00000000000 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-with-interpretation-and-action-button-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-with-interpretation-and-vi-ee08a-k-and-action-button-external-link-mobile-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-with-interpretation-and-vi-ee08a-k-and-action-button-external-link-mobile-1.png deleted file mode 100644 index 80cae9896bb..00000000000 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_default_blockscout-provider-with-interpretation-and-vi-ee08a-k-and-action-button-external-link-mobile-1.png and /dev/null differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-action-button-mobile-dark-mode-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-action-button-mobile-dark-mode-1.png deleted file mode 100644 index 0ac2392a380..00000000000 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-action-button-mobile-dark-mode-1.png and /dev/null differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-ENS-domain-mobile-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-ENS-domain-mobile-1.png index cb197d95946..820e1a20dc9 100644 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-ENS-domain-mobile-1.png and b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-ENS-domain-mobile-1.png differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-name-mobile-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-name-mobile-1.png index 6932b6bafe9..db14eeec74e 100644 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-name-mobile-1.png and b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-name-mobile-1.png differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-name-tag-mobile-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-name-tag-mobile-1.png index d075aacb423..3b98d3d01b2 100644 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-name-tag-mobile-1.png and b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-recipient-name-tag-mobile-1.png differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-vi-ee08a-k-and-action-button-external-link-mobile-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-vi-ee08a-k-and-action-button-external-link-mobile-1.png deleted file mode 100644 index dc5957cf46c..00000000000 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-vi-ee08a-k-and-action-button-external-link-mobile-1.png and /dev/null differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-view-all-link-mobile-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-view-all-link-mobile-1.png index 97c9d5ed45f..98a36e8eb33 100644 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-view-all-link-mobile-1.png and b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-and-view-all-link-mobile-1.png differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-mobile-dark-mode-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-mobile-dark-mode-1.png index ebf08b008c9..6fd2662935a 100644 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-mobile-dark-mode-1.png and b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_blockscout-provider-with-interpretation-mobile-dark-mode-1.png differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_no-interpretation-mobile-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_no-interpretation-mobile-1.png index 18784658062..300e96610d8 100644 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_no-interpretation-mobile-1.png and b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_no-interpretation-mobile-1.png differ diff --git a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_noves-provider-with-interpretation-mobile-dark-mode-1.png b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_noves-provider-with-interpretation-mobile-dark-mode-1.png index f291b8628d7..fff0062c5ed 100644 Binary files a/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_noves-provider-with-interpretation-mobile-dark-mode-1.png and b/src/slices/tx/pages/details/__screenshots__/TxSubHeading.pw.tsx_mobile_noves-provider-with-interpretation-mobile-dark-mode-1.png differ diff --git a/src/slices/tx/pages/details/info/TxDetails.pw.tsx b/src/slices/tx/pages/details/info/TxDetails.pw.tsx index f204330603d..d22636c16b2 100644 --- a/src/slices/tx/pages/details/info/TxDetails.pw.tsx +++ b/src/slices/tx/pages/details/info/TxDetails.pw.tsx @@ -1,5 +1,3 @@ -import React from 'react'; - import * as tokenInstanceMock from 'src/slices/token/mocks/instance'; import * as txMock from 'src/slices/tx/mocks/details'; @@ -10,7 +8,7 @@ import { arbitrumTxn } from 'src/features/rollup/arbitrum/mocks/tx'; import { l2tx } from 'src/features/rollup/common/mocks/tx'; import { ENVS_MAP } from 'playwright/fixtures/mockEnvs'; -import { test, expect } from 'playwright/lib'; +import { expect, test } from 'playwright/lib'; import * as pwConfig from 'playwright/utils/config'; import TxDetails from './TxDetails'; @@ -35,7 +33,8 @@ test('creating contact', async({ render, page }) => { }); }); -test('with token transfer +@mobile', async({ render, page, mockAssetResponse }) => { +test('with token transfer +@mobile', async({ render, page, mockAssetResponse, mockEnvs }) => { + await mockEnvs(ENVS_MAP.additionalTokenTypes); await mockAssetResponse(tokenInstanceMock.base.image_url as string, './playwright/mocks/image_s.jpg'); const component = await render(<TxDetails data={ txMock.withTokenTransfer } isLoading={ false }/>); diff --git a/src/slices/tx/pages/details/info/TxDetails.tsx b/src/slices/tx/pages/details/info/TxDetails.tsx index aa8b16882d6..a78ce256033 100644 --- a/src/slices/tx/pages/details/info/TxDetails.tsx +++ b/src/slices/tx/pages/details/info/TxDetails.tsx @@ -9,7 +9,6 @@ import { VStack, } from '@chakra-ui/react'; import BigNumber from 'bignumber.js'; -import { route } from 'nextjs-routes'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -50,6 +49,7 @@ import DetailedInfoNativeCoinValue from 'src/shared/detailed-info/DetailedInfoNa import DetailedInfoSponsoredItem from 'src/shared/detailed-info/DetailedInfoSponsoredItem'; import DetailedInfoTimestamp from 'src/shared/detailed-info/DetailedInfoTimestamp'; import VerificationSteps from 'src/shared/lifecycle/steps/VerificationSteps'; +import { route } from 'src/shared/router/routes'; import StatusTag from 'src/shared/tags/status-tag/StatusTag'; import TextSeparator from 'src/shared/texts/TextSeparator'; import GasPriceValue from 'src/shared/values/entity/GasPriceValue'; @@ -365,6 +365,7 @@ const TxDetails = ({ data, isLoading, socketStatus, noTxActions }: Props) => { } return message.relay_chain !== undefined ? ( <AddressEntityInterop + key={ message.nonce } chain={ message.relay_chain } address={{ hash: message.target_address_hash }} isLoading={ isLoading } @@ -372,7 +373,13 @@ const TxDetails = ({ data, isLoading, socketStatus, noTxActions }: Props) => { w="100%" /> ) : ( - <AddressEntity address={{ hash: message.target_address_hash }} isLoading={ isLoading } truncation="dynamic" w="100%"/> + <AddressEntity + key={ message.nonce } + address={{ hash: message.target_address_hash }} + isLoading={ isLoading } + truncation="dynamic" + w="100%" + /> ); }) } </VStack> diff --git a/src/slices/tx/pages/details/info/TxDetailsRpc.tsx b/src/slices/tx/pages/details/info/TxDetailsRpc.tsx index fc9a7c84abf..633747e633a 100644 --- a/src/slices/tx/pages/details/info/TxDetailsRpc.tsx +++ b/src/slices/tx/pages/details/info/TxDetailsRpc.tsx @@ -1,117 +1,28 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import { Flex } from '@chakra-ui/react'; -import { useQuery } from '@tanstack/react-query'; import React from 'react'; -import type { Chain, GetBlockReturnType, GetTransactionReturnType, TransactionReceipt } from 'viem'; -import type { schemas } from '@blockscout/api-types'; - -import { GET_BLOCK } from 'src/slices/block/stubs/rpc'; import TestnetWarning from 'src/slices/chain/TestnetWarning'; import type { TxQuery } from 'src/slices/tx/hooks/useTxQuery'; -import { GET_TRANSACTION, GET_TRANSACTION_RECEIPT, GET_TRANSACTION_CONFIRMATIONS } from 'src/slices/tx/stubs/rpc'; -import { formatTxDetailsRpcData } from 'src/slices/tx/utils/format-rpc-data'; - -import { getPublicClient } from 'src/features/connect-wallet/utils/public-client'; -import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; import ApiDegradationAlert from 'src/shared/api-degradation/ApiDegradationAlert'; -import isCustomAppError from 'src/shared/errors/is-custom-app-error'; -import throwOnResourceLoadError from 'src/shared/errors/throw-on-resource-load-error'; - -import { SECOND } from 'src/toolkit/utils/consts'; import TxDetails from './TxDetails'; -type RpcResponseType = [ - GetTransactionReturnType<Chain, 'latest'>, - TransactionReceipt | null, - bigint | null, - GetBlockReturnType<Chain, false, 'latest'> | null, -]; - interface Props { - hash: string; txQuery: TxQuery; } -const TxDetailsRpc = ({ hash, txQuery }: Props) => { - - const [ originalError ] = React.useState(txQuery.error); - - const query = useQuery<RpcResponseType, unknown, schemas['TransactionResponse'] | null>({ - queryKey: [ 'RPC', 'tx', { hash } ], - queryFn: async() => { - const publicClient = await getPublicClient(); - if (!publicClient) { - throw new Error('No public RPC client'); - } - - const tx = await publicClient.getTransaction({ hash: hash as `0x${ string }` }); - - if (!tx) { - throw new Error('Not found'); - } - - const txReceipt = await publicClient.getTransactionReceipt({ hash: hash as `0x${ string }` }).catch(() => null); - const block = await publicClient.getBlock({ blockHash: tx.blockHash }).catch(() => null); - const latestBlock = await publicClient.getBlock().catch(() => null); - const confirmations = latestBlock && block ? latestBlock.number - block.number + BigInt(1) : null; - - return [ - tx, - txReceipt, - confirmations, - block, - ]; - }, - select: (response) => { - const [ tx, receipt, confirmations, block ] = response; - - return formatTxDetailsRpcData({ tx, receipt, confirmations, block }); - }, - placeholderData: [ - GET_TRANSACTION, - GET_TRANSACTION_RECEIPT, - GET_TRANSACTION_CONFIRMATIONS, - GET_BLOCK, - ], - refetchOnMount: false, - enabled: txQuery.isFetchedAfterMount, - retry: 2, - retryDelay: 5 * SECOND, - }); - - const hasData = Boolean(query.data); - - React.useEffect(() => { - if (!query.isPlaceholderData && hasData) { - txQuery.setRefetchEnabled(true); - } - }, [ hasData, query.isPlaceholderData, txQuery ]); - - React.useEffect(() => { - return () => { - txQuery.setRefetchEnabled(false); - }; - }, [ txQuery ]); - - if (!query.data) { - if (originalError && isCustomAppError(originalError)) { - throwOnResourceLoadError({ resource: 'core:tx', error: originalError, isError: true }); - } - - return <ApiFetchAlert/>; - } - +const TxDetailsRpc = ({ txQuery }: Props) => { return ( <> <Flex rowGap={{ base: 1, lg: 2 }} mb={{ base: 3, lg: 6 }} flexDir="column"> - <TestnetWarning isLoading={ query.isPlaceholderData }/> - { originalError?.status !== 404 && <ApiDegradationAlert isLoading={ query.isPlaceholderData }/> } + <TestnetWarning isLoading={ txQuery.isPlaceholderData }/> + { /* on a 404 the API is not degraded, the transaction just is not indexed yet */ } + { txQuery.apiError?.status !== 404 && <ApiDegradationAlert isLoading={ txQuery.isPlaceholderData }/> } </Flex> - <TxDetails data={ query.data } isLoading={ query.isPlaceholderData } noTxActions/> + <TxDetails data={ txQuery.data } isLoading={ txQuery.isPlaceholderData } noTxActions/> </> ); }; diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_dark-color-mode_between-addresses-mobile-dark-mode-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_dark-color-mode_between-addresses-mobile-dark-mode-1.png index d49a2bb9a1d..64a53ef8c30 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_dark-color-mode_between-addresses-mobile-dark-mode-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_dark-color-mode_between-addresses-mobile-dark-mode-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_arbitrum-L1-status-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_arbitrum-L1-status-1.png index ab929014d76..6e520af2683 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_arbitrum-L1-status-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_arbitrum-L1-status-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_between-addresses-mobile-dark-mode-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_between-addresses-mobile-dark-mode-1.png index 858fe2b30a4..4cedcfae689 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_between-addresses-mobile-dark-mode-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_between-addresses-mobile-dark-mode-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_creating-contact-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_creating-contact-1.png index 6b62effcada..3ba8af0ae7c 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_creating-contact-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_creating-contact-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_l2-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_l2-1.png index 7a1e178a6c4..0fc81e97ee5 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_l2-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_l2-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_pending-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_pending-1.png index e7584e9807d..4c9e8141a29 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_pending-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_pending-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_stability-customization-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_stability-customization-1.png index 497786d0de0..81e7507f302 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_stability-customization-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_stability-customization-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-blob-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-blob-1.png index 9addbfd107d..8308c1aa09a 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-blob-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-blob-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-external-txs-mobile-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-external-txs-mobile-1.png index d042d674d8b..48b7cb8584b 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-external-txs-mobile-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-external-txs-mobile-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-grouped-fees-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-grouped-fees-1.png index 7575bcfe72b..b3378bc19cc 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-grouped-fees-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-grouped-fees-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-interop-message-in-mobile-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-interop-message-in-mobile-1.png index 92c40aea254..c02708337f3 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-interop-message-in-mobile-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-interop-message-in-mobile-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-interop-message-out-mobile-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-interop-message-out-mobile-1.png index 1eba1cde462..756bbc0ade8 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-interop-message-out-mobile-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_with-interop-message-out-mobile-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_without-testnet-warning-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_without-testnet-warning-1.png index 70b3bc236a3..d1259344b9d 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_without-testnet-warning-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_default_without-testnet-warning-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_between-addresses-mobile-dark-mode-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_between-addresses-mobile-dark-mode-1.png index 63f5dad7088..a4e69f1f464 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_between-addresses-mobile-dark-mode-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_between-addresses-mobile-dark-mode-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-external-txs-mobile-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-external-txs-mobile-1.png index d2a4f08da8e..5e3462cdc4a 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-external-txs-mobile-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-external-txs-mobile-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-interop-message-in-mobile-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-interop-message-in-mobile-1.png index a2afb71d607..97d41e41336 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-interop-message-in-mobile-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-interop-message-in-mobile-1.png differ diff --git a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-interop-message-out-mobile-1.png b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-interop-message-out-mobile-1.png index 7269531d47b..6314578bba7 100644 Binary files a/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-interop-message-out-mobile-1.png and b/src/slices/tx/pages/details/info/__screenshots__/TxDetails.pw.tsx_mobile_with-interop-message-out-mobile-1.png differ diff --git a/src/slices/tx/pages/details/info/parts/TxHash.tsx b/src/slices/tx/pages/details/info/parts/TxHash.tsx index 44169e121e1..402ae82069f 100644 --- a/src/slices/tx/pages/details/info/parts/TxHash.tsx +++ b/src/slices/tx/pages/details/info/parts/TxHash.tsx @@ -13,10 +13,10 @@ import config from 'src/config'; import * as DetailedInfo from 'src/shared/detailed-info/DetailedInfo'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import CopyToClipboard from 'src/shared/texts/CopyToClipboard'; -import HashStringShortenDynamic from 'src/shared/texts/HashStringShortenDynamic'; import TextSeparator from 'src/shared/texts/TextSeparator'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; +import { Truncate } from 'src/toolkit/components/truncation/Truncate'; const externalTxFeature = config.features.externalTxs; @@ -51,7 +51,7 @@ const TxHash = ({ hash, isLoading, status }: Props) => { <Flex flexWrap="nowrap" alignItems="center" overflow="hidden"> { status === null && <Spinner mr={ 2 } size="sm" flexShrink={ 0 }/> } <Skeleton loading={ isLoading } overflow="hidden"> - <HashStringShortenDynamic hash={ hash }/> + <Truncate value={ hash }/> </Skeleton> <CopyToClipboard text={ hash } isLoading={ isLoading }/> { config.features.metasuites.isEnabled && ( diff --git a/src/slices/tx/pages/details/logs/TxLogs.tsx b/src/slices/tx/pages/details/logs/TxLogs.tsx index 198a5bdc6c5..c2a5d8792b8 100644 --- a/src/slices/tx/pages/details/logs/TxLogs.tsx +++ b/src/slices/tx/pages/details/logs/TxLogs.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Box } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -13,10 +13,10 @@ import TxPendingAlert from 'src/slices/tx/components/TxPendingAlert'; import TxSocketAlert from 'src/slices/tx/components/TxSocketAlert'; import type { TxQuery } from 'src/slices/tx/hooks/useTxQuery'; -import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; +import DataList from 'src/shared/lists/DataList'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; // log rows are tall, so the initial window is smaller than the default @@ -28,7 +28,7 @@ interface Props { } const TxLogs = ({ txQuery, logsFilter }: Props) => { - const { data, isPlaceholderData, isError, pagination, queryHash } = useQueryWithPages({ + const { data, isInitialLoading, isTransitioning, isError, pagination, queryHash } = useApiPaginatedQuery({ resourceName: 'core:tx_logs', pathParams: { hash: txQuery.data?.hash }, options: { @@ -39,7 +39,7 @@ const TxLogs = ({ txQuery, logsFilter }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: data?.items, - isEnabled: !isPlaceholderData, + isEnabled: !isInitialLoading, minItemsNum: INITIAL_RENDERED_ITEMS_NUM, resetKey: queryHash, }); @@ -48,42 +48,41 @@ const TxLogs = ({ txQuery, logsFilter }: Props) => { return txQuery.socketStatus ? <TxSocketAlert status={ txQuery.socketStatus }/> : <TxPendingAlert/>; } - if (isError || txQuery.isError) { - return <ApiFetchAlert/>; - } - let items: Array<schemas['Log']> = []; if (data?.items) { - if (isPlaceholderData) { + if (isInitialLoading) { items = data?.items; } else { items = logsFilter ? data.items.filter(logsFilter) : data.items; } } - if (!items.length) { - return <Text as="span">There are no logs for this transaction.</Text>; - } + const actionBar = pagination.isVisible ? ( + <ActionBar mt={ -6 }> + <Pagination ml="auto" { ...pagination }/> + </ActionBar> + ) : null; return ( - <Box> - { pagination.isVisible && ( - <ActionBar mt={ -6 }> - <Pagination ml="auto" { ...pagination }/> - </ActionBar> - ) } + <DataList + isError={ isError || txQuery.isError } + itemsNum={ items.length } + emptyText="There are no logs for this transaction." + actionBar={ actionBar } + isTransitioning={ isTransitioning } + > { items.slice(0, renderedItemsNum).map((item, index) => ( <LogItem - key={ index } + key={ item.transaction_hash + '_' + item.index + (isInitialLoading ? index : '') } data={ item } type="transaction" - isLoading={ isPlaceholderData } + isLoading={ isInitialLoading } defaultDataType={ txQuery.data?.zilliqa?.is_scilla ? 'UTF-8' : undefined } /> )) } <Box ref={ cutRef } h={ 0 }/> - </Box> + </DataList> ); }; diff --git a/src/slices/tx/pages/details/raw-trace/TxRawTrace.tsx b/src/slices/tx/pages/details/raw-trace/TxRawTrace.tsx index 1e1b0aa7f31..5ca7fa13f5b 100644 --- a/src/slices/tx/pages/details/raw-trace/TxRawTrace.tsx +++ b/src/slices/tx/pages/details/raw-trace/TxRawTrace.tsx @@ -1,6 +1,5 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { useRouter } from 'next/router'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; @@ -18,6 +17,7 @@ import { TX_RAW_TRACE } from 'src/slices/tx/stubs/tx'; import ApiFetchAlert from 'src/shared/alerts/ApiFetchAlert'; import RawDataSnippet from 'src/shared/data/RawDataSnippet'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; interface Props { txQuery: TxQuery; diff --git a/src/slices/tx/pages/details/state/TxState.pw.tsx b/src/slices/tx/pages/details/state/TxState.pw.tsx index 939d2e6a4ec..19ede560564 100644 --- a/src/slices/tx/pages/details/state/TxState.pw.tsx +++ b/src/slices/tx/pages/details/state/TxState.pw.tsx @@ -1,10 +1,10 @@ -import React from 'react'; - import type { TxQuery } from 'src/slices/tx/hooks/useTxQuery'; import * as txMock from 'src/slices/tx/mocks/details'; import * as txStateChangesMock from 'src/slices/tx/mocks/state-changes'; -import { test, expect } from 'playwright/lib'; +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { expect, test } from 'playwright/lib'; import TxState from './TxState'; @@ -14,7 +14,8 @@ const hooksConfig = { }, }; -test('base view +@mobile', async({ render, mockApiResponse }) => { +test('base view', async({ render, mockApiResponse, mockEnvs }) => { + await mockEnvs(ENVS_MAP.additionalTokenTypes); await mockApiResponse('core:tx_state_changes', txStateChangesMock.baseResponse, { pathParams: { hash: txMock.base.hash } }); const txQuery = { data: txMock.base, diff --git a/src/slices/tx/pages/details/state/TxState.tsx b/src/slices/tx/pages/details/state/TxState.tsx index 632f408229f..d37a07f7327 100644 --- a/src/slices/tx/pages/details/state/TxState.tsx +++ b/src/slices/tx/pages/details/state/TxState.tsx @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { Box, Text } from '@chakra-ui/react'; +import { Text } from '@chakra-ui/react'; import React from 'react'; import ActionBar, { ACTION_BAR_HEIGHT_DESKTOP } from 'src/shell/page/action-bar/ActionBar'; @@ -12,9 +12,10 @@ import { TX_STATE_CHANGES } from 'src/slices/tx/stubs/state-changes'; import DataList from 'src/shared/lists/DataList'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; + +import { TableContainerScrollable } from 'src/toolkit/chakra/table'; -import TxStateList from './TxStateList'; import TxStateTable from './TxStateTable'; interface Props { @@ -22,7 +23,7 @@ interface Props { } const TxState = ({ txQuery }: Props) => { - const { data, isPlaceholderData, isError, pagination } = useQueryWithPages({ + const { data, isInitialLoading, isTransitioning, isError, pagination } = useApiPaginatedQuery({ resourceName: 'core:tx_state_changes', pathParams: { hash: txQuery.data?.hash }, options: { @@ -42,14 +43,9 @@ const TxState = ({ txQuery }: Props) => { } const content = data ? ( - <> - <Box hideBelow="lg"> - <TxStateTable data={ data.items } isLoading={ isPlaceholderData } top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 }/> - </Box> - <Box hideFrom="lg"> - <TxStateList data={ data.items } isLoading={ isPlaceholderData }/> - </Box> - </> + <TableContainerScrollable> + <TxStateTable data={ data.items } isLoading={ isInitialLoading } top={ pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0 }/> + </TableContainerScrollable> ) : null; const actionBar = pagination.isVisible ? ( @@ -71,6 +67,7 @@ const TxState = ({ txQuery }: Props) => { itemsNum={ data?.items.length } emptyText="There are no state changes for this transaction." actionBar={ actionBar } + isTransitioning={ isTransitioning } > { content } </DataList> diff --git a/src/slices/tx/pages/details/state/TxStateList.tsx b/src/slices/tx/pages/details/state/TxStateList.tsx deleted file mode 100644 index 969774e74f2..00000000000 --- a/src/slices/tx/pages/details/state/TxStateList.tsx +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import TxStateListItem from './TxStateListItem'; - -interface Props { - data: Array<schemas['StateChange']>; - isLoading?: boolean; -} - -const TxStateList = ({ data, isLoading }: Props) => { - return ( - <Box> - { data.map((item, index) => <TxStateListItem key={ index } data={ item } isLoading={ isLoading }/>) } - </Box> - ); -}; - -export default TxStateList; diff --git a/src/slices/tx/pages/details/state/TxStateListItem.tsx b/src/slices/tx/pages/details/state/TxStateListItem.tsx deleted file mode 100644 index cd5861ca0c9..00000000000 --- a/src/slices/tx/pages/details/state/TxStateListItem.tsx +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; - -import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; - -import ListItemMobileGrid from 'src/shared/lists/ListItemMobileGrid'; - -import { getStateElements } from './utils'; - -interface Props { - data: schemas['StateChange']; - isLoading?: boolean; -} - -const TxStateListItem = ({ data, isLoading }: Props) => { - - const { before, after, change, tag, tokenId } = getStateElements(data, isLoading); - - return ( - <ListItemMobileGrid.Container> - - <ListItemMobileGrid.Label isLoading={ isLoading }>Address</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value py="3px" display="flex" flexWrap="nowrap" columnGap={ 3 }> - <AddressEntity - address={ data.address } - isLoading={ isLoading } - truncation="constant" - /> - { tag } - </ListItemMobileGrid.Value> - - { before && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Before</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value>{ before }</ListItemMobileGrid.Value> - </> - ) } - - { after && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>After</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value>{ after }</ListItemMobileGrid.Value> - </> - ) } - - { change && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Change</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value>{ change }</ListItemMobileGrid.Value> - </> - ) } - - { tokenId && ( - <> - <ListItemMobileGrid.Label isLoading={ isLoading }>Token ID</ListItemMobileGrid.Label> - <ListItemMobileGrid.Value py="0">{ tokenId }</ListItemMobileGrid.Value> - </> - ) } - - </ListItemMobileGrid.Container> - ); -}; - -export default TxStateListItem; diff --git a/src/slices/tx/pages/details/state/TxStateTable.tsx b/src/slices/tx/pages/details/state/TxStateTable.tsx index cf298366ac3..5f873dd681f 100644 --- a/src/slices/tx/pages/details/state/TxStateTable.tsx +++ b/src/slices/tx/pages/details/state/TxStateTable.tsx @@ -6,6 +6,8 @@ import type { schemas } from '@blockscout/api-types'; import { AddressHighlightProvider } from 'src/slices/address/contexts/address-highlight'; +import { useMultichainContext } from 'src/features/multichain/context'; + import { TableBody, TableColumnHeader, TableHeaderSticky, TableRoot, TableRow } from 'src/toolkit/chakra/table'; import TxStateTableItem from './TxStateTableItem'; @@ -17,6 +19,8 @@ interface Props { } const TxStateTable = ({ data, isLoading, top }: Props) => { + const chainData = useMultichainContext()?.chain; + return ( <AddressHighlightProvider> <TableRoot minWidth="1000px" w="100%"> @@ -31,7 +35,7 @@ const TxStateTable = ({ data, isLoading, top }: Props) => { </TableRow> </TableHeaderSticky> <TableBody> - { data.map((item, index) => <TxStateTableItem data={ item } key={ index } isLoading={ isLoading }/>) } + { data.map((item, index) => <TxStateTableItem data={ item } key={ index } chainData={ chainData } isLoading={ isLoading }/>) } </TableBody> </TableRoot> </AddressHighlightProvider> diff --git a/src/slices/tx/pages/details/state/TxStateTableItem.tsx b/src/slices/tx/pages/details/state/TxStateTableItem.tsx index b4edee1967e..4da79208f55 100644 --- a/src/slices/tx/pages/details/state/TxStateTableItem.tsx +++ b/src/slices/tx/pages/details/state/TxStateTableItem.tsx @@ -4,6 +4,7 @@ import { Box } from '@chakra-ui/react'; import React from 'react'; import type { schemas } from '@blockscout/api-types'; +import type { ClusterChainConfig } from 'src/features/multichain/types/client'; import AddressEntity from 'src/slices/address/components/entity/AddressEntity'; @@ -13,11 +14,12 @@ import { getStateElements } from './utils'; interface Props { data: schemas['StateChange']; + chainData?: ClusterChainConfig; isLoading?: boolean; } -const TxStateTableItem = ({ data, isLoading }: Props) => { - const { before, after, change, tag, tokenId } = getStateElements(data, isLoading); +const TxStateTableItem = ({ data, chainData, isLoading }: Props) => { + const { before, after, change, tag, tokenId } = getStateElements(data, isLoading, chainData?.app_config); return ( <TableRow> diff --git a/src/slices/tx/pages/details/state/__screenshots__/TxState.pw.tsx_default_base-view-1.png b/src/slices/tx/pages/details/state/__screenshots__/TxState.pw.tsx_default_base-view-1.png new file mode 100644 index 00000000000..463fdebafa1 Binary files /dev/null and b/src/slices/tx/pages/details/state/__screenshots__/TxState.pw.tsx_default_base-view-1.png differ diff --git a/src/slices/tx/pages/details/state/__screenshots__/TxState.pw.tsx_default_base-view-mobile-1.png b/src/slices/tx/pages/details/state/__screenshots__/TxState.pw.tsx_default_base-view-mobile-1.png deleted file mode 100644 index 01555d00858..00000000000 Binary files a/src/slices/tx/pages/details/state/__screenshots__/TxState.pw.tsx_default_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/tx/pages/details/state/__screenshots__/TxState.pw.tsx_mobile_base-view-mobile-1.png b/src/slices/tx/pages/details/state/__screenshots__/TxState.pw.tsx_mobile_base-view-mobile-1.png deleted file mode 100644 index c68054503cc..00000000000 Binary files a/src/slices/tx/pages/details/state/__screenshots__/TxState.pw.tsx_mobile_base-view-mobile-1.png and /dev/null differ diff --git a/src/slices/tx/pages/details/state/utils.tsx b/src/slices/tx/pages/details/state/utils.tsx index c7bf602a350..d18e14d4837 100644 --- a/src/slices/tx/pages/details/state/utils.tsx +++ b/src/slices/tx/pages/details/state/utils.tsx @@ -2,16 +2,19 @@ import { Flex } from '@chakra-ui/react'; import BigNumber from 'bignumber.js'; -import React from 'react'; import type { schemas } from '@blockscout/api-types'; +import type { ChainConfig } from 'src/slices/token/types/client'; import { currencyUnits } from 'src/slices/chain/units'; import getChainValidatorTitle from 'src/slices/chain/verification-type/utils/get-chain-validator-title'; import NftEntity from 'src/slices/token/components/entity/NftEntity'; import TokenEntity from 'src/slices/token/components/entity/TokenEntity'; +import TokenMultiplierTag from 'src/slices/token/components/ui-multiplier/TokenMultiplierTag'; +import { getStateChangeUiMultiplier } from 'src/slices/tx/utils/get-state-change-ui-multiplier'; import config from 'src/config'; +import AssetValue from 'src/shared/values/entity/AssetValue'; import { Badge } from 'src/toolkit/chakra/badge'; import { Skeleton } from 'src/toolkit/chakra/skeleton'; @@ -19,7 +22,9 @@ import { Tooltip } from 'src/toolkit/chakra/tooltip'; import { ZERO_ADDRESS } from 'src/toolkit/utils/consts'; import { nbsp, space } from 'src/toolkit/utils/htmlEntities'; -export function getStateElements(data: schemas['StateChange'], isLoading?: boolean) { +const FULL_PRECISION = 0; + +export function getStateElements(data: schemas['StateChange'], isLoading?: boolean, chainConfig?: ChainConfig) { const tag = (() => { if (data.is_miner) { return ( @@ -85,27 +90,31 @@ export function getStateElements(data: schemas['StateChange'], isLoading?: boole w="auto" /> ); - const beforeBn = BigNumber(data.balance_before || '0').div(BigNumber(10 ** (Number(data.token?.decimals ?? 0)))); - const afterBn = BigNumber(data.balance_after || '0').div(BigNumber(10 ** (Number(data.token?.decimals ?? 0)))); + const decimals = data.token?.decimals; + const multiplier = getStateChangeUiMultiplier(data, chainConfig); + const multiplierTag = multiplier && <TokenMultiplierTag multiplier={ multiplier } loading={ isLoading } mr={ 2 } my="-2px"/>; + const change = (() => { - let differenceBn; - if (typeof data.change === 'string') { - differenceBn = BigNumber(data.change || '0').div(BigNumber(10 ** (Number(data.token?.decimals ?? 0)))); - } else { - differenceBn = afterBn.minus(beforeBn); - } + const differenceBn = typeof data.change === 'string' ? + BigNumber(data.change || '0') : + BigNumber(data.balance_after || '0').minus(BigNumber(data.balance_before || '0')); - if (!differenceBn || differenceBn.isEqualTo(0)) { + if (differenceBn.isEqualTo(0)) { return null; } - const changeColor = differenceBn.isGreaterThanOrEqualTo(0) ? 'green.500' : 'red.500'; - const changeSign = differenceBn.isGreaterThanOrEqualTo(0) ? '+' : '-'; + const isIncrease = differenceBn.isGreaterThanOrEqualTo(0); return ( - <Skeleton loading={ isLoading } display="inline-block" color={ changeColor } wordBreak="break-all"> - <span>{ changeSign }{ nbsp }{ differenceBn.abs().toFormat() }</span> - </Skeleton> + <AssetValue + amount={ differenceBn.abs().toFixed() } + decimals={ decimals } + multiplier={ multiplier } + accuracy={ FULL_PRECISION } + startElement={ <>{ multiplierTag }<span>{ isIncrease ? '+' : '-' }{ nbsp }</span></> } + loading={ isLoading } + color={ isIncrease ? 'green.500' : 'red.500' } + /> ); })(); @@ -126,14 +135,28 @@ export function getStateElements(data: schemas['StateChange'], isLoading?: boole return { before: data.balance_before ? ( <Flex whiteSpace="pre-wrap" justifyContent={{ base: 'flex-start', lg: 'flex-end' }} flexWrap="wrap"> - <Skeleton loading={ isLoading } wordBreak="break-all">{ beforeBn.toFormat() }</Skeleton> + <AssetValue + amount={ data.balance_before } + decimals={ decimals } + multiplier={ multiplier } + accuracy={ FULL_PRECISION } + startElement={ multiplierTag } + loading={ isLoading } + /> <span>{ space }</span> { tokenLink } </Flex> ) : null, after: data.balance_after ? ( <Flex whiteSpace="pre-wrap" justifyContent={{ base: 'flex-start', lg: 'flex-end' }} flexWrap="wrap"> - <Skeleton loading={ isLoading } wordBreak="break-all">{ afterBn.toFormat() }</Skeleton> + <AssetValue + amount={ data.balance_after } + decimals={ decimals } + multiplier={ multiplier } + accuracy={ FULL_PRECISION } + startElement={ multiplierTag } + loading={ isLoading } + /> <span>{ space }</span> { tokenLink } </Flex> diff --git a/src/slices/tx/pages/index/list/TxsContent.tsx b/src/slices/tx/pages/index/list/TxsContent.tsx index 3913f849bd4..15d17429bca 100644 --- a/src/slices/tx/pages/index/list/TxsContent.tsx +++ b/src/slices/tx/pages/index/list/TxsContent.tsx @@ -20,7 +20,6 @@ import getNextSortValue from 'src/shared/sort/get-next-sort-value'; import { TableContainerScrollable } from 'src/toolkit/chakra/table'; import TxsHeaderMobile from './TxsHeaderMobile'; -import TxsList from './TxsList'; import TxsTable from './TxsTable'; const SORT_SEQUENCE: Record<TransactionsSortingField, Array<TransactionsSortingValue>> = { @@ -39,13 +38,14 @@ type Props = { enableTimeIncrement?: boolean; top?: number; items?: Array<schemas['Transaction']>; - isPlaceholderData: boolean; + isInitialLoading: boolean; + isTransitioning?: boolean; isError: boolean; setSorting?: (value: TransactionsSortingValue) => void; sort: TransactionsSortingValue; stickyHeader?: boolean; - showTableView?: boolean; resetKey?: string; + withBlockSort?: boolean; }; const TxsContent = ({ @@ -58,72 +58,53 @@ const TxsContent = ({ enableTimeIncrement, top, items, - isPlaceholderData, + isInitialLoading, + isTransitioning, isError, setSorting, sort, stickyHeader = true, - showTableView, resetKey, + withBlockSort, }: Props) => { const isMobile = useIsMobile(); - const isTableView = isMobile ? showTableView : true; - const isLoading = isPlaceholderData; - const onSortToggle = React.useCallback((field: TransactionsSortingField) => { const value = getNextSortValue<TransactionsSortingField, TransactionsSortingValue>(SORT_SEQUENCE, field)(sort); setSorting?.(value); }, [ sort, setSorting ]); - const translationQuery = useDescribeTxs(items, currentAddress, isPlaceholderData); - - const content = (() => { - if (items && items.length > 0) { - if (isTableView) { - return ( - <TableContainerScrollable> - <TxsTable - txs={ items } - sort={ sort } - onSortToggle={ setSorting ? onSortToggle : undefined } - showBlockInfo={ showBlockInfo } - socketType={ socketType } - top={ top || (pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0) } - currentAddress={ currentAddress } - enableTimeIncrement={ enableTimeIncrement } - isLoading={ isLoading } - stickyHeader={ !isMobile && stickyHeader } - translationQuery={ translationQuery } - resetKey={ resetKey } - /> - </TableContainerScrollable> - ); - } - return ( - <TxsList - showBlockInfo={ showBlockInfo } - socketType={ socketType } - isLoading={ isLoading } - enableTimeIncrement={ enableTimeIncrement } - currentAddress={ currentAddress } - items={ items } - translationQuery={ translationQuery } - resetKey={ resetKey } - /> - ); - } - return null; - })(); + const translationQuery = useDescribeTxs(items, currentAddress, isInitialLoading); + + const content = items && items.length > 0 ? ( + <TableContainerScrollable> + <TxsTable + txs={ items } + sort={ sort } + onSortToggle={ setSorting ? onSortToggle : undefined } + showBlockInfo={ showBlockInfo } + socketType={ socketType } + top={ top || (pagination.isVisible ? ACTION_BAR_HEIGHT_DESKTOP : 0) } + currentAddress={ currentAddress } + enableTimeIncrement={ enableTimeIncrement } + isLoading={ isInitialLoading } + stickyHeader={ !isMobile && stickyHeader } + translationQuery={ translationQuery } + resetKey={ resetKey } + withBlockSort={ withBlockSort } + /> + </TableContainerScrollable> + ) : null; const actionBar = isMobile ? ( <TxsHeaderMobile mt={ -6 } sorting={ sort } - setSorting={ !isTableView ? setSorting : undefined } + setSorting={ setSorting } paginationProps={ pagination } showPagination={ pagination.isVisible } filterComponent={ filter } + withBlockSort={ withBlockSort } linkSlot={ currentAddress ? ( <CsvExport type="address_txs" @@ -146,6 +127,7 @@ const TxsContent = ({ emptyText="There are no transactions." actionBar={ actionBar } hasActiveFilters={ Boolean(filterValue) } + isTransitioning={ isTransitioning } emptyStateProps={{ term: 'transaction', }} diff --git a/src/slices/tx/pages/index/list/TxsHeaderMobile.tsx b/src/slices/tx/pages/index/list/TxsHeaderMobile.tsx index e7111156e92..2f743f7a5df 100644 --- a/src/slices/tx/pages/index/list/TxsHeaderMobile.tsx +++ b/src/slices/tx/pages/index/list/TxsHeaderMobile.tsx @@ -10,7 +10,7 @@ import type { TransactionsSortingValue } from 'src/slices/tx/types/api'; import ActionBar from 'src/shell/page/action-bar/ActionBar'; -import { SORT_OPTIONS } from 'src/slices/tx/hooks/useTxsSort'; +import { SORT_OPTIONS, SORT_OPTIONS_WITHOUT_BLOCK } from 'src/slices/tx/hooks/useTxsSort'; import Pagination from 'src/shared/pagination/Pagination'; import Sort from 'src/shared/sort/Sort'; @@ -23,13 +23,27 @@ type Props = { showPagination?: boolean; filterComponent?: React.ReactNode; linkSlot?: React.ReactNode; + withBlockSort?: boolean; }; const collection = createListCollection({ items: SORT_OPTIONS, }); -const TxsHeaderMobile = ({ filterComponent, sorting, setSorting, paginationProps, className, showPagination = true, linkSlot }: Props) => { +const collectionWithoutBlock = createListCollection({ + items: SORT_OPTIONS_WITHOUT_BLOCK, +}); + +const TxsHeaderMobile = ({ + filterComponent, + sorting, + setSorting, + paginationProps, + className, + showPagination = true, + linkSlot, + withBlockSort = true, +}: Props) => { const handleSortValueChange = React.useCallback(({ value }: { value: Array<string> }) => { setSorting?.(value[0] as TransactionsSortingValue); }, [ setSorting ]); @@ -46,7 +60,7 @@ const TxsHeaderMobile = ({ filterComponent, sorting, setSorting, paginationProps <Sort name="transactions_sorting" defaultValue={ [ sorting ] } - collection={ collection } + collection={ withBlockSort ? collection : collectionWithoutBlock } onValueChange={ handleSortValueChange } isLoading={ paginationProps.isLoading } /> diff --git a/src/slices/tx/pages/index/list/TxsList.tsx b/src/slices/tx/pages/index/list/TxsList.tsx deleted file mode 100644 index f4f34b52fd5..00000000000 --- a/src/slices/tx/pages/index/list/TxsList.tsx +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { Box } from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { TxsSocketType } from 'src/slices/tx/types/socket'; - -import { useMultichainContext } from 'src/features/multichain/context'; -import type { TxsTranslationQuery } from 'src/features/tx-interpretation/noves/hooks/useDescribeTxs'; - -import useInitialList from 'src/shared/lists/useInitialList'; -import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; - -import TxsSocketNotice from './socket/TxsSocketNotice'; -import TxsListItem from './TxsListItem'; - -interface Props { - showBlockInfo: boolean; - socketType?: TxsSocketType; - enableTimeIncrement?: boolean; - currentAddress?: string; - isLoading: boolean; - items: Array<schemas['Transaction']>; - translationQuery?: TxsTranslationQuery; - resetKey?: string; -} - -const TxsList = (props: Props) => { - const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: props.items, isEnabled: !props.isLoading, resetKey: props.resetKey }); - const initialList = useInitialList({ - data: props.items ?? [], - idFn: (item) => item.hash, - enabled: !props.isLoading, - }); - const multichainContext = useMultichainContext(); - const chainData = multichainContext?.chain; - - return ( - <Box> - { props.socketType && <TxsSocketNotice type={ props.socketType } place="list" isLoading={ props.isLoading }/> } - { props.items.slice(0, renderedItemsNum).map((tx, index) => { - return ( - <TxsListItem - key={ tx.hash + (props.isLoading ? index : '') } - tx={ tx } - showBlockInfo={ props.showBlockInfo } - currentAddress={ props.currentAddress } - enableTimeIncrement={ props.enableTimeIncrement } - isLoading={ props.isLoading } - animation={ initialList.getAnimationProp(tx) } - chainData={ chainData } - translationIsLoading={ props.translationQuery?.isLoading } - translationData={ props.translationQuery?.data?.find(({ txHash }) => txHash.toLowerCase() === tx.hash.toLowerCase()) } - /> - ); - }) } - <Box ref={ cutRef } h={ 0 }/> - </Box> - ); -}; - -export default React.memo(TxsList); diff --git a/src/slices/tx/pages/index/list/TxsListItem.pw.tsx b/src/slices/tx/pages/index/list/TxsListItem.pw.tsx deleted file mode 100644 index 38b9d64639b..00000000000 --- a/src/slices/tx/pages/index/list/TxsListItem.pw.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import React from 'react'; - -import * as txMock from 'src/slices/tx/mocks/list'; - -import { test, expect, devices } from 'playwright/lib'; - -import TxsListItem from './TxsListItem'; - -test.use({ viewport: devices['iPhone 13 Pro'].viewport }); - -test('base view +@dark-mode', async({ render }) => { - const component = await render(<TxsListItem tx={ txMock.withWatchListNames } showBlockInfo/>); - await expect(component).toHaveScreenshot(); -}); - -test('with base address', async({ render }) => { - const component = await render(<TxsListItem tx={ txMock.withWatchListNames } showBlockInfo currentAddress={ txMock.base.from.hash }/>); - await expect(component).toHaveScreenshot(); -}); - -test('with pending update', async({ render }) => { - const component = await render(<TxsListItem tx={ txMock.withPendingUpdate } showBlockInfo/>); - await expect(component).toHaveScreenshot(); -}); diff --git a/src/slices/tx/pages/index/list/TxsListItem.tsx b/src/slices/tx/pages/index/list/TxsListItem.tsx deleted file mode 100644 index 16b5de544e4..00000000000 --- a/src/slices/tx/pages/index/list/TxsListItem.tsx +++ /dev/null @@ -1,155 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { - HStack, - Flex, -} from '@chakra-ui/react'; -import React from 'react'; - -import type { schemas } from '@blockscout/api-types'; -import type { ClusterChainConfig } from 'src/features/multichain/types/client'; -import type { NovesDescribeTxsResponse } from 'src/features/tx-interpretation/noves/types/api'; - -import AddressFromTo from 'src/slices/address/components/from-to/AddressFromTo'; -import BlockEntity from 'src/slices/block/components/entity/BlockEntity'; -import TxEntity from 'src/slices/tx/components/entity/TxEntity'; -import TxAdditionalInfo from 'src/slices/tx/components/TxAdditionalInfo'; -import TxFee from 'src/slices/tx/components/TxFee'; -import TxStatus from 'src/slices/tx/components/TxStatus'; -import TxType from 'src/slices/tx/components/TxType'; - -import TxWatchListTags from 'src/features/account/components/TxWatchListTags'; -import MetadataTag from 'src/features/address-metadata/components/tag/MetadataTag'; -import TxTranslationType from 'src/features/tx-interpretation/noves/components/TxTranslationType'; - -import config from 'src/config'; -import TimeWithTooltip from 'src/shared/date-and-time/TimeWithTooltip'; -import ListItemMobile from 'src/shared/lists/ListItemMobile'; -import NativeCoinValue from 'src/shared/values/entity/NativeCoinValue'; - -import { Skeleton } from 'src/toolkit/chakra/skeleton'; - -interface Props { - tx: schemas['Transaction']; - showBlockInfo: boolean; - currentAddress?: string; - enableTimeIncrement?: boolean; - isLoading?: boolean; - animation?: string; - chainData?: ClusterChainConfig; - translationIsLoading?: boolean; - translationData?: NovesDescribeTxsResponse; -}; - -const TxsListItem = ({ - tx, - isLoading, - showBlockInfo, - currentAddress, - enableTimeIncrement, - animation, - chainData, - translationIsLoading, - translationData, -}: Props) => { - const dataTo = tx.to ? tx.to : tx.created_contract; - - const protocolTag = tx.to?.hash !== currentAddress && tx.to?.metadata?.tags?.find(tag => tag.tagType === 'protocol'); - - return ( - <ListItemMobile display="block" width="100%" animation={ animation } key={ tx.hash }> - <Flex justifyContent="space-between" alignItems="flex-start" mt={ 4 }> - <HStack flexWrap="wrap"> - { translationIsLoading || translationData ? ( - <TxTranslationType - txTypes={ tx.transaction_types } - isLoading={ isLoading || translationIsLoading } - type={ translationData?.type } - /> - ) : - <TxType types={ tx.transaction_types } isLoading={ isLoading }/> - } - { tx.status !== 'ok' && <TxStatus status={ tx.status } errorText={ tx.status === 'error' ? tx.result : undefined } isLoading={ isLoading }/> } - <TxWatchListTags tx={ tx } isLoading={ isLoading }/> - { protocolTag && <MetadataTag data={ protocolTag } isLoading={ isLoading } noColors/> } - </HStack> - <TxAdditionalInfo tx={ tx } isMobile isLoading={ isLoading }/> - </Flex> - <Flex justifyContent="space-between" lineHeight="24px" mt={ 3 } alignItems="center"> - <TxEntity - isLoading={ isLoading } - hash={ tx.hash } - truncation="constant_long" - fontWeight="700" - icon={ !tx.is_pending_update && tx.transaction_types.includes('blob_transaction') ? { name: 'blob' } : undefined } - chain={ chainData } - isPendingUpdate={ tx.is_pending_update ?? undefined } - /> - <TimeWithTooltip - timestamp={ tx.timestamp } - enableIncrement={ enableTimeIncrement } - isLoading={ isLoading } - color="text.secondary" - fontWeight="400" - fontSize="sm" - /> - </Flex> - { tx.method && ( - <Flex mt={ 3 }> - <Skeleton loading={ isLoading } display="inline-block" whiteSpace="pre">Method </Skeleton> - <Skeleton - loading={ isLoading } - color="text.secondary" - overflow="hidden" - whiteSpace="nowrap" - textOverflow="ellipsis" - > - <span>{ tx.method }</span> - </Skeleton> - </Flex> - ) } - { showBlockInfo && tx.block_number !== null && ( - <Flex mt={ 2 }> - <Skeleton loading={ isLoading } display="inline-block" whiteSpace="pre">Block </Skeleton> - <BlockEntity - isLoading={ isLoading } - number={ tx.block_number } - noIcon - /> - </Flex> - ) } - <AddressFromTo - from={ tx.from } - to={ dataTo } - current={ currentAddress } - isLoading={ isLoading } - mt={ 6 } - fontWeight="500" - /> - { !config.slices.tx.hiddenFields?.value && ( - <Flex mt={ 2 } columnGap={ 2 }> - <Skeleton loading={ isLoading } display="inline-block" whiteSpace="pre">Value</Skeleton> - <NativeCoinValue - amount={ tx.value } - exchangeRate={ tx.exchange_rate } - historicalExchangeRate={ tx.historic_exchange_rate } - loading={ isLoading } - color="text.secondary" - /> - </Flex> - ) } - { !config.slices.tx.hiddenFields?.tx_fee && ( - <Flex mt={ 2 } mb={ 3 } columnGap={ 2 }> - { (tx.stability_fee !== undefined || tx.fee.value !== null) && ( - <> - <Skeleton loading={ isLoading } display="inline-block" whiteSpace="pre">Fee</Skeleton> - <TxFee tx={ tx } loading={ isLoading } color="text.secondary"/> - </> - ) } - </Flex> - ) } - </ListItemMobile> - ); -}; - -export default React.memo(TxsListItem); diff --git a/src/slices/tx/pages/index/list/TxsTable.spec.tsx b/src/slices/tx/pages/index/list/TxsTable.spec.tsx new file mode 100644 index 00000000000..e4a4c3e3d2f --- /dev/null +++ b/src/slices/tx/pages/index/list/TxsTable.spec.tsx @@ -0,0 +1,33 @@ +// @vitest-environment jsdom + +import React from 'react'; + +import * as txMock from 'src/slices/tx/mocks/list'; + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent } from 'vitest/lib'; + +import TxsTable from './TxsTable'; + +afterEach(cleanup); + +describe('TxsTable', () => { + it('toggles the block number sort from the Block header', () => { + const onSortToggle = vi.fn(); + render(<TxsTable txs={ [ txMock.base ] } sort="default" onSortToggle={ onSortToggle } top={ 0 } showBlockInfo/>); + + fireEvent.click(screen.getByText('Block', { selector: 'th *' })); + + expect(onSortToggle).toHaveBeenCalledWith('block_number'); + }); + + it('keeps the Block header static when block sort is unavailable', () => { + const onSortToggle = vi.fn(); + render(<TxsTable txs={ [ txMock.base ] } sort="default" onSortToggle={ onSortToggle } top={ 0 } showBlockInfo withBlockSort={ false }/>); + + fireEvent.click(screen.getByText('Block', { selector: 'th' })); + + expect(screen.queryByText('Block', { selector: 'th *' })).toBeNull(); + expect(onSortToggle).not.toHaveBeenCalled(); + }); +}); diff --git a/src/slices/tx/pages/index/list/TxsTable.tsx b/src/slices/tx/pages/index/list/TxsTable.tsx index dbc264da595..073a404b469 100644 --- a/src/slices/tx/pages/index/list/TxsTable.tsx +++ b/src/slices/tx/pages/index/list/TxsTable.tsx @@ -15,6 +15,7 @@ import type { TxsTranslationQuery } from 'src/features/tx-interpretation/noves/h import config from 'src/config'; import TimeFormatToggle from 'src/shared/date-and-time/TimeFormatToggle'; import useIsMobile from 'src/shared/hooks/useIsMobile'; +import { useUniqueKeys } from 'src/shared/lists/get-unique-keys'; import useInitialList from 'src/shared/lists/useInitialList'; import useLazyRenderedList from 'src/shared/lists/useLazyRenderedList'; @@ -36,8 +37,11 @@ type Props = { stickyHeader?: boolean; translationQuery?: TxsTranslationQuery; resetKey?: string; + withBlockSort?: boolean; }; +const getBaseKey = (item: schemas['Transaction']): string => item.hash; + const TxsTable = ({ txs, sort, @@ -51,6 +55,7 @@ const TxsTable = ({ stickyHeader = true, translationQuery, resetKey, + withBlockSort = true, }: Props) => { const { cutRef, renderedItemsNum } = useLazyRenderedList({ list: txs, isEnabled: !isLoading, resetKey }); const initialList = useInitialList({ @@ -61,6 +66,7 @@ const TxsTable = ({ const multichainContext = useMultichainContext(); const chainData = multichainContext?.chain; const isMobile = useIsMobile(); + const keys = useUniqueKeys(txs, getBaseKey); const feeCurrency = config.slices.tx.hiddenFields?.fee_currency || config.chain.hasMultipleGasCurrencies ? '' : @@ -90,7 +96,7 @@ const TxsTable = ({ <TableColumnHeader width="160px">Type</TableColumnHeader> <TableColumnHeader width={ baseWidth }>Method</TableColumnHeader> { showBlockInfo && ( - onSortToggle ? ( + onSortToggle && withBlockSort ? ( <TableColumnHeaderSortable width={ baseWidth } sortField="block_number" @@ -138,11 +144,11 @@ const TxsTable = ({ </TableRow> </TableHeaderComponent> <TableBody> - { socketType && <TxsSocketNotice type={ socketType } place="table" isLoading={ isLoading }/> } + { socketType && <TxsSocketNotice type={ socketType } isLoading={ isLoading }/> } { txs.slice(0, renderedItemsNum).map((item, index) => { return ( <TxsTableItem - key={ item.hash + (isLoading ? index : '') } + key={ keys[index] } tx={ item } showBlockInfo={ showBlockInfo } currentAddress={ currentAddress } diff --git a/src/slices/tx/pages/index/list/TxsTableItem.tsx b/src/slices/tx/pages/index/list/TxsTableItem.tsx index 08542f4d74c..e1a15f5cd72 100644 --- a/src/slices/tx/pages/index/list/TxsTableItem.tsx +++ b/src/slices/tx/pages/index/list/TxsTableItem.tsx @@ -18,6 +18,7 @@ import TxType from 'src/slices/tx/components/TxType'; import TxWatchListTags from 'src/features/account/components/TxWatchListTags'; import MetadataTag from 'src/features/address-metadata/components/tag/MetadataTag'; +import { getVisibleProtocolTags } from 'src/features/address-metadata/utils/get-visible-protocol-tags'; import TxTranslationType from 'src/features/tx-interpretation/noves/components/TxTranslationType'; import config from 'src/config'; @@ -55,7 +56,7 @@ const TxsTableItem = ({ }: Props) => { const dataTo = tx.to ? tx.to : tx.created_contract; - const protocolTag = tx.to?.hash !== currentAddress && tx.to?.metadata?.tags?.find(tag => tag.tagType === 'protocol'); + const protocolTag = tx.to?.hash !== currentAddress && getVisibleProtocolTags(tx.to?.metadata?.tags)[0]; return ( <TableRow key={ tx.hash } animation={ animation }> @@ -113,7 +114,7 @@ const TxsTableItem = ({ { showBlockInfo && ( <TableCell> <Flex alignItems="center" gap={ 2 }> - { tx.block_number && ( + { tx.block_number !== null && ( <BlockEntity isLoading={ isLoading } number={ tx.block_number } diff --git a/src/slices/tx/pages/index/list/TxsTabs.tsx b/src/slices/tx/pages/index/list/TxsTabs.tsx index 7fdec521510..a1a07becaee 100644 --- a/src/slices/tx/pages/index/list/TxsTabs.tsx +++ b/src/slices/tx/pages/index/list/TxsTabs.tsx @@ -2,7 +2,6 @@ import { Flex } from '@chakra-ui/react'; import { capitalize } from 'es-toolkit'; -import { useRouter } from 'next/router'; import React from 'react'; import type { TabItemRegular } from 'src/toolkit/components/AdaptiveTabs/types'; @@ -19,9 +18,10 @@ import config from 'src/config'; import useIsInitialLoading from 'src/shared/hooks/useIsInitialLoading'; import useIsMobile from 'src/shared/hooks/useIsMobile'; import Pagination from 'src/shared/pagination/Pagination'; -import useQueryWithPages from 'src/shared/pagination/useQueryWithPages'; +import useApiPaginatedQuery from 'src/shared/pagination/useApiPaginatedQuery'; import { generateListStub } from 'src/shared/pagination/utils'; import getQueryParamString from 'src/shared/router/get-query-param-string'; +import { useRouter } from 'src/shared/router/useRouter'; import type { RoutedTabsProps } from 'src/toolkit/components/RoutedTabs/RoutedTabs'; import RoutedTabs from 'src/toolkit/components/RoutedTabs/RoutedTabs'; @@ -49,9 +49,9 @@ const TxsTabs = ({ parentTab, tabsHeight, ...rest }: Props) => { const isBlobTxsTab = chainConfig?.features.dataAvailability.isEnabled && tab === getTabId('blob_txs', parentTab); const isWatchlistTab = isAuth && tab === getTabId('watchlist', parentTab); - const txsValidatedQuery = useQueryWithPages({ + const txsValidatedQuery = useApiPaginatedQuery({ resourceName: 'core:txs', - filters: { filter: 'validated' }, + queryParams: { filter: 'validated' }, options: { enabled: tab === getTabId('validated', parentTab) || (parentTab ? tab === parentTab : false) || @@ -66,9 +66,9 @@ const TxsTabs = ({ parentTab, tabsHeight, ...rest }: Props) => { }, }); - const txsPendingQuery = useQueryWithPages({ + const txsPendingQuery = useApiPaginatedQuery({ resourceName: 'core:txs', - filters: { filter: 'pending' }, + queryParams: { filter: 'pending' }, options: { enabled: isPendingTab, placeholderData: generateListStub<'core:txs'>(TX_ITEM, 50, { next_page_params: { @@ -79,9 +79,9 @@ const TxsTabs = ({ parentTab, tabsHeight, ...rest }: Props) => { }, }); - const txsWithBlobsQuery = useQueryWithPages({ + const txsWithBlobsQuery = useApiPaginatedQuery({ resourceName: 'core:txs', - filters: { type: 'blob_transaction' }, + queryParams: { type: 'blob_transaction' }, options: { enabled: isBlobTxsTab, placeholderData: generateListStub<'core:txs'>(TX_ITEM, 50, { next_page_params: { @@ -92,7 +92,7 @@ const TxsTabs = ({ parentTab, tabsHeight, ...rest }: Props) => { }, }); - const txsWatchlistQuery = useQueryWithPages({ + const txsWatchlistQuery = useApiPaginatedQuery({ resourceName: 'core:txs_watchlist', options: { enabled: isWatchlistTab, @@ -115,6 +115,7 @@ const TxsTabs = ({ parentTab, tabsHeight, ...rest }: Props) => { query={ txsValidatedQuery } socketType="txs_validated" top={ tabsHeight } + withBlockSort={ false } /> }, !chainConfig?.slices.tx.hiddenViews?.pending_txs ? { id: getTabId('pending', parentTab), @@ -135,6 +136,7 @@ const TxsTabs = ({ parentTab, tabsHeight, ...rest }: Props) => { <TxsWithFrontendSorting query={ txsWithBlobsQuery } top={ tabsHeight } + withBlockSort={ false } /> ), }, diff --git a/src/slices/tx/pages/index/list/TxsWithApiSorting.tsx b/src/slices/tx/pages/index/list/TxsWithApiSorting.tsx index 2c4d6f6fba9..9a7af1b8619 100644 --- a/src/slices/tx/pages/index/list/TxsWithApiSorting.tsx +++ b/src/slices/tx/pages/index/list/TxsWithApiSorting.tsx @@ -6,14 +6,14 @@ import type { AddressFromToFilter } from 'src/slices/address/types/api'; import type { TransactionsSortingValue } from 'src/slices/tx/types/api'; import type { TxsSocketType } from 'src/slices/tx/types/socket'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; import getSortParamsFromValue from 'src/shared/sort/get-sort-params-from-value'; import TxsContent from './TxsContent'; interface Props { - query: QueryWithPagesResult<'core:address_txs'>; + query: ApiPaginatedQueryResult<'core:address_txs'>; showBlockInfo?: boolean; socketType?: TxsSocketType; currentAddress?: string; @@ -22,8 +22,6 @@ interface Props { enableTimeIncrement?: boolean; top?: number; sorting: TransactionsSortingValue; - setSort: (value: TransactionsSortingValue) => void; - showTableView?: boolean; }; const TxsWithApiSorting = ({ @@ -36,14 +34,11 @@ const TxsWithApiSorting = ({ enableTimeIncrement, top, sorting, - setSort, - showTableView, }: Props) => { - + const { onSortingChange } = query; const handleSortChange = React.useCallback((value: TransactionsSortingValue) => { - setSort(value); - query.onSortingChange(getSortParamsFromValue(value)); - }, [ setSort, query ]); + onSortingChange(getSortParamsFromValue(value)); + }, [ onSortingChange ]); return ( <TxsContent @@ -55,12 +50,12 @@ const TxsWithApiSorting = ({ enableTimeIncrement={ enableTimeIncrement } top={ top } items={ query.data?.items } - isPlaceholderData={ query.isPlaceholderData } + isInitialLoading={ query.isInitialLoading } + isTransitioning={ query.isTransitioning } isError={ query.isError } setSorting={ handleSortChange } sort={ sorting } pagination={ query.pagination } - showTableView={ showTableView } resetKey={ query.queryHash } /> ); diff --git a/src/slices/tx/pages/index/list/TxsWithFrontendSorting.tsx b/src/slices/tx/pages/index/list/TxsWithFrontendSorting.tsx index 8016c023713..d0fb8a8f3e2 100644 --- a/src/slices/tx/pages/index/list/TxsWithFrontendSorting.tsx +++ b/src/slices/tx/pages/index/list/TxsWithFrontendSorting.tsx @@ -7,14 +7,14 @@ import type { TxsSocketType } from 'src/slices/tx/types/socket'; import useTxsSort from 'src/slices/tx/hooks/useTxsSort'; -import type { QueryWithPagesResult } from 'src/shared/pagination/useQueryWithPages'; +import type { ApiPaginatedQueryResult } from 'src/shared/pagination/useApiPaginatedQuery'; import TxsContent from './TxsContent'; type Props = { - query: QueryWithPagesResult<'core:txs'> | - QueryWithPagesResult<'core:txs_watchlist'> | - QueryWithPagesResult<'core:block_txs'>; + query: ApiPaginatedQueryResult<'core:txs'> | + ApiPaginatedQueryResult<'core:txs_watchlist'> | + ApiPaginatedQueryResult<'core:block_txs'>; showBlockInfo?: boolean; socketType?: TxsSocketType; currentAddress?: string; @@ -22,6 +22,7 @@ type Props = { filterValue?: AddressFromToFilter; enableTimeIncrement?: boolean; top?: number; + withBlockSort?: boolean; }; const TxsWithFrontendSorting = ({ @@ -33,8 +34,9 @@ const TxsWithFrontendSorting = ({ currentAddress, enableTimeIncrement, top, + withBlockSort, }: Props) => { - const { data, isPlaceholderData, isError, setSortByValue, sorting } = useTxsSort(query); + const { data, isError, setSortByValue, sorting } = useTxsSort(query, withBlockSort); return ( <TxsContent @@ -46,12 +48,14 @@ const TxsWithFrontendSorting = ({ enableTimeIncrement={ enableTimeIncrement } top={ top } items={ data?.items } - isPlaceholderData={ isPlaceholderData } + isInitialLoading={ query.isInitialLoading } + isTransitioning={ query.isTransitioning } isError={ isError } setSorting={ setSortByValue } sort={ sorting } pagination={ query.pagination } resetKey={ query.queryHash } + withBlockSort={ withBlockSort } /> ); }; diff --git a/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_dark-color-mode_base-view-dark-mode-1.png deleted file mode 100644 index 0fa1e31241f..00000000000 Binary files a/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and /dev/null differ diff --git a/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_default_base-view-dark-mode-1.png b/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_default_base-view-dark-mode-1.png deleted file mode 100644 index 83d8b9d9c50..00000000000 Binary files a/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_default_base-view-dark-mode-1.png and /dev/null differ diff --git a/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_default_with-base-address-1.png b/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_default_with-base-address-1.png deleted file mode 100644 index 634e929f49b..00000000000 Binary files a/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_default_with-base-address-1.png and /dev/null differ diff --git a/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_default_with-pending-update-1.png b/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_default_with-pending-update-1.png deleted file mode 100644 index 66b816cd652..00000000000 Binary files a/src/slices/tx/pages/index/list/__screenshots__/TxsListItem.pw.tsx_default_with-pending-update-1.png and /dev/null differ diff --git a/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_dark-color-mode_base-view-dark-mode-1.png b/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_dark-color-mode_base-view-dark-mode-1.png index e7b25b26a61..a7a458a9967 100644 Binary files a/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_dark-color-mode_base-view-dark-mode-1.png and b/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_dark-color-mode_base-view-dark-mode-1.png differ diff --git a/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_default_base-view-dark-mode-1.png b/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_default_base-view-dark-mode-1.png index 78e0fbd8642..e38e962b260 100644 Binary files a/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_default_base-view-dark-mode-1.png and b/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_default_base-view-dark-mode-1.png differ diff --git a/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_default_screen-xl-base-view-1.png b/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_default_screen-xl-base-view-1.png index c99858d809e..92e550a6463 100644 Binary files a/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_default_screen-xl-base-view-1.png and b/src/slices/tx/pages/index/list/__screenshots__/TxsTable.pw.tsx_default_screen-xl-base-view-1.png differ diff --git a/src/slices/tx/pages/index/list/socket/TxsSocketNotice.tsx b/src/slices/tx/pages/index/list/socket/TxsSocketNotice.tsx index 1c87f143936..dd6f8e7c60e 100644 --- a/src/slices/tx/pages/index/list/socket/TxsSocketNotice.tsx +++ b/src/slices/tx/pages/index/list/socket/TxsSocketNotice.tsx @@ -2,34 +2,25 @@ import React from 'react'; -import type { TxsSocketNoticePlace, TxsSocketType } from 'src/slices/tx/types/socket'; - -import useIsMobile from 'src/shared/hooks/useIsMobile'; +import type { TxsSocketType } from 'src/slices/tx/types/socket'; import TxsSocketNoticeTypeAddress from './TxsSocketNoticeTypeAddress'; import TxsSocketNoticeTypeAll from './TxsSocketNoticeTypeAll'; interface Props { type: TxsSocketType; - place: TxsSocketNoticePlace; isLoading?: boolean; } -const TxsSocketNotice = ({ type, place, isLoading }: Props) => { - const isMobile = useIsMobile(); - - if ((isMobile && place === 'table') || (!isMobile && place === 'list')) { - return null; - } - +const TxsSocketNotice = ({ type, isLoading }: Props) => { switch (type) { case 'txs_home': case 'txs_validated': case 'txs_pending': { - return <TxsSocketNoticeTypeAll type={ type } place={ place } isLoading={ isLoading }/>; + return <TxsSocketNoticeTypeAll type={ type } isLoading={ isLoading }/>; } case 'address_txs': { - return <TxsSocketNoticeTypeAddress place={ place } isLoading={ isLoading }/>; + return <TxsSocketNoticeTypeAddress isLoading={ isLoading }/>; } default: diff --git a/src/slices/tx/pages/index/list/socket/TxsSocketNoticeTypeAddress.tsx b/src/slices/tx/pages/index/list/socket/TxsSocketNoticeTypeAddress.tsx index 08b8d8b94fb..4fc6e5be3d0 100644 --- a/src/slices/tx/pages/index/list/socket/TxsSocketNoticeTypeAddress.tsx +++ b/src/slices/tx/pages/index/list/socket/TxsSocketNoticeTypeAddress.tsx @@ -2,43 +2,28 @@ import React from 'react'; -import type { TxsSocketNoticePlace } from 'src/slices/tx/types/socket'; - import * as SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; import useTxsSocketTypeAddress from 'src/slices/tx/hooks/useTxsSocketTypeAddress'; interface Props { - place: TxsSocketNoticePlace; isLoading?: boolean; } -const TxsSocketNoticeTypeAddress = ({ place, isLoading }: Props) => { +const TxsSocketNoticeTypeAddress = ({ isLoading }: Props) => { const { num, showErrorAlert } = useTxsSocketTypeAddress({ isLoading }); if (num === undefined) { return null; } - if (place === 'table') { - return ( - <SocketNewItemsNotice.Desktop - showErrorAlert={ showErrorAlert } - num={ num } - isLoading={ isLoading } - /> - ); - } - - if (place === 'list') { - return ( - <SocketNewItemsNotice.Mobile - num={ num } - showErrorAlert={ showErrorAlert } - isLoading={ isLoading } - /> - ); - } + return ( + <SocketNewItemsNotice.Desktop + showErrorAlert={ showErrorAlert } + num={ num } + isLoading={ isLoading } + /> + ); }; export default React.memo(TxsSocketNoticeTypeAddress); diff --git a/src/slices/tx/pages/index/list/socket/TxsSocketNoticeTypeAll.tsx b/src/slices/tx/pages/index/list/socket/TxsSocketNoticeTypeAll.tsx index c91049af670..e55f3da4a2c 100644 --- a/src/slices/tx/pages/index/list/socket/TxsSocketNoticeTypeAll.tsx +++ b/src/slices/tx/pages/index/list/socket/TxsSocketNoticeTypeAll.tsx @@ -2,7 +2,7 @@ import React from 'react'; -import type { TxsSocketNoticePlace, TxsSocketType } from 'src/slices/tx/types/socket'; +import type { TxsSocketType } from 'src/slices/tx/types/socket'; import * as SocketNewItemsNotice from 'src/api/socket/SocketNewItemsNotice'; @@ -14,11 +14,10 @@ import { route } from 'src/shared/router/routes'; interface Props { type: TxsSocketType; - place: TxsSocketNoticePlace; isLoading?: boolean; } -const TxsSocketNoticeTypeAll = ({ type, place, isLoading }: Props) => { +const TxsSocketNoticeTypeAll = ({ type, isLoading }: Props) => { const multichainContext = useMultichainContext(); const { num, showErrorAlert } = useNewTxsSocketTypeAll({ type, isLoading }); @@ -32,27 +31,14 @@ const TxsSocketNoticeTypeAll = ({ type, place, isLoading }: Props) => { } })(); - if (place === 'table') { - return ( - <SocketNewItemsNotice.Desktop - showErrorAlert={ showErrorAlert } - num={ num } - isLoading={ isLoading } - url={ url } - /> - ); - } - - if (place === 'list') { - return ( - <SocketNewItemsNotice.Mobile - num={ num } - showErrorAlert={ showErrorAlert } - isLoading={ isLoading } - url={ url } - /> - ); - } + return ( + <SocketNewItemsNotice.Desktop + showErrorAlert={ showErrorAlert } + num={ num } + isLoading={ isLoading } + url={ url } + /> + ); }; export default React.memo(TxsSocketNoticeTypeAll); diff --git a/src/slices/tx/pages/index/stats/TxsStats.tsx b/src/slices/tx/pages/index/stats/TxsStats.tsx index 4416268ddac..6ad749900e2 100644 --- a/src/slices/tx/pages/index/stats/TxsStats.tsx +++ b/src/slices/tx/pages/index/stats/TxsStats.tsx @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { BoxProps } from '@chakra-ui/react'; -import { Box } from '@chakra-ui/react'; import React from 'react'; import useApiQuery from 'src/api/hooks/useApiQuery'; @@ -13,6 +12,7 @@ import { useMultichainContext } from 'src/features/multichain/context'; import config from 'src/config'; import getStatsLabelFromTitle from 'src/shared/stats/get-stats-label-from-title'; +import StatsContainer from 'src/shared/stats/StatsContainer'; import StatsWidget from 'src/shared/stats/StatsWidget'; import calculateUsdValue from 'src/shared/values/entity/calculateUsdValue'; @@ -71,24 +71,8 @@ const TxsStats = (props: Props) => { decimals: isStatsFeatureEnabled ? '0' : String(chainConfig.chain.currency.decimals), }) : null; - const itemsCount = [ - txCount24h, - operationalTxns24hArbitrum, - operationalTxns24hOptimistic, - pendingTxns, - txFeeSum24h, - txFeeAvg, - ].filter(item => item !== null && item !== undefined).length; - return ( - <Box - display="grid" - gridTemplateColumns={{ base: '1fr', lg: `repeat(${ itemsCount }, calc(${ 100 / itemsCount }% - 9px))` }} - rowGap={ 3 } - columnGap={ 3 } - mb={ 6 } - { ...props } - > + <StatsContainer mb={ 6 } { ...props } > { txCount24h && ( <StatsWidget label={ txsStatsQuery.data?.transactions_24h?.title ? @@ -167,7 +151,7 @@ const TxsStats = (props: Props) => { } /> ) } - </Box> + </StatsContainer> ); }; diff --git a/src/slices/tx/pages/index/stats/__screenshots__/TxsStats.pw.tsx_default_base-view-mobile-1.png b/src/slices/tx/pages/index/stats/__screenshots__/TxsStats.pw.tsx_default_base-view-mobile-1.png index 53c7ff02995..1ef5ae6eb6c 100644 Binary files a/src/slices/tx/pages/index/stats/__screenshots__/TxsStats.pw.tsx_default_base-view-mobile-1.png and b/src/slices/tx/pages/index/stats/__screenshots__/TxsStats.pw.tsx_default_base-view-mobile-1.png differ diff --git a/src/slices/tx/pages/index/stats/__screenshots__/TxsStats.pw.tsx_mobile_base-view-mobile-1.png b/src/slices/tx/pages/index/stats/__screenshots__/TxsStats.pw.tsx_mobile_base-view-mobile-1.png index 99651fb8dff..6b4a5fdfbf6 100644 Binary files a/src/slices/tx/pages/index/stats/__screenshots__/TxsStats.pw.tsx_mobile_base-view-mobile-1.png and b/src/slices/tx/pages/index/stats/__screenshots__/TxsStats.pw.tsx_mobile_base-view-mobile-1.png differ diff --git a/src/slices/tx/stubs/state-changes.ts b/src/slices/tx/stubs/state-changes.ts index 84e1948d74e..1c448725b1d 100644 --- a/src/slices/tx/stubs/state-changes.ts +++ b/src/slices/tx/stubs/state-changes.ts @@ -11,6 +11,7 @@ export const STATE_CHANGE_MINER: schemas['StateChange'] = { is_miner: true, token: null, type: 'coin', + ui_multiplier: null, }; export const STATE_CHANGE_COIN: schemas['StateChange'] = { @@ -21,6 +22,7 @@ export const STATE_CHANGE_COIN: schemas['StateChange'] = { is_miner: false, token: null, type: 'coin', + ui_multiplier: null, }; export const STATE_CHANGE_TOKEN: schemas['StateChange'] = { @@ -32,6 +34,7 @@ export const STATE_CHANGE_TOKEN: schemas['StateChange'] = { token: TOKEN_INFO_ERC_721, token_id: '1621395', type: 'token', + ui_multiplier: null, }; export const TX_STATE_CHANGES: Array<schemas['StateChange']> = [ diff --git a/src/slices/tx/types/socket.ts b/src/slices/tx/types/socket.ts index 4ec0f503a26..12103e483b9 100644 --- a/src/slices/tx/types/socket.ts +++ b/src/slices/tx/types/socket.ts @@ -1,4 +1,3 @@ // SPDX-License-Identifier: LicenseRef-Blockscout export type TxsSocketType = 'txs_validated' | 'txs_pending' | 'txs_home' | 'address_txs'; -export type TxsSocketNoticePlace = 'list' | 'table'; diff --git a/src/slices/tx/utils/get-state-change-ui-multiplier.spec.ts b/src/slices/tx/utils/get-state-change-ui-multiplier.spec.ts new file mode 100644 index 00000000000..a24b8f2b760 --- /dev/null +++ b/src/slices/tx/utils/get-state-change-ui-multiplier.spec.ts @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { schemas } from '@blockscout/api-types'; + +import { ENVS_MAP } from 'src/config/test-utils/env-presets'; + +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import { receiveCoin, receiveMintedToken, sendERC20Token, sendERC8056Token } from '../mocks/state-changes'; + +const CURRENT_TOKEN_FACTOR = '2000000000000000000'; + +function resolveWithTypeEnabled(data: schemas['StateChange']) { + return withEnvs(ENVS_MAP.additionalTokenTypes, async() => { + const { getStateChangeUiMultiplier } = await import('./get-state-change-ui-multiplier'); + return getStateChangeUiMultiplier(data); + }); +} + +describe('getStateChangeUiMultiplier', () => { + it('resolves the factor that applied to the state change', async() => { + const result = await resolveWithTypeEnabled(sendERC8056Token); + expect(result?.toFixed()).toBe('1.69'); + }); + + it('ignores the token current factor', async() => { + const result = await resolveWithTypeEnabled({ + ...sendERC8056Token, + token: { ...sendERC8056Token.token!, ui_multiplier: CURRENT_TOKEN_FACTOR }, + }); + expect(result?.toFixed()).toBe('1.69'); + }); + + it('resolves to nothing when the state change factor is null, with no fallback to the token', async() => { + const result = await resolveWithTypeEnabled({ + ...sendERC8056Token, + token: { ...sendERC8056Token.token!, ui_multiplier: CURRENT_TOKEN_FACTOR }, + ui_multiplier: null, + }); + expect(result).toBeUndefined(); + }); + + it('resolves to nothing for a state change of another fungible type', async() => { + expect(await resolveWithTypeEnabled({ ...sendERC20Token, ui_multiplier: sendERC8056Token.ui_multiplier })).toBeUndefined(); + }); + + it('resolves to nothing for an NFT state change', async() => { + expect(await resolveWithTypeEnabled(receiveMintedToken)).toBeUndefined(); + }); + + it('resolves to nothing for a coin state change', async() => { + expect(await resolveWithTypeEnabled({ ...receiveCoin, ui_multiplier: sendERC8056Token.ui_multiplier })).toBeUndefined(); + }); + + it('resolves to nothing when ERC-8056 is not among the instance additional token types', async() => { + const { getStateChangeUiMultiplier } = await import('./get-state-change-ui-multiplier'); + expect(getStateChangeUiMultiplier(sendERC8056Token)).toBeUndefined(); + }); +}); diff --git a/src/slices/tx/utils/get-state-change-ui-multiplier.ts b/src/slices/tx/utils/get-state-change-ui-multiplier.ts new file mode 100644 index 00000000000..634e23f088e --- /dev/null +++ b/src/slices/tx/utils/get-state-change-ui-multiplier.ts @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type BigNumber from 'bignumber.js'; + +import type { schemas } from '@blockscout/api-types'; +import type { ChainConfig } from 'src/slices/token/types/client'; + +import { getUiMultiplier } from 'src/slices/token/utils/ui-multiplier'; + +// A state change is scaled by the factor in force at its block (ui_multiplier), +// never by the token's current factor (token.ui_multiplier), which may have changed since. +export function getStateChangeUiMultiplier(data: schemas['StateChange'], chainConfig?: ChainConfig): BigNumber | undefined { + if (data.type !== 'token' || !data.token) { + return undefined; + } + + return getUiMultiplier({ type: data.token.type, ui_multiplier: data.ui_multiplier }, chainConfig); +} diff --git a/src/sprite/SpriteInjector.tsx b/src/sprite/SpriteInjector.ts similarity index 100% rename from src/sprite/SpriteInjector.tsx rename to src/sprite/SpriteInjector.ts diff --git a/src/sprite/icons/link.svg b/src/sprite/icons/link.svg index 5d072572aa5..2e6137bc7d7 100644 --- a/src/sprite/icons/link.svg +++ b/src/sprite/icons/link.svg @@ -1,3 +1,3 @@ -<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> - <path fill-rule="evenodd" clip-rule="evenodd" d="M16.17 3a5.073 5.073 0 0 0-3.568 1.424l-.01.01-1.401 1.393a1 1 0 0 0 1.41 1.419l1.396-1.388a3.073 3.073 0 0 1 4.346 4.344l-2.437 2.438a3.072 3.072 0 0 1-4.635-.332 1 1 0 1 0-1.601 1.198 5.074 5.074 0 0 0 7.65.548l2.444-2.444.012-.012A5.073 5.073 0 0 0 16.17 3Zm-5.34 5.657a5.073 5.073 0 0 0-3.95 1.474l-2.444 2.444-.012.012a5.073 5.073 0 0 0 7.174 7.174l.012-.013 1.393-1.393a1 1 0 1 0-1.414-1.414l-1.387 1.387a3.073 3.073 0 0 1-4.345-4.346l2.437-2.437a3.072 3.072 0 0 1 4.635.332 1 1 0 0 0 1.601-1.198 5.074 5.074 0 0 0-3.7-2.022Z" fill="currentColor"/> +<svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"> + <path d="M16.017 3.691a4.068 4.068 0 0 0-5.703-.05l-.01.011-1.055 1.05a1.001 1.001 0 0 0 1.41 1.418l1.045-1.039a2.07 2.07 0 0 1 2.925 2.924l-1.83 1.829A2.07 2.07 0 0 1 9.68 9.61 1 1 0 0 0 8.08 10.81a4.072 4.072 0 0 0 4.68 1.375 4.068 4.068 0 0 0 1.454-.936l1.854-1.853a4.068 4.068 0 0 0-.05-5.704ZM10.828 7.25A4.07 4.07 0 0 0 6 7.944L4.147 9.798a4.069 4.069 0 0 0 5.758 5.746l.007-.006 1.05-1.05a1 1 0 1 0-1.415-1.414L8.51 14.111a2.068 2.068 0 0 1-3.058-2.772l.134-.153 1.828-1.828a2.07 2.07 0 0 1 3.12.223 1 1 0 0 0 1.601-1.197 4.068 4.068 0 0 0-1.307-1.134Z" fill-rule="evenodd" clip-rule="evenodd" fill="currentColor"/> </svg> diff --git a/src/sprite/icons/list_view.svg b/src/sprite/icons/list_view.svg deleted file mode 100644 index 0557d9eed4e..00000000000 --- a/src/sprite/icons/list_view.svg +++ /dev/null @@ -1,7 +0,0 @@ -<svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"> - <path d="M16 1a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H4a3 3 0 0 1-3-3V4a3 3 0 0 1 3-3h12ZM4.2 2.2a2 2 0 0 0-2 2v11.6a2 2 0 0 0 2 2h11.6a2 2 0 0 0 2-2V4.2a2 2 0 0 0-2-2H4.2Z" fill="currentColor"/> - <rect x="4" y="5" width="12" height="1.4" rx=".7" fill="currentColor"/> - <rect x="4" y="8" width="8" height="1.4" rx=".7" fill="currentColor"/> - <rect x="4" y="10.801" width="12" height="1.4" rx=".7" fill="currentColor"/> - <rect x="4" y="13.6" width="9" height="1.4" rx=".7" fill="currentColor"/> -</svg> diff --git a/src/sprite/icons/move.svg b/src/sprite/icons/move.svg new file mode 100644 index 00000000000..42f7833eff4 --- /dev/null +++ b/src/sprite/icons/move.svg @@ -0,0 +1,8 @@ +<svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"> + <rect x="6" y="3.305" width="3" height="3" rx="1" fill="currentColor"/> + <rect x="6" y="8.305" width="3" height="3" rx="1" fill="currentColor"/> + <rect x="6" y="13.305" width="3" height="3" rx="1" fill="currentColor"/> + <rect x="11" y="3.305" width="3" height="3" rx="1" fill="currentColor"/> + <rect x="11" y="8.305" width="3" height="3" rx="1" fill="currentColor"/> + <rect x="11" y="13.305" width="3" height="3" rx="1" fill="currentColor"/> +</svg> diff --git a/src/sprite/icons/utilization.svg b/src/sprite/icons/utilization.svg new file mode 100644 index 00000000000..182d6119c05 --- /dev/null +++ b/src/sprite/icons/utilization.svg @@ -0,0 +1,3 @@ +<svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"> + <path d="M10 1a10 10 0 0 0-8.66 15 1.004 1.004 0 0 0 1.74-1A7.92 7.92 0 0 1 2 11a8 8 0 1 1 14.93 4 .998.998 0 1 0 1.73 1A10 10 0 0 0 10 1Zm2.84 5.76L11.29 8.3A2.91 2.91 0 0 0 10 8a3 3 0 1 0 3 3 2.9 2.9 0 0 0-.3-1.28l1.55-1.54a.998.998 0 0 0 0-1.42 1 1 0 0 0-1.41 0ZM10 12a1 1 0 0 1 0-2 1 1 0 0 1 .7.28 1 1 0 0 1 .3.72 1 1 0 0 1-1 1Z" fill="currentColor"/> +</svg> diff --git a/src/sprite/pages/Sprite.tsx b/src/sprite/pages/Sprite.tsx index b7920321380..956f5025cb1 100644 --- a/src/sprite/pages/Sprite.tsx +++ b/src/sprite/pages/Sprite.tsx @@ -30,15 +30,6 @@ interface IconInfo { const Item = ({ name, file_size: fileSize, bgColor }: IconInfo & HTMLChakraProps<'div'>) => { const { hasCopied, copy } = useClipboard(name, 1000); - const [ copied, setCopied ] = React.useState(false); - - React.useEffect(() => { - if (hasCopied) { - setCopied(true); - } else { - setCopied(false); - } - }, [ hasCopied ]); return ( <Flex @@ -52,7 +43,7 @@ const Item = ({ name, file_size: fileSize, bgColor }: IconInfo & HTMLChakraProps cursor="pointer" > <SpriteIcon name={ name.replace('.svg', '') as IconName } boxSize="100px" bgColor={ bgColor } borderRadius="base"/> - <Tooltip content={ copied ? 'Copied' : 'Copy to clipboard' } open={ copied }> + <Tooltip content={ hasCopied ? 'Copied' : 'Copy to clipboard' } open={ hasCopied }> <Box fontWeight={ 500 } mt={ 2 }>{ name }</Box> </Tooltip> <Box color="text.secondary">{ formatFileSize(fileSize) }</Box> diff --git a/src/toolkit/CONTEXT.md b/src/toolkit/CONTEXT.md index 653ea58c658..9b3affe88d8 100644 --- a/src/toolkit/CONTEXT.md +++ b/src/toolkit/CONTEXT.md @@ -3,9 +3,15 @@ The pnpm workspace package lives at `src/toolkit/package/` (registered in `pnpm-workspace.yaml`) and is published as `@blockscout/ui-toolkit`. It is a thin wrapper: its `package/src/index.ts` re-exports from the sibling source -folders (`chakra/`, `components/`, `hooks/`, `theme/`, `utils/`), +folders (`chakra/`, `components/`, `hooks/`, `router/`, `theme/`, `utils/`), and its `package/vite.config.ts` bundles them via Vite. +`router/` is the toolkit's own router contract (context, provider, link adapter +types, no-op defaults). Nothing under `src/toolkit/` may import a framework +routing module (`next/router`, `next/link`, `next/navigation`): the package +ships without a `next` peer dependency, and the app injects its adapter through +the provider. + When publishing or versioning, target `src/toolkit/package/package.json` — not any other `package.json` in the repo, and not the toolkit folder root (it has no manifest). diff --git a/src/toolkit/chakra/alert.tsx b/src/toolkit/chakra/alert.tsx index 602f48944b6..0a276825098 100644 --- a/src/toolkit/chakra/alert.tsx +++ b/src/toolkit/chakra/alert.tsx @@ -69,7 +69,7 @@ export const Alert = React.forwardRef<HTMLDivElement, AlertProps>( { iconElement } { children ? ( <ChakraAlert.Content> - { title && <ChakraAlert.Title>{ title }</ChakraAlert.Title> } + { Boolean(title) && <ChakraAlert.Title>{ title }</ChakraAlert.Title> } <ChakraAlert.Description display="inline-flex" flexWrap="wrap" { ...descriptionProps }>{ children }</ChakraAlert.Description> </ChakraAlert.Content> ) : ( diff --git a/src/toolkit/chakra/badge.tsx b/src/toolkit/chakra/badge.tsx index 653a719a9e3..db3c1dc07f8 100644 --- a/src/toolkit/chakra/badge.tsx +++ b/src/toolkit/chakra/badge.tsx @@ -4,7 +4,7 @@ import type { BadgeProps as ChakraBadgeProps } from '@chakra-ui/react'; import { chakra, Badge as ChakraBadge } from '@chakra-ui/react'; import React from 'react'; -import { TruncatedTextTooltip } from '../components/truncation/TruncatedTextTooltip'; +import { OverflowTooltip } from '../components/truncation/OverflowTooltip'; import { Skeleton } from './skeleton'; export interface BadgeProps extends Omit<ChakraBadgeProps, 'colorScheme'> { @@ -21,9 +21,9 @@ export const Badge = React.forwardRef<HTMLDivElement, BadgeProps>( const child = children ? <chakra.span overflow="hidden" textOverflow="ellipsis">{ children }</chakra.span> : null; const childrenElement = truncated ? ( - <TruncatedTextTooltip label={ children }> + <OverflowTooltip content={ children }> { child } - </TruncatedTextTooltip> + </OverflowTooltip> ) : child; return ( diff --git a/src/toolkit/chakra/box.tsx b/src/toolkit/chakra/box.tsx index e9fa872a2fa..c6f99e4306f 100644 --- a/src/toolkit/chakra/box.tsx +++ b/src/toolkit/chakra/box.tsx @@ -3,6 +3,7 @@ import type { BoxProps } from '@chakra-ui/react'; import { Box } from '@chakra-ui/react'; +// Renders `html` as-is. Content not authored by the app (operator envs, API data) must be sanitized by the caller. export const BoxHtml = ({ html, ...props }: { html: string } & BoxProps) => { return ( <Box diff --git a/src/toolkit/chakra/checkbox.tsx b/src/toolkit/chakra/checkbox.tsx index 6a6bff9d760..469bd111d98 100644 --- a/src/toolkit/chakra/checkbox.tsx +++ b/src/toolkit/chakra/checkbox.tsx @@ -1,18 +1,19 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import type { CheckboxGroupProps as ChakraCheckboxGroupProps } from '@chakra-ui/react'; +import type { CheckboxGroupProps as ChakraCheckboxGroupProps, CheckboxLabelProps } from '@chakra-ui/react'; import { Checkbox as ChakraCheckbox, CheckboxGroup as ChakraCheckboxGroup } from '@chakra-ui/react'; import * as React from 'react'; export interface CheckboxProps extends ChakraCheckbox.RootProps { icon?: React.ReactNode; inputProps?: React.InputHTMLAttributes<HTMLInputElement>; + labelProps?: CheckboxLabelProps; rootRef?: React.Ref<HTMLLabelElement>; } export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>( function Checkbox(props, ref) { - const { icon, children, inputProps, rootRef, ...rest } = props; + const { icon, children, inputProps, rootRef, labelProps, ...rest } = props; return ( <ChakraCheckbox.Root ref={ rootRef } { ...rest }> <ChakraCheckbox.HiddenInput ref={ ref } { ...inputProps }/> @@ -20,7 +21,7 @@ export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>( { icon || <ChakraCheckbox.Indicator/> } </ChakraCheckbox.Control> { children !== undefined && children !== null && ( - <ChakraCheckbox.Label>{ children }</ChakraCheckbox.Label> + <ChakraCheckbox.Label { ...labelProps }>{ children }</ChakraCheckbox.Label> ) } </ChakraCheckbox.Root> ); diff --git a/src/toolkit/chakra/close-button.tsx b/src/toolkit/chakra/close-button.tsx index dde28723f4a..88369b38730 100644 --- a/src/toolkit/chakra/close-button.tsx +++ b/src/toolkit/chakra/close-button.tsx @@ -25,7 +25,7 @@ export const CloseButton = React.forwardRef< return ( <IconButton aria-label="Close" ref={ ref } css={ styles } { ...rest }> - { props.children ?? <Icon boxSize={ 5 } { ...iconProps }><CloseIcon/></Icon> } + { props.children ?? <Icon boxSize="var(--close-button-icon-size)" { ...iconProps }><CloseIcon/></Icon> } </IconButton> ); }); diff --git a/src/toolkit/chakra/drawer.tsx b/src/toolkit/chakra/drawer.tsx index bff9e3426a0..f9c832aa8ca 100644 --- a/src/toolkit/chakra/drawer.tsx +++ b/src/toolkit/chakra/drawer.tsx @@ -36,7 +36,7 @@ export const DrawerCloseTrigger = React.forwardRef< return ( <ChakraDrawer.CloseTrigger position="absolute" - top="7" + top="26px" insetEnd="5" { ...props } asChild diff --git a/src/toolkit/chakra/empty-state.tsx b/src/toolkit/chakra/empty-state.tsx index c69b61ca628..bb8a324bddb 100644 --- a/src/toolkit/chakra/empty-state.tsx +++ b/src/toolkit/chakra/empty-state.tsx @@ -79,7 +79,7 @@ export const EmptyState = React.forwardRef<HTMLDivElement, EmptyStateProps>( return ( <ChakraEmptyState.Root ref={ ref } { ...rest }> <ChakraEmptyState.Content> - { iconContent && ( + { Boolean(iconContent) && ( <ChakraEmptyState.Indicator>{ iconContent }</ChakraEmptyState.Indicator> ) } { descriptionContent ? ( diff --git a/src/toolkit/chakra/field.tsx b/src/toolkit/chakra/field.tsx index 0d4bcd49244..aa2e43f5b9b 100644 --- a/src/toolkit/chakra/field.tsx +++ b/src/toolkit/chakra/field.tsx @@ -41,13 +41,13 @@ export const Field = React.forwardRef<HTMLDivElement, FieldProps>( { label } </chakra.span> <ChakraField.RequiredIndicator fallback={ optionalText }/> - { errorText && ( + { Boolean(errorText) && ( <ChakraField.ErrorText ml="2px">-{ space }{ errorText }</ChakraField.ErrorText> ) } </ChakraField.Label> ); - const helperTextElement = helperText && ( + const helperTextElement = Boolean(helperText) && ( <ChakraField.HelperText>{ helperText }</ChakraField.HelperText> ); @@ -94,17 +94,17 @@ export const Field = React.forwardRef<HTMLDivElement, FieldProps>( return ( <ChakraField.Root ref={ ref } { ...rest }> - { label && ( + { Boolean(label) && ( <ChakraField.Label> { label } <ChakraField.RequiredIndicator fallback={ optionalText }/> </ChakraField.Label> ) } { clonedChild } - { helperText && ( + { Boolean(helperText) && ( <ChakraField.HelperText>{ helperText }</ChakraField.HelperText> ) } - { errorText && ( + { Boolean(errorText) && ( <ChakraField.ErrorText>{ errorText }</ChakraField.ErrorText> ) } </ChakraField.Root> diff --git a/src/toolkit/chakra/input-group.tsx b/src/toolkit/chakra/input-group.tsx index c3b55f61981..7c04fd50206 100644 --- a/src/toolkit/chakra/input-group.tsx +++ b/src/toolkit/chakra/input-group.tsx @@ -113,7 +113,7 @@ export const InputGroup = React.forwardRef<HTMLDivElement, InputGroupProps>( }} { ...rest } > - { startElement && ( + { Boolean(startElement) && ( <InputElement pointerEvents="none" ref={ startElementRef } px={ 0 } color="input.element" { ...startElementProps }> { startElement } </InputElement> @@ -130,7 +130,7 @@ export const InputGroup = React.forwardRef<HTMLDivElement, InputGroupProps>( placeholder: inlinePaddings ? child.props.placeholder : undefined, }); }) } - { endElement && ( + { Boolean(endElement) && ( <InputElement placement="end" ref={ endElementRef } px={ 0 } color="input.element" { ...endElementProps }> { endElement } </InputElement> diff --git a/src/toolkit/chakra/input.tsx b/src/toolkit/chakra/input.ts similarity index 100% rename from src/toolkit/chakra/input.tsx rename to src/toolkit/chakra/input.ts diff --git a/src/toolkit/chakra/link.tsx b/src/toolkit/chakra/link.tsx index 76427f621dc..8db9ee95160 100644 --- a/src/toolkit/chakra/link.tsx +++ b/src/toolkit/chakra/link.tsx @@ -2,13 +2,14 @@ import type { LinkProps as ChakraLinkProps, IconProps } from '@chakra-ui/react'; import { Link as ChakraLink, LinkBox as ChakraLinkBox, LinkOverlay as ChakraLinkOverlay, Icon } from '@chakra-ui/react'; -import NextLink from 'next/link'; -import type { LinkProps as NextLinkProps } from 'next/link'; import React from 'react'; +import type { RouterLinkProps, Url } from '../router/types'; + import stripUtmParams from 'src/shared/links/strip-utm-params'; import ArrowIcon from 'src/sprite/icons/link_external.svg'; +import { useLink } from '../router/context'; import { Skeleton } from './skeleton'; export const LinkExternalIcon = ({ color, ...rest }: IconProps) => ( @@ -34,17 +35,21 @@ interface LinkPropsChakra extends ChakraLinkProps { disabled?: boolean; } -interface LinkPropsNext extends Partial<Pick<NextLinkProps, 'shallow' | 'prefetch' | 'scroll'>> {} +interface LinkPropsRouter extends Partial<Pick<RouterLinkProps, 'shallow' | 'prefetch' | 'scroll'>> {} + +export interface LinkProps extends LinkPropsChakra, LinkPropsRouter {} -export interface LinkProps extends LinkPropsChakra, LinkPropsNext {} +interface RouterLinkPropsMaybeHref extends Omit<RouterLinkProps, 'href'> { + href: Url | undefined; +} -const splitProps = (props: LinkProps): { chakra: LinkPropsChakra; next: NextLinkProps } => { +const splitProps = (props: LinkProps): { chakra: LinkPropsChakra; router: RouterLinkPropsMaybeHref } => { const { scroll = true, shallow = false, prefetch = false, ...rest } = props; return { chakra: rest, - next: { - href: rest.href as NextLinkProps['href'], + router: { + href: rest.href, scroll, shallow, prefetch, @@ -54,7 +59,8 @@ const splitProps = (props: LinkProps): { chakra: LinkPropsChakra; next: NextLink export const Link = React.forwardRef<HTMLAnchorElement, LinkProps>( function Link(props, ref) { - const { chakra, next } = splitProps(props); + const RouterLink = useLink(); + const { chakra, router } = splitProps(props); const { external, loading, href, children, disabled, noIcon, iconColor, className, ...rest } = chakra; if (external) { @@ -86,10 +92,10 @@ export const Link = React.forwardRef<HTMLAnchorElement, LinkProps>( { ...(disabled ? { 'data-disabled': true } : {}) } { ...rest } > - { next.href ? ( - <NextLink { ...next }> + { router.href ? ( + <RouterLink { ...router } href={ router.href }> { children } - </NextLink> + </RouterLink> ) : <span>{ children }</span> } @@ -103,7 +109,8 @@ export const LinkBox = ChakraLinkBox; export const LinkOverlay = React.forwardRef<HTMLAnchorElement, LinkProps>( function LinkOverlay(props, ref) { - const { chakra, next } = splitProps(props); + const RouterLink = useLink(); + const { chakra, router } = splitProps(props); const { children, external, loading, href, noIcon, iconColor, ...rest } = chakra; if (external) { @@ -118,7 +125,7 @@ export const LinkOverlay = React.forwardRef<HTMLAnchorElement, LinkProps>( rel="noopener noreferrer" { ...rest } > - { (children || (!noIcon && href)) && ( + { Boolean(children || (!noIcon && href)) && ( <Skeleton display="inline-flex" alignItems="center" loading={ loading } maxW="100%" h="100%"> { children } { !noIcon && href && <LinkExternalIcon color={ iconColor }/> } @@ -137,10 +144,10 @@ export const LinkOverlay = React.forwardRef<HTMLAnchorElement, LinkProps>( return ( <ChakraLinkOverlay ref={ ref } - asChild={ Boolean(next.href) } + asChild={ Boolean(router.href) } { ...rest } > - { next.href ? <NextLink { ...next }>{ content }</NextLink> : content } + { router.href ? <RouterLink { ...router } href={ router.href }>{ content }</RouterLink> : content } </ChakraLinkOverlay> ); }, diff --git a/src/toolkit/chakra/popover.tsx b/src/toolkit/chakra/popover.tsx index 2d7f672ac22..46c162cf878 100644 --- a/src/toolkit/chakra/popover.tsx +++ b/src/toolkit/chakra/popover.tsx @@ -72,7 +72,9 @@ export const PopoverCloseTriggerWrapper = React.forwardRef< ); }); -export const PopoverRoot = (props: ChakraPopover.RootProps) => { +export interface PopoverRootProps extends ChakraPopover.RootProps {} + +export const PopoverRoot = (props: PopoverRootProps) => { const positioning = { placement: 'bottom-start' as const, overflowPadding: 4, diff --git a/src/toolkit/chakra/radio.tsx b/src/toolkit/chakra/radio.tsx index 8c961128d97..a23bec61c7d 100644 --- a/src/toolkit/chakra/radio.tsx +++ b/src/toolkit/chakra/radio.tsx @@ -15,7 +15,7 @@ export const Radio = React.forwardRef<HTMLInputElement, RadioProps>( <ChakraRadioGroup.Item ref={ rootRef } { ...rest }> <ChakraRadioGroup.ItemHiddenInput ref={ ref } { ...inputProps }/> <ChakraRadioGroup.ItemIndicator/> - { children && ( + { Boolean(children) && ( <ChakraRadioGroup.ItemText>{ children }</ChakraRadioGroup.ItemText> ) } </ChakraRadioGroup.Item> diff --git a/src/toolkit/chakra/slider.tsx b/src/toolkit/chakra/slider.tsx index 8603cb423ce..32513977bc2 100644 --- a/src/toolkit/chakra/slider.tsx +++ b/src/toolkit/chakra/slider.tsx @@ -23,10 +23,10 @@ export const Slider = React.forwardRef<HTMLDivElement, SliderProps>( return ( <ChakraSlider.Root ref={ ref } thumbAlignment="center" { ...rest }> - { label && !showValue && ( + { Boolean(label) && !showValue && ( <ChakraSlider.Label>{ label }</ChakraSlider.Label> ) } - { label && showValue && ( + { Boolean(label) && showValue && ( <HStack justify="space-between"> <ChakraSlider.Label>{ label }</ChakraSlider.Label> <ChakraSlider.ValueText/> diff --git a/src/toolkit/chakra/switch.tsx b/src/toolkit/chakra/switch.tsx index 52de2f24ea6..b39b611cfcc 100644 --- a/src/toolkit/chakra/switch.tsx +++ b/src/toolkit/chakra/switch.tsx @@ -11,14 +11,24 @@ export interface SwitchProps extends ChakraSwitch.RootProps { thumbLabel?: { on: React.ReactNode; off: React.ReactNode }; } +// Zag visually hides the input with `position: absolute; margin: -1px` and no offsets, so it sits at its static +// position. With `direction="rtl"` (row-reverse) that is the root's end edge, where the negative margin pushes it +// 1px outside the root; focusing it then scrolls the nearest scroll container to reveal it and shifts the content. +const HIDDEN_INPUT_STYLE: React.CSSProperties = { top: 0, insetInlineStart: 0, margin: 0 }; + export const Switch = React.forwardRef<HTMLInputElement, SwitchProps>( function Switch(props, ref) { const { inputProps, children, rootRef, trackLabel, thumbLabel, labelProps, ...rest } = props; + const hiddenInputProps = React.useMemo(() => ({ + ...inputProps, + style: { ...HIDDEN_INPUT_STYLE, ...inputProps?.style }, + }), [ inputProps ]); + return ( <ChakraSwitch.Root ref={ rootRef } { ...rest }> - <ChakraSwitch.HiddenInput ref={ ref } { ...inputProps }/> + <ChakraSwitch.HiddenInput ref={ ref } { ...hiddenInputProps }/> <ChakraSwitch.Control> <ChakraSwitch.Thumb> { thumbLabel && ( diff --git a/src/toolkit/chakra/table.tsx b/src/toolkit/chakra/table.tsx index a67891b0f76..b55a26a6552 100644 --- a/src/toolkit/chakra/table.tsx +++ b/src/toolkit/chakra/table.tsx @@ -103,15 +103,31 @@ export const TableHeaderSticky = (props: TableHeaderProps) => { export const TableContainerScrollable = ({ children, + onlyMobile = true, }: { children: React.ReactNode; + onlyMobile?: boolean; }) => { + + if (!onlyMobile) { + return ( + <Box + display="grid" + overflowX="scroll" + mx={{ base: -3, lg: 0 }} + px={{ base: 3, lg: 0 }} + > + { children } + </Box> + ); + } + return ( <Box overflowX={{ base: 'scroll', lg: 'unset' }} mx={{ base: -3, lg: 0 }} px={{ base: 3, lg: 0 }} - maxW={{ base: '100vw', lg: undefined }} + maxW={{ base: '100vw', lg: 'initial' }} > { children } </Box> diff --git a/src/toolkit/chakra/tag.tsx b/src/toolkit/chakra/tag.tsx index d38e800b07b..8dc01a7f5b8 100644 --- a/src/toolkit/chakra/tag.tsx +++ b/src/toolkit/chakra/tag.tsx @@ -3,7 +3,7 @@ import { chakra, Tag as ChakraTag } from '@chakra-ui/react'; import * as React from 'react'; -import { TruncatedTextTooltip } from '../components/truncation/TruncatedTextTooltip'; +import { OverflowTooltip } from '../components/truncation/OverflowTooltip'; import { nbsp } from '../utils/htmlEntities'; import { CloseButton } from './close-button'; import { Skeleton } from './skeleton'; @@ -43,9 +43,9 @@ export const Tag = React.forwardRef<HTMLSpanElement, TagProps>( ) : null; const contentElement = truncated ? ( - <TruncatedTextTooltip label={ children }> + <OverflowTooltip content={ children }> <ChakraTag.Label>{ labelElement }{ children }</ChakraTag.Label> - </TruncatedTextTooltip> + </OverflowTooltip> ) : <ChakraTag.Label>{ labelElement }{ children }</ChakraTag.Label>; return ( @@ -56,11 +56,11 @@ export const Tag = React.forwardRef<HTMLSpanElement, TagProps>( { ...(disabled && { 'data-disabled': true }) } { ...rest } > - { startElement && ( + { Boolean(startElement) && ( <ChakraTag.StartElement _empty={{ display: 'none' }}>{ startElement }</ChakraTag.StartElement> ) } { contentElement } - { endElement && ( + { Boolean(endElement) && ( <ChakraTag.EndElement { ...endElementProps }>{ endElement }</ChakraTag.EndElement> ) } { closable && ( diff --git a/src/toolkit/chakra/textarea.tsx b/src/toolkit/chakra/textarea.ts similarity index 100% rename from src/toolkit/chakra/textarea.tsx rename to src/toolkit/chakra/textarea.ts diff --git a/src/toolkit/chakra/toaster.tsx b/src/toolkit/chakra/toaster.tsx index 5b87ef68b13..654ab716e1d 100644 --- a/src/toolkit/chakra/toaster.tsx +++ b/src/toolkit/chakra/toaster.tsx @@ -41,7 +41,7 @@ export const Toaster = () => { <Spinner size="sm" color="blue.solid" my={ 1 }/> ) : null } <Stack gap="0" flex="1" maxWidth="100%"> - { toast.title && <Toast.Title>{ toast.title }</Toast.Title> } + { Boolean(toast.title) && <Toast.Title>{ toast.title }</Toast.Title> } { (toast.meta?.renderDescription || toast.description) && ( <Toast.Description> { toast.meta?.renderDescription?.() || toast.description } diff --git a/src/toolkit/components/AdaptiveTabs/AdaptiveTabsList.tsx b/src/toolkit/components/AdaptiveTabs/AdaptiveTabsList.tsx index 6152dc615ca..a477e35f431 100644 --- a/src/toolkit/components/AdaptiveTabs/AdaptiveTabsList.tsx +++ b/src/toolkit/components/AdaptiveTabs/AdaptiveTabsList.tsx @@ -130,7 +130,7 @@ const AdaptiveTabsList = (props: Props) => { ...(typeof listProps === 'function' ? listProps({ isSticky, activeTab }) : listProps) } > - { leftSlot && ( + { Boolean(leftSlot) && ( <Box ref={ leftSlotRef } { ...leftSlotProps } diff --git a/src/toolkit/components/AdaptiveTabs/useAdaptiveTabs.tsx b/src/toolkit/components/AdaptiveTabs/useAdaptiveTabs.ts similarity index 100% rename from src/toolkit/components/AdaptiveTabs/useAdaptiveTabs.tsx rename to src/toolkit/components/AdaptiveTabs/useAdaptiveTabs.ts diff --git a/src/toolkit/components/AdaptiveTabs/useScrollToActiveTab.tsx b/src/toolkit/components/AdaptiveTabs/useScrollToActiveTab.ts similarity index 100% rename from src/toolkit/components/AdaptiveTabs/useScrollToActiveTab.tsx rename to src/toolkit/components/AdaptiveTabs/useScrollToActiveTab.ts diff --git a/src/toolkit/components/RoutedTabs/RoutedTabs.tsx b/src/toolkit/components/RoutedTabs/RoutedTabs.tsx index 558ee4c8028..3d47ac1939b 100644 --- a/src/toolkit/components/RoutedTabs/RoutedTabs.tsx +++ b/src/toolkit/components/RoutedTabs/RoutedTabs.tsx @@ -1,9 +1,9 @@ // SPDX-License-Identifier: LicenseRef-Blockscout -import { pickBy } from 'es-toolkit'; -import { useRouter } from 'next/router'; +import { omit, pickBy } from 'es-toolkit'; import React from 'react'; +import { useRouter } from '../../router/context'; import type { Props as AdaptiveTabsProps } from '../AdaptiveTabs/AdaptiveTabs'; import AdaptiveTabs from '../AdaptiveTabs/AdaptiveTabs'; import { getTabValue } from '../AdaptiveTabs/utils'; @@ -35,11 +35,7 @@ const RoutedTabs = (props: RoutedTabsProps) => { return router.pathname.includes(`[${ key }]`); }); - router.push( - { pathname: router.pathname, query: { ...queryForPathname, tab: value } }, - undefined, - { shallow: true }, - ); + router.push({ pathname: router.pathname, query: { ...queryForPathname, tab: value } }, { shallow: true }); onValueChange?.({ value }); }, [ tabs, router, onValueChange, preservedParams ]); @@ -47,15 +43,7 @@ const RoutedTabs = (props: RoutedTabsProps) => { React.useEffect(() => { if (router.query.scroll_to_tabs) { tabsRef?.current?.scrollIntoView(true); - delete router.query.scroll_to_tabs; - router.push( - { - pathname: router.pathname, - query: router.query, - }, - undefined, - { shallow: true }, - ); + router.push({ pathname: router.pathname, query: omit(router.query, [ 'scroll_to_tabs' ]) }, { shallow: true }); } // replicate componentDidMount // eslint-disable-next-line react-hooks/exhaustive-deps diff --git a/src/toolkit/components/RoutedTabs/useActiveTabFromQuery.ts b/src/toolkit/components/RoutedTabs/useActiveTabFromQuery.ts new file mode 100644 index 00000000000..6d13250f971 --- /dev/null +++ b/src/toolkit/components/RoutedTabs/useActiveTabFromQuery.ts @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { TabItem } from '../AdaptiveTabs/types'; + +import { useRouter } from '../../router/context'; +import { castToString } from '../../utils/guards'; + +export default function useActiveTabFromQuery(tabs: Array<TabItem>, defaultTabId?: string) { + const router = useRouter(); + const tabFromQuery = castToString(router.query.tab); + + if (!tabFromQuery) { + if (defaultTabId) { + return tabs.find((tab) => tab.id === defaultTabId); + } + + return; + } + + return tabs.find((tab) => { + if (Array.isArray(tab.id)) { + return tab.id.includes(tabFromQuery); + } + + return tab.id === tabFromQuery || ('subTabs' in tab && tab.subTabs?.some((id) => id === tabFromQuery)); + }); +} diff --git a/src/toolkit/components/RoutedTabs/useActiveTabFromQuery.tsx b/src/toolkit/components/RoutedTabs/useActiveTabFromQuery.tsx deleted file mode 100644 index 772330fa46d..00000000000 --- a/src/toolkit/components/RoutedTabs/useActiveTabFromQuery.tsx +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { useRouter } from 'next/router'; - -import type { TabItem } from '../AdaptiveTabs/types'; - -import { castToString } from '../../utils/guards'; - -export default function useActiveTabFromQuery(tabs: Array<TabItem>, defaultTabId?: string) { - const router = useRouter(); - const tabFromQuery = castToString(router.query.tab); - - if (!tabFromQuery) { - if (defaultTabId) { - return tabs.find((tab) => tab.id === defaultTabId); - } - - return; - } - - return tabs.find((tab) => { - if (Array.isArray(tab.id)) { - return tab.id.includes(tabFromQuery); - } - - return tab.id === tabFromQuery || ('subTabs' in tab && tab.subTabs?.some((id) => id === tabFromQuery)); - }); -} diff --git a/src/toolkit/components/charts/line/LineChart.tsx b/src/toolkit/components/charts/line/LineChart.tsx index 91fcd93b53d..c3023c57991 100644 --- a/src/toolkit/components/charts/line/LineChart.tsx +++ b/src/toolkit/components/charts/line/LineChart.tsx @@ -92,6 +92,7 @@ export const LineChart = React.memo(({ data: displayedCharts, margin, axesConfig, + resolution, }); return ( @@ -155,7 +156,7 @@ export const LineChart = React.memo(({ type="bottom" scale={ axes.x.scale } transform={ `translate(0, ${ innerHeight })` } - ticks={ axesConfig.x.ticks } + tickValues={ axes.x.tickValues } anchorEl={ overlayRef.current } tickFormatGenerator={ axes.x.tickFormatter } noAnimation diff --git a/src/toolkit/components/charts/line/parts/LineChartAxis.tsx b/src/toolkit/components/charts/line/parts/LineChartAxis.tsx index d8dd2ac0c55..919f7e5b163 100644 --- a/src/toolkit/components/charts/line/parts/LineChartAxis.tsx +++ b/src/toolkit/components/charts/line/parts/LineChartAxis.tsx @@ -6,16 +6,28 @@ import React from 'react'; import { useColorModeValue } from '../../../../chakra/color-mode'; -export interface LineChartAxisProps extends Omit<React.SVGProps<SVGGElement>, 'scale'> { - type: 'left' | 'bottom'; +interface LineChartAxisBaseProps extends Omit<React.SVGProps<SVGGElement>, 'scale'> { scale: d3.ScaleTime<number, number> | d3.ScaleLinear<number, number>; noAnimation?: boolean; - ticks: number; tickFormatGenerator?: (axis: d3.Axis<d3.NumberValue>) => (domainValue: d3.AxisDomain, index: number) => string; anchorEl?: SVGRectElement | null; } -export const LineChartAxis = React.memo(({ type, scale, ticks, tickFormatGenerator, noAnimation, anchorEl, ...props }: LineChartAxisProps) => { +interface LineChartAxisLeftProps extends LineChartAxisBaseProps { + type: 'left'; + ticks: number; + tickValues?: never; +} + +interface LineChartAxisBottomProps extends LineChartAxisBaseProps { + type: 'bottom'; + ticks?: never; + tickValues: Array<Date>; +} + +export type LineChartAxisProps = LineChartAxisLeftProps | LineChartAxisBottomProps; + +export const LineChartAxis = React.memo(({ type, scale, ticks, tickValues, tickFormatGenerator, noAnimation, anchorEl, ...props }: LineChartAxisProps) => { const ref = React.useRef<SVGGElement>(null); const textColor = useToken('colors', useColorModeValue('blackAlpha.600', 'whiteAlpha.500')); @@ -25,8 +37,7 @@ export const LineChartAxis = React.memo(({ type, scale, ticks, tickFormatGenerat return; } - const axisGenerator = type === 'left' ? d3.axisLeft : d3.axisBottom; - const axis = axisGenerator(scale).ticks(ticks); + const axis = type === 'bottom' ? d3.axisBottom(scale).tickValues(tickValues) : d3.axisLeft(scale).ticks(ticks); if (tickFormatGenerator) { axis.tickFormat(tickFormatGenerator(axis)); @@ -45,7 +56,7 @@ export const LineChartAxis = React.memo(({ type, scale, ticks, tickFormatGenerat .attr('opacity', 1) .attr('color', textColor) .style('font-size', '12px'); - }, [ scale, ticks, tickFormatGenerator, noAnimation, type, textColor ]); + }, [ scale, ticks, tickValues, tickFormatGenerator, noAnimation, type, textColor ]); React.useEffect(() => { if (!anchorEl) { diff --git a/src/toolkit/components/charts/line/types.tsx b/src/toolkit/components/charts/line/types.ts similarity index 100% rename from src/toolkit/components/charts/line/types.tsx rename to src/toolkit/components/charts/line/types.ts diff --git a/src/toolkit/components/charts/line/utils/lineChartAxis.spec.ts b/src/toolkit/components/charts/line/utils/lineChartAxis.spec.ts new file mode 100644 index 00000000000..dee715a8adf --- /dev/null +++ b/src/toolkit/components/charts/line/utils/lineChartAxis.spec.ts @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import * as d3 from 'd3'; + +import { ChartResolution } from '../../types'; +import type { LineChartData } from '../types'; + +import { describe, expect, it } from 'vitest'; + +import { getTickFormatX, getTickValuesX } from './lineChartAxis'; + +function makeData(dates: Array<string>): LineChartData { + return [ { + id: 'chart', + name: 'chart', + charts: [], + items: dates.map((date, index) => ({ date: new Date(date), value: index })), + } ]; +} + +function makeScale(data: LineChartData): d3.ScaleTime<number, number> { + const dates = data[0].items.map(({ date }) => date); + return d3.scaleUtc().domain([ dates[0], dates[dates.length - 1] ]); +} + +const toDay = (date: Date): string => date.toISOString().slice(0, 10); +const octoberDays = Array.from({ length: 30 }, (_, i) => `2025-10-${ String(i + 1).padStart(2, '0') }`); + +describe('getTickValuesX', () => { + it('puts a tick on every data point when the data fits within the tick limit', () => { + const data = makeData([ '2025-07-31', '2025-08-31', '2025-09-30', '2025-10-31' ]); + const ticks = getTickValuesX(data, makeScale(data), 4, ChartResolution.MONTH); + expect(ticks.map(toDay)).toEqual([ '2025-07-31', '2025-08-31', '2025-09-30', '2025-10-31' ]); + }); + + it('orders data-point ticks chronologically across charts', () => { + const data = [ ...makeData([ '2025-09-30' ]), ...makeData([ '2025-07-31', '2025-08-31' ]) ]; + const ticks = getTickValuesX(data, makeScale(data), 4, ChartResolution.MONTH); + expect(ticks.map(toDay)).toEqual([ '2025-07-31', '2025-08-31', '2025-09-30' ]); + }); + + it('falls back to calendar ticks when the data is denser than the tick limit', () => { + const data = makeData(octoberDays); + const ticks = getTickValuesX(data, makeScale(data), 4, ChartResolution.DAY); + expect(ticks.map(toDay)).toEqual([ '2025-10-05', '2025-10-12', '2025-10-19', '2025-10-26' ]); + }); + + it('ignores data points without a resolution', () => { + const data = makeData([ '2025-07-03', '2025-08-09' ]); + const ticks = getTickValuesX(data, makeScale(data), 4); + expect(ticks.map(toDay)).toEqual([ '2025-07-06', '2025-07-13', '2025-07-20', '2025-07-27', '2025-08-03' ]); + }); + + it('deduplicates dates shared by several charts', () => { + const data = [ ...makeData([ '2025-07-31', '2025-08-31' ]), ...makeData([ '2025-07-31', '2025-08-31' ]) ]; + expect(getTickValuesX(data, makeScale(data), 4, ChartResolution.MONTH)).toHaveLength(2); + }); +}); + +describe('getTickFormatX', () => { + const labels = (dates: Array<string>, resolution?: ChartResolution) => { + const ticks = dates.map((date) => new Date(date)); + return ticks.map(getTickFormatX(ticks, resolution)); + }; + + it('yields distinct labels for quarterly ticks over multiple years', () => { + expect(labels([ '2024-01-01', '2024-04-01', '2024-07-01', '2024-10-01', '2025-01-01' ])) + .toEqual([ 'Jan \'24', 'Apr \'24', 'Jul \'24', 'Oct \'24', 'Jan \'25' ]); + }); + + it('labels yearly ticks with the year only', () => { + expect(labels([ '2023-01-01', '2024-01-01', '2025-01-01' ])).toEqual([ '2023', '2024', '2025' ]); + }); + + it('labels month-end ticks with month and year', () => { + expect(labels([ '2025-01-31', '2025-02-28', '2025-03-31' ])).toEqual([ 'Jan \'25', 'Feb \'25', 'Mar \'25' ]); + }); + + it('labels daily ticks with day and month', () => { + expect(labels([ '2025-10-05', '2025-10-06' ])).toEqual([ '05 Oct', '06 Oct' ]); + }); + + it('labels weekly ticks with day and month', () => { + expect(labels([ '2025-10-05', '2025-10-12' ])).toEqual([ '05 Oct', '12 Oct' ]); + }); + + it('labels sub-day ticks within one day with time only', () => { + expect(labels([ '2025-10-05T10:00:00Z', '2025-10-05T13:00:00Z' ])).toEqual([ '10:00', '13:00' ]); + }); + + it('keeps the date on sub-day ticks that span a day or more', () => { + expect(labels([ '2025-10-01T00:00:00Z', '2025-10-01T12:00:00Z', '2025-10-02T00:00:00Z' ])) + .toEqual([ '01 Oct 00:00', '01 Oct 12:00', '02 Oct 00:00' ]); + }); + + it('labels a single tick by resolution', () => { + expect(labels([ '2025-10-31' ], ChartResolution.MONTH)).toEqual([ 'Oct \'25' ]); + expect(labels([ '2025-12-31' ], ChartResolution.YEAR)).toEqual([ '2025' ]); + expect(labels([ '2025-10-31' ], ChartResolution.DAY)).toEqual([ '31 Oct' ]); + expect(labels([ '2025-10-31' ])).toEqual([ '31 Oct' ]); + }); +}); diff --git a/src/toolkit/components/charts/line/utils/lineChartAxis.ts b/src/toolkit/components/charts/line/utils/lineChartAxis.ts index 38137ef24f9..8af8bc00b93 100644 --- a/src/toolkit/components/charts/line/utils/lineChartAxis.ts +++ b/src/toolkit/components/charts/line/utils/lineChartAxis.ts @@ -3,14 +3,17 @@ import * as d3 from 'd3'; import { maxBy, uniq } from 'es-toolkit'; +import { ChartResolution } from '../../types'; import type { LineChartAxesConfig, LineChartAxisConfig, LineChartData } from '../types'; -import { DAY, MONTH, YEAR } from '../../../../utils/consts'; +import { DAY, YEAR } from '../../../../utils/consts'; export const DEFAULT_MAXIMUM_SIGNIFICANT_DIGITS = 2; export const DEFAULT_MAXIMUM_FRACTION_DIGITS = 3; export const MAXIMUM_SIGNIFICANT_DIGITS_LIMIT = 8; export const DEFAULT_LABEL_LENGTH = 5; +export const DEFAULT_TICKS_NUM_X = 4; +const MIN_MONTH_GAP = 28 * DAY; export interface LabelFormatParams extends Intl.NumberFormatOptions { maxLabelLength: number; @@ -18,13 +21,15 @@ export interface LabelFormatParams extends Intl.NumberFormatOptions { type Data = LineChartData; -export function getAxesParams(data: Data, axesConfig?: LineChartAxesConfig) { +export function getAxesParams(data: Data, axesConfig?: LineChartAxesConfig, resolution?: ChartResolution) { const { labelFormatParams: labelFormatParamsY, scale: yScale } = getAxisParamsY(data, axesConfig?.y, axesConfig?.y?.tickFormatter); + const { scale: xScale, tickValues: xTickValues } = getAxisParamsX(data, axesConfig?.x, resolution); return { x: { - scale: getAxisParamsX(data).scale, - tickFormatter: axesConfig?.x?.tickFormatter ?? tickFormatterX, + scale: xScale, + tickValues: xTickValues, + tickFormatter: axesConfig?.x?.tickFormatter ?? getTickFormatterX(xTickValues, resolution), }, y: { scale: yScale, @@ -34,32 +39,65 @@ export function getAxesParams(data: Data, axesConfig?: LineChartAxesConfig) { }; } -function getAxisParamsX(data: Data) { +function getAxisParamsX(data: Data, config?: LineChartAxisConfig, resolution?: ChartResolution) { const min = d3.min(data, ({ items }) => d3.min(items, ({ date }) => date)) ?? new Date(); const max = d3.max(data, ({ items }) => d3.max(items, ({ date }) => date)) ?? new Date(); const scale = d3.scaleUtc().domain([ min, max ]); + const tickValues = getTickValuesX(data, scale, config?.ticks ?? DEFAULT_TICKS_NUM_X, resolution); - return { min, max, scale }; + return { min, max, scale, tickValues }; } -const tickFormatterX = (axis: d3.Axis<d3.NumberValue>) => (d: d3.AxisDomain) => { - let format: (date: Date) => string; - const scale = axis.scale(); - const extent = scale.domain(); - - const span = Number(extent[1]) - Number(extent[0]); - - if (span > 2 * YEAR) { - format = d3.utcFormat('%Y'); - } else if (span > 4 * MONTH) { - format = d3.utcFormat('%b \'%y'); - } else if (span > 2 * DAY) { - format = d3.utcFormat('%d %b'); - } else { - format = d3.utcFormat('%H:%M'); +export function getTickValuesX( + data: Data, + scale: d3.ScaleTime<number, number>, + maxTicks: number, + resolution?: ChartResolution, +): Array<Date> { + if (resolution) { + const dataPoints = uniq(data.flatMap(({ items }) => items.map(({ date }) => date.getTime()))).sort((a, b) => a - b); + if (dataPoints.length <= maxTicks) { + return dataPoints.map((time) => new Date(time)); + } } - return format(d as Date); + return scale.ticks(maxTicks); +} + +export function getTickFormatX(ticks: Array<Date>, resolution?: ChartResolution): (date: Date) => string { + const gaps = ticks.slice(1).map((tick, index) => tick.getTime() - ticks[index].getTime()); + const gap = d3.min(gaps); + + if (gap === undefined) { + return getTickFormatXByResolution(resolution); + } + + if (gap >= YEAR) { + return d3.utcFormat('%Y'); + } else if (gap >= MIN_MONTH_GAP) { + return d3.utcFormat('%b \'%y'); + } else if (gap >= DAY) { + return d3.utcFormat('%d %b'); + } + + const span = ticks[ticks.length - 1].getTime() - ticks[0].getTime(); + return span >= DAY ? d3.utcFormat('%d %b %H:%M') : d3.utcFormat('%H:%M'); +} + +function getTickFormatXByResolution(resolution?: ChartResolution): (date: Date) => string { + switch (resolution) { + case ChartResolution.YEAR: + return d3.utcFormat('%Y'); + case ChartResolution.MONTH: + return d3.utcFormat('%b \'%y'); + default: + return d3.utcFormat('%d %b'); + } +} + +const getTickFormatterX = (ticks: Array<Date>, resolution?: ChartResolution) => (): (d: d3.AxisDomain) => string => { + const format = getTickFormatX(ticks, resolution); + return (d: d3.AxisDomain) => format(d as Date); }; function getAxisParamsY(data: Data, config?: LineChartAxisConfig, tickFormatter?: () => (d: d3.AxisDomain) => string) { diff --git a/src/toolkit/components/charts/line/utils/useLineChartBrushX.tsx b/src/toolkit/components/charts/line/utils/useLineChartBrushX.ts similarity index 100% rename from src/toolkit/components/charts/line/utils/useLineChartBrushX.tsx rename to src/toolkit/components/charts/line/utils/useLineChartBrushX.ts diff --git a/src/toolkit/components/charts/line/utils/useLineChartController.ts b/src/toolkit/components/charts/line/utils/useLineChartController.ts new file mode 100644 index 00000000000..c02edb2130d --- /dev/null +++ b/src/toolkit/components/charts/line/utils/useLineChartController.ts @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { ChartMargin, ChartResolution } from '../../types'; +import type { LineChartAxesConfig, LineChartData } from '../types'; + +import { useClientRect } from '../../../../hooks/useClientRect'; +import { calculateInnerSize } from '../../utils/calculateInnerSize'; +import { getAxesParams } from './lineChartAxis'; + +interface Props { + data: LineChartData; + margin?: ChartMargin; + axesConfig?: LineChartAxesConfig; + resolution?: ChartResolution; +} + +export function useLineChartController({ data, margin, axesConfig, resolution }: Props) { + + const [ rect, ref ] = useClientRect<SVGSVGElement>(); + + // we need to recalculate the axis scale whenever the rect width changes + // eslint-disable-next-line react-hooks/exhaustive-deps + const axesParams = React.useMemo(() => getAxesParams(data, axesConfig, resolution), [ data, axesConfig, resolution, rect?.width ]); + + const chartMargin = React.useMemo(() => { + const PIXELS_PER_DIGIT = 8; + const leftShift = axesConfig?.y?.noLabel ? 0 : PIXELS_PER_DIGIT * axesParams.y.labelFormatParams.maxLabelLength; + + return { + ...margin, + left: (margin?.left ?? 0) + leftShift, + }; + }, [ axesParams.y.labelFormatParams.maxLabelLength, margin, axesConfig?.y?.noLabel ]); + + const { innerWidth, innerHeight } = calculateInnerSize(rect, chartMargin); + + const xScale = React.useMemo(() => { + return axesParams.x.scale.range([ 0, innerWidth ]); + }, [ axesParams.x.scale, innerWidth ]); + + const yScale = React.useMemo(() => { + return axesParams.y.scale.range([ innerHeight, 0 ]); + }, [ axesParams.y.scale, innerHeight ]); + + return React.useMemo(() => { + return { + rect, + ref, + chartMargin, + innerWidth, + innerHeight, + axes: { + x: { + tickFormatter: axesParams.x.tickFormatter, + tickValues: axesParams.x.tickValues, + scale: xScale, + }, + y: { + tickFormatter: axesParams.y.tickFormatter, + scale: yScale, + }, + }, + }; + }, [ axesParams.x.tickFormatter, axesParams.x.tickValues, axesParams.y.tickFormatter, chartMargin, innerHeight, innerWidth, rect, ref, xScale, yScale ]); +} diff --git a/src/toolkit/components/charts/line/utils/useLineChartController.tsx b/src/toolkit/components/charts/line/utils/useLineChartController.tsx deleted file mode 100644 index 08cf2513fed..00000000000 --- a/src/toolkit/components/charts/line/utils/useLineChartController.tsx +++ /dev/null @@ -1,65 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import React from 'react'; - -import type { ChartMargin } from '../../types'; -import type { LineChartAxesConfig, LineChartData } from '../types'; - -import { useClientRect } from '../../../../hooks/useClientRect'; -import { calculateInnerSize } from '../../utils/calculateInnerSize'; -import { getAxesParams } from './lineChartAxis'; - -interface Props { - data: LineChartData; - margin?: ChartMargin; - axesConfig?: LineChartAxesConfig; -} - -export function useLineChartController({ data, margin, axesConfig }: Props) { - - const [ rect, ref ] = useClientRect<SVGSVGElement>(); - - // we need to recalculate the axis scale whenever the rect width changes - // eslint-disable-next-line react-hooks/exhaustive-deps - const axesParams = React.useMemo(() => getAxesParams(data, axesConfig), [ data, axesConfig, rect?.width ]); - - const chartMargin = React.useMemo(() => { - const PIXELS_PER_DIGIT = 8; - const leftShift = axesConfig?.y?.noLabel ? 0 : PIXELS_PER_DIGIT * axesParams.y.labelFormatParams.maxLabelLength; - - return { - ...margin, - left: (margin?.left ?? 0) + leftShift, - }; - }, [ axesParams.y.labelFormatParams.maxLabelLength, margin, axesConfig?.y?.noLabel ]); - - const { innerWidth, innerHeight } = calculateInnerSize(rect, chartMargin); - - const xScale = React.useMemo(() => { - return axesParams.x.scale.range([ 0, innerWidth ]); - }, [ axesParams.x.scale, innerWidth ]); - - const yScale = React.useMemo(() => { - return axesParams.y.scale.range([ innerHeight, 0 ]); - }, [ axesParams.y.scale, innerHeight ]); - - return React.useMemo(() => { - return { - rect, - ref, - chartMargin, - innerWidth, - innerHeight, - axes: { - x: { - tickFormatter: axesParams.x.tickFormatter, - scale: xScale, - }, - y: { - tickFormatter: axesParams.y.tickFormatter, - scale: yScale, - }, - }, - }; - }, [ axesParams.x.tickFormatter, axesParams.y.tickFormatter, chartMargin, innerHeight, innerWidth, rect, ref, xScale, yScale ]); -} diff --git a/src/toolkit/components/charts/line/utils/useLineChartLegend.tsx b/src/toolkit/components/charts/line/utils/useLineChartLegend.ts similarity index 100% rename from src/toolkit/components/charts/line/utils/useLineChartLegend.tsx rename to src/toolkit/components/charts/line/utils/useLineChartLegend.ts diff --git a/src/toolkit/components/charts/line/utils/useLineChartZoom.tsx b/src/toolkit/components/charts/line/utils/useLineChartZoom.ts similarity index 100% rename from src/toolkit/components/charts/line/utils/useLineChartZoom.tsx rename to src/toolkit/components/charts/line/utils/useLineChartZoom.ts diff --git a/src/toolkit/components/forms/fields/image/useImageField.tsx b/src/toolkit/components/forms/fields/image/useImageField.ts similarity index 100% rename from src/toolkit/components/forms/fields/image/useImageField.tsx rename to src/toolkit/components/forms/fields/image/useImageField.ts diff --git a/src/toolkit/components/truncation/OverflowTooltip.tsx b/src/toolkit/components/truncation/OverflowTooltip.tsx new file mode 100644 index 00000000000..dee56a7c0e9 --- /dev/null +++ b/src/toolkit/components/truncation/OverflowTooltip.tsx @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +// Low-level primitive: wrap any single child and show a tooltip only when that child overflows +// its container. `Truncate` is the value-oriented public API built on top of this; app code should +// reach for `Truncate`, not this. Kept toolkit-internal for consumers that wrap arbitrary +// ReactNode children (tag/badge) which Truncate's `value: string` contract can't express. + +import { debounce } from 'es-toolkit'; +import React from 'react'; +import useFontFaceObserver from 'use-font-face-observer'; + +import type { TooltipProps } from '../../chakra/tooltip'; +import { Tooltip } from '../../chakra/tooltip'; +import { useDisclosure } from '../../hooks/useDisclosure'; +import { BODY_TYPEFACE } from '../../theme/foundations/typography'; + +export interface OverflowTooltipProps extends TooltipProps { + always?: boolean; +} + +export const OverflowTooltip = React.memo(({ children, always, ...rest }: OverflowTooltipProps) => { + const childRef = React.useRef<HTMLElement>(null); + const [ isTruncated, setTruncated ] = React.useState(false); + const { open, onToggle, onOpen, onClose } = useDisclosure(); + + const isFontFaceLoaded = useFontFaceObserver([ + { family: BODY_TYPEFACE }, + ]); + + const updatedTruncateState = React.useCallback(() => { + if (childRef.current) { + const scrollWidth = childRef.current.scrollWidth; + const clientWidth = childRef.current.clientWidth; + + if (scrollWidth > clientWidth) { + setTruncated(true); + } else { + setTruncated(false); + } + } + }, []); + + // FIXME: that should be useLayoutEffect, but it keeps complaining about SSR + // let's keep it as it is until the first issue + React.useEffect(() => { + updatedTruncateState(); + }, [ updatedTruncateState, isFontFaceLoaded ]); + + // we want to do recalculation when isFontFaceLoaded flag is changed + // but we don't want to create more resize event listeners + // that's why there are separate useEffect hooks + React.useEffect(() => { + const handleResize = debounce(updatedTruncateState, 1000); + window.addEventListener('resize', handleResize); + + return function cleanup() { + window.removeEventListener('resize', handleResize); + }; + }, [ updatedTruncateState ]); + + // as for now it supports only one child + // and it is not cleared how to manage case with two or more children + const child = React.Children.only(children) as React.ReactElement & { + ref?: React.Ref<React.ReactNode>; + onClick?: () => void; + onMouseEnter?: () => void; + onMouseLeave?: () => void; + }; + const handleClick = React.useCallback(() => { + onToggle(); + }, [ onToggle ]); + + const modifiedChildren = React.cloneElement( + child, + { + ref: childRef, + onClick: handleClick, + onMouseEnter: onOpen, + onMouseLeave: onClose, + } as React.HTMLAttributes<HTMLElement>, + ); + + if (isTruncated || always) { + return ( + <Tooltip + contentProps={{ maxW: { base: 'calc(100vw - 8px)', lg: '400px' } }} + open={ open } + { ...rest } + > + { modifiedChildren } + </Tooltip> + ); + } + + return modifiedChildren; +}); diff --git a/src/toolkit/components/truncation/Truncate.tsx b/src/toolkit/components/truncation/Truncate.tsx new file mode 100644 index 00000000000..f601f4fcd28 --- /dev/null +++ b/src/toolkit/components/truncation/Truncate.tsx @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +// The public text-truncation primitive. App code picks *what* to show (`value`) and *how* +// (`type`); the implementation is chosen per-type and lives in a small internal module: +// - `middle` (default) — measured middle-ellipsis (container width, binary search) +// - `middle-static` — fixed char count, pure string slice, SSR-safe, cheapest +// - `end` — measured end-ellipsis (CSS text-overflow) + +import React from 'react'; + +import { TruncateEnd } from './TruncateEnd'; +import type { TruncateEndProps } from './TruncateEnd'; +import { TruncateMiddle } from './TruncateMiddle'; +import type { TruncateMiddleProps } from './TruncateMiddle'; +import { TruncateMiddleStatic } from './TruncateMiddleStatic'; +import type { TruncateMiddleStaticProps } from './TruncateMiddleStatic'; + +export type { TruncateTooltipConfig } from './types'; + +interface TruncatePropsMiddle extends TruncateMiddleProps { + type?: 'middle'; +} + +interface TruncatePropsMiddleStatic extends TruncateMiddleStaticProps { + type: 'middle-static'; +} + +interface TruncatePropsEnd extends TruncateEndProps { + type: 'end'; +} + +export type TruncateProps = TruncatePropsMiddle | TruncatePropsMiddleStatic | TruncatePropsEnd; + +export const Truncate = (props: TruncateProps) => { + switch (props.type) { + case 'end': { + const { type, ...rest } = props; + return <TruncateEnd { ...rest }/>; + } + case 'middle-static': { + const { type, ...rest } = props; + return <TruncateMiddleStatic { ...rest }/>; + } + case 'middle': + default: { + const { type, ...rest } = props; + return <TruncateMiddle { ...rest }/>; + } + } +}; diff --git a/src/toolkit/components/truncation/TruncateEnd.tsx b/src/toolkit/components/truncation/TruncateEnd.tsx new file mode 100644 index 00000000000..b3bd216ad7e --- /dev/null +++ b/src/toolkit/components/truncation/TruncateEnd.tsx @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +// End-ellipsis truncation driven by container width via CSS `text-overflow: ellipsis`. +// A tooltip is shown only when the text actually overflows, measured by OverflowTooltip. + +import { chakra } from '@chakra-ui/react'; +import React from 'react'; + +import type { TruncateBaseProps } from './types'; + +import { Skeleton } from '../../chakra/skeleton'; +import { OverflowTooltip } from './OverflowTooltip'; + +export type TruncateEndProps = TruncateBaseProps; + +export const TruncateEnd = ({ value, as = 'span', loading, tooltip, ...styleProps }: TruncateEndProps) => { + const valueElement = ( + <Skeleton + loading={ loading } + asChild + display="inline-block" + whiteSpace="nowrap" + overflow="hidden" + textOverflow="ellipsis" + height="fit-content" + { ...styleProps } + > + <chakra.span as={ as }>{ value }</chakra.span> + </Skeleton> + ); + + if (tooltip === false) { + return valueElement; + } + + const { content, always, ...rest } = tooltip ?? {}; + + return ( + <OverflowTooltip + content={ content ?? value } + always={ always } + { ...rest } + > + { valueElement } + </OverflowTooltip> + ); +}; diff --git a/src/toolkit/components/truncation/TruncateMiddle.tsx b/src/toolkit/components/truncation/TruncateMiddle.tsx new file mode 100644 index 00000000000..e8474d1041f --- /dev/null +++ b/src/toolkit/components/truncation/TruncateMiddle.tsx @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +// Middle-ellipsis truncation driven by container width: measures a hidden shadow node and +// binary-searches the longest head that fits, keeping a fixed-length tail (0x123...4567). +// Can't be done in pure CSS — a `text-overflow: ellipsis` head + fixed tail leaves an +// unremovable gap between the dots and the tail, so it's computed in JS. + +import { chakra } from '@chakra-ui/react'; +import { debounce } from 'es-toolkit'; +import React, { useCallback, useEffect, useRef } from 'react'; +import useFontFaceObserver from 'use-font-face-observer'; + +import type { TruncateBaseProps } from './types'; + +import { Skeleton } from '../../chakra/skeleton'; +import { Tooltip } from '../../chakra/tooltip'; +import { BODY_TYPEFACE, HEADING_TYPEFACE } from '../../theme/foundations/typography'; + +const TAIL_LENGTH = 4; +const HEAD_MIN_LENGTH = 4; + +export interface TruncateMiddleProps extends TruncateBaseProps { + tailLength?: number; +} + +const DEFAULT_FONT_WEIGHT = '400'; + +export const TruncateMiddle = React.memo(({ + value, + tailLength = TAIL_LENGTH, + as = 'span', + loading, + tooltip, + ...styleProps +}: TruncateMiddleProps) => { + const elementRef = useRef<HTMLSpanElement>(null); + const [ displayedString, setDisplayedString ] = React.useState(value); + + // The font-face observer needs a concrete weight, so it falls back to 400 when the caller sets + // none. + const fontWeightForObserver = String(styleProps.fontWeight ?? DEFAULT_FONT_WEIGHT); + + const isFontFaceLoaded = useFontFaceObserver([ + { family: BODY_TYPEFACE, weight: fontWeightForObserver }, + { family: HEADING_TYPEFACE, weight: fontWeightForObserver }, + ]); + + const calculateString = useCallback(() => { + const parent = elementRef?.current?.parentNode as HTMLElement; + if (!parent) { + return; + } + + const shadowEl = document.createElement('span'); + shadowEl.style.opacity = '0'; + parent.appendChild(shadowEl); + shadowEl.textContent = value; + + const parentWidth = getWidth(parent); + + if (getWidth(shadowEl) > parentWidth) { + const tail = value.slice(-tailLength); + let leftI = HEAD_MIN_LENGTH; + let rightI = value.length - tailLength; + + while (rightI - leftI > 1) { + const medI = ((rightI - leftI) % 2) ? leftI + (rightI - leftI + 1) / 2 : leftI + (rightI - leftI) / 2; + const res = value.slice(0, medI) + '...' + tail; + shadowEl.textContent = res; + if (getWidth(shadowEl) < parentWidth) { + leftI = medI; + } else { + rightI = medI; + } + } + setDisplayedString(value.slice(0, rightI - 1) + '...' + tail); + } else { + setDisplayedString(value); + } + + parent.removeChild(shadowEl); + }, [ value, tailLength ]); + + // we want to do recalculation when isFontFaceLoaded flag is changed + // but we don't want to create more resize event listeners + // that's why there are separate useEffect hooks + useEffect(() => { + calculateString(); + }, [ calculateString, isFontFaceLoaded ]); + + useEffect(() => { + const resizeHandler = debounce(calculateString, 100); + const resizeObserver = new ResizeObserver(resizeHandler); + + resizeObserver.observe(document.body); + return function cleanup() { + resizeObserver.unobserve(document.body); + }; + }, [ calculateString ]); + + const content = ( + <Skeleton loading={ loading } asChild> + <chakra.span ref={ elementRef } as={ as } { ...styleProps }>{ displayedString }</chakra.span> + </Skeleton> + ); + const isTruncated = value !== displayedString; + + if (tooltip !== false && (isTruncated || tooltip?.always)) { + const { content: tooltipContent, always, ...rest } = tooltip ?? {}; + return ( + <Tooltip + content={ tooltipContent ?? value } + contentProps={{ maxW: { base: 'calc(100vw - 8px)', lg: '400px' } }} + { ...rest } + > + { content } + </Tooltip> + ); + } + + return content; +}); + +function getWidth(el: HTMLElement) { + return el.getBoundingClientRect().width; +} diff --git a/src/toolkit/components/truncation/TruncateMiddleStatic.tsx b/src/toolkit/components/truncation/TruncateMiddleStatic.tsx new file mode 100644 index 00000000000..bf1af556194 --- /dev/null +++ b/src/toolkit/components/truncation/TruncateMiddleStatic.tsx @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +// Middle-ellipsis truncation by a fixed character count — a pure string slice with no DOM +// measurement. SSR-safe and the cheapest option, so it is the default for high-traffic hashes +// (every hash in every table row). "Truncated" here means value.length > maxSymbols. + +import { chakra } from '@chakra-ui/react'; +import React from 'react'; + +import type { TruncateBaseProps } from './types'; + +import { Skeleton } from '../../chakra/skeleton'; +import { Tooltip } from '../../chakra/tooltip'; +import { shortenString } from '../../utils/texts'; + +const DEFAULT_MAX_SYMBOLS = 8; + +export interface TruncateMiddleStaticProps extends TruncateBaseProps { + maxSymbols?: number; +} + +export const TruncateMiddleStatic = React.memo(({ + value, + maxSymbols = DEFAULT_MAX_SYMBOLS, + as = 'span', + loading, + tooltip, + ...styleProps +}: TruncateMiddleStaticProps) => { + const isTruncated = value.length > maxSymbols; + const displayed = isTruncated ? shortenString(value, maxSymbols) : value; + + const content = ( + <Skeleton loading={ loading } asChild> + <chakra.span as={ as } { ...styleProps }>{ displayed }</chakra.span> + </Skeleton> + ); + + if (tooltip === false || (!isTruncated && !tooltip?.always)) { + return content; + } + + const { content: tooltipContent, always, ...rest } = tooltip ?? {}; + + return ( + <Tooltip + content={ tooltipContent ?? value } + contentProps={{ maxW: { base: 'calc(100vw - 8px)', lg: '400px' } }} + { ...rest } + > + { content } + </Tooltip> + ); +}); diff --git a/src/toolkit/components/truncation/TruncatedText.tsx b/src/toolkit/components/truncation/TruncatedText.tsx deleted file mode 100644 index 4271e92b045..00000000000 --- a/src/toolkit/components/truncation/TruncatedText.tsx +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -// Arbitrary text that will be truncated if there is not enough space in the container - -import React from 'react'; - -import type { ExcludeUndefined } from 'src/shared/types/utils'; - -import type { SkeletonTextProps } from '../../chakra/skeleton'; -import { Skeleton } from '../../chakra/skeleton'; -import type { TooltipProps } from '../../chakra/tooltip'; -import { Tooltip } from '../../chakra/tooltip'; -import { TruncatedTextTooltip } from './TruncatedTextTooltip'; - -export interface TruncatedTextProps extends Omit<SkeletonTextProps, 'loading'> { - text: string; - loading?: boolean; - noTooltip?: boolean; - // tooltipContent is used to display the tooltip value different from the truncated value - tooltipContent?: React.ReactNode; - tooltipPlacement?: ExcludeUndefined<TooltipProps['positioning']>['placement']; - tooltipInteractive?: boolean; -} - -export const TruncatedText = ({ text, tooltipPlacement, tooltipInteractive, tooltipContent, loading, noTooltip, ...rest }: TruncatedTextProps) => { - const valueElement = ( - <Skeleton - loading={ loading } - display="inline-block" - whiteSpace="nowrap" - overflow="hidden" - textOverflow="ellipsis" - height="fit-content" - { ...rest } - > - <span>{ text }</span> - </Skeleton> - ); - - if (noTooltip) { - return valueElement; - } - - // if tooltipContent is provided, we display the tooltip content no matter if the value is truncated or not - if (tooltipContent) { - return ( - <Tooltip - content={ tooltipContent } - positioning={{ placement: tooltipPlacement }} - interactive={ tooltipInteractive } - > - { valueElement } - </Tooltip> - ); - }; - - return ( - <TruncatedTextTooltip label={ text } placement={ tooltipPlacement } interactive={ tooltipInteractive }> - { valueElement } - </TruncatedTextTooltip> - ); -}; diff --git a/src/toolkit/components/truncation/TruncatedTextTooltip.tsx b/src/toolkit/components/truncation/TruncatedTextTooltip.tsx deleted file mode 100644 index d200e49c010..00000000000 --- a/src/toolkit/components/truncation/TruncatedTextTooltip.tsx +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: LicenseRef-Blockscout - -import { debounce } from 'es-toolkit'; -import React from 'react'; -import useFontFaceObserver from 'use-font-face-observer'; - -import type { ExcludeUndefined } from 'src/shared/types/utils'; - -import type { TooltipProps } from '../../chakra/tooltip'; -import { Tooltip } from '../../chakra/tooltip'; -import { useDisclosure } from '../../hooks/useDisclosure'; -import { BODY_TYPEFACE } from '../../theme/foundations/typography'; - -export interface TruncatedTextTooltipProps { - children: React.ReactNode; - label: React.ReactNode; - placement?: ExcludeUndefined<TooltipProps['positioning']>['placement']; - interactive?: boolean; -} - -export const TruncatedTextTooltip = React.memo(({ children, label, placement, interactive }: TruncatedTextTooltipProps) => { - const childRef = React.useRef<HTMLElement>(null); - const [ isTruncated, setTruncated ] = React.useState(false); - const { open, onToggle, onOpen, onClose } = useDisclosure(); - - const isFontFaceLoaded = useFontFaceObserver([ - { family: BODY_TYPEFACE }, - ]); - - const updatedTruncateState = React.useCallback(() => { - if (childRef.current) { - const scrollWidth = childRef.current.scrollWidth; - const clientWidth = childRef.current.clientWidth; - - if (scrollWidth > clientWidth) { - setTruncated(true); - } else { - setTruncated(false); - } - } - }, []); - - // FIXME: that should be useLayoutEffect, but it keeps complaining about SSR - // let's keep it as it is until the first issue - React.useEffect(() => { - updatedTruncateState(); - }, [ updatedTruncateState, isFontFaceLoaded ]); - - // we want to do recalculation when isFontFaceLoaded flag is changed - // but we don't want to create more resize event listeners - // that's why there are separate useEffect hooks - React.useEffect(() => { - const handleResize = debounce(updatedTruncateState, 1000); - window.addEventListener('resize', handleResize); - - return function cleanup() { - window.removeEventListener('resize', handleResize); - }; - }, [ updatedTruncateState ]); - - // as for now it supports only one child - // and it is not cleared how to manage case with two or more children - const child = React.Children.only(children) as React.ReactElement & { - ref?: React.Ref<React.ReactNode>; - onClick?: () => void; - onMouseEnter?: () => void; - onMouseLeave?: () => void; - }; - const handleClick = React.useCallback(() => { - onToggle(); - }, [ onToggle ]); - - const modifiedChildren = React.cloneElement( - child, - { - ref: childRef, - onClick: handleClick, - onMouseEnter: onOpen, - onMouseLeave: onClose, - } as React.HTMLAttributes<HTMLElement>, - ); - - if (isTruncated) { - return ( - <Tooltip - content={ label } - contentProps={{ maxW: { base: 'calc(100vw - 8px)', lg: '400px' } }} - positioning={{ placement }} - open={ open } - interactive={ interactive } - > - { modifiedChildren } - </Tooltip> - ); - } - - return modifiedChildren; -}); diff --git a/src/toolkit/components/truncation/types.ts b/src/toolkit/components/truncation/types.ts new file mode 100644 index 00000000000..be6a022f6ab --- /dev/null +++ b/src/toolkit/components/truncation/types.ts @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { HTMLChakraProps } from '@chakra-ui/react'; +import type React from 'react'; + +import type { TooltipProps } from '../../chakra/tooltip'; + +export interface TruncateTooltipConfig extends Partial<TooltipProps> { + // force the tooltip open even when the value is not truncated — for when `content` carries + // actionable UI (e.g. a link) that would otherwise be unreachable on a wide viewport + always?: boolean; +} + +export interface TruncateBaseProps extends Omit<HTMLChakraProps<'span'>, 'children' | 'as'> { + value: string; + loading?: boolean; + as?: React.ElementType; + // omitted → tooltip only when truncated; object → override content/placement; false → suppress entirely + tooltip?: false | TruncateTooltipConfig; +} diff --git a/src/toolkit/hooks/useClientRect.tsx b/src/toolkit/hooks/useClientRect.ts similarity index 100% rename from src/toolkit/hooks/useClientRect.tsx rename to src/toolkit/hooks/useClientRect.ts diff --git a/src/toolkit/hooks/useClipboard.tsx b/src/toolkit/hooks/useClipboard.ts similarity index 100% rename from src/toolkit/hooks/useClipboard.tsx rename to src/toolkit/hooks/useClipboard.ts diff --git a/src/toolkit/hooks/useDisclosure.tsx b/src/toolkit/hooks/useDisclosure.ts similarity index 100% rename from src/toolkit/hooks/useDisclosure.tsx rename to src/toolkit/hooks/useDisclosure.ts diff --git a/src/toolkit/hooks/useFirstMountState.tsx b/src/toolkit/hooks/useFirstMountState.ts similarity index 100% rename from src/toolkit/hooks/useFirstMountState.tsx rename to src/toolkit/hooks/useFirstMountState.ts diff --git a/src/toolkit/hooks/useIsSticky.tsx b/src/toolkit/hooks/useIsSticky.ts similarity index 100% rename from src/toolkit/hooks/useIsSticky.tsx rename to src/toolkit/hooks/useIsSticky.ts diff --git a/src/toolkit/hooks/useLazyActivation.spec.tsx b/src/toolkit/hooks/useLazyActivation.spec.ts similarity index 100% rename from src/toolkit/hooks/useLazyActivation.spec.tsx rename to src/toolkit/hooks/useLazyActivation.spec.ts diff --git a/src/toolkit/hooks/useLazyActivation.tsx b/src/toolkit/hooks/useLazyActivation.ts similarity index 100% rename from src/toolkit/hooks/useLazyActivation.tsx rename to src/toolkit/hooks/useLazyActivation.ts diff --git a/src/toolkit/hooks/useUpdateEffect.tsx b/src/toolkit/hooks/useUpdateEffect.ts similarity index 100% rename from src/toolkit/hooks/useUpdateEffect.tsx rename to src/toolkit/hooks/useUpdateEffect.ts diff --git a/src/toolkit/hooks/useViewportSize.tsx b/src/toolkit/hooks/useViewportSize.ts similarity index 100% rename from src/toolkit/hooks/useViewportSize.tsx rename to src/toolkit/hooks/useViewportSize.ts diff --git a/src/toolkit/package/README.md b/src/toolkit/package/README.md index 7c70d7f9493..755cb8e21b7 100644 --- a/src/toolkit/package/README.md +++ b/src/toolkit/package/README.md @@ -39,7 +39,6 @@ Ensure you have the following peer dependencies installed: "dayjs": ">=1.11.5", "dom-to-image": ">=2.6.0", "es-toolkit": ">=1.39.10", - "next": ">=16.2.4", "next-themes": ">=0.4.4", "react": ">=18.3.1", "react-dom": ">=18.3.1", @@ -119,6 +118,55 @@ Add the following script to your `package.json` to generate Chakra UI type defin } ``` +### 4. Routing + +The toolkit has no router of its own. `Link`, `LinkOverlay`, `RoutedTabs` and `useActiveTabFromQuery` read +the navigation primitives from a `RouterProvider`; the adapter interface they rely on is +`RouterContextValue` in `src/toolkit/router/types.ts` (exported as types from the package): + +- `Link` — a forward-ref component taking `href` (a string or `{ pathname, query, hash }`), the navigation + hints `scroll` / `shallow` / `prefetch`, anchor attributes and `children`. +- `router` — `{ query, pathname, asPath, push(url, options?), replace(url, options?) }`, with options + `{ shallow?, scroll? }`. +- `pathname` — the current path, or `null` when the host cannot tell. + +Without a provider the toolkit falls back to a plain `<a href>` (an object `href` is stringified) and a +router whose `push` / `replace` resolve `false`; client-side navigation needs the provider. + +A minimal Next.js (Pages Router) adapter: + +```tsx +import NextLink from 'next/link'; +import { usePathname } from 'next/navigation'; +import { useRouter } from 'next/router'; +import React from 'react'; +import { RouterProvider } from '@blockscout/ui-toolkit'; +import type { RouterContextValue, RouterLinkProps } from '@blockscout/ui-toolkit'; + +const Link = React.forwardRef<HTMLAnchorElement, RouterLinkProps>(function Link(props, ref) { + return <NextLink ref={ref} {...props} href={props.href as never} />; +}); + +function AppRouterProvider({ children }: { children: React.ReactNode }) { + const nextRouter = useRouter(); + const pathname = usePathname(); + + const value = React.useMemo((): RouterContextValue => ({ + Link, + router: { + query: nextRouter.query, + pathname: nextRouter.pathname, + asPath: nextRouter.asPath, + push: (url, options) => nextRouter.push(url as never, undefined, options), + replace: (url, options) => nextRouter.replace(url as never, undefined, options), + }, + pathname, + }), [nextRouter, pathname]); + + return <RouterProvider value={value}>{children}</RouterProvider>; +} +``` + ## Development ### Local Development diff --git a/src/toolkit/package/package.json b/src/toolkit/package/package.json index a6864a1275a..46f1c9097ca 100644 --- a/src/toolkit/package/package.json +++ b/src/toolkit/package/package.json @@ -49,7 +49,6 @@ "dayjs": ">=1.11.21", "dom-to-image": ">=2.6.0", "es-toolkit": ">=1.39.10", - "next": ">=16.2.6", "next-themes": ">=0.4.4", "react": ">=18.3.1", "react-dom": ">=18.3.1", @@ -57,19 +56,18 @@ }, "devDependencies": { "@svgr/plugin-jsx": "8.1.0", - "@types/node": "20.16.7", + "@types/node": "24.13.4", "@types/react": "18.3.12", "@types/react-dom": "18.3.1", "@typescript/native": "npm:typescript@7.0.2", - "@vitejs/plugin-react": "4.3.4", + "@vitejs/plugin-react": "6.1.2", "typescript": "npm:@typescript/typescript6@6.0.2", - "vite": "6.4.3", + "vite": "8.3.5", "vite-plugin-dts": "4.5.4", - "vite-plugin-svgr": "4.5.0", - "vite-tsconfig-paths": "5.1.4" + "vite-plugin-svgr": "5.2.0" }, "engines": { - "node": ">=22.14.0" + "node": ">=24.21.0" }, "publishConfig": { "access": "public" diff --git a/src/toolkit/package/src/index.ts b/src/toolkit/package/src/index.ts index b01f681db79..627cc68f73b 100644 --- a/src/toolkit/package/src/index.ts +++ b/src/toolkit/package/src/index.ts @@ -112,8 +112,8 @@ export * from '../../components/forms/inputs'; export * from '../../components/forms/utils'; export * from '../../components/forms/validators'; export * from '../../components/loaders/ContentLoader'; -export * from '../../components/truncation/TruncatedTextTooltip'; -export * from '../../components/truncation/TruncatedText'; +export { Truncate } from '../../components/truncation/Truncate'; +export type { TruncateProps, TruncateTooltipConfig } from '../../components/truncation/Truncate'; // Export utils export { default as getComponentDisplayName } from '../../utils/getComponentDisplayName'; @@ -124,6 +124,13 @@ export * as guards from '../../utils/guards'; export * as file from '../../utils/file'; export * from '../../utils/url'; export * from '../../utils/isBrowser'; +export * from '../../utils/texts'; + +// Export router +export * from '../../router/context'; +export * from '../../router/defaults'; +export * from '../../router/format-url'; +export type * from '../../router/types'; // Export hooks export { useClipboard } from '../../hooks/useClipboard'; diff --git a/src/toolkit/package/tsconfig.json b/src/toolkit/package/tsconfig.json index 9ec829d503c..e008c82ef68 100644 --- a/src/toolkit/package/tsconfig.json +++ b/src/toolkit/package/tsconfig.json @@ -35,6 +35,7 @@ "../components", "../utils", "../hooks", + "../router", "../../../global.d.ts", "../../../decs.d.ts", "../../../reset.d.ts", diff --git a/src/toolkit/package/vite.config.ts b/src/toolkit/package/vite.config.ts index 6fcfc2b3691..27ae895ae9b 100644 --- a/src/toolkit/package/vite.config.ts +++ b/src/toolkit/package/vite.config.ts @@ -3,12 +3,10 @@ import { resolve } from 'path'; import { defineConfig } from 'vite'; import dts from 'vite-plugin-dts'; import svgr from 'vite-plugin-svgr'; -import tsconfigPaths from 'vite-tsconfig-paths'; export default defineConfig({ plugins: [ react(), - tsconfigPaths({ ignoreConfigErrors: true }), svgr({ include: '**/*.svg', exclude: '', @@ -39,6 +37,7 @@ export default defineConfig({ '../components/**/*', '../utils/**/*.ts', '../hooks/**/*.tsx', + '../router/**/*', './src/**/*.ts', '../../../global.d.ts', '../../../decs.d.ts', @@ -57,6 +56,7 @@ export default defineConfig({ }), ], resolve: { + tsconfigPaths: true, alias: { src: resolve(__dirname, '../../../src'), }, @@ -68,7 +68,7 @@ export default defineConfig({ fileName: 'index', }, outDir: './dist', - rollupOptions: { + rolldownOptions: { external: [ 'react', 'react-dom', @@ -76,8 +76,6 @@ export default defineConfig({ 'react/jsx-dev-runtime', '@chakra-ui/react', '@emotion/react', - 'next/link', - 'next/router', 'next-themes', 'react-hook-form', // regexps so subpath imports (es-toolkit/compat, dayjs/plugin/*) stay external too @@ -92,7 +90,6 @@ export default defineConfig({ preserveModules: false, preserveModulesRoot: '..', exports: 'named', - interop: 'auto', }, }, }, diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png index 7558b3523d3..f447dec2ea3 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_dark-color-mode_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_dark-color-mode_default-dark-mode-1.png index 28ab634ce3d..176991053e9 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_dark-color-mode_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_dark-color-mode_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_default_color-theme-overrides-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_default_color-theme-overrides-dark-mode-1.png index be9faadcf26..ef839784982 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_default_color-theme-overrides-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_default_color-theme-overrides-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_default_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_default_default-dark-mode-1.png index 9b7604160c9..9cedcf1d8fa 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_default_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Button.pw.tsx_default_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Field.pw.tsx_dark-color-mode_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Field.pw.tsx_dark-color-mode_default-dark-mode-1.png index 6fe8726a841..a855f34164d 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Field.pw.tsx_dark-color-mode_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Field.pw.tsx_dark-color-mode_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/IconButton.pw.tsx_dark-color-mode_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/IconButton.pw.tsx_dark-color-mode_default-dark-mode-1.png index 364e196b0cb..d86b7aec9ae 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/IconButton.pw.tsx_dark-color-mode_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/IconButton.pw.tsx_dark-color-mode_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/IconButton.pw.tsx_default_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/IconButton.pw.tsx_default_default-dark-mode-1.png index 2c173ed3bcf..7041a1ef4b9 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/IconButton.pw.tsx_default_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/IconButton.pw.tsx_default_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png index 7cc1bcca4d3..fe0a4acd5f2 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_dark-color-mode_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_dark-color-mode_default-dark-mode-1.png index 40c6a259a0c..7a59af53448 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_dark-color-mode_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_dark-color-mode_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_default_color-theme-overrides-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_default_color-theme-overrides-dark-mode-1.png index 4ec58e14151..582530e146f 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_default_color-theme-overrides-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_default_color-theme-overrides-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_default_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_default_default-dark-mode-1.png index 221a7052589..22b6f1dc09a 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_default_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Link.pw.tsx_default_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Pagination.pw.tsx_dark-color-mode_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Pagination.pw.tsx_dark-color-mode_default-dark-mode-1.png index 4db31941b55..e0496f70f91 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Pagination.pw.tsx_dark-color-mode_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Pagination.pw.tsx_dark-color-mode_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Pagination.pw.tsx_default_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Pagination.pw.tsx_default_default-dark-mode-1.png index c4cf544fa58..187b085836a 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Pagination.pw.tsx_default_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Pagination.pw.tsx_default_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_dark-color-mode_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_dark-color-mode_default-dark-mode-1.png index c6e89aaf3f3..9cc398f826d 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_dark-color-mode_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_dark-color-mode_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_dark-color-mode_default-dark-mode-2.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_dark-color-mode_default-dark-mode-2.png index 7f72e550803..4cf563838ca 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_dark-color-mode_default-dark-mode-2.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_dark-color-mode_default-dark-mode-2.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_default_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_default_default-dark-mode-1.png index 22e63ce02a5..c3a1b8717fa 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_default_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_default_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_default_default-dark-mode-2.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_default_default-dark-mode-2.png index b06917b0728..e59d60ed675 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_default_default-dark-mode-2.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Select.pw.tsx_default_default-dark-mode-2.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png index 42e16abfcaa..4d426b87d96 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_dark-color-mode_color-theme-overrides-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_dark-color-mode_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_dark-color-mode_default-dark-mode-1.png index 134b2f7af04..c77a0b8e124 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_dark-color-mode_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_dark-color-mode_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_default_color-theme-overrides-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_default_color-theme-overrides-dark-mode-1.png index 11d8cb6b69e..77acfaf6838 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_default_color-theme-overrides-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_default_color-theme-overrides-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_default_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_default_default-dark-mode-1.png index 670758e5260..ac415210316 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_default_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Tabs.pw.tsx_default_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Tag.pw.tsx_dark-color-mode_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Tag.pw.tsx_dark-color-mode_default-dark-mode-1.png index 5e35253c24f..d1360014a7d 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Tag.pw.tsx_dark-color-mode_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Tag.pw.tsx_dark-color-mode_default-dark-mode-1.png differ diff --git a/src/toolkit/pages/design-system/tabs/__screenshots__/Tag.pw.tsx_default_default-dark-mode-1.png b/src/toolkit/pages/design-system/tabs/__screenshots__/Tag.pw.tsx_default_default-dark-mode-1.png index 6c714e16ad2..2b6b49dedc3 100644 Binary files a/src/toolkit/pages/design-system/tabs/__screenshots__/Tag.pw.tsx_default_default-dark-mode-1.png and b/src/toolkit/pages/design-system/tabs/__screenshots__/Tag.pw.tsx_default_default-dark-mode-1.png differ diff --git a/src/toolkit/router/context.spec.tsx b/src/toolkit/router/context.spec.tsx new file mode 100644 index 00000000000..aa42f6cda72 --- /dev/null +++ b/src/toolkit/router/context.spec.tsx @@ -0,0 +1,146 @@ +// @vitest-environment jsdom + +// The toolkit is exercised outside the app provider stack on purpose: `vitest/lib` mounts the Next adapter, +// and the no-provider defaults are what is under test here. + +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import React from 'react'; + +import type { RouterContextValue, RouterLinkProps } from './types'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { Link } from '../chakra/link'; +import { Provider as ChakraProvider } from '../chakra/provider'; +import { RoutedTabs } from '../components/RoutedTabs/index'; +import { RouterProvider } from './context'; +import { defaultRouterContextValue } from './defaults'; +import { formatUrl } from './format-url'; + +const renderInChakra = (ui: React.ReactElement) => render(<ChakraProvider>{ ui }</ChakraProvider>); + +const InjectedLink = React.forwardRef<HTMLAnchorElement, RouterLinkProps>( + function InjectedLink({ href, scroll, shallow, prefetch, children, ...rest }, ref) { + return ( + <a + ref={ ref } + data-testid="injected-link" + data-scroll={ String(scroll) } + data-shallow={ String(shallow) } + data-prefetch={ String(prefetch) } + href={ formatUrl(href) } + { ...rest } + > + { children } + </a> + ); + }, +); + +const buildContextValue = (overrides: Partial<RouterContextValue> = {}): RouterContextValue => ({ + ...defaultRouterContextValue, + Link: InjectedLink, + ...overrides, +}); + +const TABS = [ + { id: 'first', title: 'First', component: <div>first content</div> }, + { id: 'second', title: 'Second', component: <div>second content</div> }, +]; + +describe('toolkit router context', () => { + afterEach(cleanup); + + describe('without a provider', () => { + it('Link renders a plain anchor with the string href', () => { + renderInChakra(<Link href="/blocks">Blocks</Link>); + + const anchor = screen.getByRole('link', { name: 'Blocks' }); + expect(anchor.tagName).toBe('A'); + expect(anchor.getAttribute('href')).toBe('/blocks'); + expect(screen.queryByTestId('injected-link')).toBeNull(); + }); + + it('Link stringifies an object href', () => { + renderInChakra( + <Link href={{ pathname: '/txs', query: { tab: 'internal', ids: [ '1', '2' ], skipped: undefined }, hash: 'top' } as never}> + Txs + </Link>, + ); + + expect(screen.getByRole('link', { name: 'Txs' }).getAttribute('href')).toBe('/txs?tab=internal&ids=1&ids=2#top'); + }); + + it('RoutedTabs mounts over the no-op router and a tab click leaves the URL-driven tab in place', () => { + renderInChakra(<RoutedTabs tabs={ TABS }/>); + + fireEvent.click(screen.getByRole('tab', { name: 'Second' })); + + expect(screen.getByRole('tab', { name: 'First' }).getAttribute('aria-selected')).toBe('true'); + expect(screen.getByRole('tab', { name: 'Second' }).getAttribute('aria-selected')).toBe('false'); + expect(screen.getByText('first content')).toBeDefined(); + }); + }); + + describe('with a provider', () => { + it('Link renders the injected component and forwards href and navigation props', () => { + renderInChakra( + <RouterProvider value={ buildContextValue() }> + <Link href="/address/0x1" scroll={ false } shallow prefetch>Address</Link> + </RouterProvider>, + ); + + const anchor = screen.getByTestId('injected-link'); + expect(anchor.getAttribute('href')).toBe('/address/0x1'); + expect(anchor.getAttribute('data-scroll')).toBe('false'); + expect(anchor.getAttribute('data-shallow')).toBe('true'); + expect(anchor.getAttribute('data-prefetch')).toBe('true'); + expect(anchor.textContent).toBe('Address'); + }); + + it('Link applies the toolkit defaults for scroll, shallow and prefetch', () => { + renderInChakra( + <RouterProvider value={ buildContextValue() }> + <Link href="/blocks">Blocks</Link> + </RouterProvider>, + ); + + const anchor = screen.getByTestId('injected-link'); + expect(anchor.getAttribute('data-scroll')).toBe('true'); + expect(anchor.getAttribute('data-shallow')).toBe('false'); + expect(anchor.getAttribute('data-prefetch')).toBe('false'); + }); + + it('an external Link bypasses the injected component', () => { + renderInChakra( + <RouterProvider value={ buildContextValue() }> + <Link href="https://example.com" external>Docs</Link> + </RouterProvider>, + ); + + expect(screen.queryByTestId('injected-link')).toBeNull(); + expect(screen.getByRole('link', { name: /Docs/ }).getAttribute('target')).toBe('_blank'); + }); + + it('RoutedTabs pushes a shallow tab change through the injected router', async() => { + const push = vi.fn(() => Promise.resolve(true)); + const value = buildContextValue({ + router: { query: { hash: '0x1', page: '2' }, pathname: '/address/[hash]', asPath: '/address/0x1?page=2', push, replace: push }, + }); + + renderInChakra( + <RouterProvider value={ value }> + <RoutedTabs tabs={ TABS } preservedParams={ [ 'page' ] }/> + </RouterProvider>, + ); + + fireEvent.click(screen.getByRole('tab', { name: 'Second' })); + + await waitFor(() => expect(push).toHaveBeenCalledTimes(1)); + expect(push).toHaveBeenCalledWith( + { pathname: '/address/[hash]', query: { hash: '0x1', page: '2', tab: 'second' } }, + { shallow: true }, + ); + }); + }); +}); diff --git a/src/toolkit/router/context.tsx b/src/toolkit/router/context.tsx new file mode 100644 index 00000000000..e8eaaf62ff5 --- /dev/null +++ b/src/toolkit/router/context.tsx @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { Router, RouterContextValue, RouterLinkComponent } from './types'; + +import { defaultRouterContextValue } from './defaults'; + +export const RouterContext = React.createContext<RouterContextValue>(defaultRouterContextValue); + +export interface RouterProviderProps { + readonly value: RouterContextValue; + readonly children: React.ReactNode; +} + +export const RouterProvider = ({ value, children }: RouterProviderProps) => { + return <RouterContext.Provider value={ value }>{ children }</RouterContext.Provider>; +}; + +export const useRouterContext = (): RouterContextValue => React.useContext(RouterContext); + +export const useRouter = (): Router => useRouterContext().router; + +export const useLink = (): RouterLinkComponent => useRouterContext().Link; diff --git a/src/toolkit/router/defaults.tsx b/src/toolkit/router/defaults.tsx new file mode 100644 index 00000000000..74529abc738 --- /dev/null +++ b/src/toolkit/router/defaults.tsx @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import React from 'react'; + +import type { Router, RouterContextValue, RouterLinkProps } from './types'; + +import { formatUrl } from './format-url'; + +export const DefaultLink = React.forwardRef<HTMLAnchorElement, RouterLinkProps>( + function DefaultLink({ href, scroll, shallow, prefetch, children, ...rest }, ref) { + return <a ref={ ref } href={ formatUrl(href) } { ...rest }>{ children }</a>; + }, +); + +const EMPTY_QUERY = {}; + +export const defaultRouter: Router = { + query: EMPTY_QUERY, + pathname: '', + asPath: '', + push: () => Promise.resolve(false), + replace: () => Promise.resolve(false), +}; + +export const defaultRouterContextValue: RouterContextValue = { + Link: DefaultLink, + router: defaultRouter, + pathname: null, +}; diff --git a/src/toolkit/router/format-url.ts b/src/toolkit/router/format-url.ts new file mode 100644 index 00000000000..eac87d3723e --- /dev/null +++ b/src/toolkit/router/format-url.ts @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type { Query, Url } from './types'; + +const formatQuery = (query: Query | null | undefined): string => { + const searchParams = new URLSearchParams(); + + Object.entries(query ?? {}).forEach(([ key, value ]) => { + (Array.isArray(value) ? value : [ value ]).forEach((item) => { + if (item !== undefined) { + searchParams.append(key, item); + } + }); + }); + + return searchParams.toString(); +}; + +const formatHash = (hash: string | undefined): string => { + if (!hash) { + return ''; + } + + return hash.startsWith('#') ? hash : `#${ hash }`; +}; + +export const formatUrl = (url: Url): string => { + if (typeof url === 'string') { + return url; + } + + const search = formatQuery(url.query); + + return `${ url.pathname ?? '' }${ search ? `?${ search }` : '' }${ formatHash(url.hash) }`; +}; diff --git a/src/toolkit/router/types.ts b/src/toolkit/router/types.ts new file mode 100644 index 00000000000..dc7247672fe --- /dev/null +++ b/src/toolkit/router/types.ts @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +import type React from 'react'; + +export type Query = Record<string, string | Array<string> | undefined>; + +export interface UrlObject { + readonly pathname?: string; + readonly query?: Query | null; + readonly hash?: string; +} + +export type Url = string | UrlObject; + +export interface NavigateOptions { + readonly shallow?: boolean; + readonly scroll?: boolean; +} + +export interface Router { + readonly query: Query; + readonly pathname: string; + readonly asPath: string; + push(url: Url, options?: NavigateOptions): Promise<boolean>; + replace(url: Url, options?: NavigateOptions): Promise<boolean>; +} + +export interface RouterLinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> { + readonly href: Url; + readonly scroll?: boolean; + readonly shallow?: boolean; + readonly prefetch?: boolean; + readonly children?: React.ReactNode; +} + +export interface RouterLinkPropsWithRef extends RouterLinkProps, React.RefAttributes<HTMLAnchorElement> {} + +export type RouterLinkComponent = React.ComponentType<RouterLinkPropsWithRef>; + +export interface RouterContextValue { + readonly Link: RouterLinkComponent; + readonly router: Router; + readonly pathname: string | null; +} diff --git a/src/toolkit/theme/foundations/colors.ts b/src/toolkit/theme/foundations/colors.ts index 258532268a2..12b6252065b 100644 --- a/src/toolkit/theme/foundations/colors.ts +++ b/src/toolkit/theme/foundations/colors.ts @@ -4,290 +4,10 @@ import { defaultsDeep } from 'es-toolkit/compat'; import config from 'src/config'; -const DEFAULT_THEME_COLORS = { - bg: { - primary: { - // for some reason links to colors.white and colors.black variables are not working here - // so we use hex values instead - // but it is not the case for other colors - _light: { value: '#FFFFFF' }, // colors.white - _dark: { value: '#101112' }, // colors.black - }, - }, - text: { - primary: { - _light: { value: '{colors.blackAlpha.800}' }, - _dark: { value: '{colors.whiteAlpha.800}' }, - }, - secondary: { - _light: { value: '{colors.gray.500}' }, - _dark: { value: '{colors.gray.400}' }, - }, - }, - hover: { - _light: { value: '{colors.blue.400}' }, - _dark: { value: '{colors.blue.400}' }, - }, - selected: { - control: { - text: { - _light: { value: '{colors.blue.700}' }, - _dark: { value: '{colors.gray.50}' }, - }, - bg: { - _light: { value: '{colors.blue.50}' }, - _dark: { value: '{colors.whiteAlpha.50}' }, - }, - }, - option: { - bg: { - _light: { value: '{colors.blue.500}' }, - _dark: { value: '{colors.blue.500}' }, - }, - }, - }, - icon: { - primary: { - _light: { value: '{colors.gray.500}' }, - _dark: { value: '{colors.gray.400}' }, - }, - secondary: { - _light: { value: '{colors.gray.400}' }, - _dark: { value: '{colors.gray.500}' }, - }, - }, - button: { - primary: { - _light: { value: '{colors.blue.600}' }, - _dark: { value: '{colors.blue.600}' }, - text: { - _light: { value: '{colors.white}' }, - _dark: { value: '{colors.white}' }, - }, - }, - }, - link: { - primary: { - _light: { value: '{colors.blue.600}' }, - _dark: { value: '{colors.blue.300}' }, - }, - }, - graph: { - line: { - _light: { value: '{colors.blue.500}' }, - _dark: { value: '{colors.blue.200}' }, - }, - gradient: { - start: { - _light: { value: 'rgba(144, 205, 244, 0.3)' }, // blue.200 with opacity 0.3 - _dark: { value: 'rgba(144, 205, 244, 0.3)' }, // blue.200 with opacity 0.3 - }, - stop: { - _light: { value: 'rgba(144, 205, 244, 0)' }, // blue.200 with opacity 0 - _dark: { value: 'rgba(144, 205, 244, 0)' }, // blue.200 with opacity 0 - }, - }, - }, - navigation: { - bg: { - selected: { - _light: { value: '{colors.blue.50}' }, - _dark: { value: '{colors.gray.800}' }, - }, - }, - text: { - selected: { - _light: { value: '{colors.blue.700}' }, - _dark: { value: '{colors.gray.50}' }, - }, - }, - }, - stats: { - bg: { - _light: { value: '{colors.gray.50}' }, - _dark: { value: '{colors.whiteAlpha.100}' }, - }, - }, - topbar: { - bg: { - _light: { value: '{colors.gray.50}' }, - _dark: { value: '{colors.whiteAlpha.100}' }, - }, - }, - tabs: { - text: { - primary: { - _light: { value: '{colors.blue.700}' }, - _dark: { value: '{colors.blue.100}' }, - }, - }, - }, -}; +import { DEFAULT_THEME_COLORS, PALETTE_COLORS } from './colorsDefault'; const colors = { - // BASE COLORS - green: { - '50': { value: '#F0FFF4' }, - '100': { value: '#C6F6D5' }, - '200': { value: '#9AE6B4' }, - '300': { value: '#68D391' }, - '400': { value: '#48BB78' }, - '500': { value: '#38A169' }, - '600': { value: '#25855A' }, - '700': { value: '#276749' }, - '800': { value: '#22543D' }, - '900': { value: '#1C4532' }, - }, - blue: { - '50': { value: '#EBF8FF' }, - '100': { value: '#BEE3F8' }, - '200': { value: '#90CDF4' }, - '300': { value: '#63B3ED' }, - '400': { value: '#4299E1' }, - '500': { value: '#3182CE' }, - '600': { value: '#2B6CB0' }, - '700': { value: '#2C5282' }, - '800': { value: '#2A4365' }, - '900': { value: '#1A365D' }, - }, - red: { - '50': { value: '#FFF5F5' }, - '100': { value: '#FED7D7' }, - '200': { value: '#FEB2B2' }, - '300': { value: '#FC8181' }, - '400': { value: '#F56565' }, - '500': { value: '#E53E3E' }, - '600': { value: '#C53030' }, - '700': { value: '#9B2C2C' }, - '800': { value: '#822727' }, - '900': { value: '#63171B' }, - }, - orange: { - '50': { value: '#FFFAF0' }, - '100': { value: '#FEEBCB' }, - '200': { value: '#FBD38D' }, - '300': { value: '#F6AD55' }, - '400': { value: '#ED8936' }, - '500': { value: '#DD6B20' }, - '600': { value: '#C05621' }, - '700': { value: '#9C4221' }, - '800': { value: '#7B341E' }, - '900': { value: '#652B19' }, - }, - yellow: { - '50': { value: '#FFFFF0' }, - '100': { value: '#FEFCBF' }, - '200': { value: '#FAF089' }, - '300': { value: '#F6E05E' }, - '400': { value: '#ECC94B' }, - '500': { value: '#D69E2E' }, - '600': { value: '#B7791F' }, - '700': { value: '#975A16' }, - '800': { value: '#744210' }, - '900': { value: '#5F370E' }, - }, - gray: { - '50': { value: '#F7FAFC' }, - '100': { value: '#EDF2F7' }, - '200': { value: '#E2E8F0' }, - '300': { value: '#CBD5E0' }, - '400': { value: '#A0AEC0' }, - '500': { value: '#718096' }, - '600': { value: '#4A5568' }, - '700': { value: '#2D3748' }, - '800': { value: '#1A202C' }, - '900': { value: '#171923' }, - }, - teal: { - '50': { value: '#E6FFFA' }, - '100': { value: '#B2F5EA' }, - '200': { value: '#81E6D9' }, - '300': { value: '#4FD1C5' }, - '400': { value: '#38B2AC' }, - '500': { value: '#319795' }, - '600': { value: '#2C7A7B' }, - '700': { value: '#285E61' }, - '800': { value: '#234E52' }, - '900': { value: '#1D4044' }, - }, - cyan: { - '50': { value: '#EDFDFD' }, - '100': { value: '#C4F1F9' }, - '200': { value: '#9DECF9' }, - '300': { value: '#76E4F7' }, - '400': { value: '#0BC5EA' }, - '500': { value: '#00B5D8' }, - '600': { value: '#00A3C4' }, - '700': { value: '#0987A0' }, - '800': { value: '#086F83' }, - '900': { value: '#065666' }, - }, - purple: { - '50': { value: '#FAF5FF' }, - '100': { value: '#E9D8FD' }, - '200': { value: '#D6BCFA' }, - '300': { value: '#B794F4' }, - '400': { value: '#9F7AEA' }, - '500': { value: '#805AD5' }, - '600': { value: '#6B46C1' }, - '700': { value: '#553C9A' }, - '800': { value: '#44337A' }, - '900': { value: '#322659' }, - }, - pink: { - '50': { value: '#FFF5F7' }, - '100': { value: '#FED7E2' }, - '200': { value: '#FBB6CE' }, - '300': { value: '#F687B3' }, - '400': { value: '#ED64A6' }, - '500': { value: '#D53F8C' }, - '600': { value: '#B83280' }, - '700': { value: '#97266D' }, - '800': { value: '#702459' }, - '900': { value: '#521B41' }, - }, - black: { value: '#101112' }, - white: { value: '#ffffff' }, - whiteAlpha: { - '50': { value: 'RGBA(255, 255, 255, 0.04)' }, - '100': { value: 'RGBA(255, 255, 255, 0.06)' }, - '200': { value: 'RGBA(255, 255, 255, 0.08)' }, - '300': { value: 'RGBA(255, 255, 255, 0.16)' }, - '400': { value: 'RGBA(255, 255, 255, 0.24)' }, - '500': { value: 'RGBA(255, 255, 255, 0.36)' }, - '600': { value: 'RGBA(255, 255, 255, 0.48)' }, - '700': { value: 'RGBA(255, 255, 255, 0.64)' }, - '800': { value: 'RGBA(255, 255, 255, 0.80)' }, - '900': { value: 'RGBA(255, 255, 255, 0.92)' }, - }, - blackAlpha: { - '50': { value: 'RGBA(16, 17, 18, 0.04)' }, - '100': { value: 'RGBA(16, 17, 18, 0.06)' }, - '200': { value: 'RGBA(16, 17, 18, 0.08)' }, - '300': { value: 'RGBA(16, 17, 18, 0.16)' }, - '400': { value: 'RGBA(16, 17, 18, 0.24)' }, - '500': { value: 'RGBA(16, 17, 18, 0.36)' }, - '600': { value: 'RGBA(16, 17, 18, 0.48)' }, - '700': { value: 'RGBA(16, 17, 18, 0.64)' }, - '800': { value: 'RGBA(16, 17, 18, 0.80)' }, - '900': { value: 'RGBA(16, 17, 18, 0.92)' }, - }, - - // BRAND COLORS - github: { value: '#171923' }, - telegram: { value: '#2775CA' }, - linkedin: { value: '#1564BA' }, - discord: { value: '#9747FF' }, - slack: { value: '#1BA27A' }, - twitter: { value: '#000000' }, - opensea: { value: '#2081E2' }, - facebook: { value: '#4460A0' }, - medium: { value: '#231F20' }, - reddit: { value: '#FF4500' }, - celo: { value: '#FCFF52' }, - clusters: { value: '#DE6061' }, - - // THEME COLORS + ...PALETTE_COLORS, theme: defaultsDeep(config.shell.topBar.colorTheme.overrides, DEFAULT_THEME_COLORS), }; diff --git a/src/toolkit/theme/foundations/colorsDefault.ts b/src/toolkit/theme/foundations/colorsDefault.ts new file mode 100644 index 00000000000..34b64e15761 --- /dev/null +++ b/src/toolkit/theme/foundations/colorsDefault.ts @@ -0,0 +1,288 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +// Config-free theme defaults: the runtime theme composes them with the app config in ./colors.ts, +// the design-readout color map reads them as they are (tools/design-readout/). + +export const DEFAULT_THEME_COLORS = { + bg: { + primary: { + // for some reason links to colors.white and colors.black variables are not working here + // so we use hex values instead + // but it is not the case for other colors + _light: { value: '#FFFFFF' }, // colors.white + _dark: { value: '#101112' }, // colors.black + }, + }, + text: { + primary: { + _light: { value: '{colors.blackAlpha.800}' }, + _dark: { value: '{colors.whiteAlpha.800}' }, + }, + secondary: { + _light: { value: '{colors.gray.500}' }, + _dark: { value: '{colors.gray.400}' }, + }, + }, + hover: { + _light: { value: '{colors.blue.400}' }, + _dark: { value: '{colors.blue.400}' }, + }, + selected: { + control: { + text: { + _light: { value: '{colors.blackAlpha.800}' }, + _dark: { value: '{colors.gray.50}' }, + }, + bg: { + _light: { value: '{colors.blackAlpha.100}' }, + _dark: { value: '{colors.whiteAlpha.100}' }, + }, + }, + option: { + bg: { + _light: { value: '{colors.blue.500}' }, + _dark: { value: '{colors.blue.500}' }, + }, + }, + }, + icon: { + primary: { + _light: { value: '{colors.gray.500}' }, + _dark: { value: '{colors.gray.400}' }, + }, + secondary: { + _light: { value: '{colors.gray.400}' }, + _dark: { value: '{colors.gray.500}' }, + }, + }, + button: { + primary: { + _light: { value: '{colors.blue.600}' }, + _dark: { value: '{colors.blue.600}' }, + text: { + _light: { value: '{colors.white}' }, + _dark: { value: '{colors.white}' }, + }, + }, + }, + link: { + primary: { + _light: { value: '{colors.blue.600}' }, + _dark: { value: '{colors.blue.300}' }, + }, + }, + graph: { + line: { + _light: { value: '{colors.blue.500}' }, + _dark: { value: '{colors.blue.200}' }, + }, + gradient: { + start: { + _light: { value: 'rgba(144, 205, 244, 0.3)' }, // blue.200 with opacity 0.3 + _dark: { value: 'rgba(144, 205, 244, 0.3)' }, // blue.200 with opacity 0.3 + }, + stop: { + _light: { value: 'rgba(144, 205, 244, 0)' }, // blue.200 with opacity 0 + _dark: { value: 'rgba(144, 205, 244, 0)' }, // blue.200 with opacity 0 + }, + }, + }, + navigation: { + bg: { + selected: { + _light: { value: '{colors.blackAlpha.50}' }, + _dark: { value: '{colors.gray.800}' }, + }, + }, + text: { + selected: { + _light: { value: '{colors.blackAlpha.800}' }, + _dark: { value: '{colors.gray.50}' }, + }, + }, + }, + stats: { + bg: { + _light: { value: '{colors.gray.50}' }, + _dark: { value: '{colors.whiteAlpha.100}' }, + }, + }, + topbar: { + bg: { + _light: { value: '{colors.blackAlpha.50}' }, + _dark: { value: '{colors.whiteAlpha.100}' }, + }, + }, + tabs: { + text: { + primary: { + _light: { value: '{colors.blackAlpha.800}' }, + _dark: { value: '{colors.gray.50}' }, + }, + }, + }, +}; + +export const PALETTE_COLORS = { + // BASE COLORS + green: { + '50': { value: '#F0FFF4' }, + '100': { value: '#C6F6D5' }, + '200': { value: '#9AE6B4' }, + '300': { value: '#68D391' }, + '400': { value: '#48BB78' }, + '500': { value: '#38A169' }, + '600': { value: '#25855A' }, + '700': { value: '#276749' }, + '800': { value: '#22543D' }, + '900': { value: '#1C4532' }, + }, + blue: { + '50': { value: '#EBF8FF' }, + '100': { value: '#BEE3F8' }, + '200': { value: '#90CDF4' }, + '300': { value: '#63B3ED' }, + '400': { value: '#4299E1' }, + '500': { value: '#3182CE' }, + '600': { value: '#2B6CB0' }, + '700': { value: '#2C5282' }, + '800': { value: '#2A4365' }, + '900': { value: '#1A365D' }, + }, + red: { + '50': { value: '#FFF5F5' }, + '100': { value: '#FED7D7' }, + '200': { value: '#FEB2B2' }, + '300': { value: '#FC8181' }, + '400': { value: '#F56565' }, + '500': { value: '#E53E3E' }, + '600': { value: '#C53030' }, + '700': { value: '#9B2C2C' }, + '800': { value: '#822727' }, + '900': { value: '#63171B' }, + }, + orange: { + '50': { value: '#FFFAF0' }, + '100': { value: '#FEEBCB' }, + '200': { value: '#FBD38D' }, + '300': { value: '#F6AD55' }, + '400': { value: '#ED8936' }, + '500': { value: '#DD6B20' }, + '600': { value: '#C05621' }, + '700': { value: '#9C4221' }, + '800': { value: '#7B341E' }, + '900': { value: '#652B19' }, + }, + yellow: { + '50': { value: '#FFFFF0' }, + '100': { value: '#FEFCBF' }, + '200': { value: '#FAF089' }, + '300': { value: '#F6E05E' }, + '400': { value: '#ECC94B' }, + '500': { value: '#D69E2E' }, + '600': { value: '#B7791F' }, + '700': { value: '#975A16' }, + '800': { value: '#744210' }, + '900': { value: '#5F370E' }, + }, + gray: { + '50': { value: '#F7FAFC' }, + '100': { value: '#EDF2F7' }, + '200': { value: '#E2E8F0' }, + '300': { value: '#CBD5E0' }, + '400': { value: '#A0AEC0' }, + '500': { value: '#718096' }, + '600': { value: '#4A5568' }, + '700': { value: '#2D3748' }, + '800': { value: '#1A202C' }, + '900': { value: '#171923' }, + }, + teal: { + '50': { value: '#E6FFFA' }, + '100': { value: '#B2F5EA' }, + '200': { value: '#81E6D9' }, + '300': { value: '#4FD1C5' }, + '400': { value: '#38B2AC' }, + '500': { value: '#319795' }, + '600': { value: '#2C7A7B' }, + '700': { value: '#285E61' }, + '800': { value: '#234E52' }, + '900': { value: '#1D4044' }, + }, + cyan: { + '50': { value: '#EDFDFD' }, + '100': { value: '#C4F1F9' }, + '200': { value: '#9DECF9' }, + '300': { value: '#76E4F7' }, + '400': { value: '#0BC5EA' }, + '500': { value: '#00B5D8' }, + '600': { value: '#00A3C4' }, + '700': { value: '#0987A0' }, + '800': { value: '#086F83' }, + '900': { value: '#065666' }, + }, + purple: { + '50': { value: '#FAF5FF' }, + '100': { value: '#E9D8FD' }, + '200': { value: '#D6BCFA' }, + '300': { value: '#B794F4' }, + '400': { value: '#9F7AEA' }, + '500': { value: '#805AD5' }, + '600': { value: '#6B46C1' }, + '700': { value: '#553C9A' }, + '800': { value: '#44337A' }, + '900': { value: '#322659' }, + }, + pink: { + '50': { value: '#FFF5F7' }, + '100': { value: '#FED7E2' }, + '200': { value: '#FBB6CE' }, + '300': { value: '#F687B3' }, + '400': { value: '#ED64A6' }, + '500': { value: '#D53F8C' }, + '600': { value: '#B83280' }, + '700': { value: '#97266D' }, + '800': { value: '#702459' }, + '900': { value: '#521B41' }, + }, + black: { value: '#101112' }, + white: { value: '#ffffff' }, + whiteAlpha: { + '50': { value: 'RGBA(255, 255, 255, 0.04)' }, + '100': { value: 'RGBA(255, 255, 255, 0.06)' }, + '200': { value: 'RGBA(255, 255, 255, 0.08)' }, + '300': { value: 'RGBA(255, 255, 255, 0.16)' }, + '400': { value: 'RGBA(255, 255, 255, 0.24)' }, + '500': { value: 'RGBA(255, 255, 255, 0.36)' }, + '600': { value: 'RGBA(255, 255, 255, 0.48)' }, + '700': { value: 'RGBA(255, 255, 255, 0.64)' }, + '800': { value: 'RGBA(255, 255, 255, 0.80)' }, + '900': { value: 'RGBA(255, 255, 255, 0.92)' }, + }, + blackAlpha: { + '50': { value: 'RGBA(16, 17, 18, 0.04)' }, + '100': { value: 'RGBA(16, 17, 18, 0.06)' }, + '200': { value: 'RGBA(16, 17, 18, 0.08)' }, + '300': { value: 'RGBA(16, 17, 18, 0.16)' }, + '400': { value: 'RGBA(16, 17, 18, 0.24)' }, + '500': { value: 'RGBA(16, 17, 18, 0.36)' }, + '600': { value: 'RGBA(16, 17, 18, 0.48)' }, + '700': { value: 'RGBA(16, 17, 18, 0.64)' }, + '800': { value: 'RGBA(16, 17, 18, 0.80)' }, + '900': { value: 'RGBA(16, 17, 18, 0.92)' }, + }, + + // BRAND COLORS + github: { value: '#171923' }, + telegram: { value: '#2775CA' }, + linkedin: { value: '#1564BA' }, + discord: { value: '#9747FF' }, + slack: { value: '#1BA27A' }, + twitter: { value: '#000000' }, + opensea: { value: '#2081E2' }, + facebook: { value: '#4460A0' }, + medium: { value: '#231F20' }, + reddit: { value: '#FF4500' }, + celo: { value: '#FCFF52' }, + clusters: { value: '#DE6061' }, +}; diff --git a/src/toolkit/theme/foundations/semanticTokens.spec.ts b/src/toolkit/theme/foundations/semanticTokens.spec.ts new file mode 100644 index 00000000000..d0d674ebf3a --- /dev/null +++ b/src/toolkit/theme/foundations/semanticTokens.spec.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest'; +import withEnvs from 'vitest/utils/mockEnvs'; + +import { SEMANTIC_TOKENS_DEFAULT } from './semanticTokensDefault'; + +async function loadSemanticTokens(heroBannerButton: object | undefined) { + const envs: Array<[ string, string ]> = heroBannerButton ? + [ [ 'NEXT_PUBLIC_HOMEPAGE_HERO_BANNER_CONFIG', JSON.stringify({ button: heroBannerButton }) ] ] : + []; + return withEnvs(envs, async() => { + const loaded = await import('./semanticTokens'); + return loaded.default as typeof SEMANTIC_TOKENS_DEFAULT; + }); +} + +describe('semanticTokens', () => { + it('is the config-free default when no hero banner button is configured', async() => { + expect(await loadSemanticTokens(undefined)).toEqual(SEMANTIC_TOKENS_DEFAULT); + }); + + it('lets the hero banner button config override only the values it names', async() => { + const tokens = await loadSemanticTokens({ + _default: { background: [ '#111111', '#222222' ], text_color: [ '#333333' ] }, + _hover: { background: [ '#444444' ] }, + }); + const hero = tokens.colors.button.hero; + expect(hero.bg.DEFAULT.value).toEqual({ _light: '#111111', _dark: '#222222' }); + expect(hero.fg.DEFAULT.value).toEqual({ _light: '#333333', _dark: '#333333' }); + expect(hero.bg.hover.value).toEqual({ _light: '#444444', _dark: '#444444' }); + expect(hero.bg.selected).toEqual(SEMANTIC_TOKENS_DEFAULT.colors.button.hero.bg.selected); + expect(hero.fg.hover).toEqual(SEMANTIC_TOKENS_DEFAULT.colors.button.hero.fg.hover); + expect(tokens.colors.text).toEqual(SEMANTIC_TOKENS_DEFAULT.colors.text); + }); +}); diff --git a/src/toolkit/theme/foundations/semanticTokens.ts b/src/toolkit/theme/foundations/semanticTokens.ts index 14a33e442c0..3d49024b829 100644 --- a/src/toolkit/theme/foundations/semanticTokens.ts +++ b/src/toolkit/theme/foundations/semanticTokens.ts @@ -1,526 +1,40 @@ // SPDX-License-Identifier: LicenseRef-Blockscout import type { ThemingConfig } from '@chakra-ui/react'; +import { defaultsDeep } from 'es-toolkit/compat'; -import config from 'src/config'; - -const heroBannerButton = config.slices.home.heroBanner?.button; +import type { ColorModeValue } from 'src/config/types'; -const semanticTokens: ThemingConfig['semanticTokens'] = { - colors: { - // COMMON STATES - hover: { - DEFAULT: { value: { _light: '{colors.theme.hover._light}', _dark: '{colors.theme.hover._dark}' } }, - }, - selected: { - control: { - bg: { value: { _light: '{colors.theme.selected.control.bg._light}', _dark: '{colors.theme.selected.control.bg._dark}' } }, - text: { value: { _light: '{colors.theme.selected.control.text._light}', _dark: '{colors.theme.selected.control.text._dark}' } }, - }, - option: { - bg: { value: { _light: '{colors.theme.selected.option.bg._light}', _dark: '{colors.theme.selected.option.bg._dark}' } }, - }, - }, +import config from 'src/config'; - // GLOBAL - global: { - body: { - bg: { value: '{colors.bg.primary}' }, - fg: { value: '{colors.text.primary}' }, - }, - mark: { - bg: { value: { _light: '{colors.green.100}', _dark: '{colors.green.800}' } }, - }, - scrollbar: { - thumb: { value: { _light: '{colors.blackAlpha.300}', _dark: '{colors.whiteAlpha.300}' } }, - }, - selection: { - bg: { value: { _light: '#E3CFE7', _dark: '#754B7D' } }, - }, - }, +import { SEMANTIC_TOKENS_DEFAULT } from './semanticTokensDefault'; - // FOUNDATIONS - heading: { - DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - text: { - primary: { value: { _light: '{colors.theme.text.primary._light}', _dark: '{colors.theme.text.primary._dark}' } }, - secondary: { value: { _light: '{colors.theme.text.secondary._light}', _dark: '{colors.theme.text.secondary._dark}' } }, - error: { value: '{colors.red.500}' }, - success: { value: { _light: '{colors.green.500}', _dark: '{colors.green.200}' } }, - }, - bg: { - primary: { value: { _light: '{colors.theme.bg.primary._light}', _dark: '{colors.theme.bg.primary._dark}' } }, - }, - border: { - divider: { value: { _light: '{colors.blackAlpha.100}', _dark: '{colors.whiteAlpha.100}' } }, - error: { value: '{colors.red.500}' }, - }, - icon: { - primary: { value: { _light: '{colors.theme.icon.primary._light}', _dark: '{colors.theme.icon.primary._dark}' } }, - secondary: { value: { _light: '{colors.theme.icon.secondary._light}', _dark: '{colors.theme.icon.secondary._dark}' } }, - }, +const heroBannerButton = config.slices.home.heroBanner?.button; - // ELEMENTS - address: { - highlighted: { - bg: { value: { _light: '{colors.blue.50}', _dark: '{colors.blue.900}' } }, - border: { value: { _light: '{colors.blue.200}', _dark: '{colors.blue.600}' } }, - }, - }, +// A configured pair fills both modes, a single value serves both; anything undefined keeps the default. +function modePair(values: ColorModeValue | undefined) { + return { value: { _light: values?.[0], _dark: values?.[1] || values?.[0] } }; +} - // COMPONENTS +const heroButtonOverrides = { + colors: { button: { - solid: { - bg: { - DEFAULT: { value: { _light: '{colors.theme.button.primary._light}', _dark: '{colors.theme.button.primary._dark}' } }, - }, - text: { - DEFAULT: { value: { _light: '{colors.theme.button.primary.text._light}', _dark: '{colors.theme.button.primary.text._dark}' } }, - }, - }, - outline: { - fg: { - DEFAULT: { value: { _light: '{colors.theme.button.primary._light}', _dark: '{colors.theme.button.primary._dark}' } }, - }, - }, - subtle: { - fg: { - DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - bg: { - DEFAULT: { value: { _light: '{colors.blackAlpha.200}', _dark: '{colors.whiteAlpha.200}' } }, - }, - }, - dropdown: { - fg: { - DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - border: { - DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.600}' } }, - }, - }, - header: { - fg: { - DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.gray.400}' } }, - selected: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - highlighted: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - bg: { - selected: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.100}' } }, - highlighted: { value: { _light: '{colors.orange.100}', _dark: '{colors.orange.900}' } }, - }, - border: { - DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.600}' } }, - }, - }, - segmented: { - fg: { - DEFAULT: { value: '{colors.text.primary}' }, - }, - }, - icon_background: { - bg: { - DEFAULT: { value: { _light: '{colors.gray.50}', _dark: '{colors.whiteAlpha.50}' } }, - }, - }, - pagination: { - fg: { - DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.gray.50}' } }, - }, - border: { - DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.whiteAlpha.100}' } }, - }, - }, hero: { bg: { - DEFAULT: { - value: { - _light: heroBannerButton?._default?.background?.[0] || '{colors.theme.button.primary._light}', - _dark: heroBannerButton?._default?.background?.[1] || heroBannerButton?._default?.background?.[0] || '{colors.theme.button.primary._dark}', - }, - }, - hover: { - value: { - _light: heroBannerButton?._hover?.background?.[0] || '{colors.hover}', - _dark: heroBannerButton?._hover?.background?.[1] || heroBannerButton?._hover?.background?.[0] || '{colors.hover}', - }, - }, - selected: { - value: { - _light: heroBannerButton?._selected?.background?.[0] || '{colors.blue.50}', - _dark: heroBannerButton?._selected?.background?.[1] || heroBannerButton?._selected?.background?.[0] || '{colors.blue.50}', - }, - }, - }, - fg: { - DEFAULT: { - value: { - _light: heroBannerButton?._default?.text_color?.[0] || '{colors.white}', - _dark: heroBannerButton?._default?.text_color?.[1] || heroBannerButton?._default?.text_color?.[0] || '{colors.white}', - }, - }, - hover: { - value: { - _light: heroBannerButton?._hover?.text_color?.[0] || '{colors.white}', - _dark: heroBannerButton?._hover?.text_color?.[1] || heroBannerButton?._hover?.text_color?.[0] || '{colors.white}', - }, - }, - selected: { - value: { - _light: heroBannerButton?._selected?.text_color?.[0] || '{colors.blackAlpha.800}', - _dark: heroBannerButton?._selected?.text_color?.[1] || heroBannerButton?._selected?.text_color?.[0] || '{colors.blackAlpha.800}', - }, - }, - }, - }, - }, - closeButton: { - fg: { - DEFAULT: { value: { _light: '{colors.blackAlpha.500}', _dark: '{colors.whiteAlpha.500}' } }, - }, - }, - link: { - primary: { - DEFAULT: { value: { _light: '{colors.theme.link.primary._light}', _dark: '{colors.theme.link.primary._dark}' } }, - hover: { value: '{colors.hover}' }, - }, - secondary: { - DEFAULT: { value: '{colors.text.secondary}' }, - }, - underlaid: { - bg: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.800}' } }, - }, - subtle: { - DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.gray.400}' } }, - hover: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.gray.400}' } }, - }, - navigation: { - fg: { - DEFAULT: { value: '{colors.text.primary}' }, - selected: { value: { _light: '{colors.theme.navigation.text.selected._light}', _dark: '{colors.theme.navigation.text.selected._dark}' } }, - hover: { value: { _light: '{colors.hover}' } }, - active: { value: { _light: '{colors.hover}' } }, - }, - bg: { - selected: { value: { _light: '{colors.theme.navigation.bg.selected._light}', _dark: '{colors.theme.navigation.bg.selected._dark}' } }, - group: { value: { _light: '{colors.white}', _dark: '{colors.black}' } }, - }, - }, - menu: { - DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - }, - tooltip: { - DEFAULT: { - bg: { value: '{colors.gray.900}' }, - fg: { value: '{colors.white}' }, - }, - }, - popover: { - DEFAULT: { - bg: { value: { _light: '{colors.white}', _dark: '{colors.gray.900}' } }, - shadow: { value: { _light: '{colors.blackAlpha.200}', _dark: '{colors.whiteAlpha.300}' } }, - }, - }, - progress: { - track: { - DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.whiteAlpha.100}' } }, - }, - }, - progressCircle: { - track: { - DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.whiteAlpha.100}' } }, - }, - }, - skeleton: { - bg: { - start: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.50}' } }, - end: { value: { _light: '{colors.blackAlpha.100}', _dark: '{colors.whiteAlpha.100}' } }, - }, - }, - tabs: { - solid: { - fg: { - DEFAULT: { value: { _light: '{colors.theme.tabs.text.primary._light}', _dark: '{colors.theme.tabs.text.primary._dark}' } }, - }, - }, - secondary: { - fg: { - DEFAULT: { value: '{colors.text.primary}' }, - }, - border: { - DEFAULT: { value: { _light: '{colors.gray.300}', _dark: '{colors.gray.600}' } }, - }, - }, - segmented: { - fg: { - DEFAULT: { value: '{colors.text.primary}' }, - }, - }, - }, - 'switch': { - primary: { - bg: { - DEFAULT: { value: { _light: '{colors.gray.300}', _dark: '{colors.whiteAlpha.400}' } }, + DEFAULT: modePair(heroBannerButton?._default?.background), + hover: modePair(heroBannerButton?._hover?.background), + selected: modePair(heroBannerButton?._selected?.background), }, - }, - }, - alert: { - fg: { - DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - bg: { - info: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.100}' } }, - warning: { value: { _light: '{colors.orange.100}', _dark: '{colors.orange.800/44}' } }, - warning_table: { value: { _light: '{colors.orange.50}', _dark: '{colors.orange.800/44}' } }, - success: { value: { _light: '{colors.green.100}', _dark: '{colors.green.900}' } }, - error: { value: { _light: '{colors.red.100}', _dark: '{colors.red.900}' } }, - }, - }, - toast: { - fg: { - DEFAULT: { value: '{colors.alert.fg}' }, - }, - bg: { - DEFAULT: { value: '{colors.alert.bg.info}' }, - info: { value: { _light: '{colors.blue.100}', _dark: '{colors.blue.900}' } }, - warning: { value: { _light: '{colors.orange.100}', _dark: '{colors.orange.900}' } }, - success: { value: '{colors.alert.bg.success}' }, - error: { value: '{colors.alert.bg.error}' }, - loading: { value: { _light: '{colors.blue.100}', _dark: '{colors.blue.900}' } }, - }, - }, - input: { - fg: { - DEFAULT: { value: { _light: '{colors.gray.800}', _dark: '{colors.gray.50}' } }, - error: { value: '{colors.text.error}' }, - }, - bg: { - DEFAULT: { value: '{colors.bg.primary}' }, - readOnly: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.800}' } }, - }, - border: { - DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.600}' } }, - hover: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.500}' } }, - focus: { value: '{colors.hover}' }, - filled: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.600}' } }, - readOnly: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.800}' } }, - error: { value: '{colors.red.500}' }, - }, - placeholder: { - DEFAULT: { value: { _light: '{colors.gray.400}', _dark: '{colors.gray.500}' } }, - error: { value: '{colors.red.500}' }, - }, - element: { - DEFAULT: { value: { _light: '{colors.gray.400}', _dark: '{colors.gray.500}' } }, - }, - }, - field: { - placeholder: { - DEFAULT: { value: { _light: '{colors.gray.400}', _dark: '{colors.gray.500}' } }, - disabled: { value: '{colors.gray.500/20}' }, - error: { value: '{colors.red.500}' }, - }, - }, - dialog: { - bg: { - DEFAULT: { value: { _light: '{colors.white}', _dark: '{colors.gray.900}' } }, - }, - fg: { - DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - }, - drawer: { - bg: { - DEFAULT: { value: { _light: '{colors.white}', _dark: '{colors.gray.900}' } }, - }, - }, - select: { - trigger: { - outline: { - fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - }, - indicator: { fg: { - DEFAULT: { value: { _light: '{colors.gray.400}', _dark: '{colors.gray.500}' } }, + DEFAULT: modePair(heroBannerButton?._default?.text_color), + hover: modePair(heroBannerButton?._hover?.text_color), + selected: modePair(heroBannerButton?._selected?.text_color), }, }, - placeholder: { - fg: { - DEFAULT: { value: { _light: '{colors.gray.400}', _dark: '{colors.gray.500}' } }, - error: { value: '{colors.red.500}' }, - }, - }, - }, - spinner: { - track: { - DEFAULT: { value: { _light: '{colors.blackAlpha.200}', _dark: '{colors.whiteAlpha.200}' } }, - }, - }, - badge: { - gray: { - bg: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.100}' } }, - fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - green: { - bg: { value: { _light: '{colors.green.50}', _dark: '{colors.green.800}' } }, - fg: { value: { _light: '{colors.green.500}', _dark: '{colors.green.200}' } }, - }, - red: { - bg: { value: { _light: '{colors.red.50}', _dark: '{colors.red.800}' } }, - fg: { value: { _light: '{colors.red.500}', _dark: '{colors.red.200}' } }, - }, - purple: { - bg: { value: { _light: '{colors.purple.50}', _dark: '{colors.purple.800}' } }, - fg: { value: { _light: '{colors.purple.500}', _dark: '{colors.purple.100}' } }, - }, - purple_alt: { - bg: { value: { _light: '{colors.purple.100}', _dark: '{colors.purple.800}' } }, - fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - orange: { - bg: { value: { _light: '{colors.orange.50}', _dark: '{colors.orange.800}' } }, - fg: { value: { _light: '{colors.orange.500}', _dark: '{colors.orange.100}' } }, - }, - blue: { - bg: { value: { _light: '{colors.blue.50}', _dark: '{colors.blue.800}' } }, - fg: { value: { _light: '{colors.blue.500}', _dark: '{colors.blue.100}' } }, - }, - blue_alt: { - bg: { value: { _light: '{colors.blue.50}', _dark: '{colors.blue.800}' } }, - fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - yellow: { - bg: { value: { _light: '{colors.yellow.50}', _dark: '{colors.yellow.800}' } }, - fg: { value: { _light: '{colors.yellow.500}', _dark: '{colors.yellow.100}' } }, - }, - teal: { - bg: { value: { _light: '{colors.teal.50}', _dark: '{colors.teal.800}' } }, - fg: { value: { _light: '{colors.teal.500}', _dark: '{colors.teal.100}' } }, - }, - cyan: { - bg: { value: { _light: '{colors.cyan.50}', _dark: '{colors.cyan.800}' } }, - fg: { value: { _light: '{colors.cyan.500}', _dark: '{colors.cyan.100}' } }, - }, - pink: { - bg: { value: { _light: '{colors.pink.50}', _dark: '{colors.pink.800}' } }, - fg: { value: { _light: '{colors.pink.500}', _dark: '{colors.pink.100}' } }, - }, - // bright badges mainly used in other projects (e.g. autoscout, dev portal, etc.) - bright: { - gray: { - bg: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.800}' } }, - fg: { value: { _light: '{colors.gray.600}', _dark: '{colors.gray.200}' } }, - }, - green: { - bg: { value: { _light: '{colors.green.100}', _dark: '{colors.green.800}' } }, - fg: { value: { _light: '{colors.green.600}', _dark: '{colors.green.200}' } }, - }, - red: { - bg: { value: { _light: '{colors.red.100}', _dark: '{colors.red.800}' } }, - fg: { value: { _light: '{colors.red.600}', _dark: '{colors.red.200}' } }, - }, - blue: { - bg: { value: { _light: '{colors.blue.100}', _dark: '{colors.blue.800}' } }, - fg: { value: { _light: '{colors.blue.600}', _dark: '{colors.blue.200}' } }, - }, - yellow: { - bg: { value: { _light: '{colors.yellow.100}', _dark: '{colors.yellow.800}' } }, - fg: { value: { _light: '{colors.yellow.600}', _dark: '{colors.yellow.200}' } }, - }, - teal: { - bg: { value: { _light: '{colors.teal.100}', _dark: '{colors.teal.800}' } }, - fg: { value: { _light: '{colors.teal.600}', _dark: '{colors.teal.200}' } }, - }, - cyan: { - bg: { value: { _light: '{colors.cyan.100}', _dark: '{colors.cyan.800}' } }, - fg: { value: { _light: '{colors.cyan.600}', _dark: '{colors.cyan.200}' } }, - }, - orange: { - bg: { value: { _light: '{colors.orange.100}', _dark: '{colors.orange.600}' } }, - fg: { value: { _light: '{colors.orange.600}', _dark: '{colors.orange.100}' } }, - }, - purple: { - bg: { value: { _light: '{colors.purple.50}', _dark: '{colors.purple.600}' } }, - fg: { value: { _light: '{colors.purple.600}', _dark: '{colors.purple.50}' } }, - }, - pink: { - bg: { value: { _light: '{colors.pink.50}', _dark: '{colors.pink.600}' } }, - fg: { value: { _light: '{colors.pink.600}', _dark: '{colors.pink.50}' } }, - }, - }, - }, - tag: { - root: { - subtle: { - bg: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.100}' } }, - fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - clickable: { - bg: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.800}' } }, - fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, - }, - filter: { - bg: { value: { _light: '{colors.blue.50}', _dark: '{colors.whiteAlpha.200}' } }, - }, - select: { - bg: { - DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.800}' } }, - }, - fg: { value: { _light: '{colors.gray.500}', _dark: '{colors.whiteAlpha.800}' } }, - }, - }, - }, - table: { - header: { - bg: { value: { _light: '{colors.blackAlpha.100}', _dark: '{colors.whiteAlpha.200}' } }, - fg: { value: { _light: '{colors.blackAlpha.700}', _dark: '{colors.whiteAlpha.700}' } }, - }, - }, - checkbox: { - control: { - border: { - DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.700}' } }, - hover: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.500}' } }, - readOnly: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.800}' } }, - }, - }, - }, - radio: { - control: { - border: { - DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.700}' } }, - hover: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.500}' } }, - readOnly: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.800}' } }, - }, - }, - }, - stat: { - indicator: { - up: { value: { _light: '{colors.green.500}', _dark: '{colors.green.400}' } }, - down: { value: { _light: '{colors.red.600}', _dark: '{colors.red.400}' } }, - }, - }, - rating: { - DEFAULT: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.700}' } }, - highlighted: { value: '{colors.yellow.400}' }, - }, - }, - shadows: { - popover: { - DEFAULT: { value: { _light: '{shadows.size.2xl}', _dark: '{shadows.dark-lg}' } }, - }, - drawer: { - DEFAULT: { value: { _light: '{shadows.size.lg}', _dark: '{shadows.dark-lg}' } }, - }, - }, - opacity: { - control: { - disabled: { value: '0.2' }, }, }, }; +const semanticTokens: ThemingConfig['semanticTokens'] = defaultsDeep(heroButtonOverrides, SEMANTIC_TOKENS_DEFAULT); + export default semanticTokens; diff --git a/src/toolkit/theme/foundations/semanticTokensDefault.ts b/src/toolkit/theme/foundations/semanticTokensDefault.ts new file mode 100644 index 00000000000..e91ebda4b33 --- /dev/null +++ b/src/toolkit/theme/foundations/semanticTokensDefault.ts @@ -0,0 +1,518 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +// Config-free theme defaults: the runtime theme composes them with the app config in ./colors.ts, +// the design-readout color map reads them as they are (tools/design-readout/). + +export const SEMANTIC_TOKENS_DEFAULT = { + colors: { + // COMMON STATES + hover: { + DEFAULT: { value: { _light: '{colors.theme.hover._light}', _dark: '{colors.theme.hover._dark}' } }, + }, + selected: { + control: { + bg: { value: { _light: '{colors.theme.selected.control.bg._light}', _dark: '{colors.theme.selected.control.bg._dark}' } }, + text: { value: { _light: '{colors.theme.selected.control.text._light}', _dark: '{colors.theme.selected.control.text._dark}' } }, + }, + option: { + bg: { value: { _light: '{colors.theme.selected.option.bg._light}', _dark: '{colors.theme.selected.option.bg._dark}' } }, + }, + }, + + // GLOBAL + global: { + body: { + bg: { value: '{colors.bg.primary}' }, + fg: { value: '{colors.text.primary}' }, + }, + mark: { + bg: { value: { _light: '{colors.green.100}', _dark: '{colors.green.800}' } }, + }, + scrollbar: { + thumb: { value: { _light: '{colors.blackAlpha.300}', _dark: '{colors.whiteAlpha.300}' } }, + }, + selection: { + bg: { value: { _light: '#E3CFE7', _dark: '#754B7D' } }, + }, + }, + + // FOUNDATIONS + heading: { + DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + text: { + primary: { value: { _light: '{colors.theme.text.primary._light}', _dark: '{colors.theme.text.primary._dark}' } }, + secondary: { value: { _light: '{colors.theme.text.secondary._light}', _dark: '{colors.theme.text.secondary._dark}' } }, + error: { value: '{colors.red.500}' }, + success: { value: { _light: '{colors.green.500}', _dark: '{colors.green.200}' } }, + }, + bg: { + primary: { value: { _light: '{colors.theme.bg.primary._light}', _dark: '{colors.theme.bg.primary._dark}' } }, + }, + border: { + divider: { value: { _light: '{colors.blackAlpha.100}', _dark: '{colors.whiteAlpha.100}' } }, + error: { value: '{colors.red.500}' }, + }, + icon: { + primary: { value: { _light: '{colors.theme.icon.primary._light}', _dark: '{colors.theme.icon.primary._dark}' } }, + secondary: { value: { _light: '{colors.theme.icon.secondary._light}', _dark: '{colors.theme.icon.secondary._dark}' } }, + }, + + // ELEMENTS + address: { + highlighted: { + bg: { value: { _light: '{colors.blue.50}', _dark: '{colors.blue.900}' } }, + border: { value: { _light: '{colors.blue.200}', _dark: '{colors.blue.600}' } }, + }, + }, + + // COMPONENTS + button: { + solid: { + bg: { + DEFAULT: { value: { _light: '{colors.theme.button.primary._light}', _dark: '{colors.theme.button.primary._dark}' } }, + }, + text: { + DEFAULT: { value: { _light: '{colors.theme.button.primary.text._light}', _dark: '{colors.theme.button.primary.text._dark}' } }, + }, + }, + outline: { + fg: { + DEFAULT: { value: { _light: '{colors.theme.button.primary._light}', _dark: '{colors.theme.button.primary._dark}' } }, + }, + }, + subtle: { + fg: { + DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + bg: { + DEFAULT: { value: { _light: '{colors.blackAlpha.200}', _dark: '{colors.whiteAlpha.200}' } }, + }, + }, + dropdown: { + fg: { + DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + border: { + DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.600}' } }, + }, + }, + header: { + fg: { + DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.gray.400}' } }, + selected: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + highlighted: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + bg: { + selected: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.100}' } }, + highlighted: { value: { _light: '{colors.orange.100}', _dark: '{colors.orange.900}' } }, + }, + border: { + DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.600}' } }, + }, + }, + segmented: { + fg: { + DEFAULT: { value: '{colors.text.primary}' }, + }, + }, + icon_background: { + bg: { + DEFAULT: { value: { _light: '{colors.gray.50}', _dark: '{colors.whiteAlpha.50}' } }, + }, + }, + pagination: { + fg: { + DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.gray.50}' } }, + }, + border: { + DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.whiteAlpha.100}' } }, + }, + }, + hero: { + bg: { + DEFAULT: { + value: { + _light: '{colors.theme.button.primary._light}', + _dark: '{colors.theme.button.primary._dark}', + }, + }, + hover: { + value: { + _light: '{colors.hover}', + _dark: '{colors.hover}', + }, + }, + selected: { + value: { + _light: '{colors.blue.50}', + _dark: '{colors.blue.50}', + }, + }, + }, + fg: { + DEFAULT: { + value: { + _light: '{colors.white}', + _dark: '{colors.white}', + }, + }, + hover: { + value: { + _light: '{colors.white}', + _dark: '{colors.white}', + }, + }, + selected: { + value: { + _light: '{colors.blackAlpha.800}', + _dark: '{colors.blackAlpha.800}', + }, + }, + }, + }, + }, + closeButton: { + fg: { + DEFAULT: { value: { _light: '{colors.blackAlpha.500}', _dark: '{colors.whiteAlpha.500}' } }, + }, + }, + link: { + primary: { + DEFAULT: { value: { _light: '{colors.theme.link.primary._light}', _dark: '{colors.theme.link.primary._dark}' } }, + hover: { value: '{colors.hover}' }, + }, + secondary: { + DEFAULT: { value: '{colors.text.secondary}' }, + }, + underlaid: { + bg: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.100}' } }, + }, + subtle: { + DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.gray.400}' } }, + hover: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.gray.400}' } }, + }, + navigation: { + fg: { + DEFAULT: { value: '{colors.text.primary}' }, + selected: { value: { _light: '{colors.theme.navigation.text.selected._light}', _dark: '{colors.theme.navigation.text.selected._dark}' } }, + hover: { value: { _light: '{colors.hover}' } }, + active: { value: { _light: '{colors.hover}' } }, + }, + bg: { + selected: { value: { _light: '{colors.theme.navigation.bg.selected._light}', _dark: '{colors.theme.navigation.bg.selected._dark}' } }, + group: { value: { _light: '{colors.white}', _dark: '{colors.black}' } }, + }, + }, + menu: { + DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + }, + tooltip: { + DEFAULT: { + bg: { value: '{colors.gray.900}' }, + fg: { value: '{colors.white}' }, + }, + }, + popover: { + DEFAULT: { + bg: { value: { _light: '{colors.white}', _dark: '{colors.gray.900}' } }, + shadow: { value: { _light: '{colors.blackAlpha.200}', _dark: '{colors.whiteAlpha.300}' } }, + }, + }, + progress: { + track: { + DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.whiteAlpha.100}' } }, + }, + }, + progressCircle: { + track: { + DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.whiteAlpha.100}' } }, + }, + }, + skeleton: { + bg: { + start: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.50}' } }, + end: { value: { _light: '{colors.blackAlpha.100}', _dark: '{colors.whiteAlpha.100}' } }, + }, + }, + tabs: { + solid: { + fg: { + DEFAULT: { value: { _light: '{colors.theme.tabs.text.primary._light}', _dark: '{colors.theme.tabs.text.primary._dark}' } }, + }, + }, + secondary: { + fg: { + DEFAULT: { value: '{colors.text.primary}' }, + }, + border: { + DEFAULT: { value: { _light: '{colors.gray.300}', _dark: '{colors.gray.600}' } }, + }, + }, + segmented: { + fg: { + DEFAULT: { value: '{colors.text.primary}' }, + }, + }, + }, + 'switch': { + primary: { + bg: { + DEFAULT: { value: { _light: '{colors.gray.300}', _dark: '{colors.whiteAlpha.400}' } }, + }, + }, + }, + alert: { + fg: { + DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + bg: { + info: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.100}' } }, + warning: { value: { _light: '{colors.orange.100}', _dark: '{colors.orange.800/44}' } }, + warning_table: { value: { _light: '{colors.orange.50}', _dark: '{colors.orange.800/44}' } }, + success: { value: { _light: '{colors.green.100}', _dark: '{colors.green.900}' } }, + error: { value: { _light: '{colors.red.100}', _dark: '{colors.red.900}' } }, + }, + }, + toast: { + fg: { + DEFAULT: { value: '{colors.alert.fg}' }, + }, + bg: { + DEFAULT: { value: '{colors.alert.bg.info}' }, + info: { value: { _light: '{colors.blue.100}', _dark: '{colors.blue.900}' } }, + warning: { value: { _light: '{colors.orange.100}', _dark: '{colors.orange.900}' } }, + success: { value: '{colors.alert.bg.success}' }, + error: { value: '{colors.alert.bg.error}' }, + loading: { value: { _light: '{colors.blue.100}', _dark: '{colors.blue.900}' } }, + }, + }, + input: { + fg: { + DEFAULT: { value: { _light: '{colors.gray.800}', _dark: '{colors.gray.50}' } }, + error: { value: '{colors.text.error}' }, + }, + bg: { + DEFAULT: { value: '{colors.bg.primary}' }, + readOnly: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.800}' } }, + }, + border: { + DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.600}' } }, + hover: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.500}' } }, + focus: { value: '{colors.hover}' }, + filled: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.600}' } }, + readOnly: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.800}' } }, + error: { value: '{colors.red.500}' }, + }, + placeholder: { + DEFAULT: { value: { _light: '{colors.gray.400}', _dark: '{colors.gray.500}' } }, + error: { value: '{colors.red.500}' }, + }, + element: { + DEFAULT: { value: { _light: '{colors.gray.400}', _dark: '{colors.gray.500}' } }, + }, + }, + field: { + placeholder: { + DEFAULT: { value: { _light: '{colors.gray.400}', _dark: '{colors.gray.500}' } }, + disabled: { value: '{colors.gray.500/20}' }, + error: { value: '{colors.red.500}' }, + }, + }, + dialog: { + bg: { + DEFAULT: { value: { _light: '{colors.white}', _dark: '{colors.gray.900}' } }, + }, + fg: { + DEFAULT: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + }, + drawer: { + bg: { + DEFAULT: { value: { _light: '{colors.white}', _dark: '{colors.gray.900}' } }, + }, + }, + select: { + trigger: { + outline: { + fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + }, + indicator: { + fg: { + DEFAULT: { value: { _light: '{colors.gray.400}', _dark: '{colors.gray.500}' } }, + }, + }, + placeholder: { + fg: { + DEFAULT: { value: { _light: '{colors.gray.400}', _dark: '{colors.gray.500}' } }, + error: { value: '{colors.red.500}' }, + }, + }, + }, + spinner: { + track: { + DEFAULT: { value: { _light: '{colors.blackAlpha.200}', _dark: '{colors.whiteAlpha.200}' } }, + }, + }, + badge: { + gray: { + bg: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.100}' } }, + fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + green: { + bg: { value: { _light: '{colors.green.50}', _dark: '{colors.green.800}' } }, + fg: { value: { _light: '{colors.green.500}', _dark: '{colors.green.200}' } }, + }, + red: { + bg: { value: { _light: '{colors.red.50}', _dark: '{colors.red.800}' } }, + fg: { value: { _light: '{colors.red.500}', _dark: '{colors.red.200}' } }, + }, + purple: { + bg: { value: { _light: '{colors.purple.50}', _dark: '{colors.purple.800}' } }, + fg: { value: { _light: '{colors.purple.500}', _dark: '{colors.purple.100}' } }, + }, + purple_alt: { + bg: { value: { _light: '{colors.purple.100}', _dark: '{colors.purple.800}' } }, + fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + orange: { + bg: { value: { _light: '{colors.orange.50}', _dark: '{colors.orange.800}' } }, + fg: { value: { _light: '{colors.orange.500}', _dark: '{colors.orange.100}' } }, + }, + blue: { + bg: { value: { _light: '{colors.blue.50}', _dark: '{colors.blue.800}' } }, + fg: { value: { _light: '{colors.blue.500}', _dark: '{colors.blue.100}' } }, + }, + blue_alt: { + bg: { value: { _light: '{colors.blue.50}', _dark: '{colors.blue.800}' } }, + fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + yellow: { + bg: { value: { _light: '{colors.yellow.50}', _dark: '{colors.yellow.800}' } }, + fg: { value: { _light: '{colors.yellow.500}', _dark: '{colors.yellow.100}' } }, + }, + teal: { + bg: { value: { _light: '{colors.teal.50}', _dark: '{colors.teal.800}' } }, + fg: { value: { _light: '{colors.teal.500}', _dark: '{colors.teal.100}' } }, + }, + cyan: { + bg: { value: { _light: '{colors.cyan.50}', _dark: '{colors.cyan.800}' } }, + fg: { value: { _light: '{colors.cyan.500}', _dark: '{colors.cyan.100}' } }, + }, + pink: { + bg: { value: { _light: '{colors.pink.50}', _dark: '{colors.pink.800}' } }, + fg: { value: { _light: '{colors.pink.500}', _dark: '{colors.pink.100}' } }, + }, + // bright badges mainly used in other projects (e.g. autoscout, dev portal, etc.) + bright: { + gray: { + bg: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.800}' } }, + fg: { value: { _light: '{colors.gray.600}', _dark: '{colors.gray.200}' } }, + }, + green: { + bg: { value: { _light: '{colors.green.100}', _dark: '{colors.green.800}' } }, + fg: { value: { _light: '{colors.green.600}', _dark: '{colors.green.200}' } }, + }, + red: { + bg: { value: { _light: '{colors.red.100}', _dark: '{colors.red.800}' } }, + fg: { value: { _light: '{colors.red.600}', _dark: '{colors.red.200}' } }, + }, + blue: { + bg: { value: { _light: '{colors.blue.100}', _dark: '{colors.blue.800}' } }, + fg: { value: { _light: '{colors.blue.600}', _dark: '{colors.blue.200}' } }, + }, + yellow: { + bg: { value: { _light: '{colors.yellow.100}', _dark: '{colors.yellow.800}' } }, + fg: { value: { _light: '{colors.yellow.600}', _dark: '{colors.yellow.200}' } }, + }, + teal: { + bg: { value: { _light: '{colors.teal.100}', _dark: '{colors.teal.800}' } }, + fg: { value: { _light: '{colors.teal.600}', _dark: '{colors.teal.200}' } }, + }, + cyan: { + bg: { value: { _light: '{colors.cyan.100}', _dark: '{colors.cyan.800}' } }, + fg: { value: { _light: '{colors.cyan.600}', _dark: '{colors.cyan.200}' } }, + }, + orange: { + bg: { value: { _light: '{colors.orange.100}', _dark: '{colors.orange.600}' } }, + fg: { value: { _light: '{colors.orange.600}', _dark: '{colors.orange.100}' } }, + }, + purple: { + bg: { value: { _light: '{colors.purple.50}', _dark: '{colors.purple.600}' } }, + fg: { value: { _light: '{colors.purple.600}', _dark: '{colors.purple.50}' } }, + }, + pink: { + bg: { value: { _light: '{colors.pink.50}', _dark: '{colors.pink.600}' } }, + fg: { value: { _light: '{colors.pink.600}', _dark: '{colors.pink.50}' } }, + }, + }, + }, + tag: { + root: { + subtle: { + bg: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.100}' } }, + fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + clickable: { + bg: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.800}' } }, + fg: { value: { _light: '{colors.blackAlpha.800}', _dark: '{colors.whiteAlpha.800}' } }, + }, + filter: { + bg: { value: { _light: '{colors.blue.50}', _dark: '{colors.whiteAlpha.200}' } }, + }, + select: { + border: { value: { _light: '{colors.blackAlpha.50}', _dark: '{colors.whiteAlpha.100}' } }, + }, + }, + }, + table: { + header: { + bg: { value: { _light: '{colors.blackAlpha.100}', _dark: '{colors.whiteAlpha.200}' } }, + fg: { value: { _light: '{colors.blackAlpha.700}', _dark: '{colors.whiteAlpha.700}' } }, + }, + }, + checkbox: { + control: { + border: { + DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.700}' } }, + hover: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.500}' } }, + readOnly: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.800}' } }, + }, + }, + }, + radio: { + control: { + border: { + DEFAULT: { value: { _light: '{colors.gray.100}', _dark: '{colors.gray.700}' } }, + hover: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.500}' } }, + readOnly: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.800}' } }, + }, + }, + }, + stat: { + indicator: { + up: { value: { _light: '{colors.green.500}', _dark: '{colors.green.400}' } }, + down: { value: { _light: '{colors.red.600}', _dark: '{colors.red.400}' } }, + }, + }, + rating: { + DEFAULT: { value: { _light: '{colors.gray.200}', _dark: '{colors.gray.700}' } }, + highlighted: { value: '{colors.yellow.400}' }, + }, + }, + shadows: { + popover: { + DEFAULT: { value: { _light: '{shadows.size.2xl}', _dark: '{shadows.dark-lg}' } }, + }, + drawer: { + DEFAULT: { value: { _light: '{shadows.size.lg}', _dark: '{shadows.dark-lg}' } }, + }, + }, + opacity: { + control: { + disabled: { value: '0.2' }, + }, + }, +}; diff --git a/src/toolkit/theme/recipes/button.recipe.ts b/src/toolkit/theme/recipes/button.recipe.ts index 594c7c7281f..50295c891b1 100644 --- a/src/toolkit/theme/recipes/button.recipe.ts +++ b/src/toolkit/theme/recipes/button.recipe.ts @@ -219,6 +219,7 @@ export const recipe = defineRecipe({ _selected: { bg: 'selected.control.bg', color: 'selected.control.text', + borderColor: 'transparent', _hover: { bg: 'selected.control.bg', color: 'selected.control.text', diff --git a/src/toolkit/theme/recipes/close-button.recipe.ts b/src/toolkit/theme/recipes/close-button.recipe.ts index c1554af95c6..1c9ba14332e 100644 --- a/src/toolkit/theme/recipes/close-button.recipe.ts +++ b/src/toolkit/theme/recipes/close-button.recipe.ts @@ -12,6 +12,7 @@ export const recipe = defineRecipe({ opacity: 'control.disabled', }, minWidth: 'auto', + '--close-button-icon-size': 'sizes.5', }, variants: { visual: { diff --git a/src/toolkit/theme/recipes/skeleton.recipe.ts b/src/toolkit/theme/recipes/skeleton.recipe.ts index 79aa48d73aa..ed5a09535e4 100644 --- a/src/toolkit/theme/recipes/skeleton.recipe.ts +++ b/src/toolkit/theme/recipes/skeleton.recipe.ts @@ -26,6 +26,9 @@ export const recipe = defineRecipe({ '& > *': { visibility: 'hidden', }, + _firstLine: { + color: 'transparent', + }, }, }, variant: { diff --git a/src/toolkit/theme/recipes/table.recipe.ts b/src/toolkit/theme/recipes/table.recipe.ts index a663057f759..0212ec3de08 100644 --- a/src/toolkit/theme/recipes/table.recipe.ts +++ b/src/toolkit/theme/recipes/table.recipe.ts @@ -67,7 +67,7 @@ export const recipe = defineSlotRecipe({ }, cell: { px: '6px', - py: { base: 2, lg: 4 }, + py: { base: 2, lg: 3 }, _first: { pl: 3, }, diff --git a/src/toolkit/theme/recipes/tabs.recipe.ts b/src/toolkit/theme/recipes/tabs.recipe.ts index 5ff2dcbaec2..9ccf08df92a 100644 --- a/src/toolkit/theme/recipes/tabs.recipe.ts +++ b/src/toolkit/theme/recipes/tabs.recipe.ts @@ -193,7 +193,7 @@ export const recipe = defineSlotRecipe({ _selected: { color: 'selected.control.text', bg: 'selected.control.bg', - borderColor: 'selected.control.bg', + borderColor: 'transparent', _hover: { color: 'selected.control.text', }, diff --git a/src/toolkit/theme/recipes/tag.recipe.ts b/src/toolkit/theme/recipes/tag.recipe.ts index fd4b8f460cc..73c36a5751e 100644 --- a/src/toolkit/theme/recipes/tag.recipe.ts +++ b/src/toolkit/theme/recipes/tag.recipe.ts @@ -123,22 +123,26 @@ export const recipe = defineSlotRecipe({ root: { bgColor: 'tag.root.filter.bg', }, + closeTrigger: { + '--close-button-icon-size': '12px', + }, }, select: { root: { cursor: 'pointer', - bgColor: 'tag.root.select.bg', - color: 'tag.root.select.fg', + bgColor: 'transparent', + color: 'text.primary', + border: '2px solid', + borderColor: 'tag.root.select.border', _hover: { color: 'hover', - opacity: 0.76, }, _selected: { - bgColor: 'selected.option.bg', - color: 'whiteAlpha.800', + bgColor: 'selected.control.bg', + color: 'selected.control.text', + borderColor: 'transparent', _hover: { - color: 'whiteAlpha.800', - opacity: 0.76, + color: 'selected.control.text', }, }, }, diff --git a/src/toolkit/utils/texts.ts b/src/toolkit/utils/texts.ts new file mode 100644 index 00000000000..38252de6e5b --- /dev/null +++ b/src/toolkit/utils/texts.ts @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: LicenseRef-Blockscout + +export function shortenString(string: string | null, charNumber: number | undefined = 8) { + if (!string) { + return ''; + } + + if (string.length <= charNumber) { + return string; + } + + const tailLength = charNumber < 8 ? 2 : 4; + + return string.slice(0, charNumber - tailLength) + '...' + string.slice(-tailLength); +} diff --git a/tools/cli/checkout.spec.ts b/tools/cli/checkout.spec.ts new file mode 100644 index 00000000000..c0773bee6b0 --- /dev/null +++ b/tools/cli/checkout.spec.ts @@ -0,0 +1,38 @@ +import { execFileSync } from 'child_process'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import { resolveCheckoutRoot, resolveMainCheckout } from './checkout'; + +let tmp = ''; + +afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; +}); + +function git(cwd: string, ...args: Array<string>): void { + execFileSync('git', [ '-c', 'user.email=t@t.t', '-c', 'user.name=t', ...args ], { cwd, stdio: 'ignore' }); +} + +describe('resolveMainCheckout', () => { + it('is the main checkout from both the main checkout and one of its worktrees', () => { + tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cli-checkout-'))); + const main = path.join(tmp, 'main'); + fs.mkdirSync(main); + git(main, 'init', '-b', 'main'); + fs.writeFileSync(path.join(main, 'a.txt'), 'a\n'); + git(main, 'add', '.'); + git(main, 'commit', '-m', 'a'); + const worktree = path.join(tmp, 'wt'); + git(main, 'worktree', 'add', '-b', 'feature', worktree); + + expect(resolveMainCheckout(main)).toBe(main); + expect(resolveMainCheckout(worktree)).toBe(main); + expect(resolveCheckoutRoot(main)).toBe(main); + expect(resolveCheckoutRoot(worktree)).toBe(worktree); + }); +}); diff --git a/tools/cli/checkout.ts b/tools/cli/checkout.ts new file mode 100644 index 00000000000..bb6b98a2f9d --- /dev/null +++ b/tools/cli/checkout.ts @@ -0,0 +1,14 @@ +import { execFileSync } from 'child_process'; +import path from 'path'; + +// `--git-common-dir` is the one answer that is the same from a worktree and from the main checkout; +// git may print it relative to `cwd`. +export function resolveMainCheckout(cwd: string): string { + const commonDir = execFileSync('git', [ 'rev-parse', '--git-common-dir' ], { cwd, encoding: 'utf8' }).trim(); + return path.dirname(path.resolve(cwd, commonDir)); +} + +// The root of the checkout `cwd` is in: a worktree's own root, where its tracked files live. +export function resolveCheckoutRoot(cwd: string): string { + return execFileSync('git', [ 'rev-parse', '--show-toplevel' ], { cwd, encoding: 'utf8' }).trim(); +} diff --git a/tools/cli/exec.ts b/tools/cli/exec.ts new file mode 100644 index 00000000000..8bb6ff10ace --- /dev/null +++ b/tools/cli/exec.ts @@ -0,0 +1,3 @@ +// Node caps a child process's captured stdout at 1MB by default; a large diff or coverage report +// overruns that and throws, so every tool that shells out reads with this limit. +export const EXEC_MAX_BUFFER = 64 * 1024 * 1024; diff --git a/tools/cli/flags.spec.ts b/tools/cli/flags.spec.ts new file mode 100644 index 00000000000..4735609a067 --- /dev/null +++ b/tools/cli/flags.spec.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from 'vitest'; + +import type { FlagSpec, UnknownTokenPolicy } from './flags'; +import { parseArgs } from './flags'; + +interface TestOptions { + verbose: boolean; + base: string | undefined; + changed: boolean; + changedRef: string | undefined; +} + +const USAGE = 'Usage: test-tool [--verbose] [--base <ref>] [--changed[=<ref>]]'; +const REJECT: UnknownTokenPolicy = { kind: 'reject', usage: USAGE }; +const PASSTHROUGH: UnknownTokenPolicy = { kind: 'passthrough' }; + +const FLAGS: ReadonlyMap<string, FlagSpec<TestOptions>> = new Map<string, FlagSpec<TestOptions>>([ + [ '--verbose', { kind: 'switch', apply: (options) => { + options.verbose = true; + } } ], + [ '--base', { kind: 'value', apply: (options, value) => { + options.base = value; + } } ], + [ '--changed', { kind: 'optional', apply: (options, value) => { + options.changed = true; + options.changedRef = value; + } } ], +]); + +function initialOptions(): TestOptions { + return { verbose: false, base: undefined, changed: false, changedRef: undefined }; +} + +function parse(argv: ReadonlyArray<string>, policy: UnknownTokenPolicy = REJECT) { + return parseArgs(argv, FLAGS, initialOptions(), policy); +} + +describe('parseArgs', () => { + it('returns the initial options untouched and no rest for an empty argv', () => { + expect(parse([])).toEqual({ options: initialOptions(), rest: [] }); + }); + + it('mutates and returns the options object it was given', () => { + const options = initialOptions(); + expect(parseArgs([ '--verbose' ], FLAGS, options, REJECT).options).toBe(options); + expect(options.verbose).toBe(true); + }); + + it('applies a switch flag', () => { + expect(parse([ '--verbose' ]).options.verbose).toBe(true); + }); + + it('rejects a value passed to a switch flag', () => { + expect(() => parse([ '--verbose=yes' ])).toThrow('--verbose takes no value'); + expect(() => parse([ '--verbose=yes' ], PASSTHROUGH)).toThrow('--verbose takes no value'); + }); + + it('reads a value flag in both the separate-token and inline forms', () => { + expect(parse([ '--base', 'upstream/main' ])).toEqual({ options: { ...initialOptions(), base: 'upstream/main' }, rest: [] }); + expect(parse([ '--base=upstream/main' ])).toEqual({ options: { ...initialOptions(), base: 'upstream/main' }, rest: [] }); + }); + + it('splits an inline value at the first equals sign only', () => { + expect(parse([ '--base=a=b' ]).options.base).toBe('a=b'); + }); + + it('keeps an empty inline value rather than taking the following token', () => { + expect(parse([ '--base=', 'src/a.ts' ])).toEqual({ options: { ...initialOptions(), base: '' }, rest: [ 'src/a.ts' ] }); + }); + + // Swallowing the token after --base=<ref> would drop a positional, and not swallowing it after a + // bare --base would turn the ref itself into one. + it('consumes the token after a value flag only when the value is not inline', () => { + expect(parse([ '--base', 'upstream/main', 'src/a.ts' ]).rest).toEqual([ 'src/a.ts' ]); + expect(parse([ '--base=upstream/main', 'src/a.ts' ]).rest).toEqual([ 'src/a.ts' ]); + }); + + it('lets a value flag take the following token even when it looks like a flag', () => { + expect(parse([ '--base', '--verbose' ])).toEqual({ options: { ...initialOptions(), base: '--verbose' }, rest: [] }); + }); + + it('rejects a value flag with no value', () => { + expect(() => parse([ '--base' ])).toThrow('Missing value for --base'); + }); + + it('reads an optional flag bare or with an inline value', () => { + expect(parse([ '--changed' ]).options).toMatchObject({ changed: true, changedRef: undefined }); + expect(parse([ '--changed=upstream/main' ]).options).toMatchObject({ changed: true, changedRef: 'upstream/main' }); + }); + + // The CI invocation: a bare --changed is followed by another flag or a positional, never its ref. + it('never lets an optional flag swallow the following token', () => { + expect(parse([ '--changed', 'upstream/main' ])).toEqual({ + options: { ...initialOptions(), changed: true, changedRef: undefined }, + rest: [ 'upstream/main' ], + }); + expect(parse([ '--changed', '--verbose' ]).options).toMatchObject({ changed: true, changedRef: undefined, verbose: true }); + }); + + it('collects positionals into rest, in order, under either policy', () => { + expect(parse([ 'src/a.ts', '--verbose', 'src/b.ts' ]).rest).toEqual([ 'src/a.ts', 'src/b.ts' ]); + expect(parse([ 'src/a.ts', '--verbose', 'src/b.ts' ], PASSTHROUGH).rest).toEqual([ 'src/a.ts', 'src/b.ts' ]); + }); + + it('applies the last of two conflicting values', () => { + expect(parse([ '--base', 'one', '--base=two' ]).options.base).toBe('two'); + }); + + describe('with the reject policy', () => { + it('throws on an unknown flag, with the usage text attached', () => { + expect(() => parse([ '--nope' ])).toThrow(`Unknown flag: --nope\n${ USAGE }`); + }); + + it('names only the flag part of an unknown inline flag', () => { + expect(() => parse([ '--nope=1' ])).toThrow('Unknown flag: --nope\n'); + }); + + // A near-miss of a real flag is unknown too, not a loose prefix match. + it('does not prefix-match a known flag', () => { + expect(() => parse([ '--verbosely' ])).toThrow('Unknown flag: --verbosely'); + expect(() => parse([ '--bas=main' ])).toThrow('Unknown flag: --bas'); + }); + }); + + describe('with the passthrough policy', () => { + it('collects unknown flags and positionals into rest in argv order, applying the known ones', () => { + const argv = [ 'a.pw.tsx', '--project=default', '--verbose', '-g', 'two words', '--changed', '--update-snapshots', 'b.pw.tsx' ]; + + expect(parse(argv, PASSTHROUGH)).toEqual({ + options: { ...initialOptions(), verbose: true, changed: true }, + rest: [ 'a.pw.tsx', '--project=default', '-g', 'two words', '--update-snapshots', 'b.pw.tsx' ], + }); + }); + + it('passes an unknown flag through verbatim, inline value included', () => { + expect(parse([ '--shard=1/3' ], PASSTHROUGH).rest).toEqual([ '--shard=1/3' ]); + }); + + it('still errors on a known flag used wrongly', () => { + expect(() => parse([ '--base' ], PASSTHROUGH)).toThrow('Missing value for --base'); + }); + }); +}); diff --git a/tools/cli/flags.ts b/tools/cli/flags.ts new file mode 100644 index 00000000000..cd3c6c11bdc --- /dev/null +++ b/tools/cli/flags.ts @@ -0,0 +1,90 @@ +// One flag's behaviour, discriminated by how it takes its value: +// 'switch' — no value at all (--verbose) +// 'value' — required, from `--flag=value` or the following token (--base) +// 'optional' — inline-only and optional (--changed[=<ref>]); a bare --changed keeps the default +// ref, and the flag must never swallow the following token, which in CI is another flag +export type FlagSpec<Options> = + { readonly kind: 'switch'; readonly apply: (options: Options) => void } | + { readonly kind: 'value'; readonly apply: (options: Options, value: string) => void } | + { readonly kind: 'optional'; readonly apply: (options: Options, value: string | undefined) => void }; + +// What happens to a flag the table does not know. A tool that owns its whole surface rejects it, with +// its usage text attached; a tool that wraps another CLI passes it through for that CLI to judge. +export type UnknownTokenPolicy = + { readonly kind: 'reject'; readonly usage: string } | + { readonly kind: 'passthrough' }; + +export interface ParsedArgs<Options> { + readonly options: Options; + // Positionals under either policy, plus unknown flags under 'passthrough', in argv order. An unknown + // flag's value is a separate token the parser cannot tell apart from a positional, so keeping the + // order is what hands `--project default` to the wrapped CLI intact. + readonly rest: Array<string>; +} + +// Split a token into its flag name and inline value: `--flag=value` splits at the first `=`, a bare +// `--flag` has no inline value. +function splitFlag(arg: string): { readonly name: string; readonly inline: string | undefined } { + const equals = arg.indexOf('='); + if (equals === -1) return { name: arg, inline: undefined }; + return { name: arg.slice(0, equals), inline: arg.slice(equals + 1) }; +} + +// Apply one argv token, returning how many tokens it consumed — 2 when a value flag took the following +// token, 1 otherwise. This is the validation half: it resolves the value form, applies the unknown-token +// policy, and rejects a missing or unwanted value. `parseArgs` below is the reading half and does +// nothing but walk the cursor. +function applyArg<Options>( + arg: string, + next: string | undefined, + flags: ReadonlyMap<string, FlagSpec<Options>>, + parsed: ParsedArgs<Options>, + policy: UnknownTokenPolicy, +): number { + if (!arg.startsWith('-')) { + parsed.rest.push(arg); + return 1; + } + + const { name, inline } = splitFlag(arg); + const spec = flags.get(name); + if (spec === undefined) { + if (policy.kind === 'reject') throw new Error(`Unknown flag: ${ name }\n${ policy.usage }`); + parsed.rest.push(arg); + return 1; + } + + if (spec.kind === 'optional') { + spec.apply(parsed.options, inline); + return 1; + } + if (spec.kind === 'switch') { + if (inline !== undefined) throw new Error(`${ name } takes no value`); + spec.apply(parsed.options); + return 1; + } + + const value = inline ?? next; + if (value === undefined) throw new Error(`Missing value for ${ name }`); + spec.apply(parsed.options, value); + return inline === undefined ? 2 : 1; +} + +// The flag surface is a lookup table rather than an if/else chain, which removes the prefix-shadowing +// hazard a `startsWith` chain has (`--max-cognitive` matching `--max-cognitive-jsx` unless the arms are +// ordered just so). `options` is mutated in place. +export function parseArgs<Options>( + argv: ReadonlyArray<string>, + flags: ReadonlyMap<string, FlagSpec<Options>>, + options: Options, + policy: UnknownTokenPolicy, +): ParsedArgs<Options> { + const parsed: ParsedArgs<Options> = { options, rest: [] }; + + let index = 0; + while (index < argv.length) { + index += applyArg(argv[index], argv[index + 1], flags, parsed, policy); + } + + return parsed; +} diff --git a/tools/code-complexity/CONTEXT.md b/tools/code-complexity/CONTEXT.md new file mode 100644 index 00000000000..41e1aaee563 --- /dev/null +++ b/tools/code-complexity/CONTEXT.md @@ -0,0 +1,94 @@ +# Code complexity — context + +A code-quality gate that flags code which is either hard to read *or* both complex and +under-tested. Two independent gates run: + +- **Cognitive Complexity (CC)** — the readability gate. "Should a human decompose this?" Capped per + function class. +- **Change Risk Anti-Patterns (CRAP)** — the under-testedness gate. "Complex and untested?" functions, fed by + *cyclomatic* complexity joined with coverage. + +## Where to look + +| Question | Answer lives in | +| --- | --- | +| The gate failed. What do I change? | the next section | +| Why is this function's score *that* number? | `./docs/MODEL.md` | +| Which files and functions get gated at all? | `./docs/MODEL.md` | +| How do I run it? What feeds the coverage half? | `pnpm test:code-complexity --help` or `./docs/RUNNING.md` for more details | +| Can I move a cap? | short answer: no; `./docs/CALIBRATION.md` | +| Why is the counting model like this? | `./adr/` | +| Which file implements what? | the file map at the bottom | + +## The gate failed — what now + +Reproduce it on just your file: + +```bash +pnpm test:code-complexity path/to/your/file.ts +``` + +The `BROKE` column names which cap you crossed. In CI you also get an inline annotation on the diff: + +``` +classify: cognitive 21 > 20 [top: if +10 (L11), switch +5 (L6), if +2 (L4); + deepest nesting 3 at L11, flattening saves ~5] +``` + +**`COG` — decompose it.** The annotation is built to be actionable: it names the increment sites that +cost the most, the deepest nesting pocket, and what flattening that pocket by one level would save. +Above, a single `if` at depth 3 accounts for 10 of the 21 — extract it, invert it into an early +return, or lift the `switch` out from around it. Nesting is charged quadratically, so the deepest +level is where the points are and pulling it out is almost always the cheapest win. + +**`CRAP` — add a test.** CRAP joins cyclomatic complexity with coverage, and coverage is the only +lever. Simplifying the function lowers its *cognitive* score, not its CRAP. A `behavior` function +with no co-located spec reads 0%, accurately — no unit test exercises it. + +**Raising the cap is not the fix.**. + +## File map + +Four directories, one per pipeline stage, and files at the root that tie them together. Specs +sit next to what they test, and each file's header comment carries its own local detail. + +Measuring and judging are separate jobs. `select/`, `measure/` and `coverage/` compute the numbers +and never see a cap; the caps enter once, at `./analyze.ts`, which stamps a verdict onto each row. +The table, the exit code and the GitHub annotations all read that verdict rather than re-deriving +it. + +**Root** — the CLI, the caps, and the join. + +- `./index.ts` — parse the flags, pick the selection, orchestrate, set the exit code + (`./docs/RUNNING.md`); the flag mechanics are shared with the sibling tools in `../cli/flags.ts` +- `./config.ts` — the three caps, so a local run and a CI run gate identically + (`./docs/CALIBRATION.md`) +- `./analyze.ts` — complexity × coverage → one row per function, each stamped with its verdict +- `./run.sh` — compile-on-run wrapper; callable from any directory, but git reads the one you call + it from (`./docs/RUNNING.md`) + +**`select/`** — which files, and which lines inside them. + +- `./select/scope.ts` — the in-scope rule, and why each excluded category is out +- `./select/diff.ts` — git plumbing: changed files, changed line ranges, merge-base + (`./docs/RUNNING.md`) + +**`measure/`** — one AST walk, no caps in sight. + +- `./measure/complexity.ts` — cognitive, cyclomatic, the function class and the contributions + (`./docs/MODEL.md`) +- `./measure/jsx.ts` — file-level JSX detection, which decides who needs coverage generated + (`./docs/RUNNING.md`) +- `./measure/crap.ts` — the CRAP formula, six lines of it (`./docs/MODEL.md`) + +**`coverage/`** — the CRAP half's input. + +- `./coverage/generate.ts` — run vitest scoped to the selection, into a throwaway dir + (`./docs/RUNNING.md`) +- `./coverage/read.ts` — parse `coverage-final.json`, derive per-function line coverage + (`./docs/MODEL.md`) + +**`render/`** — rows out. + +- `./render/report.ts` — the score table, the sort order, the offender test (`./docs/RUNNING.md`) +- `./render/github.ts` — `::error` annotations and the step summary (`./docs/RUNNING.md`) diff --git a/tools/code-complexity/adr/0001-optional-chaining-excluded-from-complexity.md b/tools/code-complexity/adr/0001-optional-chaining-excluded-from-complexity.md new file mode 100644 index 00000000000..0d627406d92 --- /dev/null +++ b/tools/code-complexity/adr/0001-optional-chaining-excluded-from-complexity.md @@ -0,0 +1,52 @@ +# 0001 — optional chaining `?.` is excluded from cyclomatic complexity + +| | | +| --- | --- | +| Status | accepted | +| Date | 2026-08-27 | +| Deciders | @tom2drum | +| Supersedes | — | + +## Decision + +This gate does **not** count optional chaining `?.` +toward a function's cyclomatic complexity. Every other construct matches ESLint's `complexity` +rule (`if`/`else if`, loops, `case`, `catch`, ternary, `&&`/`||`/`??`); `?.` is the single +deliberate divergence. + +The textbook cyclomatic definition, and ESLint's rule, treat each `?.` as a branch because it +short-circuits. This gate does not. + +## Why + +**A `?.` is not a path a test must cover.** Cyclomatic complexity is only useful here as a proxy +for the number of independent paths through a function — roughly, the test cases needed to exercise +its branches — because CRAP (`c²·(1 − cov)³ + c`) multiplies that count against how untested the +code is. TypeScript already proves the nullability at every `?.` site at compile time; a unit test +adds nothing there. Counting `?.` therefore measures null-safety verbosity, not the branching risk +the gate exists to flag. + +**It was the largest source of tail inflation.** Measured across all in-scope `src/**` functions +while calibrating the gate (issue #3663), `?.` was by a wide margin the biggest single contributor +to counted branch points, and dropping it materially lowered the top of the complexity distribution. +The inflation clustered on JSX components stuffed with optional prop reads — object literals and +JSX with many defensive field accesses and no control flow — not on genuinely branchy logic, so it +was noise for exactly the code the gate is meant to distinguish. The figures are in that work's PR. + +**The "match ESLint" argument does not apply.** The counting was originally framed as matching +ESLint's `complexity` rule, but the repo does not configure or run that rule (`eslint.config.mjs` +has no `complexity` entry) and has no plan to. With no live rule to agree with, aligning to its +`?.` behavior buys nothing and costs the distortion above. The spec explicitly left this open to be +settled at calibration. + +## Consequences + +- The gate is a **conscious divergence** from ESLint's cyclomatic definition. A future reader — or a + PR trying to align the tool with a standard complexity implementation — will see the gap and may + try to "fix" it back; this record is what says not to. The counting convention and this caveat + live in `../docs/MODEL.md`. +- The gate's calibrated thresholds (`../config.ts`) were set from the distribution *with `?.` already + dropped*. Re-introducing `?.` counting would silently make the caps far more aggressive; the two + decisions are coupled, and changing one demands recalibrating the other. +- Reversing is a one-case change in `countsAsBranch` (`../measure/complexity.ts`) plus its spec — cheap in + code, but it invalidates the calibration, so it is an ADR-level decision, not a tweak. diff --git a/tools/code-complexity/adr/0002-quadratic-nesting-and-null-coalescing-in-cognitive-complexity.md b/tools/code-complexity/adr/0002-quadratic-nesting-and-null-coalescing-in-cognitive-complexity.md new file mode 100644 index 00000000000..c07f3b4ee24 --- /dev/null +++ b/tools/code-complexity/adr/0002-quadratic-nesting-and-null-coalescing-in-cognitive-complexity.md @@ -0,0 +1,70 @@ +# 0002 — cognitive complexity penalises nesting quadratically and ignores `??` + +| | | +| --- | --- | +| Status | accepted | +| Date | 2026-08-31 | +| Deciders | @tom2drum | +| Supersedes | — | + +## Decision + +This gate's Cognitive Complexity (CC) score diverges from the SonarSource model +in two coupled ways: + +1. **Nesting is charged `1 + n²`, not `1 + n`** (n = 0-based depth). Every structural increment that + carries a nesting penalty — `if`, ternary, the loops, `catch`, `switch` — pays the quadratic + price. `else`/`else if` and boolean runs stay flat `+1`, and `switch` is still one increment + regardless of case count. +2. **Null-coalescing `??` and `??=` add nothing.** They are dropped from the boolean-sequence + operator set. `&&` and `||` still cost `+1` per run. + +The two are one decision: the caps in `../config.ts` are calibrated against this exact model. + +## Why + +**The gate's thesis is "forgive breadth, punish nesting" — the linear model cannot express it.** +The SonarSource white paper counts breadth: every `if`/ternary/loop/`catch` is `+1` whether flat or +not, with nesting layered on as an *additional* per-level increment. Under that model the repo's +worst flat-breadth hooks scored 18 while its deep-nested `switch`-tree hook — the example the parent +spec named as a required trip — scored 15. They **overlap**, so no cap separates them: tight enough +to catch the nesting also catches the breadth. That was the false-positive problem the first-pass +caps shipped with. + +**Quadratic nesting is a surgical surcharge on the deep tail.** Consecutive differences are the odd +numbers (1, 3, 5, …): each level costs 2 more than the last. It is *identical* to linear at depths 0 +and 1 and diverges only from the third level in, so flat and shallow code — the bulk of the +distribution, whose percentiles do not move — is untouched while genuinely-nested code accelerates +away. That separation is what a single cap needs. On the full repo it lifts 7 of the 8 functions +firing at the recalibrated behavior cap of 20, including the nested anchor above (15 → 23, tripping +with margin), while leaving the flat-breadth band below the cap. + +**`??` was a spec-conformance bug, not a divergence.** The SonarSource paper explicitly ignores +null-coalescing as readable shorthand, in the same class as `?.`. Counting it measured defaulting +verbosity: at calibration the worst case was an API-model mapper — a flat wall of `x ?? null` field +assignments with no control flow — scoring 14, as much as genuinely branchy logic. Dropping it takes +that to 0. This is ADR 0001's reasoning +(`?.` is null-safety verbosity, not a path a reader or a test must follow) extended from cyclomatic +to cognitive, and applied to the operator the paper already excluded. + +**Right-leaning ternary-chain flattening was considered and rejected.** SonarSource flattens +`a ? x : b ? y : z` so the chain reads as one decision ladder. An eslint rule already bans nested +ternaries in this repo, so any nested ternary that survives review is genuine nesting and should be +priced as such. + +## Consequences + +- **CC here is not the SonarSource number, and is not expected to be.** Comparing against + `eslint-plugin-sonarjs` will show us reading higher on anything nested past depth 1. That is by + design; oracle parity is not a regression test. The counting conventions and the full list of + divergences live in `../docs/MODEL.md`. +- **The model and the caps are one decision.** `DEFAULT_MAX_COGNITIVE_BEHAVIOR` / `_JSX` were set + from the full-repo distribution *under this model*. Reverting either change — re-counting `??`, or + going back to linear nesting — silently makes the caps wrong (far looser, since scores collapse), + so a change to the increment model demands a fresh full-repo recalibration in the same PR. +- The behavior cap sits at a natural gap in the resulting distribution rather than being pinned to + one trip example: the flat-breadth band tops out at 20 and the nested band starts at 21. That gap + exists *because* of the quadratic penalty; it does not survive a return to linear. +- Reversing is small in code — `nestingIncrement` in `../measure/complexity.ts` and one entry in + `SEQUENCE_OPERATORS` — which is exactly why it needs this record: it looks like a two-line + simplification and is not. diff --git a/tools/code-complexity/analyze.spec.ts b/tools/code-complexity/analyze.spec.ts new file mode 100644 index 00000000000..d81ec0dea56 --- /dev/null +++ b/tools/code-complexity/analyze.spec.ts @@ -0,0 +1,142 @@ +import { describe, it, expect } from 'vitest'; + +import { buildFileRows } from './analyze'; +import type { BuildOptions } from './analyze'; +import type { CoverageData, LineHits } from './coverage/read'; + +const THRESHOLDS = { maxCognitiveJsx: 20, maxCognitiveBehavior: 20, maxCrap: 30 }; + +// Build BuildOptions with sensible defaults (diff-style 0%-for-missing, gate all), overridable +// per test. +function opts(overrides: Partial<BuildOptions> = {}): BuildOptions { + return { + thresholds: THRESHOLDS, + gate: () => true, + missingCoverageIsZero: true, + ...overrides, + }; +} + +// A stub coverage report: given line hits keyed by relative path, hand them back on lookup. +function coverageStub(byPath: Record<string, ReadonlyArray<[ number, number ]>>): CoverageData { + return { + lineHitsFor(relativePath: string): LineHits | undefined { + const entry = byPath[relativePath]; + return entry ? new Map(entry) : undefined; + }, + }; +} + +// A wide-but-shallow body: cyclomatic 8 (base 1 + 7 `&&`), but cognitive 1 — a single boolean run. +// It drives the CRAP tests (CRAP is fed by cyclomatic) and confirms flat logic scores near-zero +// cognitively. On one line so coverage maps to it. No JSX -> `behavior`. +const WIDE_LOGIC = 'export function f(a: any) { return a && a && a && a && a && a && a && a; }'; + +// A genuinely-nested body: three nested ifs -> cognitive 6 (1 + 2 + 3), cyclomatic 4. No JSX -> +// `behavior`; the JSX variant renders and so classifies `jsx`. +const NESTED_LOGIC = 'export function g(a: any, b: any, c: any) { if (a) { if (b) { if (c) { return 1; } } } return 0; }'; +const NESTED_JSX = 'export const C = (a: any, b: any, c: any) => { if (a) { if (b) { if (c) { return <i/>; } } } return <b/>; };'; + +describe('buildFileRows — CRAP gate on behavior functions', () => { + it('computes CRAP from cyclomatic complexity and joined coverage', () => { + // cyclomatic 8, coverage 0 -> CRAP 8² + 8 = 72, over the cap of 30 + const rows = buildFileRows('src/f.ts', WIDE_LOGIC, coverageStub({ 'src/f.ts': [ [ 1, 0 ] ] }), opts()); + expect(rows).toHaveLength(1); + expect(rows[0].kind).toBe('behavior'); + expect(rows[0].complexity).toBe(8); + expect(rows[0].cognitive).toBe(1); // wide-but-shallow: a single && run + expect(rows[0].coverage).toBe(0); + expect(rows[0].crap).toBe(72); + expect(rows[0].brokeCrap).toBe(true); + expect(rows[0].brokeCognitive).toBe(false); // cognitive 1 is far under the behavior cap + }); + + it('lowers CRAP below the cap when the function is well covered', () => { + // the whole function sits on line 1; mark it executed -> coverage 1 -> CRAP = cyclomatic 8 + const rows = buildFileRows('src/f.ts', WIDE_LOGIC, coverageStub({ 'src/f.ts': [ [ 1, 3 ] ] }), opts()); + expect(rows[0].coverage).toBe(1); + expect(rows[0].crap).toBe(8); + expect(rows[0].brokeCrap).toBe(false); + }); + + it('scores a behavior function the same way whatever the file extension', () => { + // Living in a .tsx file does not make a JSX-less function `jsx`: classification is per-function. + const rows = buildFileRows('src/C.tsx', WIDE_LOGIC, coverageStub({ 'src/C.tsx': [ [ 1, 0 ] ] }), opts()); + expect(rows[0].kind).toBe('behavior'); + expect(rows[0].crap).toBe(72); + expect(rows[0].brokeCrap).toBe(true); + }); +}); + +describe('buildFileRows — behavior function absent from the coverage report', () => { + const absent = coverageStub({ 'src/other.ts': [] }); + + it('scores 0% and flags it when missing means untested (generated/CI coverage)', () => { + const rows = buildFileRows('src/missing.ts', WIDE_LOGIC, absent, opts({ missingCoverageIsZero: true })); + expect(rows[0].coverage).toBe(0); + expect(rows[0].crap).toBe(72); + expect(rows[0].brokeCrap).toBe(true); + }); + + it('reports no coverage data (— / no CRAP) when missing means "no data" (user --coverage-file)', () => { + const rows = buildFileRows('src/missing.ts', WIDE_LOGIC, absent, opts({ missingCoverageIsZero: false })); + expect(rows[0].coverage).toBeNull(); + expect(rows[0].crap).toBeNull(); + expect(rows[0].brokeCrap).toBe(false); + }); +}); + +describe('buildFileRows — jsx functions carry the cognitive cap only', () => { + it('never scores CRAP on a jsx function, even with coverage present', () => { + const rows = buildFileRows('src/C.tsx', NESTED_JSX, coverageStub({ 'src/C.tsx': [ [ 1, 0 ] ] }), opts()); + expect(rows[0].kind).toBe('jsx'); + expect(rows[0].cognitive).toBe(8); + expect(rows[0].coverage).toBeNull(); + expect(rows[0].crap).toBeNull(); + expect(rows[0].brokeCrap).toBe(false); + }); + + it('still breaks the cognitive gate when over the jsx cap', () => { + const thresholds = { maxCognitiveJsx: 5, maxCognitiveBehavior: 20, maxCrap: 30 }; + const rows = buildFileRows('src/C.tsx', NESTED_JSX, coverageStub({}), opts({ thresholds })); + expect(rows[0].brokeCognitive).toBe(true); // cognitive 8 > jsx cap 5 + }); +}); + +describe('buildFileRows — the two cognitive caps gate by class', () => { + const thresholds = { maxCognitiveJsx: 20, maxCognitiveBehavior: 5, maxCrap: 30 }; + + it('gates a jsx function against the jsx cap', () => { + // cognitive 8: under the jsx cap of 20, so not flagged despite exceeding the behavior cap. + const rows = buildFileRows('src/C.tsx', NESTED_JSX, null, opts({ thresholds })); + expect(rows[0].kind).toBe('jsx'); + expect(rows[0].brokeCognitive).toBe(false); + }); + + it('gates a behavior function against the behavior cap', () => { + // same cognitive 8: over the behavior cap of 5, so flagged. + const rows = buildFileRows('src/f.ts', NESTED_LOGIC, null, opts({ thresholds })); + expect(rows[0].kind).toBe('behavior'); + expect(rows[0].brokeCognitive).toBe(true); + }); +}); + +describe('buildFileRows — no coverage report', () => { + it('runs the cognitive gate alone, leaving coverage/CRAP null', () => { + const rows = buildFileRows('src/f.ts', NESTED_LOGIC, null, opts({ thresholds: { maxCognitiveJsx: 20, maxCognitiveBehavior: 5, maxCrap: 30 } })); + expect(rows[0].coverage).toBeNull(); + expect(rows[0].crap).toBeNull(); + expect(rows[0].brokeCognitive).toBe(true); + expect(rows[0].brokeCrap).toBe(false); + }); +}); + +describe('buildFileRows — gate scoping', () => { + it('never flags a function the gate excludes, even over threshold', () => { + const thresholds = { maxCognitiveJsx: 5, maxCognitiveBehavior: 5, maxCrap: 30 }; + const rows = buildFileRows('src/f.ts', NESTED_LOGIC, coverageStub({ 'src/f.ts': [ [ 1, 0 ] ] }), opts({ gate: () => false, thresholds })); + expect(rows[0].cognitive).toBe(8); // still reported... + expect(rows[0].brokeCognitive).toBe(false); // ...but not flagged + expect(rows[0].brokeCrap).toBe(false); + }); +}); diff --git a/tools/code-complexity/analyze.ts b/tools/code-complexity/analyze.ts new file mode 100644 index 00000000000..dd84165fee1 --- /dev/null +++ b/tools/code-complexity/analyze.ts @@ -0,0 +1,64 @@ +import type { CoverageData } from './coverage/read'; +import { functionLineCoverage } from './coverage/read'; +import { computeFunctionComplexities } from './measure/complexity'; +import type { FunctionComplexity } from './measure/complexity'; +import { crapScore } from './measure/crap'; +import type { FunctionKind, ReportRow, Thresholds } from './render/report'; +import { maxCognitiveFor } from './render/report'; + +export type Gate = (fn: Pick<FunctionComplexity, 'startLine' | 'endLine'>) => boolean; + +export interface BuildOptions { + readonly thresholds: Thresholds; + readonly gate: Gate; + // How to score a `behavior` function absent from the coverage report: `true` reads absence as + // "no spec executed it" (0%), `false` as "no data" (`—`). Which mode passes which, and why: + // ./docs/MODEL.md. + readonly missingCoverageIsZero: boolean; +} + +// Joins the pieces into report rows for one file's source, applying both gates per function. +// `gate` decides which functions the thresholds apply to — focused/full gate all functions, diff +// gates only the ones a changed line falls within. Kept pure (no fs/git) so both gates are +// unit-testable without a working tree. +export function buildFileRows( + file: string, + source: string, + coverage: CoverageData | null, + options: BuildOptions, +): Array<ReportRow> { + const { thresholds, gate, missingCoverageIsZero } = options; + const functions = computeFunctionComplexities(source, file); + + const lineHits = coverage !== null ? coverage.lineHitsFor(file) : undefined; + + // CRAP applies only to `behavior` functions, and only when coverage data exists at all. + const coverageOf = (fn: FunctionComplexity): number | null => { + if (fn.containsJsx || coverage === null) return null; + if (lineHits) return functionLineCoverage(lineHits, fn.startLine, fn.endLine); + // File absent from the report: 0% only where a missing entry means "untested" (diff/CI). + return missingCoverageIsZero ? 0 : null; + }; + + return functions.map((fn) => { + const gated = gate(fn); + const kind: FunctionKind = fn.containsJsx ? 'jsx' : 'behavior'; + + const coverageFraction = coverageOf(fn); + const crap = coverageFraction === null ? null : crapScore(fn.complexity, coverageFraction); + + return { + file, + line: fn.startLine, + name: fn.name, + kind, + complexity: fn.complexity, + cognitive: fn.cognitive, + contributions: fn.contributions, + coverage: coverageFraction, + crap, + brokeCognitive: gated && fn.cognitive > maxCognitiveFor(kind, thresholds), + brokeCrap: gated && crap !== null && crap > thresholds.maxCrap, + }; + }); +} diff --git a/tools/code-complexity/config.ts b/tools/code-complexity/config.ts new file mode 100644 index 00000000000..d5dddc6d1ce --- /dev/null +++ b/tools/code-complexity/config.ts @@ -0,0 +1,6 @@ +export const DEFAULT_MAX_COGNITIVE_JSX = 25; +export const DEFAULT_MAX_COGNITIVE_BEHAVIOR = 20; + +export const DEFAULT_MAX_CRAP = 80; + +export const DEFAULT_BASE_REF = 'origin/main'; diff --git a/tools/code-complexity/coverage/generate.spec.ts b/tools/code-complexity/coverage/generate.spec.ts new file mode 100644 index 00000000000..f807b6b8134 --- /dev/null +++ b/tools/code-complexity/coverage/generate.spec.ts @@ -0,0 +1,19 @@ +import { describe, it, expect } from 'vitest'; + +import { vitestSelectionArgs } from './generate'; + +describe('vitestSelectionArgs', () => { + it('scopes to the given files in focused mode via `related --run`', () => { + const args = vitestSelectionArgs({ mode: 'related', paths: [ 'src/a.ts', 'src/b.ts' ] }); + expect(args).toEqual([ 'related', 'src/a.ts', 'src/b.ts', '--run' ]); + }); + + it('runs the affected specs since the base commit in diff mode', () => { + const args = vitestSelectionArgs({ mode: 'changed', since: 'abc123' }); + expect(args).toEqual([ 'run', '--changed=abc123' ]); + }); + + it('runs the whole suite in full-repo mode', () => { + expect(vitestSelectionArgs({ mode: 'full' })).toEqual([ 'run' ]); + }); +}); diff --git a/tools/code-complexity/coverage/generate.ts b/tools/code-complexity/coverage/generate.ts new file mode 100644 index 00000000000..e25dc05bf4f --- /dev/null +++ b/tools/code-complexity/coverage/generate.ts @@ -0,0 +1,86 @@ +/* eslint-disable no-console -- CLI: surfacing vitest status to the user is part of the job */ +import { execFileSync } from 'child_process'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { EXEC_MAX_BUFFER } from '../../cli/exec'; +import type { CoverageData } from './read'; +import { readCoverageOrEmpty } from './read'; + +// Auto-generates coverage by running vitest and reading the coverage-final.json it writes, so a user +// never has to produce a report by hand. Each mode maps to a vitest selection — 'related' → +// `vitest related <paths>`, 'changed' → `vitest run --changed <since>`, 'full' → `vitest run`. All +// three select through the module graph, which is what makes a file's coverage independent of how it +// was reached (../docs/RUNNING.md). +// +// Output goes to a throwaway temp dir (never the user's ./coverage) and is removed once read. + +const VITEST_BIN = path.join('node_modules', '.bin', 'vitest'); +const COVERAGE_FILE = 'coverage-final.json'; + +// Primed-request drift tests (src/server/primedRequests/CONTEXT.md) import huge swaths of the app, so +// `related` pulls them in for almost any file at a large page-mount cost and no useful coverage. +const COVERAGE_TEST_EXCLUDES: ReadonlyArray<string> = [ '**/*.primed.spec.tsx' ]; + +export type CoverageRequest = + | { readonly mode: 'related'; readonly paths: ReadonlyArray<string> } | + { readonly mode: 'changed'; readonly since: string } | + { readonly mode: 'full' }; + +export function vitestSelectionArgs(request: CoverageRequest): Array<string> { + switch (request.mode) { + case 'related': + // `related` starts a single run under `--run`, scoped to specs importing the given files. + return [ 'related', ...request.paths, '--run' ]; + case 'changed': + return [ 'run', `--changed=${ request.since }` ]; + case 'full': + return [ 'run' ]; + } +} + +export interface GenerateOptions { + // Stream vitest's own output live instead of capturing it. Off by default so the score table is + // what the user sees; the captured output is still surfaced if the run fails. + readonly verbose: boolean; +} + +function runVitestCoverage(reportsDirectory: string, request: CoverageRequest, options: GenerateOptions): void { + const args = [ + ...vitestSelectionArgs(request), + // A selection with no matching specs still yields (empty) coverage instead of failing the run. + '--passWithNoTests', + ...COVERAGE_TEST_EXCLUDES.map((glob) => `--exclude=${ glob }`), + '--coverage', + '--coverage.provider=v8', + '--coverage.reporter=json', + `--coverage.reportsDirectory=${ reportsDirectory }`, + ]; + try { + // Quiet by default: capture vitest's output so only the report table reaches stdout. --verbose + // streams it live (`inherit`) for debugging a slow or failing run. + execFileSync(VITEST_BIN, args, { + stdio: options.verbose ? 'inherit' : [ 'ignore', 'ignore', 'ignore' ], + maxBuffer: EXEC_MAX_BUFFER, + }); + } catch { + // A non-zero vitest exit (a failing test) must not sink the whole gate: vitest still writes + // coverage for what did run, and the complexity half needs none. Warn and press on with + // whatever coverage landed — a failing suite means the coverage numbers may be incomplete. + // Point at --verbose so the hidden failure is recoverable. + console.error('warning: vitest exited non-zero; coverage may be incomplete (re-run with --verbose to see why).'); + } +} + +export function generateCoverage(request: CoverageRequest, options: GenerateOptions): CoverageData { + const reportsDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'crap-cov-')); + try { + if (!options.verbose) console.error('› Running vitest to collect coverage…'); + runVitestCoverage(reportsDirectory, request, options); + // The report is parsed fully into memory, so the temp dir is safe to delete straight after. + return readCoverageOrEmpty(path.join(reportsDirectory, COVERAGE_FILE)); + } finally { + fs.rmSync(reportsDirectory, { recursive: true, force: true }); + } +} diff --git a/tools/code-complexity/coverage/read.spec.ts b/tools/code-complexity/coverage/read.spec.ts new file mode 100644 index 00000000000..50f4ffd5c90 --- /dev/null +++ b/tools/code-complexity/coverage/read.spec.ts @@ -0,0 +1,83 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { describe, it, expect } from 'vitest'; + +import { parseCoverage, functionLineCoverage, readCoverageOrEmpty } from './read'; + +// A minimal istanbul-shaped report: one statement per line, `s` giving each line's hit count. +function reportFor(absolutePath: string, hitsByLine: Record<number, number>): string { + const statementMap: Record<string, { start: { line: number }; end: { line: number } }> = {}; + const s: Record<string, number> = {}; + Object.entries(hitsByLine).forEach(([ line, hits ], index) => { + const id = String(index); + statementMap[id] = { start: { line: Number(line) }, end: { line: Number(line) } }; + s[id] = hits; + }); + return JSON.stringify({ [absolutePath]: { path: absolutePath, statementMap, s } }); +} + +describe('parseCoverage + lineHitsFor', () => { + it('matches a repo-relative path against the absolute key by suffix', () => { + const data = parseCoverage(reportFor('/Users/dev/frontend/src/lib/foo.ts', { '1': 3, '2': 0 })); + const lineHits = data.lineHitsFor('src/lib/foo.ts'); + expect(lineHits).toBeDefined(); + expect(lineHits?.get(1)).toBe(3); + expect(lineHits?.get(2)).toBe(0); + }); + + it('returns undefined for a file absent from the report', () => { + const data = parseCoverage(reportFor('/Users/dev/frontend/src/lib/foo.ts', { '1': 1 })); + expect(data.lineHitsFor('src/lib/bar.ts')).toBeUndefined(); + }); + + it('takes the highest count among statements sharing a line', () => { + const raw = JSON.stringify({ + '/x/src/f.ts': { + path: '/x/src/f.ts', + statementMap: { a: { start: { line: 5 } }, b: { start: { line: 5 } } }, + s: { a: 0, b: 4 }, + }, + }); + expect(parseCoverage(raw).lineHitsFor('src/f.ts')?.get(5)).toBe(4); + }); +}); + +describe('readCoverageOrEmpty', () => { + it('reads a report that is there', () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'crap-cov-spec-')); + const file = path.join(directory, 'coverage-final.json'); + try { + fs.writeFileSync(file, reportFor('/x/src/f.ts', { '1': 1 })); + expect(readCoverageOrEmpty(file).lineHitsFor('src/f.ts')?.get(1)).toBe(1); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); + + // A run that selected no specs writes no report. Empty coverage scores its behavior functions 0%; + // throwing ENOENT would fail the CI job instead of gating the untested code. + it('reads an absent report as empty coverage rather than throwing', () => { + const data = readCoverageOrEmpty(path.join(os.tmpdir(), 'crap-cov-spec-nonexistent', 'coverage-final.json')); + expect(data.lineHitsFor('src/f.ts')).toBeUndefined(); + }); +}); + +describe('functionLineCoverage', () => { + const lineHits = new Map<number, number>([ [ 10, 2 ], [ 11, 0 ], [ 12, 5 ], [ 13, 0 ], [ 20, 1 ] ]); + + it('is the fraction of coverable lines executed within the range', () => { + // lines 10-13: 4 coverable, 2 executed (10, 12) -> 0.5 + expect(functionLineCoverage(lineHits, 10, 13)).toBe(0.5); + }); + + it('ignores lines outside the range', () => { + // only line 20 in range, executed -> 1 + expect(functionLineCoverage(lineHits, 20, 25)).toBe(1); + }); + + it('treats a range with no coverable lines as fully covered', () => { + expect(functionLineCoverage(lineHits, 100, 110)).toBe(1); + }); +}); diff --git a/tools/code-complexity/coverage/read.ts b/tools/code-complexity/coverage/read.ts new file mode 100644 index 00000000000..90f4ea66a38 --- /dev/null +++ b/tools/code-complexity/coverage/read.ts @@ -0,0 +1,85 @@ +import fs from 'fs'; + +// Coverage join: read per-function line coverage from a v8/istanbul `coverage-final.json`. The v8 +// provider remaps its data into istanbul's shape, so both are read the same way: a `statementMap` +// (statement id -> source range) paired with `s` (statement id -> hit count). + +interface SourcePosition { + readonly line: number; +} + +interface StatementRange { + readonly start: SourcePosition; +} + +interface IstanbulFileCoverage { + readonly path?: string; + readonly statementMap: Record<string, StatementRange>; + readonly s: Record<string, number>; +} + +type CoverageJson = Record<string, IstanbulFileCoverage>; + +// line number (1-based) -> hit count. A line present with count 0 is coverable but unexecuted. +export type LineHits = ReadonlyMap<number, number>; + +export interface CoverageData { + // Line coverage for a repo-relative path, or undefined when the file is absent from the report. + readonly lineHitsFor: (relativePath: string) => LineHits | undefined; +} + +function buildLineHits(fileCoverage: IstanbulFileCoverage): Map<number, number> { + const lineHits = new Map<number, number>(); + for (const [ id, count ] of Object.entries(fileCoverage.s)) { + const statement = fileCoverage.statementMap[id]; + if (!statement) continue; + const { line } = statement.start; + const previous = lineHits.get(line); + if (previous === undefined || previous < count) lineHits.set(line, count); + } + return lineHits; +} + +export function parseCoverage(jsonText: string): CoverageData { + const raw = JSON.parse(jsonText) as CoverageJson; + + // The report keys files by absolute path; the gate looks them up by repo-relative path, so match + // on a path suffix (`.../src/foo.ts` ends with `src/foo.ts`). Line maps are built once up front. + const entries = Object.entries(raw).map(([ key, fileCoverage ]) => ({ + path: (fileCoverage.path ?? key).replace(/\\/g, '/'), + lineHits: buildLineHits(fileCoverage), + })); + + return { + lineHitsFor(relativePath: string): LineHits | undefined { + const relative = relativePath.replace(/\\/g, '/'); + const match = entries.find((entry) => entry.path === relative || entry.path.endsWith(`/${ relative }`)); + return match?.lineHits; + }, + }; +} + +export function readCoverage(filePath: string): CoverageData { + return parseCoverage(fs.readFileSync(filePath, 'utf8')); +} + +// A vitest run that covered nothing writes no report at all, so an absent file means "nothing was +// covered", not a broken invocation. Both readers go through here: the tool's own generated run, and +// the CI `--coverage-file` artifact, whose `--changed --passWithNoTests` run can select no specs. +export function readCoverageOrEmpty(filePath: string): CoverageData { + return fs.existsSync(filePath) ? readCoverage(filePath) : parseCoverage('{}'); +} + +// Fraction (0..1) of coverable lines within a function's [startLine, endLine] range that were +// executed. A line is coverable when it carries a statement; a function with no coverable lines +// (e.g. a bare type-only body) counts as fully covered, so CRAP reduces to its complexity. +export function functionLineCoverage(lineHits: LineHits, startLine: number, endLine: number): number { + let coverable = 0; + let covered = 0; + for (const [ line, hits ] of lineHits) { + if (line < startLine || line > endLine) continue; + coverable++; + if (hits > 0) covered++; + } + return coverable === 0 ? 1 : covered / coverable; +} diff --git a/tools/code-complexity/docs/CALIBRATION.md b/tools/code-complexity/docs/CALIBRATION.md new file mode 100644 index 00000000000..683592f195c --- /dev/null +++ b/tools/code-complexity/docs/CALIBRATION.md @@ -0,0 +1,32 @@ +# Code complexity — the caps and how to re-tune them + +The numbers in `../config.ts` and the procedure for deriving them again. Read this before changing a cap. + +**Raising a cap is a recalibration, not a way to unblock a PR.** The three caps are coupled to each +other and to the counting model in `./MODEL.md` — the model's job is to separate wide-but-shallow +code from genuinely-nested code, and the caps are placed at where that separation actually falls in +this repo's distribution. Move one in isolation and the gate stops measuring what it was set up to +measure. If a function trips a cap, the fix is in the function. + +## Re-tuning + +1. **Get the CC distribution.** `pnpm test:code-complexity --no-coverage --verbose` scores every + in-scope function with no vitest run at all, so it returns in seconds. +2. **Split by `KIND`.** `jsx` and `behavior` have different shapes and are tuned independently; a + figure pooled across both is meaningless. +3. **Look for the gap, not the percentile.** A cap is defensible when it sits in a break between two + bands, and a judgment call when it sits on a smooth shoulder — say which one you found. +4. **Classify what each candidate cap fires on.** For every function over the line, check whether it + is nesting-driven (an increment at depth ≥ 2 — the annotation names the deepest pocket) or + flat-breadth. The cap is right when it catches the former and clears the latter. Record the + one-step-tighter and one-step-looser outcomes; a cap with no stated neighbours is a cap + nobody can review. +5. **Confirm the anchors.** The functions the gate exists to catch must still trip, with margin. +6. **For CRAP,** generate whole-suite coverage once and iterate against it rather than regenerating + per run: + + ```bash + npx vitest run --coverage --coverage.provider=v8 --coverage.reporter=json \ + --coverage.reportsDirectory=/tmp/cc-cov + pnpm test:code-complexity --coverage-file /tmp/cc-cov/coverage-final.json + ``` diff --git a/tools/code-complexity/docs/MODEL.md b/tools/code-complexity/docs/MODEL.md new file mode 100644 index 00000000000..bb8310d0068 --- /dev/null +++ b/tools/code-complexity/docs/MODEL.md @@ -0,0 +1,179 @@ +# Code complexity — the model + +What the gate measures: which files it looks at, which functions inside them, how each function is +classified, and how the two scores are computed. Read this when a score surprises you, or before +changing anything that counts. + +Both scores are produced on **one** walk of the syntax tree in `../measure/complexity.ts`, using the +`typescript` compiler API (`ts.createSourceFile` + `ts.SyntaxKind`). There is no type-checker and no +external service, which is what makes some of the approximations below necessary. + +## Which files are in scope + +See `../select/scope.ts`. + +## Which functions are gated + +In diff mode, only functions a changed line falls within. Focused mode bypasses diff-scoping entirely and +scores every function in the given files. + +## Function classes + +Every function is classified — independently of its file's extension — by whether **JSX appears +directly in its own body**, outside any nested function: + +- **`jsx`** — a render body (a component, or an inline `items.map(x => <Row/>)` callback: the JSX is + in the callback's own body). A component's handlers are separate units. +- **`behavior`** — everything else: event handlers, `useCallback`/`useMemo` bodies, hooks, and utils, + *wherever they live* — including nested inside a component. A JSX-less hook is `behavior`; + a handler defined inside a component is `behavior` even though the component around it is `jsx`. + +Classification is read from the AST, not the extension. The two classes gate differently: + +| class | cognitive cap | CRAP | +| --- | --- | --- | +| `jsx` | `--max-cognitive-jsx` (high backstop) | never scored | +| `behavior` | `--max-cognitive-behavior` (tighter) | scored | + +**Why `jsx` carries no CRAP.** A component's rendering is covered by Playwright visual tests +(`*.pw.tsx`), which emit no vitest coverage — so a `jsx` function would read ~0% and flood the report. +Its cognitive cap is the backstop instead: hitting it means "decompose this render body." + +Which *files* trigger a vitest run is a separate question, answered in `./RUNNING.md`. It never +decides which functions are scored. + +## Cognitive Complexity — the readability gate + +CC follows the SonarSource model: flat control flow scores cheap, nesting is penalised +progressively, and boolean runs collapse. A function starts at **0** and accrues: + +| Construct | Increment | +| --- | --- | +| `if`, `for`, `for..of`, `for..in`, `while`, `do`, `catch`, ternary (`? :`), `switch` | `1 + nesting²` | +| `else`, `else if` | `+1` (no nesting penalty; the chain stays at its base level) | +| a run of like boolean operators (`&&` / `\|\|`) | `+1` per run | +| direct self-recursion (name match) | `+1` | +| labelled `break` / `continue` | `+1` | + +### A worked example + +```ts +function classify(items, mode) { + const out = []; + for (const item of items) { // for-of, nesting 0 → +1 + if (!item.active) continue; // if, nesting 1 → +2 + if (mode === 'strict' && item.score > 0) { // if, nesting 1 → +2 + switch (item.kind) { // && run (flat) → +1 + case 'a': // switch, nesting 2 → +5 + out.push(item.a ?? item.b); // ?? → +0 + break; + default: + if (item.fallback) { // if, nesting 3 → +10 + out.push(item.fallback); + } + } + } + } + return out; +} +``` + +**CC 21** and **Cyclomatic 8**, which is the whole point: eight independent paths is unremarkable, +but the shape is hard to read. + +Read the accounting: the innermost `if` costs `+10` on its own, half the function's score, purely for +sitting at depth 3. The two `if`s at depth 1 cost `+2` each. Flattening the deepest level by one +would save `5` (`1 + 3²` becomes `1 + 2²`); flattening the `switch` out of the second `if` would take +far more off. The `&&` costs `+1` however deep it sits, and the `??` costs nothing. + +That is the model's thesis in one function: **breadth is cheap, depth is not.** + +### Boolean sequences + +A maximal run of the *same* operator costs `+1`; switching operator starts a new run. `a && b && c` = +`+1`; `a && b || c` = `+2` (an `&&` run and a `||` run). Parentheses break a run. Boolean increments +carry no nesting penalty. Compound logical assignments (`&&=`, `||=`) are not sequence operators and +add nothing to CC. + +### Recursion is approximate + +With no type-checker, self-recursion is detected by name match — a call whose callee is the bare +identifier the function is bound to. This catches direct self-recursion in a function declaration, a +named function expression, or a `const f = () => … f() …` arrow. It does not catch `this.method()`, +destructured or aliased calls, or indirect and mutual recursion. A documented approximation, not a +bug. Labelled `break`/`continue` is exact (purely syntactic). + +### `?.` and `??` are not counted + +Optional chaining is excluded per ADR 0001 — CC's model does not treat it as a branch or a nesting +structure, so the exclusion carries over for free. Null-coalescing (`??`, `??=`) is excluded because +the SonarSource white paper itself ignores it as readable shorthand, in the same class as `?.` +(ADR 0002). Cyclomatic complexity still counts `??` — the two scores diverge here on purpose. + +### Per-function units, and the nesting reset + +Every function is its own unit: nested functions, arrows, methods, accessors and the constructor each +start their own count, and both nesting and increments accrue only to the innermost enclosing +function. **Nesting resets to 0 at a nested-function boundary** — a control structure inside a +callback is scored relative to that callback, not to the component around it. + +Constructs at module scope belong to no function and are ignored, matching ESLint's per-function +reporting. + +### Contributions + +Every increment is recorded as a `{ line, amount, reason, nesting }` contribution, in walk order. +That record is what lets a violation annotation name the sites that cost the most and point at the +deepest nesting pocket, rather than just reporting a number. + +## Cyclomatic complexity — the CRAP input + +Not a gate on its own. It counts independent paths ≈ tests needed, which makes it the correct input +to CRAP and a poor readability signal: it scores a flat `switch` the same as an equivalent nested +`if` chain, and is blind to nesting. That is why CC, not cyclomatic, is the decomposition gate. + +Because CC governs decomposition, the only fix for a CRAP failure is added coverage, never lowering +`c`. So `CX` is not a default report column; it appears only under `--verbose`, for calibration and +tool debugging. + +## CRAP + +CRAP (Change Risk Anti-Patterns) combines **cyclomatic** complexity with test coverage: + +``` +CRAP = c²·(1 − cov)³ + c +``` + +where `c` is the function's cyclomatic complexity and `cov` is its line-coverage fraction (0..1). +Well-covered code scores near its complexity (`cov = 1` gives exactly `c`); the cubic `(1 − cov)` +term makes complex, untested code explode. At 0% coverage the score is `c² + c`. + +### The coverage join + +Per-function coverage is read from a v8/istanbul `coverage-final.json` (the v8 provider emits the +istanbul shape). A function's coverage is the fraction of *coverable* lines in its line range that +were executed — a line is coverable when it carries a statement, and its hit count is the highest +among the statements starting on it, exactly as istanbul's `getLineCoverage()` computes it. A +function with no coverable lines counts as fully covered, so CRAP reduces to its complexity. + +**Missing coverage = 0% vs "no data".** A `behavior` function absent from the coverage report scores +0% when absence means "no spec executed it". The one exception is a +**user-supplied `--coverage-file` in focused mode**: a hand-passed report may simply predate the file, +so absence there reports `—` (no data). + +## Divergences from the reference models + +Three, and only these: + +1. **Nesting is quadratic, not linear** - see ADR 0002. +2. **Per-function units with a nesting reset** - see above. +3. **`?.` and `??` are excluded** - see ADR 0001, 0002. + +### On comparing against `eslint-plugin-sonarjs` + +CC was validated by diffing against that plugin's `cognitive-complexity` rule during calibration. +The exercise confirmed the *shape* of the model and the scores agreed on flat and shallow code. + +Numeric parity is **not** expected and is not a regression test. Nesting-heavy code reads higher here +by design: at calibration a hook built from nested `switch` trees scored 23 here against the linear +model's 15. diff --git a/tools/code-complexity/docs/RUNNING.md b/tools/code-complexity/docs/RUNNING.md new file mode 100644 index 00000000000..a695fdac04a --- /dev/null +++ b/tools/code-complexity/docs/RUNNING.md @@ -0,0 +1,64 @@ +# Code complexity — running it + +`pnpm test:code-complexity --help` is the flag reference. This document is what the flag list does not +tell you: how a selection turns into a vitest run, and how to read what comes back. + +## Two independent axes + +The interface mirrors vitest — **selection** (which functions) and **coverage source** (how the CRAP +half is fed). Any selection combines with any source. + +| Selection | Scores | +| --- | --- | +| *(no arguments)* | every in-scope function, repo-wide | +| `<path...>` | every function in the given files, ignoring the diff | +| `--changed[=<ref>]` | only functions a changed line falls within | + +`--changed` shells out to git without setting a working directory, so the diff it scores is the one at +the directory you invoked the command from. `../run.sh` resolves its own location in order to compile, +which lets it run from anywhere — that part is cwd-independent, the diff is not. + +| Coverage source | How the CRAP half is fed | +| --- | --- | +| *(default)* | the tool runs vitest itself, scoped to the selection, into a throwaway temp dir | +| `--coverage-file <path>` | consume a prebuilt report and skip vitest | +| `--no-coverage` | cognitive gate only, which is always enforced either way | + +`--verbose` streams vitest's output live and adds the cyclomatic (`CX`) column; otherwise vitest is +silent so the score table is what you see. + +## Which files trigger a vitest run (generation scope) + +Separately from per-function scoring, a *file* needs vitest coverage generated for it when it is a +**JSX-less logic file** *or* a **JSX file with a co-located vitest spec** (`Component.spec.tsx` next +to `Component.tsx`; Playwright `*.pw.tsx` does not count). This only decides whether +`vitest related`/`--changed` pulls the file in. A `behavior` function in a JSX file outside that set +is absent from the report and scores 0% without triggering a run. + +Four consequences: + +- **Vitest is skipped when nothing needs coverage.** Only files in the generation scope cause a run, + so a focused run on a spec-less JSX component returns instantly — scoring its `behavior` functions + 0%, exactly as it would have had the run happened. Skipping the run is not `--no-coverage`: + generation scope never decides which functions are scored, so a function's score never depends on + what else shared its selection. A diff with nothing in scope prints "No functions to check." and + runs nothing. +- **All three generated scopes select through the module graph** (`vitest related <paths>`, + `vitest run --changed <merge-base>`, or the whole suite), so a file's coverage is the same however + it was reached. A selection with no matching specs passes; a failing suite warns and still reports + whatever coverage landed. +- **Primed-request drift tests (`*.primed.spec.tsx`) are excluded** from generated runs. They mount + whole page trees to check the primer registry rather than to exercise behavior, costing tens of seconds + of page-mount time while contributing no meaningful coverage. +- **A function absent from the coverage report usually scores 0%, not `—`.** The one exception is a + user-supplied `--coverage-file` in focused mode. + +## The report + +The default table shows `KIND`, `COG`, `COV`, `CRAP` and `BROKE`, sorted by CRAP descending; +`jsx` and no-coverage rows sort to the bottom, tie-broken by `COG`. The two gates are independent: +the cognitive cap trips on any in-scope function over its class's cap, the CRAP cap only on `behavior` +functions with coverage data. + +Under `$GITHUB_ACTIONS` the tool also emits `::error file=,line=::` annotations for offenders and +writes the table to `$GITHUB_STEP_SUMMARY`. diff --git a/tools/code-complexity/index.spec.ts b/tools/code-complexity/index.spec.ts new file mode 100644 index 00000000000..eb62f53d9f9 --- /dev/null +++ b/tools/code-complexity/index.spec.ts @@ -0,0 +1,132 @@ +import { describe, it, expect } from 'vitest'; + +import { DEFAULT_BASE_REF, DEFAULT_MAX_COGNITIVE_BEHAVIOR, DEFAULT_MAX_COGNITIVE_JSX, DEFAULT_MAX_CRAP } from './config'; +import { parseArgs } from './index'; + +// Caps used as flag values: arbitrary, but distinct from every default so an assertion can only pass +// if the flag actually took effect. +const CAP = 7; +const OTHER_CAP = 9; + +describe('parseArgs', () => { + it('defaults to full-repo mode with the configured thresholds', () => { + expect(parseArgs([])).toEqual({ + baseRef: DEFAULT_BASE_REF, + diffSelected: false, + maxCognitiveJsx: DEFAULT_MAX_COGNITIVE_JSX, + maxCognitiveBehavior: DEFAULT_MAX_COGNITIVE_BEHAVIOR, + maxCrap: DEFAULT_MAX_CRAP, + coverageMode: 'generate', + coverageFile: undefined, + verbose: false, + focusPaths: [], + }); + }); + + it('collects non-flag arguments as focus paths', () => { + expect(parseArgs([ 'src/a.ts', 'src/b.tsx' ]).focusPaths).toEqual([ 'src/a.ts', 'src/b.tsx' ]); + }); + + it('reads the switch flags', () => { + expect(parseArgs([ '--verbose' ]).verbose).toBe(true); + expect(parseArgs([ '--no-coverage' ]).coverageMode).toBe('off'); + }); + + it('rejects a value passed to a switch flag', () => { + expect(() => parseArgs([ '--verbose=yes' ])).toThrow('--verbose takes no value'); + }); + + it('reads a value flag in both the separate-token and inline forms', () => { + expect(parseArgs([ '--coverage-file', 'coverage/final.json' ])).toMatchObject({ + coverageMode: 'file', + coverageFile: 'coverage/final.json', + }); + expect(parseArgs([ '--coverage-file=coverage/final.json' ])).toMatchObject({ + coverageMode: 'file', + coverageFile: 'coverage/final.json', + }); + }); + + it('does not let a value flag swallow the following flag', () => { + expect(parseArgs([ '--coverage-file=coverage/final.json', '--verbose' ])).toMatchObject({ + coverageFile: 'coverage/final.json', + verbose: true, + }); + }); + + it('selects diff mode from --changed, with an optional inline ref', () => { + expect(parseArgs([ '--changed' ])).toMatchObject({ diffSelected: true, baseRef: DEFAULT_BASE_REF }); + expect(parseArgs([ '--changed=upstream/main' ])).toMatchObject({ diffSelected: true, baseRef: 'upstream/main' }); + }); + + // The CI invocation: --changed must not consume --coverage-file as its ref. + it('leaves the token after a bare --changed alone', () => { + expect(parseArgs([ '--changed', '--coverage-file', 'coverage/final.json' ])).toMatchObject({ + diffSelected: true, + baseRef: DEFAULT_BASE_REF, + coverageMode: 'file', + coverageFile: 'coverage/final.json', + }); + }); + + it('selects diff mode from --base and takes its ref', () => { + expect(parseArgs([ '--base', 'upstream/main' ])).toMatchObject({ diffSelected: true, baseRef: 'upstream/main' }); + expect(parseArgs([ '--base=upstream/main' ])).toMatchObject({ diffSelected: true, baseRef: 'upstream/main' }); + }); + + it('overrides the cognitive caps per class', () => { + expect(parseArgs([ '--max-cognitive-jsx', String(CAP) ])).toMatchObject({ + maxCognitiveJsx: CAP, + maxCognitiveBehavior: DEFAULT_MAX_COGNITIVE_BEHAVIOR, + }); + expect(parseArgs([ '--max-cognitive-behavior', String(CAP) ])).toMatchObject({ + maxCognitiveJsx: DEFAULT_MAX_COGNITIVE_JSX, + maxCognitiveBehavior: CAP, + }); + }); + + it('does not let --max-cognitive shadow its longer siblings', () => { + expect(parseArgs([ '--max-cognitive-jsx=' + String(CAP) ]).maxCognitiveJsx).toBe(CAP); + expect(parseArgs([ '--max-cognitive-jsx=' + String(CAP) ]).maxCognitiveBehavior).toBe(DEFAULT_MAX_COGNITIVE_BEHAVIOR); + }); + + it('clamps both cognitive caps from bare --max-cognitive', () => { + expect(parseArgs([ '--max-cognitive', String(CAP) ])).toMatchObject({ + maxCognitiveJsx: CAP, + maxCognitiveBehavior: CAP, + }); + }); + + it('overrides the CRAP cap', () => { + expect(parseArgs([ '--max-crap', String(CAP) ]).maxCrap).toBe(CAP); + }); + + it('applies the last of two conflicting overrides', () => { + expect(parseArgs([ '--max-crap', String(CAP), '--max-crap', String(OTHER_CAP) ]).maxCrap).toBe(OTHER_CAP); + }); + + it('combines flags and focus paths in any order', () => { + expect(parseArgs([ '--verbose', 'src/a.ts', '--max-crap=' + String(CAP), 'src/b.ts' ])).toMatchObject({ + verbose: true, + maxCrap: CAP, + focusPaths: [ 'src/a.ts', 'src/b.ts' ], + }); + }); + + it('rejects an unknown flag', () => { + expect(() => parseArgs([ '--nope' ])).toThrow('Unknown flag: --nope'); + // A near-miss of a real flag is unknown too, not a loose prefix match. + expect(() => parseArgs([ '--max-crappy=1' ])).toThrow('Unknown flag: --max-crappy'); + }); + + it('rejects a value flag with no value', () => { + expect(() => parseArgs([ '--max-crap' ])).toThrow('Missing value for --max-crap'); + expect(() => parseArgs([ '--base' ])).toThrow('Missing value for --base'); + }); + + it('rejects a cap that is not a positive number', () => { + expect(() => parseArgs([ '--max-crap', 'abc' ])).toThrow('Invalid value for --max-crap: abc'); + expect(() => parseArgs([ '--max-crap', '0' ])).toThrow('Invalid value for --max-crap: 0'); + expect(() => parseArgs([ '--max-cognitive=-1' ])).toThrow('Invalid value for --max-cognitive: -1'); + }); +}); diff --git a/tools/code-complexity/index.ts b/tools/code-complexity/index.ts new file mode 100644 index 00000000000..6ce6d407d6f --- /dev/null +++ b/tools/code-complexity/index.ts @@ -0,0 +1,282 @@ +/* eslint-disable no-console -- this is a CLI whose entire job is to print a report to stdout */ +import fs from 'fs'; + +import type { FlagSpec } from '../cli/flags'; +import { parseArgs as parseFlags } from '../cli/flags'; +import { buildFileRows } from './analyze'; +import { DEFAULT_BASE_REF, DEFAULT_MAX_COGNITIVE_BEHAVIOR, DEFAULT_MAX_COGNITIVE_JSX, DEFAULT_MAX_CRAP } from './config'; +import { generateCoverage } from './coverage/generate'; +import type { CoverageRequest } from './coverage/generate'; +import type { CoverageData } from './coverage/read'; +import { parseCoverage, readCoverageOrEmpty } from './coverage/read'; +import { fileContainsJsx } from './measure/jsx'; +import { githubAnnotations, stepSummary } from './render/github'; +import type { ReportRow, Thresholds } from './render/report'; +import { formatTable, isOffender } from './render/report'; +import { getAllSourceFiles, getChangedFiles, getChangedLineRanges, rangesOverlap, resolveBaseCommit } from './select/diff'; +import { hasCoLocatedSpec } from './select/eligibility'; +import { isInScope } from './select/scope'; + +// The CLI has two independent axes, mirroring vitest: selection (which functions to score) and +// coverage source (how the CRAP half is fed). Any selection combines with any source; ./docs/RUNNING.md +// tabulates both. USAGE below is the flag reference. +type CoverageMode = 'generate' | 'file' | 'off'; + +interface CliOptions { + baseRef: string; + diffSelected: boolean; + maxCognitiveJsx: number; + maxCognitiveBehavior: number; + maxCrap: number; + coverageMode: CoverageMode; + coverageFile: string | undefined; // set only when coverageMode === 'file' + verbose: boolean; + focusPaths: Array<string>; +} + +const USAGE = `Usage: + test:code-complexity [--max-cognitive <n>] [--max-cognitive-jsx <n>] + [--max-cognitive-behavior <n>] [--max-crap <n>] + [--coverage-file <path> | --no-coverage] [--verbose] + Full-repo mode (default): score every in-scope function (src/** and tools/**). + The readability gate is cognitive complexity, capped per function class: + --max-cognitive-jsx for render bodies, --max-cognitive-behavior for handlers/hooks/utils; + bare --max-cognitive sets both. --max-crap caps the CRAP score (cyclomatic × coverage). + + test:code-complexity <path...> [...] Focused mode: score every function in the given files. + + test:code-complexity --changed[=<ref>] [--base <ref>] [...] + Diff mode: gate only functions the diff touches vs the base ref (default origin/main). + + Coverage is generated by running vitest (scoped to the selection) unless --coverage-file supplies + a prebuilt report (the CI path, skips vitest) or --no-coverage skips it (cognitive gate only). + Vitest output is hidden by default; --verbose streams it live and adds the cyclomatic (CX) column.`; + +// Cap values are positive integers; anything else is a typo worth failing on rather than silently +// defaulting. +function readCap(flag: string, raw: string): number { + const value = Number(raw); + if (!Number.isFinite(value) || value < 1) throw new Error(`Invalid value for ${ flag }: ${ raw }`); + return value; +} + +// The whole flag surface as data. Keeping it a lookup rather than an if/else chain is what leaves +// readability budget for the next flag. +const FLAGS: ReadonlyMap<string, FlagSpec<CliOptions>> = new Map<string, FlagSpec<CliOptions>>([ + [ '--help', { kind: 'switch', apply: () => { + console.log(USAGE); + process.exit(0); + } } ], + [ '-h', { kind: 'switch', apply: () => { + console.log(USAGE); + process.exit(0); + } } ], + [ '--verbose', { kind: 'switch', apply: (options) => { + options.verbose = true; + } } ], + [ '--no-coverage', { kind: 'switch', apply: (options) => { + options.coverageMode = 'off'; + } } ], + [ '--coverage-file', { kind: 'value', apply: (options, value) => { + options.coverageMode = 'file'; + options.coverageFile = value; + } } ], + [ '--changed', { kind: 'optional', apply: (options, value) => { + options.diffSelected = true; + if (value !== undefined) options.baseRef = value; + } } ], + [ '--base', { kind: 'value', apply: (options, value) => { + options.diffSelected = true; + options.baseRef = value; + } } ], + [ '--max-cognitive-jsx', { kind: 'value', apply: (options, value) => { + options.maxCognitiveJsx = readCap('--max-cognitive-jsx', value); + } } ], + [ '--max-cognitive-behavior', { kind: 'value', apply: (options, value) => { + options.maxCognitiveBehavior = readCap('--max-cognitive-behavior', value); + } } ], + // Bare --max-cognitive is a global that clamps both per-class caps. + [ '--max-cognitive', { kind: 'value', apply: (options, value) => { + const cap = readCap('--max-cognitive', value); + options.maxCognitiveJsx = cap; + options.maxCognitiveBehavior = cap; + } } ], + [ '--max-crap', { kind: 'value', apply: (options, value) => { + options.maxCrap = readCap('--max-crap', value); + } } ], +]); + +export function parseArgs(argv: ReadonlyArray<string>): CliOptions { + const { options, rest } = parseFlags<CliOptions>(argv, FLAGS, { + baseRef: DEFAULT_BASE_REF, + diffSelected: false, + maxCognitiveJsx: DEFAULT_MAX_COGNITIVE_JSX, + maxCognitiveBehavior: DEFAULT_MAX_COGNITIVE_BEHAVIOR, + maxCrap: DEFAULT_MAX_CRAP, + coverageMode: 'generate', + coverageFile: undefined, + verbose: false, + focusPaths: [], + }, { kind: 'reject', usage: USAGE }); + + options.focusPaths = rest; + return options; +} + +function normalizeDisplayPath(filePath: string): string { + return filePath.replace(/\\/g, '/').replace(/^\.\//, ''); +} + +function readFile(filePath: string): string { + return fs.readFileSync(filePath, 'utf8'); +} + +function thresholdsOf(options: CliOptions): Thresholds { + return { + maxCognitiveJsx: options.maxCognitiveJsx, + maxCognitiveBehavior: options.maxCognitiveBehavior, + maxCrap: options.maxCrap, + }; +} + +// Resolve coverage from the chosen mode. `request` steers generation; it is ignored for 'file' and +// 'off'. `anyNeedsCoverage` short-circuits generation: when no file in the selection needs coverage +// generated (see fileNeedsCoverage) vitest would produce nothing, so we skip the run. +// +// Only 'off' yields null. Skipping the run yields *empty* coverage instead, because null means "the +// CRAP gate is disabled" to analyze.ts — which would let generation scope decide which functions are +// scored, and make a function's score depend on what else happened to be in the same selection. +function resolveCoverage(options: CliOptions, request: CoverageRequest, anyNeedsCoverage: boolean): CoverageData | null { + switch (options.coverageMode) { + case 'off': + return null; + case 'file': + // coverageFile is always set when the mode is 'file' (parseArgs reads its value). + return readCoverageOrEmpty(options.coverageFile as string); + case 'generate': + return anyNeedsCoverage ? generateCoverage(request, { verbose: options.verbose }) : parseCoverage('{}'); + } +} + +// Whether a file needs vitest coverage generated for it: a JSX-less logic file always does; a JSX +// component only when it has a co-located vitest spec. This drives only the generation scope +// (./docs/RUNNING.md); per-function CRAP applicability is decided in analyze.ts. +function fileNeedsCoverage(file: string, source: string): boolean { + return !fileContainsJsx(source, file) || hasCoLocatedSpec(file); +} + +// Focused mode: score every function in the given files, no diff-scoping. Coverage comes from the +// files' transitive importers (`related`), matching what diff/full would give. +function runFocusedMode(options: CliOptions): Array<ReportRow> { + const displayPaths = options.focusPaths.map(normalizeDisplayPath); + const sources = new Map(displayPaths.map((displayPath) => [ displayPath, readFile(displayPath) ] as const)); + const needsCoverage = (displayPath: string): boolean => fileNeedsCoverage(displayPath, sources.get(displayPath) as string); + + // Generate coverage only for the files that need it, and only run vitest if there are any. + const relatedPaths = displayPaths.filter(needsCoverage); + const coverage = resolveCoverage(options, { mode: 'related', paths: relatedPaths }, relatedPaths.length > 0); + + return displayPaths.flatMap((displayPath) => buildFileRows(displayPath, sources.get(displayPath) as string, coverage, { + thresholds: thresholdsOf(options), + gate: () => true, + // The one mode where a missing entry may just mean the hand-passed report predates the file. + missingCoverageIsZero: options.coverageMode !== 'file', + })); +} + +// Full-repo mode (default): score every in-scope function, across both allowlisted roots. This is +// the mode threshold calibration runs (./docs/CALIBRATION.md). The repo always has files that need +// coverage and generation runs the whole suite regardless, so there is no per-file skip here. +function runFullMode(options: CliOptions): Array<ReportRow> { + const files = getAllSourceFiles(process.cwd()); + if (files.length === 0) return []; + const coverage = resolveCoverage(options, { mode: 'full' }, true); + + return files.flatMap((file) => { + const source = readFile(file); + return buildFileRows(file, source, coverage, { + thresholds: thresholdsOf(options), + gate: () => true, + missingCoverageIsZero: true, + }); + }); +} + +// Diff mode: gate only functions a changed line falls within, across in-scope changed files. +// Untouched functions in a changed file are listed but never flagged. +function runDiffMode(options: CliOptions): Array<ReportRow> { + const baseCommit = resolveBaseCommit(options.baseRef, process.cwd()); + const changedFiles = getChangedFiles(baseCommit, process.cwd()).filter(isInScope).filter((file) => fs.existsSync(file)); + if (changedFiles.length === 0) return []; // nothing in scope: skip vitest entirely + + const sources = new Map(changedFiles.map((file) => [ file, readFile(file) ] as const)); + const needsCoverage = (file: string): boolean => fileNeedsCoverage(file, sources.get(file) as string); + // A change that touches nothing needing coverage (e.g. only JSX components without specs) skips + // the vitest run entirely. + const coverage = resolveCoverage(options, { mode: 'changed', since: baseCommit }, changedFiles.some(needsCoverage)); + + return changedFiles.flatMap((file) => { + const changedRanges = getChangedLineRanges(baseCommit, file, process.cwd()); + return buildFileRows(file, sources.get(file) as string, coverage, { + thresholds: thresholdsOf(options), + gate: (fn) => rangesOverlap(changedRanges, fn.startLine, fn.endLine), + // A changed behavior function missing from coverage is untested changed code -> 0%. + missingCoverageIsZero: true, + }); + }); +} + +function selectRows(options: CliOptions): Array<ReportRow> { + if (options.focusPaths.length > 0) return runFocusedMode(options); + if (options.diffSelected) return runDiffMode(options); + return runFullMode(options); +} + +// Under $GITHUB_ACTIONS, add the two CI outputs: `::error` annotations that surface each offender +// inline on the PR diff, and the full table written to the job summary. The plain-stdout table has +// already been printed. +function emitGithubActionsOutput(rows: ReadonlyArray<ReportRow>, thresholds: Thresholds, table: string): void { + for (const annotation of githubAnnotations(rows, thresholds)) console.log(annotation); + // eslint-disable-next-line no-restricted-properties -- Node CLI reading a CI-provided path, not an app env var + const summaryPath = process.env.GITHUB_STEP_SUMMARY; + if (summaryPath) fs.appendFileSync(summaryPath, `${ stepSummary(table) }\n`); +} + +function main(): void { + const options = parseArgs(process.argv.slice(2)); + const rows = selectRows(options); + + if (rows.length === 0) { + console.log('No functions to check.'); + return; + } + + const table = formatTable(rows, thresholdsOf(options), options.verbose); + console.log(table); + + // eslint-disable-next-line no-restricted-properties -- Node CLI detecting the CI runtime, not an app env var + if (process.env.GITHUB_ACTIONS) emitGithubActionsOutput(rows, thresholdsOf(options), table); + + if (rows.some(isOffender)) { + process.exitCode = 1; + } +} + +// run.sh always executes the compiled `tools/code-complexity/dist/code-complexity/index.js`, so that +// path is what marks this module as the process entry point. The guard exists so `index.spec.ts` can +// import parseArgs without kicking off a whole report run — under vitest the entry is vitest's own binary. +const CLI_ENTRY_PATH = 'code-complexity/dist/code-complexity/index.js'; + +function isProcessEntryPoint(): boolean { + const entry = process.argv[1]?.replace(/\\/g, '/'); + return entry !== undefined && entry.endsWith(CLI_ENTRY_PATH); +} + +if (isProcessEntryPoint()) { + try { + main(); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + } +} diff --git a/tools/code-complexity/measure/complexity.spec.ts b/tools/code-complexity/measure/complexity.spec.ts new file mode 100644 index 00000000000..6f34bd658fa --- /dev/null +++ b/tools/code-complexity/measure/complexity.spec.ts @@ -0,0 +1,386 @@ +import { describe, it, expect } from 'vitest'; + +import { computeFunctionComplexities } from './complexity'; + +// Complexity of the single function in `source`, or the map of name -> complexity when several. +function complexityOf(source: string, fileName = 'sample.tsx'): number { + const results = computeFunctionComplexities(source, fileName); + expect(results).toHaveLength(1); + return results[0].complexity; +} + +// Cognitive complexity of the single function in `source`. +function cognitiveOf(source: string, fileName = 'sample.tsx'): number { + const results = computeFunctionComplexities(source, fileName); + expect(results).toHaveLength(1); + return results[0].cognitive; +} + +function complexityByName(source: string, fileName = 'sample.tsx'): Record<string, number> { + return Object.fromEntries( + computeFunctionComplexities(source, fileName).map((fn) => [ fn.name, fn.complexity ]), + ); +} + +describe('computeFunctionComplexities — ESLint `complexity` parity', () => { + it('counts base 1 for a function with no branches', () => { + expect(complexityOf('function f(x: number) { return x + 1; }')).toBe(1); + }); + + it('counts if, else if (but not else), and each logical operator', () => { + // base 1 + if 1 + && 1 + (else if) 1 = 4; the bare `else` adds nothing + expect(complexityOf(` + function f(x: number) { + if (x > 1 && x < 10) return 1; + else if (x === 0) return 2; + else return 3; + } + `)).toBe(4); + }); + + it('counts &&, ||, and ?? each', () => { + // base 1 + && 1 + || 1 + ?? 1 = 4 + expect(complexityOf('function f(a: any, b: any, c: any) { return a && b || (c ?? a); }')).toBe(4); + }); + + it('counts logical-assignment operators &&=, ||=, ?? =', () => { + // base 1 + three logical assignments = 4 + expect(complexityOf('function f(x: any) { x &&= 1; x ||= 2; x ??= 3; return x; }')).toBe(4); + }); + + it('counts for, for..of, and for..in', () => { + // base 1 + 3 loops = 4 + expect(complexityOf(` + function f(o: any) { + for (let i = 0; i < 1; i++) {} + for (const v of []) { v; } + for (const k in o) { k; } + } + `)).toBe(4); + }); + + it('counts while and do..while', () => { + // base 1 + while 1 + do 1 = 3 + expect(complexityOf('function f(x: number) { while (x) { break; } do { x--; } while (x); }')).toBe(3); + }); + + it('counts each case but not default or the switch itself', () => { + // base 1 + case 1 + case 1 = 3; default and `switch` add nothing + expect(complexityOf(` + function f(x: number) { + switch (x) { + case 1: return 1; + case 2: return 2; + default: return 0; + } + } + `)).toBe(3); + }); + + it('counts catch and ternary', () => { + // base 1 + catch 1 + ternary 1 = 3 + expect(complexityOf('function f(x: number) { try { return x ? 1 : 2; } catch (e) { return 0; } }')).toBe(3); + }); + + it('does NOT count optional-chaining `?.` (property, call, or element access)', () => { + // `?.` is null-safety verbosity, not a branch a test must cover: TypeScript proves the + // nullability at each site (ADR 0001). base 1 only, whatever the `?.` shape. + expect(complexityOf('function f(x: any) { return x?.y?.z?.toString(); }')).toBe(1); + expect(complexityOf('function f(x: any) { const a = x?.(1); const b = x?.[0]; return a; }')).toBe(1); + }); + + it('does NOT count JSX structure', () => { + // base 1 only; JSX elements/fragments/self-closing tags add nothing + expect(complexityOf('const f = (x: number) => <div className="a"><span/>{ x }</div>;')).toBe(1); + }); + + it('DOES count a logical operator inside a JSX expression container', () => { + // the `&&` is a real logical operator, not JSX structure: base 1 + && 1 = 2 + expect(complexityOf('const f = (x: number) => <div>{ x > 0 && <span/> }</div>;')).toBe(2); + }); +}); + +describe('computeFunctionComplexities — function units', () => { + it('treats nested arrow functions as their own units', () => { + const byName = complexityByName(` + export const outer = () => { + const inner = (n: number) => (n > 0 && n < 9 ? 1 : 2); + return inner; + }; + `); + // outer's own body has no branches (base 1); inner has && + ternary (base 1 + 2) + expect(byName).toEqual({ outer: 1, inner: 3 }); + }); + + it('names methods, getters, setters, and the constructor', () => { + const byName = complexityByName(` + class C { + constructor(private x: number) {} + m(v: number) { return v > 0 ? 1 : 0; } + get value() { return this.x; } + set value(v: number) { this.x = v || 0; } + } + `); + expect(byName).toEqual({ constructor: 1, m: 2, 'get value': 1, 'set value': 2 }); + }); + + it('recovers a name for arrow and function expressions from their binding', () => { + const byName = complexityByName(` + const a = () => 1; + const b = function named() { return 2; }; + const obj = { c: () => 3 }; + `); + expect(byName).toHaveProperty('a'); + expect(byName).toHaveProperty('named'); + expect(byName).toHaveProperty('c'); + }); + + it('reports the 1-based start line of each function', () => { + const [ fn ] = computeFunctionComplexities('\n\nfunction f() { return 1; }', 'sample.ts'); + expect(fn.startLine).toBe(3); + }); +}); + +describe('computeFunctionComplexities — cognitive complexity (SonarSource model, quadratic nesting)', () => { + it('scores a branchless function 0', () => { + expect(cognitiveOf('function f(x: number) { return x + 1; }')).toBe(0); + }); + + it('adds 1 for a flat if, 1 for a bare else', () => { + // if +1, else +1 = 2 (neither is nested) + expect(cognitiveOf(` + function f(x: number) { + if (x > 0) { return 1; } else { return 2; } + } + `)).toBe(2); + }); + + it('treats else-if as a flat +1 continuation, not a nested if', () => { + // if +1, else if +1, else if +1, else +1 = 4; the chain never nests + expect(cognitiveOf(` + function f(x: number) { + if (x === 1) return 1; + else if (x === 2) return 2; + else if (x === 3) return 3; + else return 0; + } + `)).toBe(4); + }); + + it('penalises nesting quadratically (1 + nesting²)', () => { + // if +1 (n0), for +2 (n1), while +5 (n2) = 8 — linear would have scored 6 + expect(cognitiveOf(` + function f(a: boolean, xs: Array<number>, b: boolean) { + if (a) { + for (const x of xs) { + while (b) { break; } + } + } + } + `)).toBe(8); + }); + + it('charges 1 + nesting² at every depth, so each level costs more than the last', () => { + // if +1 (n0), if +2 (n1), if +5 (n2), if +10 (n3) = 18: the same nesting under the linear model + // would be 1+2+3+4 = 10. Identical to linear at depths 0-1; the surcharge starts at depth 2. + expect(cognitiveOf(` + function f(a: boolean, b: boolean, c: boolean, d: boolean) { + if (a) { + if (b) { + if (c) { + if (d) { return 1; } + } + } + } + } + `)).toBe(18); + }); + + it('nests inside a bare else body', () => { + // if +1 (n0), else +1 (n0), inner if +2 (n1) = 4 + expect(cognitiveOf(` + function f(a: boolean, b: boolean) { + if (a) { return 1; } + else { + if (b) { return 2; } + } + } + `)).toBe(4); + }); + + it('scores a flat switch +1 regardless of case count', () => { + // switch +1 only; cases add nothing + expect(cognitiveOf(` + function f(x: number) { + switch (x) { + case 1: return 1; + case 2: return 2; + case 3: return 3; + default: return 0; + } + } + `)).toBe(1); + }); + + it('penalises a switch nested inside another structure (1 + nesting²)', () => { + // if +1 (n0), inner switch +2 (n1) = 3 — a nested switch is not free + expect(cognitiveOf(` + function f(a: boolean, x: number) { + if (a) { + switch (x) { case 1: return 1; default: return 0; } + } + return -1; + } + `)).toBe(3); + }); + + it('penalises control flow nested inside a switch case', () => { + // switch +1 (n0), if inside a case +2 (n1) = 3 + expect(cognitiveOf(` + function f(x: number, y: boolean) { + switch (x) { + case 1: if (y) { return 1; } return 2; + default: return 0; + } + } + `)).toBe(3); + }); + + it('collapses a run of like boolean operators to +1, and counts +1 per switch of operator', () => { + expect(cognitiveOf('function f(a: any, b: any, c: any) { return a && b && c; }')).toBe(1); + // `a && b || c` = (a && b) || c: the || run +1, the nested && run +1 = 2 + expect(cognitiveOf('function f(a: any, b: any, c: any) { return a && b || c; }')).toBe(2); + // two distinct runs; the parenthesised `??` is not a sequence operator and adds nothing + expect(cognitiveOf('function f(a: any, b: any, c: any, d: any) { return a && b || (c ?? d); }')).toBe(2); + }); + + it('does not count null-coalescing `??` or `??=`', () => { + // The SonarSource paper ignores null-coalescing as readable shorthand, like `?.` (ADR 0002): a + // wall of defaulting is verbose, not hard to follow. + expect(cognitiveOf('function f(a: any, b: any, c: any) { return a ?? b ?? c; }')).toBe(0); + expect(cognitiveOf('function f(x: any) { x ??= 1; return x; }')).toBe(0); + }); + + it('adds 1 + nesting² for a ternary and nests its branches', () => { + // outer ternary +1 (n0); nested ternary in the whenFalse +2 (n1) = 3 + expect(cognitiveOf('function f(a: any, b: any) { return a ? 1 : (b ? 2 : 3); }')).toBe(3); + }); + + it('adds 1 + nesting² for catch', () => { + // if +1 (n0), catch nested inside it +2 (n1) = 3 + expect(cognitiveOf(` + function f(a: boolean) { + if (a) { + try { doThing(); } catch (e) { handle(e); } + } + } + `)).toBe(3); + }); + + it('adds 1 for direct self-recursion detected by name', () => { + // if +1, two recursive calls +1 each = 3 + expect(cognitiveOf(` + function fib(n: number): number { + if (n < 2) return n; + return fib(n - 1) + fib(n - 2); + } + `)).toBe(3); + }); + + it('detects recursion for a name-bound arrow function', () => { + expect(cognitiveOf('const walk = (n: number): number => n <= 0 ? 0 : walk(n - 1);')).toBe(2); // ternary +1, recursion +1 + }); + + it('adds 1 for a labelled break/continue', () => { + // for n0 +1, for n1 +2, if n2 +5, labelled break +1 = 9 + expect(cognitiveOf(` + function f(xs: Array<Array<number>>) { + outer: for (const row of xs) { + for (const v of row) { + if (v < 0) break outer; + } + } + } + `)).toBe(9); + }); + + it('resets nesting for a nested function — each function is its own unit', () => { + const results = computeFunctionComplexities(` + function outer(xs: Array<number>) { + if (xs.length) { + xs.forEach((x) => { + if (x > 0) { doThing(x); } + }); + } + } + `, 'sample.ts'); + const byName = Object.fromEntries(results.map((fn) => [ fn.name, fn.cognitive ])); + // outer: if +1 (n0) = 1; the callback is its own unit: if +1 (n0) = 1 (nesting does NOT carry in) + expect(byName).toEqual({ outer: 1, '<anonymous>': 1 }); + }); + + it('records a contribution per increment with line, amount, reason and nesting', () => { + const [ fn ] = computeFunctionComplexities(` + function f(a: boolean, b: boolean) { + if (a) { + if (b) { return 1; } + } + } + `, 'sample.ts'); + expect(fn.contributions).toEqual([ + { line: 3, amount: 1, reason: 'if', nesting: 0 }, + { line: 4, amount: 2, reason: 'if', nesting: 1 }, + ]); + }); + + it('does not count optional chaining toward cognitive complexity', () => { + expect(cognitiveOf('function f(x: any) { return x?.y?.z; }')).toBe(0); + }); +}); + +describe('computeFunctionComplexities — jsx/behavior classification (containsJsx)', () => { + // containsJsx keyed by function name, for asserting the direct-JSX boundary. + function jsxByName(source: string): Record<string, boolean> { + return Object.fromEntries( + computeFunctionComplexities(source, 'sample.tsx').map((fn) => [ fn.name, fn.containsJsx ]), + ); + } + + it('marks a render body that directly contains JSX', () => { + expect(jsxByName('const C = () => <div><span/></div>;')).toEqual({ C: true }); + }); + + it('marks an inline `.map(x => <Row/>)` callback jsx, and the component too', () => { + // Both directly contain JSX in their own bodies: the component holds <ul>, the callback holds <li>. + expect(jsxByName(` + const List = (items: Array<number>) => <ul>{ items.map((n) => <li>{ n }</li>) }</ul>; + `)).toEqual({ List: true, '<anonymous>': true }); + }); + + it('classifies an onClick/useCallback handler that renders nothing as behavior', () => { + // The handler's own body has no JSX (it only reaches JSX through no nested function) -> behavior; + // the component around it is jsx. + const byName = jsxByName(` + const Button = () => { + const handleClick = () => { doThing(); }; + return <button onClick={ handleClick }>go</button>; + }; + `); + expect(byName).toEqual({ Button: true, handleClick: false }); + }); + + it('classifies a hook whose JSX only lives in a nested function as behavior', () => { + // The hook body reaches JSX solely through the returned render function, so the JSX marks the + // nested function, not the hook itself. + const byName = jsxByName(` + const useRenderRow = () => { + return (n: number) => <div>{ n }</div>; + }; + `); + expect(byName).toEqual({ useRenderRow: false, '<anonymous>': true }); + }); + + it('classifies a JSX-less `.tsx` hook as behavior', () => { + expect(jsxByName('const useValue = (x: number) => { return x > 0 ? 1 : 0; };')).toEqual({ useValue: false }); + }); +}); diff --git a/tools/code-complexity/measure/complexity.ts b/tools/code-complexity/measure/complexity.ts new file mode 100644 index 00000000000..dce77ab753f --- /dev/null +++ b/tools/code-complexity/measure/complexity.ts @@ -0,0 +1,339 @@ +import ts from 'typescript'; + +// Per-function complexity from a single walk of the syntax tree produced by ts.createSourceFile +// (no type-checker). Two scores accrue on the *same* walk: `complexity` (cyclomatic, the CRAP input) +// and `cognitive` (the readability gate), with every cognitive increment recorded in +// `contributions` so a violation can name the sites that cost the most. +// +// ../docs/MODEL.md is the specification — which constructs increment, how nesting is charged, and the +// divergences from SonarSource and ESLint. The ADRs cited below live in ../adr/. + +export interface Contribution { + // Line of the construct that added the increment (1-based). + readonly line: number; + // Cognitive-complexity points this construct added. + readonly amount: number; + // Human-readable construct name, surfaced in violation annotations. + readonly reason: string; + // Nesting depth this construct sits at (0 = function top level). Used to locate the deepest pocket + // for the "flatten this" annotation. + readonly nesting: number; +} + +export interface FunctionComplexity { + name: string; + // 1-based inclusive line range of the whole function node, used by diff-scoping to decide + // whether a changed line falls within the function. + startLine: number; + endLine: number; + // Cyclomatic complexity — the CRAP input. Never gated directly. + complexity: number; + // Cognitive complexity — the readability gate. + cognitive: number; + // Every cognitive increment, in walk order. Empty when `cognitive` is 0. + contributions: Array<Contribution>; + // Whether JSX appears directly in this function's own body — outside any nested function. This + // classifies the function `jsx` vs `behavior`, which selects its cognitive cap and whether CRAP + // applies (../docs/MODEL.md). A `.map(x => <Row/>)` callback is `jsx`; an `onClick` handler that + // renders nothing is `behavior`, even inside a component. + containsJsx: boolean; +} + +// JSX node kinds that mark a function as directly containing JSX. Exported so ./jsx.ts (the +// file-level detector) shares one definition rather than keeping a parallel copy. +export const JSX_KINDS: ReadonlySet<ts.SyntaxKind> = new Set([ + ts.SyntaxKind.JsxElement, + ts.SyntaxKind.JsxSelfClosingElement, + ts.SyntaxKind.JsxFragment, +]); + +const FUNCTION_KINDS: ReadonlySet<ts.SyntaxKind> = new Set([ + ts.SyntaxKind.FunctionDeclaration, + ts.SyntaxKind.FunctionExpression, + ts.SyntaxKind.ArrowFunction, + ts.SyntaxKind.MethodDeclaration, + ts.SyntaxKind.Constructor, + ts.SyntaxKind.GetAccessor, + ts.SyntaxKind.SetAccessor, +]); + +// Binary operators that introduce a branch: the short-circuiting logical operators and their +// compound-assignment forms. ESLint's `complexity` rule counts all of these toward cyclomatic. +const LOGICAL_OPERATORS: ReadonlySet<ts.SyntaxKind> = new Set([ + ts.SyntaxKind.AmpersandAmpersandToken, + ts.SyntaxKind.BarBarToken, + ts.SyntaxKind.QuestionQuestionToken, + ts.SyntaxKind.AmpersandAmpersandEqualsToken, + ts.SyntaxKind.BarBarEqualsToken, + ts.SyntaxKind.QuestionQuestionEqualsToken, +]); + +// The expression-level logical operators that form cognitive "boolean sequences": a run of the same +// operator costs +1 for the whole run, and switching operator starts a new run. Compound-assignment +// forms are not sequence operators (they are statements, not chains). Null-coalescing (`??`, `??=`) +// is deliberately absent — ADR 0002. +const SEQUENCE_OPERATORS: ReadonlyMap<ts.SyntaxKind, string> = new Map([ + [ ts.SyntaxKind.AmpersandAmpersandToken, '&&' ], + [ ts.SyntaxKind.BarBarToken, '||' ], +]); + +// Cognitive-complexity reasons whose increment carries the nesting penalty (`1 + nesting²`). Used to +// estimate how much flattening the deepest pocket would save. +const NESTING_STRUCTURE_REASONS: ReadonlySet<string> = new Set([ + 'if', 'ternary', 'catch', 'switch', 'for loop', 'for-in loop', 'for-of loop', 'while loop', 'do-while loop', +]); + +export function isNestingStructureReason(reason: string): boolean { + return NESTING_STRUCTURE_REASONS.has(reason); +} + +// What one nesting structure costs at `nesting` levels deep. SonarSource charges `1 + nesting`; we +// charge `1 + nesting²` — a deliberate divergence, and the caps are calibrated against it (ADR 0002). +export function nestingIncrement(nesting: number): number { + return 1 + nesting * nesting; +} + +// What flattening the deepest pocket by one level saves per nesting structure sitting there: +// `nesting² − (nesting − 1)²`, i.e. the odd numbers 1, 3, 5, … as depth grows. +export function flatteningSaving(nesting: number): number { + return nestingIncrement(nesting) - nestingIncrement(nesting - 1); +} + +function countsAsBranch(node: ts.Node): boolean { + switch (node.kind) { + case ts.SyntaxKind.IfStatement: + case ts.SyntaxKind.ForStatement: + case ts.SyntaxKind.ForInStatement: + case ts.SyntaxKind.ForOfStatement: + case ts.SyntaxKind.WhileStatement: + case ts.SyntaxKind.DoStatement: + case ts.SyntaxKind.CaseClause: // DefaultClause is intentionally not counted + case ts.SyntaxKind.CatchClause: + case ts.SyntaxKind.ConditionalExpression: // ternary + return true; + case ts.SyntaxKind.BinaryExpression: + return LOGICAL_OPERATORS.has((node as ts.BinaryExpression).operatorToken.kind); + // Optional chaining `?.` short-circuits but is deliberately not counted — ADR 0001. + default: + return false; + } +} + +const LOOP_REASONS: ReadonlyMap<ts.SyntaxKind, string> = new Map([ + [ ts.SyntaxKind.ForStatement, 'for loop' ], + [ ts.SyntaxKind.ForInStatement, 'for-in loop' ], + [ ts.SyntaxKind.ForOfStatement, 'for-of loop' ], + [ ts.SyntaxKind.WhileStatement, 'while loop' ], + [ ts.SyntaxKind.DoStatement, 'do-while loop' ], +]); + +function inferName(node: ts.Node): string { + if (ts.isFunctionDeclaration(node)) { + return node.name?.text ?? '<anonymous>'; + } + if (ts.isConstructorDeclaration(node)) { + return 'constructor'; + } + if (ts.isMethodDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node)) { + const base = node.name.getText(); + if (ts.isGetAccessorDeclaration(node)) return `get ${ base }`; + if (ts.isSetAccessorDeclaration(node)) return `set ${ base }`; + return base; + } + if (ts.isFunctionExpression(node) && node.name) { + return node.name.text; + } + // Arrow functions and anonymous function expressions: recover a name from the binding context. + const parent = node.parent; + if (parent) { + if (ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name)) { + return parent.name.text; + } + if (ts.isPropertyDeclaration(parent) || ts.isPropertyAssignment(parent)) { + return parent.name.getText(); + } + if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken) { + return parent.left.getText(); + } + } + return '<anonymous>'; +} + +// The bare identifier a function calls to recur on itself, when it has one. Recursion is detected by +// name match only (no type-checker): a call whose callee is this identifier is direct self-recursion. +// Methods/`this.x()` and destructured/aliased calls are not caught — a documented approximation. +function selfCallName(node: ts.Node): string | undefined { + if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) { + if (node.name) return node.name.text; + } + if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) { + const parent = node.parent; + if (parent && ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name)) { + return parent.name.text; + } + } + return undefined; +} + +export function scriptKind(fileName: string): ts.ScriptKind { + return fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS; +} + +interface Frame { + readonly node: ts.Node; + readonly selfName: string | undefined; + complexity: number; + cognitive: number; + containsJsx: boolean; + readonly contributions: Array<Contribution>; +} + +function isElseIf(node: ts.IfStatement): boolean { + const parent = node.parent; + return parent !== undefined && ts.isIfStatement(parent) && parent.elseStatement === node; +} + +export function computeFunctionComplexities(sourceText: string, fileName: string): Array<FunctionComplexity> { + const sourceFile = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.Latest, true, scriptKind(fileName)); + const results: Array<FunctionComplexity> = []; + + const lineOf = (pos: number): number => sourceFile.getLineAndCharacterOfPosition(pos).line + 1; + + const add = (frame: Frame, node: ts.Node, amount: number, reason: string, nesting: number): void => { + frame.cognitive += amount; + frame.contributions.push({ line: lineOf(node.getStart(sourceFile)), amount, reason, nesting }); + }; + + const recurse = (node: ts.Node, frame: Frame | null, nesting: number): void => + ts.forEachChild(node, (child) => visit(child, frame, nesting)); + + // Cyclomatic, JSX classification, recursion and labelled-jump increments apply to every node + // identically, however the node is reached. Cognitive nesting-structure increments are applied by + // the per-kind traversal below, because they depend on `nesting` and on how children are descended. + const applyUniversal = (node: ts.Node, frame: Frame, nesting: number): void => { + if (countsAsBranch(node)) frame.complexity += 1; + if (JSX_KINDS.has(node.kind)) frame.containsJsx = true; + + if (ts.isBinaryExpression(node)) { + const operator = SEQUENCE_OPERATORS.get(node.operatorToken.kind); + if (operator !== undefined) { + // A run of like operators costs +1 once; a different operator (or any non-logical parent, + // e.g. parentheses) starts a fresh run. `a && b && c` = +1; `a && b || c` = +2. + const parent = node.parent; + const continuesRun = parent !== undefined && ts.isBinaryExpression(parent) && + parent.operatorToken.kind === node.operatorToken.kind; + if (!continuesRun) add(frame, node, 1, `logical sequence (${ operator })`, nesting); + } + } + + if ((ts.isBreakStatement(node) || ts.isContinueStatement(node)) && node.label) { + add(frame, node, 1, ts.isBreakStatement(node) ? 'labelled break' : 'labelled continue', nesting); + } + + if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && + frame.selfName !== undefined && node.expression.text === frame.selfName) { + add(frame, node, 1, 'recursion', nesting); + } + }; + + // An `if` chain is the one construct whose traversal needs its own branch pocket — a leading `if` + // pays the nesting price, an `else if` continues flat, and a bare `else` nests its body. Kept out + // of `visit` so that pocket is scored against this function rather than deepening every other arm + // of the dispatch below. + const visitIfStatement = (node: ts.IfStatement, frame: Frame, nesting: number): void => { + // `else if` (an if that is its parent's else branch) is a flat continuation: +1, no nesting + // penalty, and the chain stays at the same base level. A leading `if` pays the nesting price. + if (isElseIf(node)) add(frame, node, 1, 'else if', nesting); + else add(frame, node, nestingIncrement(nesting), 'if', nesting); + + visit(node.expression, frame, nesting); + visit(node.thenStatement, frame, nesting + 1); + + const elseStatement = node.elseStatement; + if (elseStatement === undefined) return; + if (ts.isIfStatement(elseStatement)) { + visit(elseStatement, frame, nesting); // else-if handled as its own continuation + return; + } + // A bare `else` costs +1 with no nesting penalty; its body nests one level deeper. + add(frame, elseStatement, 1, 'else', nesting); + visit(elseStatement, frame, nesting + 1); + }; + + const visit = (node: ts.Node, frame: Frame | null, nesting: number): void => { + if (FUNCTION_KINDS.has(node.kind)) { + // Every function is its own unit: nesting resets to 0 and branches accrue only to it. A nested + // function is a separate frame, so its body never counts toward the enclosing one. + const inner: Frame = { + node, + selfName: selfCallName(node), + complexity: 1, + cognitive: 0, + containsJsx: false, + contributions: [], + }; + recurse(node, inner, 0); + results.push({ + name: inferName(node), + startLine: lineOf(node.getStart(sourceFile)), + endLine: lineOf(node.getEnd()), + complexity: inner.complexity, + cognitive: inner.cognitive, + contributions: inner.contributions, + containsJsx: inner.containsJsx, + }); + return; + } + + // Constructs at module scope belong to no function and are ignored (only nested functions matter), + // matching ESLint's per-function reporting. + if (frame === null) { + recurse(node, null, nesting); + return; + } + + applyUniversal(node, frame, nesting); + + if (ts.isIfStatement(node)) { + visitIfStatement(node, frame, nesting); + return; + } + + if (ts.isConditionalExpression(node)) { + add(frame, node, nestingIncrement(nesting), 'ternary', nesting); + visit(node.condition, frame, nesting); + visit(node.whenTrue, frame, nesting + 1); + visit(node.whenFalse, frame, nesting + 1); + return; + } + + const loopReason = LOOP_REASONS.get(node.kind); + if (loopReason !== undefined) { + add(frame, node, nestingIncrement(nesting), loopReason, nesting); + // Only the loop body nests; the header (init/condition/update) stays at the current level. + ts.forEachChild(node, (child) => visit(child, frame, child === (node as ts.IterationStatement).statement ? nesting + 1 : nesting)); + return; + } + + if (ts.isCatchClause(node)) { + add(frame, node, nestingIncrement(nesting), 'catch', nesting); + if (node.variableDeclaration) visit(node.variableDeclaration, frame, nesting); + visit(node.block, frame, nesting + 1); + return; + } + + if (ts.isSwitchStatement(node)) { + // One increment for the whole switch, never per-case as cyclomatic does; its body nests a level + // so control flow inside a case pays for the depth. + add(frame, node, nestingIncrement(nesting), 'switch', nesting); + visit(node.expression, frame, nesting); + visit(node.caseBlock, frame, nesting + 1); + return; + } + + recurse(node, frame, nesting); + }; + + visit(sourceFile, null, 0); + return results; +} diff --git a/tools/code-complexity/measure/crap.spec.ts b/tools/code-complexity/measure/crap.spec.ts new file mode 100644 index 00000000000..9e0ee951d45 --- /dev/null +++ b/tools/code-complexity/measure/crap.spec.ts @@ -0,0 +1,26 @@ +import { describe, it, expect } from 'vitest'; + +import { crapScore } from './crap'; + +describe('crapScore', () => { + it('reduces to the complexity when fully covered', () => { + // cov 1 -> c²·0 + c = c + expect(crapScore(5, 1)).toBe(5); + }); + + it('is c² + c at zero coverage', () => { + // cov 0 -> c²·1 + c + expect(crapScore(5, 0)).toBe(30); + expect(crapScore(10, 0)).toBe(110); + }); + + it('crosses 30 at complexity 6 with zero coverage but not at 5', () => { + expect(crapScore(5, 0)).toBe(30); // not > 30 + expect(crapScore(6, 0)).toBe(42); // > 30 + }); + + it('scales the coverage gap cubically', () => { + // c=4, cov=0.5 -> 16·0.125 + 4 = 6 + expect(crapScore(4, 0.5)).toBe(6); + }); +}); diff --git a/tools/code-complexity/measure/crap.ts b/tools/code-complexity/measure/crap.ts new file mode 100644 index 00000000000..e2b663b0df2 --- /dev/null +++ b/tools/code-complexity/measure/crap.ts @@ -0,0 +1,9 @@ +// CRAP (Change Risk Anti-Patterns) score: CRAP = c²·(1 − cov)³ + c, where c is the cyclomatic +// complexity and cov is the line-coverage fraction (0..1). Well-covered code scores near its +// complexity (cov = 1 gives exactly c); the cubic (1 − cov) term makes complex, untested code +// explode. At 0% coverage the score is c² + c. The cap it is measured against lives in ../config.ts. + +export function crapScore(complexity: number, coverage: number): number { + const uncovered = 1 - coverage; + return complexity * complexity * uncovered * uncovered * uncovered + complexity; +} diff --git a/tools/code-complexity/measure/jsx.spec.ts b/tools/code-complexity/measure/jsx.spec.ts new file mode 100644 index 00000000000..e063fba3462 --- /dev/null +++ b/tools/code-complexity/measure/jsx.spec.ts @@ -0,0 +1,37 @@ +import { describe, it, expect } from 'vitest'; + +import { fileContainsJsx } from './jsx'; + +describe('fileContainsJsx', () => { + it('detects a JSX element', () => { + expect(fileContainsJsx('const C = () => <div className="a">hi</div>;', 'C.tsx')).toBe(true); + }); + + it('detects a self-closing element', () => { + expect(fileContainsJsx('const C = () => <br/>;', 'C.tsx')).toBe(true); + }); + + it('detects a fragment', () => { + expect(fileContainsJsx('const C = () => <><span/></>;', 'C.tsx')).toBe(true); + }); + + it('classifies a .tsx hook with no JSX as logic', () => { + // A useX.tsx hook that returns data, never markup — the case FR4 exists for. + const source = ` + export function useThing(x: number) { + const doubled = x * 2; + return { doubled, ok: doubled > 0 }; + } + `; + expect(fileContainsJsx(source, 'useThing.tsx')).toBe(false); + }); + + it('is false for a plain .ts logic file', () => { + expect(fileContainsJsx('export const add = (a: number, b: number) => a + b;', 'add.ts')).toBe(false); + }); + + it('does not treat a generic type argument as JSX in a .ts file', () => { + // `<T>` here is a type parameter, not JSX; a .ts file never parses JSX. + expect(fileContainsJsx('const f = <T,>(x: T): T => x;', 'f.ts')).toBe(false); + }); +}); diff --git a/tools/code-complexity/measure/jsx.ts b/tools/code-complexity/measure/jsx.ts new file mode 100644 index 00000000000..a717151d514 --- /dev/null +++ b/tools/code-complexity/measure/jsx.ts @@ -0,0 +1,26 @@ +import ts from 'typescript'; + +import { JSX_KINDS, scriptKind } from './complexity'; + +// File-level JSX detection: whether a file contains JSX *anywhere*, read from the AST rather than +// from the extension, which is an unreliable component-vs-logic signal here (../docs/MODEL.md). +// +// This drives only the "does this file need vitest coverage generated" decision. Per-function +// `jsx`/`behavior` classification is a separate walk, in ./complexity.ts. + +export function fileContainsJsx(sourceText: string, fileName: string): boolean { + const sourceFile = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.Latest, true, scriptKind(fileName)); + + let found = false; + const visit = (node: ts.Node): void => { + if (found) return; + if (JSX_KINDS.has(node.kind)) { + found = true; + return; + } + ts.forEachChild(node, visit); + }; + visit(sourceFile); + + return found; +} diff --git a/tools/code-complexity/render/github.spec.ts b/tools/code-complexity/render/github.spec.ts new file mode 100644 index 00000000000..9683e0d3dbd --- /dev/null +++ b/tools/code-complexity/render/github.spec.ts @@ -0,0 +1,83 @@ +import { describe, it, expect } from 'vitest'; + +import type { Contribution } from '../measure/complexity'; +import { githubAnnotations, stepSummary } from './github'; +import type { ReportRow } from './report'; + +const THRESHOLDS = { maxCognitiveJsx: 25, maxCognitiveBehavior: 20, maxCrap: 30 }; + +function row(overrides: Partial<ReportRow>): ReportRow { + return { + file: 'src/f.ts', + line: 1, + name: 'fn', + kind: 'behavior', + complexity: 1, + cognitive: 1, + contributions: [], + coverage: null, + crap: null, + brokeCognitive: false, + brokeCrap: false, + ...overrides, + }; +} + +// A cognitive-complexity offender's increment sites: a shallow if and a deeply-nested one. +const CONTRIBUTIONS: Array<Contribution> = [ + { line: 3, amount: 1, reason: 'if', nesting: 0 }, + { line: 5, amount: 5, reason: 'if', nesting: 2 }, +]; + +describe('githubAnnotations', () => { + it('emits one actionable ::error per cognitive offender, naming top sites and the deepest pocket', () => { + const annotations = githubAnnotations([ + row({ file: 'src/a.ts', line: 12, name: 'big', kind: 'behavior', cognitive: 25, brokeCognitive: true, contributions: CONTRIBUTIONS }), + row({ file: 'src/b.ts', line: 3, name: 'ok' }), + ], THRESHOLDS); + expect(annotations).toEqual([ + '::error file=src/a.ts,line=12::big: cognitive 25 > 20 [top: if +5 (L5), if +1 (L3); deepest nesting 2 at L5, flattening saves ~3]', + ]); + }); + + it('omits the deepest-pocket clause when nothing is nested', () => { + const [ annotation ] = githubAnnotations([ + row({ name: 'flat', cognitive: 21, brokeCognitive: true, contributions: [ { line: 2, amount: 1, reason: 'switch', nesting: 0 } ] }), + ], THRESHOLDS); + expect(annotation).toBe('::error file=src/f.ts,line=1::flat: cognitive 21 > 20 [top: switch +1 (L2)]'); + }); + + it('names both thresholds when a function breaks both', () => { + const [ annotation ] = githubAnnotations([ + row({ name: 'both', cognitive: 25, coverage: 0, crap: 90, brokeCognitive: true, brokeCrap: true, contributions: CONTRIBUTIONS }), + ], THRESHOLDS); + const cognitivePart = 'cognitive 25 > 20 [top: if +5 (L5), if +1 (L3); deepest nesting 2 at L5, flattening saves ~3]'; + expect(annotation).toBe(`::error file=src/f.ts,line=1::both: ${ cognitivePart }; CRAP 90.0 > 30`); + }); + + it('emits only the CRAP clause for a CRAP-only offender', () => { + const [ annotation ] = githubAnnotations([ + row({ name: 'crapOnly', coverage: 0, crap: 72, brokeCrap: true }), + ], THRESHOLDS); + expect(annotation).toBe('::error file=src/f.ts,line=1::crapOnly: CRAP 72.0 > 30'); + }); + + it('names the jsx cap for a jsx offender', () => { + const [ annotation ] = githubAnnotations([ + row({ name: 'render', kind: 'jsx', cognitive: 30, brokeCognitive: true, contributions: [ { line: 4, amount: 1, reason: 'ternary', nesting: 0 } ] }), + ], THRESHOLDS); + expect(annotation).toBe('::error file=src/f.ts,line=1::render: cognitive 30 > 25 [top: ternary +1 (L4)]'); + }); + + it('returns nothing when no function broke a threshold', () => { + expect(githubAnnotations([ row({ crap: 3, coverage: 1 }) ], THRESHOLDS)).toEqual([]); + }); +}); + +describe('stepSummary', () => { + it('fences the table under a heading so the job summary keeps its alignment', () => { + const summary = stepSummary('FUNCTION COG\nsrc/f.ts 1'); + expect(summary).toContain('## Cognitive complexity & CRAP gate'); + expect(summary).toContain('```\nFUNCTION COG\nsrc/f.ts 1\n```'); + }); +}); diff --git a/tools/code-complexity/render/github.ts b/tools/code-complexity/render/github.ts new file mode 100644 index 00000000000..cfa74ca6d66 --- /dev/null +++ b/tools/code-complexity/render/github.ts @@ -0,0 +1,63 @@ +// GitHub Actions output path: inline `::error` annotations on the PR diff for each +// offender, plus the full report table written to the job summary. Pure formatters here; the +// side effects (stdout + $GITHUB_STEP_SUMMARY) live in index.ts, guarded by $GITHUB_ACTIONS. + +import type { Contribution } from '../measure/complexity'; +import { flatteningSaving, isNestingStructureReason } from '../measure/complexity'; +import type { ReportRow, Thresholds } from './report'; +import { isOffender, maxCognitiveFor } from './report'; + +// How many top increment sites to name in a cognitive-complexity annotation before the reader should +// just open the function. +const TOP_CONTRIBUTORS = 3; + +// Annotation directives are single-line; a newline would truncate the message and break the rest. +function sanitize(message: string): string { + return message.replace(/[\r\n]+/g, ' '); +} + +// The heaviest increment sites, worst first, as "reason +amount (L<line>)". +function topContributors(contributions: ReadonlyArray<Contribution>): string { + return [ ...contributions ] + .sort((a, b) => b.amount - a.amount) + .slice(0, TOP_CONTRIBUTORS) + .map((contribution) => `${ contribution.reason } +${ contribution.amount } (L${ contribution.line })`) + .join(', '); +} + +// The deepest nesting pocket and what flattening it by one level would save. Only nesting structures +// count toward the saving — flat increments (else, boolean runs) carry no nesting penalty. +function deepestPocket(contributions: ReadonlyArray<Contribution>): string { + const maxNesting = Math.max(0, ...contributions.map((contribution) => contribution.nesting)); + if (maxNesting === 0) return ''; // nothing nested to flatten + + const atDepth = contributions.filter((contribution) => contribution.nesting === maxNesting); + const line = atDepth[0].line; + const saving = atDepth.filter((contribution) => isNestingStructureReason(contribution.reason)).length * + flatteningSaving(maxNesting); + const savingText = saving > 0 ? `, flattening saves ~${ saving }` : ''; + return `deepest nesting ${ maxNesting } at L${ line }${ savingText }`; +} + +function offenderMessage(row: ReportRow, thresholds: Thresholds): string { + const parts: Array<string> = []; + if (row.brokeCognitive) { + const detail = [ `top: ${ topContributors(row.contributions) }`, deepestPocket(row.contributions) ].filter(Boolean).join('; '); + parts.push(`cognitive ${ row.cognitive } > ${ maxCognitiveFor(row.kind, thresholds) } [${ detail }]`); + } + // crap is non-null whenever brokeCrap is true (the CRAP gate only trips on a scored function). + if (row.brokeCrap) parts.push(`CRAP ${ (row.crap as number).toFixed(1) } > ${ thresholds.maxCrap }`); + return `${ row.name }: ${ parts.join('; ') }`; +} + +// One `::error file=<f>,line=<n>::<msg>` per offender — GitHub surfaces these inline on the diff. +export function githubAnnotations(rows: ReadonlyArray<ReportRow>, thresholds: Thresholds): Array<string> { + return rows + .filter(isOffender) + .map((row) => `::error file=${ row.file },line=${ row.line }::${ sanitize(offenderMessage(row, thresholds)) }`); +} + +// The full table, fenced so the job summary renders it monospace (its column alignment survives). +export function stepSummary(table: string): string { + return [ '## Cognitive complexity & CRAP gate', '', '```', table, '```', '' ].join('\n'); +} diff --git a/tools/code-complexity/render/report.spec.ts b/tools/code-complexity/render/report.spec.ts new file mode 100644 index 00000000000..b2150b80eb4 --- /dev/null +++ b/tools/code-complexity/render/report.spec.ts @@ -0,0 +1,83 @@ +import { describe, it, expect } from 'vitest'; + +import type { ReportRow } from './report'; +import { formatTable } from './report'; + +const THRESHOLDS = { maxCognitiveJsx: 25, maxCognitiveBehavior: 20, maxCrap: 30 }; + +function row(overrides: Partial<ReportRow>): ReportRow { + return { + file: 'src/f.ts', + line: 1, + name: 'fn', + kind: 'behavior', + complexity: 1, + cognitive: 1, + contributions: [], + coverage: null, + crap: null, + brokeCognitive: false, + brokeCrap: false, + ...overrides, + }; +} + +describe('formatTable', () => { + it('sorts by CRAP descending, null-CRAP rows last', () => { + const table = formatTable([ + row({ name: 'low', crap: 12, coverage: 0.5 }), + row({ name: 'jsx', crap: null, coverage: null }), + row({ name: 'high', crap: 72, coverage: 0 }), + ], THRESHOLDS); + const order = table.split('\n').slice(1, 4).map((l) => l.match(/high|low|jsx/)?.[0]); + expect(order).toEqual([ 'high', 'low', 'jsx' ]); + }); + + it('renders coverage% and CRAP, showing — when the coverage half does not apply', () => { + const table = formatTable([ row({ name: 'logic', crap: 72, coverage: 0 }), row({ name: 'comp', crap: null, coverage: null }) ], THRESHOLDS); + expect(table).toContain('0%'); + expect(table).toContain('72.0'); + expect(table).toContain('—'); + }); + + it('shows COG (not CX) by default; CX appears only under --verbose', () => { + const rows = [ row({ name: 'fn', cognitive: 7, complexity: 12, crap: 5, coverage: 1 }) ]; + const header = formatTable(rows, THRESHOLDS).split('\n')[0]; + expect(header).toContain('COG'); + expect(header).not.toMatch(/\bCX\b/); + + const verboseHeader = formatTable(rows, THRESHOLDS, true).split('\n')[0]; + expect(verboseHeader).toContain('COG'); + expect(verboseHeader).toContain('CX'); + }); + + it('names which threshold each offender broke', () => { + const table = formatTable([ + row({ name: 'both', cognitive: 25, crap: 90, coverage: 0, brokeCognitive: true, brokeCrap: true }), + row({ name: 'crapOnly', cognitive: 8, crap: 72, coverage: 0, brokeCrap: true }), + ], THRESHOLDS); + expect(table).toMatch(/both.*COG\+CRAP/); + expect(table).toMatch(/crapOnly.*CRAP/); + }); + + it('flags offenders and summarises the count', () => { + const table = formatTable([ row({ crap: 72, coverage: 0, brokeCrap: true }) ], THRESHOLDS); + expect(table).toContain('✗'); + expect(table).toContain('1 function(s) broke a threshold'); + }); + + it('reports all-clear when nothing broke', () => { + const table = formatTable([ row({ crap: 3, coverage: 1 }) ], THRESHOLDS); + expect(table).toContain('within thresholds'); + }); + + it('renders a KIND column showing each function class', () => { + const table = formatTable([ + row({ name: 'render', kind: 'jsx', crap: null, coverage: null }), + row({ name: 'handler', kind: 'behavior', crap: 5, coverage: 1 }), + ], THRESHOLDS); + expect(table).toContain('KIND'); + expect(table).toMatch(/render.*jsx/); + expect(table).toMatch(/handler.*behavior/); + }); +}); diff --git a/tools/code-complexity/render/report.ts b/tools/code-complexity/render/report.ts new file mode 100644 index 00000000000..05476987a49 --- /dev/null +++ b/tools/code-complexity/render/report.ts @@ -0,0 +1,122 @@ +// Renders the results table: every checked function with its cognitive complexity, coverage%, CRAP, +// and which threshold (if any) it broke, sorted by CRAP descending with offenders flagged. + +import type { Contribution } from '../measure/complexity'; + +// A function's class, decided by whether JSX appears directly in its own body (../measure/complexity.ts). +export type FunctionKind = 'jsx' | 'behavior'; + +export interface ReportRow { + readonly file: string; + readonly line: number; + readonly name: string; + readonly kind: FunctionKind; + // Cyclomatic complexity — the CRAP input, shown only under --verbose. + readonly complexity: number; + // Cognitive complexity — the readability gate. + readonly cognitive: number; + // Cognitive-complexity increment sites, for the actionable violation annotation. + readonly contributions: ReadonlyArray<Contribution>; + // 0..1 line-coverage fraction; null when the coverage half does not apply (a `jsx` function, or no + // coverage report supplied). + readonly coverage: number | null; + readonly crap: number | null; // null whenever coverage is null + readonly brokeCognitive: boolean; + readonly brokeCrap: boolean; +} + +export interface Thresholds { + readonly maxCognitiveJsx: number; + readonly maxCognitiveBehavior: number; + readonly maxCrap: number; +} + +// The cognitive-complexity cap that applies to a function, chosen by its class. +export function maxCognitiveFor(kind: FunctionKind, thresholds: Thresholds): number { + return kind === 'jsx' ? thresholds.maxCognitiveJsx : thresholds.maxCognitiveBehavior; +} + +const OFFENDER_MARK = '✗'; +const OK_MARK = ''; +const NA = '—'; + +export function isOffender(row: ReportRow): boolean { + return row.brokeCognitive || row.brokeCrap; +} + +function pad(value: string, width: number): string { + return value.length >= width ? value : value + ' '.repeat(width - value.length); +} + +function padStart(value: string, width: number): string { + return value.length >= width ? value : ' '.repeat(width - value.length) + value; +} + +function coverageText(row: ReportRow): string { + return row.coverage === null ? NA : `${ Math.round(row.coverage * 100) }%`; +} + +function crapText(row: ReportRow): string { + return row.crap === null ? NA : row.crap.toFixed(1); +} + +function brokeText(row: ReportRow): string { + if (row.brokeCognitive && row.brokeCrap) return 'COG+CRAP'; + if (row.brokeCognitive) return 'COG'; + if (row.brokeCrap) return 'CRAP'; + return ''; +} + +// Sort by CRAP descending so the worst offenders lead; JSX/no-coverage rows (null CRAP) fall to the +// bottom, tie-broken by cognitive complexity so they stay usefully ordered. +function byCrapDescending(a: ReportRow, b: ReportRow): number { + return (b.crap ?? -1) - (a.crap ?? -1) || b.cognitive - a.cognitive; +} + +// A column: header, a cell renderer, and whether cells right-align (numbers) or left-align (text). +interface Column { + readonly header: string; + readonly cell: (row: ReportRow) => string; + readonly alignRight: boolean; +} + +// `verbose` adds the CX (cyclomatic) column, off by default: coverage is the only fix for a CRAP +// failure, so CX is never actionable in the default view. +function columnsFor(verbose: boolean): Array<Column> { + const columns: Array<Column> = [ + { header: 'FUNCTION', cell: (row) => `${ row.file }:${ row.line }`, alignRight: false }, + { header: 'NAME', cell: (row) => row.name, alignRight: false }, + { header: 'KIND', cell: (row) => row.kind, alignRight: false }, + { header: 'COG', cell: (row) => String(row.cognitive), alignRight: true }, + { header: 'COV', cell: coverageText, alignRight: true }, + { header: 'CRAP', cell: crapText, alignRight: true }, + { header: 'BROKE', cell: brokeText, alignRight: false }, + ]; + if (verbose) columns.splice(3, 0, { header: 'CX', cell: (row) => String(row.complexity), alignRight: true }); + return columns; +} + +export function formatTable(rows: ReadonlyArray<ReportRow>, thresholds: Thresholds, verbose = false): string { + const sorted = [ ...rows ].sort(byCrapDescending); + const columns = columnsFor(verbose); + + // The flag column is a fixed 1-char gutter; the rest size to their widest cell. + const widths = columns.map((column) => Math.max(column.header.length, ...sorted.map((row) => column.cell(row).length))); + const renderRow = (flag: string, cells: ReadonlyArray<string>): string => + [ pad(flag, 1), ...cells.map((cell, index) => columns[index].alignRight ? padStart(cell, widths[index]) : pad(cell, widths[index])) ].join(' '); + + const lines: Array<string> = []; + lines.push(renderRow('', columns.map((column) => column.header))); + for (const row of sorted) { + lines.push(renderRow(isOffender(row) ? OFFENDER_MARK : OK_MARK, columns.map((column) => column.cell(row)))); + } + + const caps = `cognitive jsx ${ thresholds.maxCognitiveJsx } / behavior ${ thresholds.maxCognitiveBehavior }, CRAP ${ thresholds.maxCrap }`; + const offenderCount = sorted.filter(isOffender).length; + lines.push(''); + lines.push(offenderCount > 0 ? + `${ offenderCount } function(s) broke a threshold (${ caps }).` : + `All ${ sorted.length } checked function(s) are within thresholds (${ caps }).`); + + return lines.join('\n'); +} diff --git a/tools/code-complexity/run.sh b/tools/code-complexity/run.sh new file mode 100755 index 00000000000..acba4a2fcb8 --- /dev/null +++ b/tools/code-complexity/run.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +# Usage: tools/code-complexity/run.sh [--base <ref>] [--max-cognitive <n>] [<path>...] + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" + +# The tool imports the shared flag parser from ../cli, so tsc's rootDir spans the tools folder and +# the entry point lands one level deeper than the outDir. +"$ROOT/node_modules/.bin/tsc" -p "$DIR/tsconfig.json" +node "$DIR/dist/code-complexity/index.js" "$@" diff --git a/tools/code-complexity/select/diff.spec.ts b/tools/code-complexity/select/diff.spec.ts new file mode 100644 index 00000000000..6e1bdab59ab --- /dev/null +++ b/tools/code-complexity/select/diff.spec.ts @@ -0,0 +1,48 @@ +import { describe, it, expect } from 'vitest'; + +import { parseHunkNewRanges, rangesOverlap } from './diff'; + +describe('parseHunkNewRanges', () => { + it('reads new-side ranges from unified=0 hunk headers', () => { + const diff = [ + 'diff --git a/src/f.ts b/src/f.ts', + '--- a/src/f.ts', + '+++ b/src/f.ts', + '@@ -10,0 +11,3 @@ some context', + '+a', + '+b', + '+c', + '@@ -20,2 +24 @@', + '+x', + ].join('\n'); + expect(parseHunkNewRanges(diff)).toEqual([ [ 11, 13 ], [ 24, 24 ] ]); + }); + + it('treats an omitted count as a single line', () => { + expect(parseHunkNewRanges('@@ -1 +5 @@')).toEqual([ [ 5, 5 ] ]); + }); + + it('skips pure deletions (new-side count of 0)', () => { + expect(parseHunkNewRanges('@@ -3,4 +2,0 @@')).toEqual([]); + }); + + it('ignores non-header lines', () => { + expect(parseHunkNewRanges('not a hunk\n+added\n-removed')).toEqual([]); + }); +}); + +describe('rangesOverlap', () => { + const ranges: Array<[ number, number ]> = [ [ 11, 13 ], [ 24, 24 ] ]; + + it('is true when a function range contains a changed line', () => { + expect(rangesOverlap(ranges, 5, 12)).toBe(true); // function spans lines 5..12, change at 11-13 + }); + + it('is true when a changed range sits fully inside the function', () => { + expect(rangesOverlap(ranges, 1, 30)).toBe(true); + }); + + it('is false when no changed line falls within the function', () => { + expect(rangesOverlap(ranges, 14, 23)).toBe(false); + }); +}); diff --git a/tools/code-complexity/select/diff.ts b/tools/code-complexity/select/diff.ts new file mode 100644 index 00000000000..a3f52792b93 --- /dev/null +++ b/tools/code-complexity/select/diff.ts @@ -0,0 +1,64 @@ +import { execFileSync } from 'child_process'; + +import { EXEC_MAX_BUFFER } from '../../cli/exec'; +import { isInScope } from './scope'; + +// Diff-scoping: map git-diff hunks against a base ref to the new-side line ranges a +// change added or modified, so the gate can select the functions those lines fall within. No +// baseline artifact is kept. + +export type LineRange = [ start: number, end: number ]; + +// Which repository the caller is asking about, passed explicitly rather than taken from the +// process's own directory: the mutation-testing specs point these at a throwaway repo, and +// process.chdir() is unavailable in the worker threads Stryker runs vitest in. +function git(args: ReadonlyArray<string>, cwd: string): string { + return execFileSync('git', args as Array<string>, { cwd, encoding: 'utf8', maxBuffer: EXEC_MAX_BUFFER }); +} + +// Compare against the merge-base of the branch and the base ref rather than the base ref tip: +// this captures the branch's own commits plus any uncommitted working-tree edits, and never +// reports files that only changed on the base branch since the fork point. +export function resolveBaseCommit(baseRef: string, cwd: string): string { + return git([ 'merge-base', baseRef, 'HEAD' ], cwd).trim(); +} + +export function getChangedFiles(baseCommit: string, cwd: string): Array<string> { + const out = git([ 'diff', '--name-only', baseCommit, '--' ], cwd); + return out.split('\n').map((line) => line.trim()).filter(Boolean); +} + +// Every in-scope file in the repo, for full-repo mode. It enumerates all tracked files and narrows +// them through isInScope rather than restating the scope rule as a git pathspec — ./scope.ts owns +// that rule, and a pathspec here would be a second copy to keep in sync with it. +export function getAllSourceFiles(cwd: string): Array<string> { + const out = git([ 'ls-files' ], cwd); + return out.split('\n').map((line) => line.trim()).filter(isInScope); +} + +export function getChangedLineRanges(baseCommit: string, file: string, cwd: string): Array<LineRange> { + const out = git([ 'diff', '--unified=0', '--no-color', baseCommit, '--', file ], cwd); + return parseHunkNewRanges(out); +} + +const HUNK_HEADER = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/; + +// Parse the new-side ('+') line ranges out of a `git diff --unified=0` body. A hunk header +// `@@ -a,b +c,d @@` means d lines starting at line c on the new side; d omitted means 1, and +// d === 0 is a pure deletion that adds no new lines. +export function parseHunkNewRanges(diffText: string): Array<LineRange> { + const ranges: Array<LineRange> = []; + for (const line of diffText.split('\n')) { + const match = HUNK_HEADER.exec(line); + if (!match) continue; + const start = Number(match[1]); + const count = match[2] === undefined ? 1 : Number(match[2]); + if (count === 0) continue; + ranges.push([ start, start + count - 1 ]); + } + return ranges; +} + +export function rangesOverlap(ranges: ReadonlyArray<LineRange>, start: number, end: number): boolean { + return ranges.some(([ rangeStart, rangeEnd ]) => rangeStart <= end && rangeEnd >= start); +} diff --git a/tools/code-complexity/select/eligibility.ts b/tools/code-complexity/select/eligibility.ts new file mode 100644 index 00000000000..cc09a21032d --- /dev/null +++ b/tools/code-complexity/select/eligibility.ts @@ -0,0 +1,9 @@ +import fs from 'fs'; + +// Whether a source file has a co-located vitest spec, by naming convention +// (foo.ts -> foo.spec.ts / foo.spec.tsx). Playwright tests (*.pw.tsx) do not count: no vitest +// coverage comes out of them. +export function hasCoLocatedSpec(file: string): boolean { + const base = file.slice(0, file.lastIndexOf('.')); + return fs.existsSync(`${ base }.spec.ts`) || fs.existsSync(`${ base }.spec.tsx`); +} diff --git a/tools/code-complexity/select/scope.spec.ts b/tools/code-complexity/select/scope.spec.ts new file mode 100644 index 00000000000..93730821504 --- /dev/null +++ b/tools/code-complexity/select/scope.spec.ts @@ -0,0 +1,85 @@ +import { describe, it, expect } from 'vitest'; + +import { isInScope, resolveScopedFiles } from './scope'; + +describe('isInScope', () => { + it('includes src .ts and .tsx files', () => { + expect(isInScope('src/lib/foo.ts')).toBe(true); + expect(isInScope('src/ui/Button.tsx')).toBe(true); + }); + + it('includes the repo tooling under tools/', () => { + expect(isInScope('tools/code-complexity/index.ts')).toBe(true); + expect(isInScope('tools/dev-server/fetch.ts')).toBe(true); + expect(isInScope('tools/profiling/aggregate.ts')).toBe(true); + }); + + it('includes the plain-JS extensions', () => { + expect(isInScope('src/server/redirects.js')).toBe(true); + expect(isInScope('tools/mutation-testing/eslint/well-formed-disable.mjs')).toBe(true); + expect(isInScope('tools/release/legacy.cjs')).toBe(true); + }); + + it('includes the container-startup tools under deploy/tools/', () => { + expect(isInScope('deploy/tools/envs-validator/index.ts')).toBe(true); + expect(isInScope('deploy/tools/envs-validator/schemas/features/rollup.ts')).toBe(true); + expect(isInScope('deploy/tools/favicon-generator/index.js')).toBe(true); + expect(isInScope('deploy/tools/llms-txt-generator/generate-standard.ts')).toBe(true); + }); + + it('excludes the deploy shell scripts', () => { + expect(isInScope('deploy/scripts/run.ts')).toBe(false); + }); + + it('excludes test support and configuration', () => { + expect(isInScope('playwright/TestApp.tsx')).toBe(false); + expect(isInScope('vitest/setup.ts')).toBe(false); + expect(isInScope('src/toolkit/package/vite.config.ts')).toBe(false); + expect(isInScope('tools/code-complexity/vitest.config.ts')).toBe(false); + }); + + it('excludes everything outside the allowlisted roots', () => { + expect(isInScope('startup.node.ts')).toBe(false); + expect(isInScope('instrumentation.ts')).toBe(false); + expect(isInScope('docs/example.ts')).toBe(false); + }); + + it('excludes non-source extensions', () => { + expect(isInScope('src/lib/data.json')).toBe(false); + expect(isInScope('src/lib/styles.css')).toBe(false); + expect(isInScope('tools/code-complexity/run.sh')).toBe(false); + }); + + it('excludes spec and Playwright test/story files', () => { + expect(isInScope('src/lib/foo.spec.ts')).toBe(false); + expect(isInScope('src/ui/Button.spec.tsx')).toBe(false); + expect(isInScope('src/ui/Button.pw.tsx')).toBe(false); + expect(isInScope('src/ui/Button.pwstory.tsx')).toBe(false); + expect(isInScope('tools/code-complexity/scope.spec.ts')).toBe(false); + }); + + it('excludes declaration files', () => { + expect(isInScope('src/types/global.d.ts')).toBe(false); + }); + + it('excludes build output', () => { + expect(isInScope('src/toolkit/package/dist/index.ts')).toBe(false); + expect(isInScope('tools/code-complexity/dist/index.js')).toBe(false); + // but toolkit source itself stays in scope + expect(isInScope('src/toolkit/components/Button.tsx')).toBe(true); + }); +}); + +describe('resolveScopedFiles', () => { + it('keeps only the in-scope paths', () => { + const input = [ + 'src/a.ts', + 'src/a.spec.ts', + 'tools/b.ts', + 'deploy/c.ts', + 'src/c.tsx', + 'src/d.d.ts', + ]; + expect(resolveScopedFiles(input)).toEqual([ 'src/a.ts', 'tools/b.ts', 'src/c.tsx' ]); + }); +}); diff --git a/tools/code-complexity/select/scope.ts b/tools/code-complexity/select/scope.ts new file mode 100644 index 00000000000..cb54e311682 --- /dev/null +++ b/tools/code-complexity/select/scope.ts @@ -0,0 +1,47 @@ +// File-scope resolution. The rule is an allowlist of directories — the app (`src/`), the repo's +// own tooling (`tools/`) and the container-startup tools (`deploy/tools/`) — rather than a prefix +// test plus exclusions: nothing about tooling code makes complexity or missing tests cheaper there, +// and `tools/code-complexity` in particular is gated by the very thing it implements. +// +// Three categories are deliberately out: +// +// - `deploy/scripts/**` — shell orchestration; the one TypeScript-free corner of deploy/. +// - `playwright/**`, `vitest/**`, `*.config.*` — test support and configuration, out on the same +// grounds specs are. +// - repo-root runtime files (`instrumentation*.ts`, `startup.node.ts`) — measured clean, +// and a short allowlist of directories is worth more than covering them. + +const ROOTS: ReadonlyArray<string> = [ 'src/', 'tools/', 'deploy/tools/' ]; + +const EXTENSIONS: ReadonlyArray<string> = [ '.ts', '.tsx', '.mjs', '.js', '.cjs' ]; + +const SPEC_PATTERNS: ReadonlyArray<RegExp> = [ + /\.spec\./, // *.spec.ts / *.spec.tsx + /\.pw\.tsx$/, // Playwright component tests + /\.pwstory\.tsx$/, // Playwright stories + /\.config\./, // vitest.config.ts, next.config.js and friends +]; + +// Build output, generated or checked in. `tools/**/dist/` is where run.sh compiles the gate itself. +const GENERATED_PREFIXES: ReadonlyArray<string> = [ 'src/toolkit/package/' ]; +const GENERATED_SEGMENTS: ReadonlyArray<string> = [ '/dist/' ]; + +export function isInScope(filePath: string): boolean { + const path = filePath.replace(/\\/g, '/'); + + if (!ROOTS.some((root) => path.startsWith(root))) return false; + if (!EXTENSIONS.some((extension) => path.endsWith(extension))) return false; + if (path.endsWith('.d.ts')) return false; + if (GENERATED_PREFIXES.some((prefix) => path.startsWith(prefix))) return false; + if (GENERATED_SEGMENTS.some((segment) => path.includes(segment))) return false; + + const base = path.slice(path.lastIndexOf('/') + 1); + if (base === 'envs.js') return false; // generated at container startup + if (SPEC_PATTERNS.some((pattern) => pattern.test(base))) return false; + + return true; +} + +export function resolveScopedFiles(filePaths: ReadonlyArray<string>): Array<string> { + return filePaths.filter(isInScope); +} diff --git a/tools/code-complexity/tsconfig.json b/tools/code-complexity/tsconfig.json new file mode 100644 index 00000000000..a34d8336541 --- /dev/null +++ b/tools/code-complexity/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "node16", + "target": "es2022", + "moduleResolution": "node16", + "resolveJsonModule": true, + "isolatedModules": false, + "noEmit": false, + "incremental": false, + "rootDir": "..", + "outDir": "./dist" + }, + "include": [ + "./index.ts" + ], + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/tools/design-readout/CONTEXT.md b/tools/design-readout/CONTEXT.md new file mode 100644 index 00000000000..b098cd7c3ec --- /dev/null +++ b/tools/design-readout/CONTEXT.md @@ -0,0 +1,78 @@ +# Design readout — context + +Reads one Figma node and writes what it found to a sidecar: the content root and the chrome dropped +on the way down, the values of every leaf under the confirmed regions, and per leaf what the tool +recognizes from those values. The developer runs it through the `design-readout` skill once the +task's spec is written and before its tickets are cut (`.agents/tasks/README.md`). It reads through +the Figma REST API, never the MCP. The task spec behind the tool: `.agents/tasks/3756-design-readout/spec.md`. + +Usage and flags: `pnpm design:readout --help`. Every tunable and list (chrome names, gap categories +and stages, lookalike characters, adjacency gaps) is in `./config.ts`. + +## Where to look + +| Question | Answer lives in | +| --- | --- | +| Where is a run's record? | `<main checkout>/.ai/design-readout/<fileKey>-<nodeId>.json`, one per node, shared by every worktree (`../cli/checkout.ts` resolves it through the git common dir). `./record/sidecar.ts` is the shape | +| Where is the gap log? | `<main checkout>/.ai/design-readout/gaps.md`, written by `./record/gaps.ts`, append-only | +| Which layout questions are settled? | `./layout-conventions.md`, one table; its header row is the format, the `design-readout` skill appends to it | +| What does the raw payload look like? | `./fixtures/`, one `--dump` per node, named `<node id>-<light\|dark>.json` | + +## Calibration + +`./calibration/entries/<entry>/` holds `expected.json` (Figma link, node id, shipped component path, +and per cell the component, props and the signals recognition must give, keyed by leaf id) and +`snapshot.json`, the tool's own extraction of the node. `./calibration/index.ts` has the schemas. + +To add an entry: write `expected.json` with `cells: {}`, run `pnpm design:readout --refresh <entry>` +to capture the snapshot, then fill the cells from the shipped component's JSX. `--calibrate` must +pass before the commit. + +A cell pins what recognition says today, which is not always the truth. An identicon beside an +address or a `Fire` instance for the `flame` sprite is `unrecognized`, and the entry says so; the gap +log is where the truth is recorded. A `--calibrate` miss is offline and never means Figma changed. It +means a rule change moved a cell, and the entry is updated in the same change. + +## What an editor here must keep true + +- **A failed fetch is a failed run.** No token, a rejected token, a node not in the file: exit + non-zero, one line on stderr, nothing on stdout. The opposite of `tools/review-screen/`, whose + failures still produce output; do not copy that rule over. +- **The token variable is named in `./config.ts` only.** An agent told the variable's name will try + to set it. +- **Scoping is a pure function of the REST payload.** `./extract/scope.ts` takes the document and nothing + else, so its specs run over `./fixtures/` and never reach Figma. A rule that needs a second request + belongs in `./fetch/figma.ts` and reaches `./extract/scope.ts` as data. +- **Nothing under this folder imports `src/config`**, directly or through the composed theme + modules. The color map is built from the config-free theme defaults, so an instance's runtime + color overrides are never in it. +- **Recognition names no component.** The tool decides a signal and what it says; mapping that to a + repo component is the skill's judgment with the ticket in hand. Icon names come from the generated + `public/icons/name.d.ts`, read at run time, so the tool and the sprite cannot drift. +- **Hints are never stored.** A Figma style, component or layer name is printed beside the value and + goes nowhere else; a hint in the record would be read back as a fact by the next phase. +- **A correction is always a miss, an override never is.** `--correct` and `--note` without `--gap` + exit non-zero. The phase 2 decision is a hand count over `gaps.md`, and a miss that skips the log + makes the count lie small. A correction with the category `convention` lets that count set the + line aside, so `layout` lines mean real misses. +- **Snapshots and fixtures are captured by the tool, never hand-edited.** A payload field the tool + starts reading is already in a fixture; a snapshot has to be captured again with `--refresh`. +- **The committed calibration set passes.** A recognition change that moves a calibrated cell lands + together with the entry update that says so. + +## File map + +- `./index.ts` — dispatch and the entry-point guard +- `./config.ts` — every constant and list the tool reads +- `./cli/` — the usage text and argument parsing; the per-flag runs and what they print +- `./fetch/` — Figma node link to file key and node id; the nodes request and its failures +- `./extract/` — the descent and the chrome rules; the leaf walk under the confirmed regions, hints, + the color-mode vote +- `./recognize/` — hex to theme tokens from the theme defaults; text-shape rules, icon matching, + composites, the per-leaf status +- `./record/` — the sidecar with its correction and override slots; the diff and carry-over on a + second run; the gap log +- `./calibration/` — the calibration checks and refresh; `entries/` is the committed set +- `./layout-conventions.md` — the settled layout questions +- `./fixtures/` — raw payloads captured with `--dump`, the only Figma data the specs touch +- `./run.sh`, `./tsconfig.json` — compile-on-run wrapper; the compiled output is git-ignored diff --git a/tools/design-readout/calibration/entries/address-3rd-party-widget-card/expected.json b/tools/design-readout/calibration/entries/address-3rd-party-widget-card/expected.json new file mode 100644 index 00000000000..6aa5d4c97ae --- /dev/null +++ b/tools/design-readout/calibration/entries/address-3rd-party-widget-card/expected.json @@ -0,0 +1,66 @@ +{ + "url": "https://www.figma.com/design/ErLH8qySSkpprB87H0onWw/?node-id=21998-159259", + "nodeId": "I21998:159259;20539:210205;27896:45000;27896:44423", + "component": "src/features/address-3rd-party-widgets/pages/address/Address3rdPartyWidgetCard.tsx", + "stale": false, + "cells": { + "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52869": { + "component": "Text", + "props": { + "textStyle": "heading.xl", + "color": "text.primary" + }, + "shape": "number", + "color": { + "text": "text.primary" + } + }, + "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52871": { + "component": "Text", + "props": { + "textStyle": "sm" + }, + "status": "unrecognized", + "color": { + "text": "text.primary" + } + }, + "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52872": { + "component": "Hint", + "props": {}, + "status": "unrecognized", + "color": { + "icon": "icon.secondary" + } + }, + "I21998:159259;20539:210205;27896:45000;27896:44423;27805:53460": { + "component": "Image", + "props": { + "boxSize": 5 + }, + "status": "unrecognized" + }, + "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52894": { + "component": "Text", + "props": { + "textStyle": "xs", + "color": "text.secondary" + }, + "status": "unrecognized", + "color": { + "text": "text.secondary" + } + }, + "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52898": { + "component": "SpriteIcon", + "props": { + "name": "link_external", + "boxSize": 3 + }, + "status": "unrecognized", + "color": { + "icon": "icon.secondary" + } + } + } +} diff --git a/tools/design-readout/calibration/entries/address-3rd-party-widget-card/snapshot.json b/tools/design-readout/calibration/entries/address-3rd-party-widget-card/snapshot.json new file mode 100644 index 00000000000..911dec67026 --- /dev/null +++ b/tools/design-readout/calibration/entries/address-3rd-party-widget-card/snapshot.json @@ -0,0 +1,177 @@ +{ + "version": 1, + "fileKey": "ErLH8qySSkpprB87H0onWw", + "nodeId": "I21998:159259;20539:210205;27896:45000;27896:44423", + "capturedAt": "2026-10-08T09:19:01.543Z", + "file": { + "lastModified": "2026-10-06T08:17:32Z", + "version": "2407877869758240031" + }, + "regions": [ + "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52867" + ], + "frameBackground": { + "role": "background", + "hex": "#101112", + "alpha": 0.03999999910593033 + }, + "leaves": [ + { + "id": "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52869", + "values": { + "kind": "text", + "text": "149", + "font": { + "family": "Poppins", + "weight": 500, + "size": 32, + "lineHeight": 40 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 751, + "y": 177, + "width": 52, + "height": 40 + } + }, + { + "id": "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52871", + "values": { + "kind": "text", + "text": "Builder score", + "font": { + "family": "Inter", + "weight": 400, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 751, + "y": 221, + "width": 87, + "height": 20 + } + }, + { + "id": "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52872", + "values": { + "kind": "icon", + "icon": "Info Square", + "colors": [ + { + "role": "icon", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 842, + "y": 221, + "width": 20, + "height": 20 + } + }, + { + "id": "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52874", + "values": { + "kind": "box", + "colors": [ + { + "role": "border", + "hex": "#101112", + "alpha": 0.03999999910593033 + } + ] + }, + "bbox": { + "x": 751, + "y": 253, + "width": 149, + "height": 28 + } + }, + { + "id": "I21998:159259;20539:210205;27896:45000;27896:44423;27805:53460", + "values": { + "kind": "icon", + "icon": "Widgets_app_logos", + "colors": [ + { + "role": "icon", + "hex": "#262621", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 751, + "y": 261, + "width": 20, + "height": 20 + } + }, + { + "id": "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52894", + "values": { + "kind": "text", + "text": "Talent Protocol", + "font": { + "family": "Inter", + "weight": 400, + "size": 12, + "lineHeight": 16 + }, + "colors": [ + { + "role": "text", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 779, + "y": 263, + "width": 86, + "height": 16 + } + }, + { + "id": "I21998:159259;20539:210205;27896:45000;27896:44423;27805:52898", + "values": { + "kind": "icon", + "icon": "send", + "colors": [ + { + "role": "icon", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 888, + "y": 265, + "width": 12, + "height": 12 + } + } + ] +} diff --git a/tools/design-readout/calibration/entries/address-net-worth/expected.json b/tools/design-readout/calibration/entries/address-net-worth/expected.json new file mode 100644 index 00000000000..2810b6a03b3 --- /dev/null +++ b/tools/design-readout/calibration/entries/address-net-worth/expected.json @@ -0,0 +1,19 @@ +{ + "url": "https://www.figma.com/design/ErLH8qySSkpprB87H0onWw/?node-id=21998-159259", + "nodeId": "I21998:159259;20539:210205;20534:197023", + "component": "src/slices/address/pages/details/info/AddressNetWorth.tsx", + "stale": false, + "cells": { + "I21998:159259;20539:210205;20534:197143": { + "component": "SimpleValue", + "props": { + "prefix": "$", + "overflowed": true + }, + "status": "unrecognized", + "color": { + "text": "text.primary" + } + } + } +} diff --git a/tools/design-readout/calibration/entries/address-net-worth/snapshot.json b/tools/design-readout/calibration/entries/address-net-worth/snapshot.json new file mode 100644 index 00000000000..f61f0cbe872 --- /dev/null +++ b/tools/design-readout/calibration/entries/address-net-worth/snapshot.json @@ -0,0 +1,42 @@ +{ + "version": 1, + "fileKey": "ErLH8qySSkpprB87H0onWw", + "nodeId": "I21998:159259;20539:210205;20534:197023", + "capturedAt": "2026-10-08T09:19:09.191Z", + "file": { + "lastModified": "2026-10-06T08:17:32Z", + "version": "2407877869758240031" + }, + "regions": [ + "I21998:159259;20539:210205;20534:197143" + ], + "frameBackground": null, + "leaves": [ + { + "id": "I21998:159259;20539:210205;20534:197143", + "values": { + "kind": "text", + "text": ">$15,453.11", + "font": { + "family": "Inter", + "weight": 400, + "size": 16, + "lineHeight": 24 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 739, + "y": -197, + "width": 90, + "height": 24 + } + } + ] +} diff --git a/tools/design-readout/calibration/entries/blocks-table-item/expected.json b/tools/design-readout/calibration/entries/blocks-table-item/expected.json new file mode 100644 index 00000000000..cce6434ee31 --- /dev/null +++ b/tools/design-readout/calibration/entries/blocks-table-item/expected.json @@ -0,0 +1,145 @@ +{ + "url": "https://www.figma.com/design/ErLH8qySSkpprB87H0onWw/?node-id=28972-117729", + "nodeId": "28972:117729", + "component": "src/slices/block/pages/index/BlocksTableItem.tsx", + "stale": false, + "cells": { + "I28972:117729;933:17025": { + "component": "BlockEntity", + "props": { + "noIcon": true, + "fontWeight": 600 + }, + "shape": "number", + "color": { + "text": "link.primary" + } + }, + "I28972:117729;26785:88384;13460:162892": { + "component": "TimeWithTooltip", + "props": { + "color": "text.secondary", + "fontWeight": 400 + }, + "shape": "relative-timestamp", + "color": { + "text": "text.secondary" + } + }, + "I28972:117729;933:17038": { + "component": "Skeleton", + "props": { + "display": "inline-block" + }, + "shape": "number", + "color": { + "text": "text.primary" + } + }, + "I28972:117729;933:17033": { + "component": "AddressEntity", + "props": { + "truncation": "constant" + }, + "status": "unrecognized", + "color": { + "text": "link.primary" + } + }, + "I28972:117729;29855:20523": { + "component": "AddressEntity", + "props": { + "truncation": "constant" + }, + "icon": "copy" + }, + "I28972:117729;29855:20172": { + "component": "Link", + "props": {}, + "shape": "number", + "color": { + "text": "link.primary" + } + }, + "I28972:117729;933:17042": { + "component": "Skeleton", + "props": { + "display": "inline-block" + }, + "shape": "number", + "color": { + "text": "text.primary" + } + }, + "I28972:117729;1024:24251": { + "component": "GasUsed", + "props": {}, + "status": "unrecognized" + }, + "I28972:117729;1024:24254": { + "component": "GasUsed", + "props": {}, + "status": "unrecognized", + "color": { + "text": "text.secondary" + } + }, + "I28972:117729;11004:131274": { + "component": "GasUsed", + "props": {}, + "status": "unrecognized", + "color": { + "text": "text.secondary" + } + }, + "I28972:117729;933:17697": { + "component": "SimpleValue", + "props": {}, + "shape": "amount", + "color": { + "text": "text.primary" + } + }, + "I28972:117729;933:17685": { + "component": "SpriteIcon", + "props": { + "name": "flame", + "boxSize": 5 + }, + "status": "unrecognized", + "color": { + "icon": "icon.primary" + } + }, + "I28972:117729;933:17686": { + "component": "NativeCoinValue", + "props": { + "noSymbol": true, + "display": "flex" + }, + "shape": "amount", + "color": { + "text": "text.primary" + } + }, + "I28972:117729;966:16008": { + "component": "Utilization", + "props": {}, + "status": "unrecognized", + "color": { + "text": "text.success" + } + }, + "I28972:117729;29855:20491": { + "component": "NativeCoinValue", + "props": { + "gweiThreshold": 4, + "units": "wei" + }, + "shape": "amount", + "color": { + "text": "text.primary" + } + } + } +} diff --git a/tools/design-readout/calibration/entries/blocks-table-item/snapshot.json b/tools/design-readout/calibration/entries/blocks-table-item/snapshot.json new file mode 100644 index 00000000000..823b21bbdd1 --- /dev/null +++ b/tools/design-readout/calibration/entries/blocks-table-item/snapshot.json @@ -0,0 +1,487 @@ +{ + "version": 1, + "fileKey": "ErLH8qySSkpprB87H0onWw", + "nodeId": "28972:117729", + "capturedAt": "2026-10-08T09:19:17.669Z", + "file": { + "lastModified": "2026-10-06T08:17:32Z", + "version": "2407877869758240031" + }, + "regions": [ + "I28972:117729;29855:20225" + ], + "frameBackground": null, + "leaves": [ + { + "id": "I28972:117729;933:17025", + "values": { + "kind": "text", + "text": "1248136", + "font": { + "family": "Inter", + "weight": 700, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -7475, + "y": -690, + "width": 60, + "height": 30 + } + }, + { + "id": "I28972:117729;26785:88384;13460:162892", + "values": { + "kind": "text", + "text": "10s ago", + "font": { + "family": "Inter", + "weight": 400, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -7475, + "y": -660, + "width": 52, + "height": 30 + } + }, + { + "id": "I28972:117729;933:17038", + "values": { + "kind": "text", + "text": "238375275275827", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": -7358.85693359375, + "y": -685, + "width": 74, + "height": 20 + } + }, + { + "id": "I28972:117729;933:17033", + "values": { + "kind": "text", + "text": "KuCoin Pool", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -7243.71435546875, + "y": -685, + "width": 81, + "height": 20 + } + }, + { + "id": "I28972:117729;29855:20523", + "values": { + "kind": "icon", + "icon": "copy", + "colors": [ + { + "role": "icon", + "hex": "#CBD5E0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -7157.71435546875, + "y": -685, + "width": 20, + "height": 20 + } + }, + { + "id": "I28972:117729;29855:20172", + "values": { + "kind": "text", + "text": "74", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -7112.5712890625, + "y": -685, + "width": 60, + "height": 20 + } + }, + { + "id": "I28972:117729;933:17042", + "values": { + "kind": "text", + "text": "8,195,212", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": -7036.4287109375, + "y": -685, + "width": 63, + "height": 20 + } + }, + { + "id": "I28972:117729;1024:24251", + "values": { + "kind": "icon", + "icon": "Progress", + "colors": [ + { + "role": "icon", + "hex": "#E2E8F0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -7036.4287109375, + "y": -647, + "width": 50, + "height": 4 + } + }, + { + "id": "I28972:117729;1024:24254", + "values": { + "kind": "text", + "text": "23.32%", + "font": { + "family": "Inter", + "weight": 600, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -6978.4287109375, + "y": -655, + "width": 51, + "height": 20 + } + }, + { + "id": "I28972:117729;10998:129147", + "values": { + "kind": "text", + "text": "|", + "trailingGlyphs": "|", + "font": { + "family": "Inter", + "weight": 500, + "size": 12, + "lineHeight": 16 + }, + "colors": [ + { + "role": "text", + "hex": "#E2E8F0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -6923.4287109375, + "y": -655, + "width": 4, + "height": 20 + } + }, + { + "id": "I28972:117729;11004:131274", + "values": { + "kind": "text", + "text": "+36.09%", + "font": { + "family": "Inter", + "weight": 400, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -6915.4287109375, + "y": -655, + "width": 80, + "height": 20 + } + }, + { + "id": "I28972:117729;933:17697", + "values": { + "kind": "text", + "text": "2.36345", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": -6836.28564453125, + "y": -685, + "width": 57, + "height": 20 + } + }, + { + "id": "I28972:117729;16273:37494", + "values": { + "kind": "text", + "text": "$39703", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -6836.28564453125, + "y": -655, + "width": 53, + "height": 20 + } + }, + { + "id": "I28972:117729;933:17685", + "values": { + "kind": "icon", + "icon": "Fire", + "colors": [ + { + "role": "icon", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -6737.14306640625, + "y": -685, + "width": 20, + "height": 20 + } + }, + { + "id": "I28972:117729;933:17686", + "values": { + "kind": "text", + "text": "0.134165", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": -6709.14306640625, + "y": -685, + "width": 61, + "height": 20 + } + }, + { + "id": "I28972:117729;16700:228085", + "values": { + "kind": "text", + "text": "$0.03", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -6640.14306640625, + "y": -685, + "width": 40, + "height": 20 + } + }, + { + "id": "I28972:117729;966:16124", + "values": { + "kind": "icon", + "icon": "Progress", + "colors": [ + { + "role": "icon", + "hex": "#EDF2F7", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -6737.14306640625, + "y": -647, + "width": 50, + "height": 4 + } + }, + { + "id": "I28972:117729;966:16008", + "values": { + "kind": "text", + "text": "52.05%", + "font": { + "family": "Inter", + "weight": 600, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#38A169", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -6679.14306640625, + "y": -655, + "width": 52, + "height": 20 + } + }, + { + "id": "I28972:117729;29855:20491", + "values": { + "kind": "text", + "text": "0.5668", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": -6532, + "y": -685, + "width": 48, + "height": 20 + } + } + ] +} diff --git a/tools/design-readout/calibration/entries/detailed-info-timestamp/expected.json b/tools/design-readout/calibration/entries/detailed-info-timestamp/expected.json new file mode 100644 index 00000000000..be435947a34 --- /dev/null +++ b/tools/design-readout/calibration/entries/detailed-info-timestamp/expected.json @@ -0,0 +1,34 @@ +{ + "url": "https://www.figma.com/design/ErLH8qySSkpprB87H0onWw/?node-id=29024-135150", + "nodeId": "I29024:135150;28406:92845;17439:63824", + "component": "src/shared/detailed-info/DetailedInfoTimestamp.tsx", + "stale": false, + "cells": { + "I29024:135150;28406:92845;26864:6728": { + "component": "DetailedInfoTimestamp", + "props": {}, + "shape": "relative-timestamp", + "color": { + "text": "text.primary" + } + }, + "I29024:135150;28406:92845;31535:2910": { + "component": "SpriteIcon", + "props": { + "name": "clock-light", + "boxSize": "14px" + }, + "status": "unrecognized" + }, + "I29024:135150;28406:92845;26864:6730": { + "component": "Truncate", + "props": { + "type": "end" + }, + "shape": "absolute-timestamp", + "color": { + "text": "text.primary" + } + } + } +} diff --git a/tools/design-readout/calibration/entries/detailed-info-timestamp/snapshot.json b/tools/design-readout/calibration/entries/detailed-info-timestamp/snapshot.json new file mode 100644 index 00000000000..ddd76825ada --- /dev/null +++ b/tools/design-readout/calibration/entries/detailed-info-timestamp/snapshot.json @@ -0,0 +1,88 @@ +{ + "version": 1, + "fileKey": "ErLH8qySSkpprB87H0onWw", + "nodeId": "I29024:135150;28406:92845;17439:63824", + "capturedAt": "2026-10-08T09:19:23.935Z", + "file": { + "lastModified": "2026-10-06T08:17:32Z", + "version": "2407877869758240031" + }, + "regions": [ + "I29024:135150;28406:92845;26864:6726" + ], + "frameBackground": null, + "leaves": [ + { + "id": "I29024:135150;28406:92845;26864:6728", + "values": { + "kind": "text", + "text": "11s ago", + "font": { + "family": "Inter", + "weight": 400, + "size": 16, + "lineHeight": 24 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": -5915, + "y": -568, + "width": 57, + "height": 24 + } + }, + { + "id": "I29024:135150;28406:92845;31535:2910", + "values": { + "kind": "icon", + "icon": "Timestamp", + "colors": [ + { + "role": "icon", + "hex": "#101112", + "alpha": 0.05999999865889549 + } + ] + }, + "bbox": { + "x": -5841, + "y": -566, + "width": 20, + "height": 20 + } + }, + { + "id": "I29024:135150;28406:92845;26864:6730", + "values": { + "kind": "text", + "text": "Jun 23 2022 02:51:55 PM ", + "font": { + "family": "Inter", + "weight": 400, + "size": 16, + "lineHeight": 24 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": -5817, + "y": -568, + "width": 194, + "height": 24 + } + } + ] +} diff --git a/tools/design-readout/calibration/entries/gas-tracker-prices/expected.json b/tools/design-readout/calibration/entries/gas-tracker-prices/expected.json new file mode 100644 index 00000000000..7669ff51772 --- /dev/null +++ b/tools/design-readout/calibration/entries/gas-tracker-prices/expected.json @@ -0,0 +1,69 @@ +{ + "url": "https://www.figma.com/design/ErLH8qySSkpprB87H0onWw/?node-id=22842-177328", + "nodeId": "22842:177328", + "component": "src/features/gas-tracker/components/GasTrackerPrices.tsx", + "stale": false, + "cells": { + "22842:177342": { + "component": "GasTrackerPriceSnippet", + "props": { + "type": "fast" + }, + "status": "unrecognized", + "color": { + "text": "text.primary" + } + }, + "22842:177356": { + "component": "GasPrice", + "props": { + "fontWeight": 600, + "fontFamily": "heading" + }, + "status": "unrecognized", + "color": { + "text": "text.primary" + } + }, + "I22842:177360;1024:23743": { + "component": "GasPrice", + "props": { + "unitMode": "secondary" + }, + "status": "unrecognized", + "color": { + "text": "text.secondary" + } + }, + "I22842:177361;1024:23743": { + "component": "GasTrackerPriceSnippet", + "props": { + "type": "fast" + }, + "status": "unrecognized", + "color": { + "text": "text.secondary" + } + }, + "22842:177368": { + "component": "GasTrackerPriceSnippet", + "props": { + "type": "average" + }, + "status": "unrecognized", + "color": { + "text": "text.primary" + } + }, + "22842:177388": { + "component": "GasTrackerPriceSnippet", + "props": { + "type": "slow" + }, + "status": "unrecognized", + "color": { + "text": "text.primary" + } + } + } +} diff --git a/tools/design-readout/calibration/entries/gas-tracker-prices/snapshot.json b/tools/design-readout/calibration/entries/gas-tracker-prices/snapshot.json new file mode 100644 index 00000000000..f39082832c5 --- /dev/null +++ b/tools/design-readout/calibration/entries/gas-tracker-prices/snapshot.json @@ -0,0 +1,523 @@ +{ + "version": 1, + "fileKey": "ErLH8qySSkpprB87H0onWw", + "nodeId": "22842:177328", + "capturedAt": "2026-10-08T09:19:29.866Z", + "file": { + "lastModified": "2026-10-06T08:17:32Z", + "version": "2407877869758240031" + }, + "regions": [ + "22842:177328" + ], + "frameBackground": null, + "leaves": [ + { + "id": "22842:177331", + "values": { + "kind": "box", + "colors": [ + { + "role": "border", + "hex": "#FFFFFF", + "alpha": 0.1599999964237213 + } + ] + }, + "bbox": { + "x": 1461, + "y": -526, + "width": 1115, + "height": 200 + } + }, + { + "id": "22842:177332", + "values": { + "kind": "box", + "colors": [ + { + "role": "border", + "hex": "#FFFFFF", + "alpha": 0.1599999964237213 + } + ] + }, + "bbox": { + "x": 1461, + "y": -526, + "width": 1115, + "height": 200 + } + }, + { + "id": "22842:177342", + "values": { + "kind": "text", + "text": "Fast", + "font": { + "family": "Poppins", + "weight": 500, + "size": 24, + "lineHeight": 32 + }, + "colors": [ + { + "role": "text", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1497, + "y": -502, + "width": 138, + "height": 32 + } + }, + { + "id": "22842:177350", + "values": { + "kind": "box", + "colors": [ + { + "role": "icon", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1497, + "y": -454, + "width": 39.9999885559082, + "height": 40 + } + }, + { + "id": "22842:177356", + "values": { + "kind": "text", + "text": "18 Gwei", + "font": { + "family": "Poppins", + "weight": 600, + "size": 48, + "lineHeight": 48 + }, + "colors": [ + { + "role": "text", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1549, + "y": -458, + "width": 174, + "height": 48 + } + }, + { + "id": "I22842:177360;1024:23743", + "values": { + "kind": "text", + "text": "≈ $0.82 per transaction / 1s", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1497, + "y": -397, + "width": 184, + "height": 20 + } + }, + { + "id": "I22842:177361;1024:23743", + "values": { + "kind": "text", + "text": "Base 10 / Priority 8", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1497, + "y": -368, + "width": 126, + "height": 20 + } + }, + { + "id": "22842:177362", + "values": { + "kind": "box", + "colors": [ + { + "role": "background", + "hex": "#FFFFFF", + "alpha": 0.05999999865889549 + } + ] + }, + "bbox": { + "x": 1832.6666259765625, + "y": -526, + "width": 371.66668701171875, + "height": 200 + } + }, + { + "id": "22842:177368", + "values": { + "kind": "text", + "text": "Normal", + "font": { + "family": "Poppins", + "weight": 500, + "size": 24, + "lineHeight": 32 + }, + "colors": [ + { + "role": "text", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1868.6666259765625, + "y": -502, + "width": 90, + "height": 32 + } + }, + { + "id": "22842:177374", + "values": { + "kind": "box", + "colors": [ + { + "role": "icon", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + }, + { + "role": "border", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1868.6666259765625, + "y": -454, + "width": 40, + "height": 40 + } + }, + { + "id": "22842:177376", + "values": { + "kind": "text", + "text": "15 Gwei", + "font": { + "family": "Poppins", + "weight": 600, + "size": 48, + "lineHeight": 48 + }, + "colors": [ + { + "role": "text", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1920.6666259765625, + "y": -458, + "width": 175, + "height": 48 + } + }, + { + "id": "I22842:177380;1024:23743", + "values": { + "kind": "text", + "text": "≈ $0.56 per transaction / 1s", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1868.6666259765625, + "y": -393, + "width": 185, + "height": 20 + } + }, + { + "id": "I22842:177381;1024:23743", + "values": { + "kind": "text", + "text": "Base 10 / Priority 6", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1868.6666259765625, + "y": -364, + "width": 126, + "height": 20 + } + }, + { + "id": "22842:177382", + "values": { + "kind": "box", + "colors": [ + { + "role": "background", + "hex": "#FFFFFF", + "alpha": 0.05999999865889549 + } + ] + }, + "bbox": { + "x": 2204.33349609375, + "y": -526, + "width": 371.66668701171875, + "height": 200 + } + }, + { + "id": "22842:177388", + "values": { + "kind": "text", + "text": "Slow ", + "font": { + "family": "Poppins", + "weight": 500, + "size": 24, + "lineHeight": 32 + }, + "colors": [ + { + "role": "text", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 2240.33349609375, + "y": -502, + "width": 56, + "height": 32 + } + }, + { + "id": "22842:177389", + "values": { + "kind": "icon", + "icon": "up and down/up", + "colors": [] + }, + "bbox": { + "x": 2304.33349609375, + "y": -498, + "width": 63, + "height": 24 + } + }, + { + "id": "22842:177398", + "values": { + "kind": "box", + "colors": [ + { + "role": "icon", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + }, + { + "role": "border", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 2240.33349609375, + "y": -454, + "width": 40, + "height": 40 + } + }, + { + "id": "22842:177400", + "values": { + "kind": "text", + "text": "13 Gwei", + "font": { + "family": "Poppins", + "weight": 600, + "size": 48, + "lineHeight": 48 + }, + "colors": [ + { + "role": "text", + "hex": "#FFFFFF", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 2292.33349609375, + "y": -458, + "width": 172, + "height": 48 + } + }, + { + "id": "I22842:177404;1024:23743", + "values": { + "kind": "text", + "text": "≈ $0.36 per transaction / 1s", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 2240.33349609375, + "y": -393, + "width": 185, + "height": 20 + } + }, + { + "id": "I22842:177405;1024:23743", + "values": { + "kind": "text", + "text": "Base 10 / Priority 3", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 2240.33349609375, + "y": -364, + "width": 126, + "height": 20 + } + }, + { + "id": "22842:177494", + "values": { + "kind": "box", + "colors": [ + { + "role": "border", + "hex": "#FFFFFF", + "alpha": 0.1599999964237213 + } + ] + }, + "bbox": { + "x": 1832.9999921756903, + "y": -526, + "width": 0.000007824309705029009, + "height": 200 + } + }, + { + "id": "22842:177495", + "values": { + "kind": "box", + "colors": [ + { + "role": "border", + "hex": "#FFFFFF", + "alpha": 0.1599999964237213 + } + ] + }, + "bbox": { + "x": 2205.9999921756903, + "y": -526, + "width": 0.000007824309705029009, + "height": 200 + } + } + ] +} diff --git a/tools/design-readout/calibration/entries/hot-contracts-table-item/expected.json b/tools/design-readout/calibration/entries/hot-contracts-table-item/expected.json new file mode 100644 index 00000000000..9079ffa029f --- /dev/null +++ b/tools/design-readout/calibration/entries/hot-contracts-table-item/expected.json @@ -0,0 +1,72 @@ +{ + "url": "https://www.figma.com/design/ErLH8qySSkpprB87H0onWw/?node-id=29131-74920", + "nodeId": "29131:74920", + "component": "src/features/hot-contracts/pages/index/HotContractsTableItem.tsx", + "stale": false, + "cells": { + "I29131:74925;28249:17341": { + "component": "AddressEntity", + "props": {}, + "status": "unrecognized" + }, + "I29131:74925;28249:17345": { + "component": "AddressEntity", + "props": {}, + "status": "unrecognized", + "color": { + "text": "link.primary" + } + }, + "29949:25549": { + "component": "MetadataTags", + "props": { + "noColors": true + }, + "status": "unrecognized", + "color": { + "icon": "icon.secondary" + } + }, + "29949:25603": { + "component": "MetadataTags", + "props": { + "noColors": true + }, + "status": "unrecognized", + "color": { + "text": "text.primary" + } + }, + "29131:74937": { + "component": "Truncate", + "props": { + "type": "end" + }, + "shape": "number", + "color": { + "text": "text.primary" + } + }, + "29131:74938": { + "component": "Truncate", + "props": { + "type": "end" + }, + "shape": "amount", + "color": { + "text": "text.primary" + } + }, + "29131:74940": { + "component": "NativeCoinValue", + "props": { + "layout": "vertical", + "rowGap": "10px" + }, + "shape": "amount", + "color": { + "text": "text.primary" + } + } + } +} diff --git a/tools/design-readout/calibration/entries/hot-contracts-table-item/snapshot.json b/tools/design-readout/calibration/entries/hot-contracts-table-item/snapshot.json new file mode 100644 index 00000000000..d34f707a0b9 --- /dev/null +++ b/tools/design-readout/calibration/entries/hot-contracts-table-item/snapshot.json @@ -0,0 +1,355 @@ +{ + "version": 1, + "fileKey": "ErLH8qySSkpprB87H0onWw", + "nodeId": "29131:74920", + "capturedAt": "2026-10-08T09:19:37.018Z", + "file": { + "lastModified": "2026-10-06T08:17:32Z", + "version": "2407877869758240031" + }, + "regions": [ + "29131:74920" + ], + "frameBackground": null, + "leaves": [ + { + "id": "I29131:74925;28249:17341", + "values": { + "kind": "icon", + "icon": "Contract", + "colors": [ + { + "role": "icon", + "hex": "#38A169", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 843, + "y": 531, + "width": 20, + "height": 20 + } + }, + { + "id": "I29131:74925;28249:17345", + "values": { + "kind": "text", + "text": "Uniswap V3: Universal Router", + "font": { + "family": "Inter", + "weight": 600, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 867, + "y": 531, + "width": 201, + "height": 20 + } + }, + { + "id": "29131:74929", + "values": { + "kind": "box", + "colors": [ + { + "role": "background", + "hex": "#FE017A", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 843, + "y": 559, + "width": 116, + "height": 24 + } + }, + { + "id": "29131:74932", + "values": { + "kind": "text", + "text": "Uniswap V2", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#FFFFFF", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 863, + "y": 561, + "width": 80, + "height": 20 + } + }, + { + "id": "29131:74933", + "values": { + "kind": "icon", + "icon": "send", + "colors": [ + { + "role": "icon", + "hex": "#FFFFFF", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 943, + "y": 565, + "width": 12, + "height": 12 + } + }, + { + "id": "29949:25599", + "values": { + "kind": "box", + "colors": [ + { + "role": "background", + "hex": "#EDF2F7", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 963, + "y": 559, + "width": 100, + "height": 24 + } + }, + { + "id": "29949:25603", + "values": { + "kind": "text", + "text": "Uniswap V2", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 967, + "y": 561, + "width": 80, + "height": 20 + } + }, + { + "id": "29949:25604", + "values": { + "kind": "icon", + "icon": "send", + "colors": [ + { + "role": "icon", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1047, + "y": 565, + "width": 12, + "height": 12 + } + }, + { + "id": "29949:25548", + "values": { + "kind": "box", + "colors": [ + { + "role": "background", + "hex": "#EDF2F7", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1067, + "y": 559, + "width": 132, + "height": 24 + } + }, + { + "id": "29949:25549", + "values": { + "kind": "icon", + "icon": "Tags", + "colors": [ + { + "role": "icon", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1071, + "y": 565, + "width": 12, + "height": 12 + } + }, + { + "id": "29949:25551", + "values": { + "kind": "text", + "text": "Uniswap V2", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1103, + "y": 561, + "width": 80, + "height": 20 + } + }, + { + "id": "29949:25552", + "values": { + "kind": "icon", + "icon": "send", + "colors": [ + { + "role": "icon", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1183, + "y": 565, + "width": 12, + "height": 12 + } + }, + { + "id": "29131:74937", + "values": { + "kind": "text", + "text": "16", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1193, + "y": 526, + "width": 130, + "height": 30 + } + }, + { + "id": "29131:74938", + "values": { + "kind": "text", + "text": "0.27646303", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1323, + "y": 526, + "width": 320.5, + "height": 30 + } + }, + { + "id": "29131:74940", + "values": { + "kind": "text", + "text": "0.25264", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1907, + "y": 526, + "width": 57, + "height": 30 + } + } + ] +} diff --git a/tools/design-readout/calibration/entries/name-domains-table-item/expected.json b/tools/design-readout/calibration/entries/name-domains-table-item/expected.json new file mode 100644 index 00000000000..c96427cc1d3 --- /dev/null +++ b/tools/design-readout/calibration/entries/name-domains-table-item/expected.json @@ -0,0 +1,70 @@ +{ + "url": "https://www.figma.com/design/ErLH8qySSkpprB87H0onWw/?node-id=13828-42285", + "nodeId": "13828:42285", + "component": "src/features/name-services/domains/pages/index/NameDomainsTableItem.tsx", + "stale": false, + "cells": { + "13828:42397": { + "component": "EnsEntity", + "props": { + "fontWeight": 600 + }, + "status": "unrecognized", + "color": { + "text": "link.primary" + } + }, + "14092:333172": { + "component": "EnsEntity", + "props": { + "fontWeight": 600 + }, + "icon": "copy", + "color": { + "icon": "icon.secondary" + } + }, + "13859:49012": { + "component": "AddressEntity", + "props": { + "fontWeight": 500 + }, + "status": "unrecognized" + }, + "13859:49014": { + "component": "AddressEntity", + "props": { + "fontWeight": 500 + }, + "shape": "truncated-hash", + "color": { + "text": "link.primary" + } + }, + "13859:49015": { + "component": "AddressEntity", + "props": { + "fontWeight": 500 + }, + "icon": "copy", + "color": { + "icon": "icon.secondary" + } + }, + "13859:49010": { + "component": "TimeWithTooltip", + "props": {}, + "shape": "absolute-timestamp", + "color": { + "text": "text.primary" + } + }, + "13849:5495": { + "component": "TimeWithTooltip", + "props": { + "color": "inherit" + }, + "shape": "absolute-timestamp" + } + } +} diff --git a/tools/design-readout/calibration/entries/name-domains-table-item/snapshot.json b/tools/design-readout/calibration/entries/name-domains-table-item/snapshot.json new file mode 100644 index 00000000000..ac94eb9e618 --- /dev/null +++ b/tools/design-readout/calibration/entries/name-domains-table-item/snapshot.json @@ -0,0 +1,188 @@ +{ + "version": 1, + "fileKey": "ErLH8qySSkpprB87H0onWw", + "nodeId": "13828:42285", + "capturedAt": "2026-10-08T09:19:43.908Z", + "file": { + "lastModified": "2026-10-06T08:17:32Z", + "version": "2407877869758240031" + }, + "regions": [ + "13828:42285" + ], + "frameBackground": null, + "leaves": [ + { + "id": "28854:24515", + "values": { + "kind": "icon", + "icon": "Component 1", + "colors": [] + }, + "bbox": { + "x": 2976, + "y": -142, + "width": 20, + "height": 20 + } + }, + { + "id": "13828:42397", + "values": { + "kind": "text", + "text": "tatyana.gno", + "font": { + "family": "Inter", + "weight": 600, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 3004, + "y": -142, + "width": 81, + "height": 20 + } + }, + { + "id": "14092:333172", + "values": { + "kind": "icon", + "icon": "copy", + "colors": [ + { + "role": "icon", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 3093, + "y": -142, + "width": 20, + "height": 20 + } + }, + { + "id": "13859:49012", + "values": { + "kind": "icon", + "icon": "Avatar", + "colors": [] + }, + "bbox": { + "x": 3288, + "y": -142, + "width": 20, + "height": 20 + } + }, + { + "id": "13859:49014", + "values": { + "kind": "text", + "text": "0xd0...4567", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 3316, + "y": -147, + "width": 81, + "height": 30 + } + }, + { + "id": "13859:49015", + "values": { + "kind": "icon", + "icon": "copy", + "colors": [ + { + "role": "icon", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 3405, + "y": -142, + "width": 20, + "height": 20 + } + }, + { + "id": "13859:49010", + "values": { + "kind": "text", + "text": "Jul 17 2023 16:50:24 PM", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 3500, + "y": -147, + "width": 270.5, + "height": 30 + } + }, + { + "id": "13849:5495", + "values": { + "kind": "text", + "text": "Aug 17 2023 16:50:24 PM", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#1A202C", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 3782.5, + "y": -147, + "width": 270.5, + "height": 30 + } + } + ] +} diff --git a/tools/design-readout/calibration/entries/optimistic-l2-withdrawals-table-item/expected.json b/tools/design-readout/calibration/entries/optimistic-l2-withdrawals-table-item/expected.json new file mode 100644 index 00000000000..baa5850db20 --- /dev/null +++ b/tools/design-readout/calibration/entries/optimistic-l2-withdrawals-table-item/expected.json @@ -0,0 +1,96 @@ +{ + "url": "https://www.figma.com/design/ErLH8qySSkpprB87H0onWw/?node-id=29167-7007", + "nodeId": "29167:7007", + "component": "src/features/rollup/optimism/pages/withdrawals/OptimisticL2WithdrawalsTableItem.tsx", + "stale": false, + "cells": { + "I29167:7007;31015:32759": { + "component": "Skeleton", + "props": { + "display": "inline-block" + }, + "status": "unrecognized", + "color": { + "text": "text.primary" + } + }, + "I29167:7007;31015:32763": { + "component": "AddressEntity", + "props": { + "truncation": "constant" + }, + "status": "unrecognized" + }, + "I29167:7007;31015:32765": { + "component": "AddressEntity", + "props": { + "truncation": "constant" + }, + "shape": "truncated-hash", + "color": { + "text": "link.primary" + } + }, + "I29167:7007;31015:32766": { + "component": "AddressEntity", + "props": { + "truncation": "constant" + }, + "icon": "copy", + "color": { + "icon": "icon.secondary" + } + }, + "I29167:7007;31015:32778": { + "component": "TxEntity", + "props": { + "truncation": "constant_long", + "noIcon": true + }, + "shape": "truncated-hash", + "color": { + "text": "link.primary" + } + }, + "I29167:7007;31015:33335": { + "component": "TxEntity", + "props": { + "truncation": "constant_long", + "noIcon": true + }, + "icon": "copy", + "color": { + "icon": "icon.secondary" + } + }, + "I29167:7007;31015:32780;13460:162892": { + "component": "TimeWithTooltip", + "props": { + "fallbackText": "N/A", + "color": "text.secondary" + }, + "shape": "relative-timestamp", + "color": { + "text": "text.secondary" + } + }, + "I29167:7007;31015:33343": { + "component": "OptimisticL2WithdrawalsItemStatus", + "props": {}, + "status": "unrecognized", + "color": { + "text": "text.primary" + } + }, + "I29167:7007;31015:32808": { + "component": "Skeleton", + "props": { + "color": "text.secondary" + }, + "status": "unrecognized", + "color": { + "text": "text.secondary" + } + } + } +} diff --git a/tools/design-readout/calibration/entries/optimistic-l2-withdrawals-table-item/snapshot.json b/tools/design-readout/calibration/entries/optimistic-l2-withdrawals-table-item/snapshot.json new file mode 100644 index 00000000000..3e2e5b2c508 --- /dev/null +++ b/tools/design-readout/calibration/entries/optimistic-l2-withdrawals-table-item/snapshot.json @@ -0,0 +1,226 @@ +{ + "version": 1, + "fileKey": "ErLH8qySSkpprB87H0onWw", + "nodeId": "29167:7007", + "capturedAt": "2026-10-08T09:19:50.087Z", + "file": { + "lastModified": "2026-10-06T08:17:32Z", + "version": "2407877869758240031" + }, + "regions": [ + "29167:7007" + ], + "frameBackground": null, + "leaves": [ + { + "id": "I29167:7007;31015:32759", + "values": { + "kind": "text", + "text": "1-29743", + "font": { + "family": "Inter", + "weight": 700, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": -281, + "y": 2545, + "width": 71, + "height": 20 + } + }, + { + "id": "I29167:7007;31015:32763", + "values": { + "kind": "icon", + "icon": "Avatar", + "colors": [] + }, + "bbox": { + "x": -119, + "y": 2545, + "width": 20, + "height": 20 + } + }, + { + "id": "I29167:7007;31015:32765", + "values": { + "kind": "text", + "text": "0xd0...4567", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -91, + "y": 2540, + "width": 81, + "height": 30 + } + }, + { + "id": "I29167:7007;31015:32766", + "values": { + "kind": "icon", + "icon": "copy", + "colors": [ + { + "role": "icon", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -2, + "y": 2545, + "width": 20, + "height": 20 + } + }, + { + "id": "I29167:7007;31015:32778", + "values": { + "kind": "text", + "text": "0xd637...4567", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 43, + "y": 2545, + "width": 97, + "height": 20 + } + }, + { + "id": "I29167:7007;31015:33335", + "values": { + "kind": "icon", + "icon": "copy", + "colors": [ + { + "role": "icon", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 148, + "y": 2545, + "width": 20, + "height": 20 + } + }, + { + "id": "I29167:7007;31015:32780;13460:162892", + "values": { + "kind": "text", + "text": "10s ago", + "font": { + "family": "Inter", + "weight": 400, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 205, + "y": 2540, + "width": 52, + "height": 30 + } + }, + { + "id": "I29167:7007;31015:33343", + "values": { + "kind": "text", + "text": "Ready to prove", + "font": { + "family": "Inter", + "weight": 400, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 377, + "y": 2545, + "width": 100, + "height": 20 + } + }, + { + "id": "I29167:7007;31015:32808", + "values": { + "kind": "text", + "text": "n/a", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 589, + "y": 2545, + "width": 84, + "height": 20 + } + } + ] +} diff --git a/tools/design-readout/calibration/entries/txs-table-item/expected.json b/tools/design-readout/calibration/entries/txs-table-item/expected.json new file mode 100644 index 00000000000..98032a2d863 --- /dev/null +++ b/tools/design-readout/calibration/entries/txs-table-item/expected.json @@ -0,0 +1,121 @@ +{ + "url": "https://www.figma.com/design/ErLH8qySSkpprB87H0onWw/?node-id=21998-143467", + "nodeId": "I21998:143467;20539:206951", + "component": "src/slices/tx/pages/index/list/TxsTableItem.tsx", + "stale": false, + "cells": { + "I21998:143467;20539:206953": { + "component": "TxAdditionalInfo", + "props": {}, + "status": "unrecognized", + "color": { + "icon": "icon.secondary" + } + }, + "I21998:143467;20539:206955": { + "component": "TxEntity", + "props": { + "fontWeight": "bold", + "noIcon": true, + "truncation": "constant" + }, + "shape": "truncated-hash", + "color": { + "text": "link.primary" + } + }, + "I21998:143467;26785:88063;13460:162892": { + "component": "TimeWithTooltip", + "props": { + "color": "text.secondary" + }, + "shape": "relative-timestamp", + "color": { + "text": "text.secondary" + } + }, + "I21998:143467;20539:206966;1015:22864": { + "component": "TxType", + "props": {}, + "status": "unrecognized" + }, + "I21998:143467;26785:88079;1003:19143": { + "component": "TxStatus", + "props": {}, + "status": "unrecognized" + }, + "I21998:143467;26785:88079;1003:19144": { + "component": "TxStatus", + "props": {}, + "status": "unrecognized", + "color": { + "text": "text.success" + } + }, + "I21998:143467;20539:206977;1003:19153": { + "component": "Badge", + "props": { + "colorPalette": "gray", + "truncated": true + }, + "status": "unrecognized" + }, + "I21998:143467;20539:206981": { + "component": "BlockEntity", + "props": { + "noIcon": true, + "textStyle": "sm", + "fontWeight": 500 + }, + "shape": "number", + "color": { + "text": "link.primary" + } + }, + "I21998:143467;20539:206992": { + "component": "AddressFromTo", + "props": { + "mode": "compact" + }, + "status": "unrecognized" + }, + "I21998:143467;20539:206993": { + "component": "AddressFromTo", + "props": { + "mode": "compact" + }, + "shape": "truncated-hash", + "color": { + "text": "text.primary" + } + }, + "I21998:143467;20539:206999": { + "component": "AddressFromTo", + "props": { + "mode": "compact" + }, + "status": "unrecognized", + "color": { + "text": "link.primary" + } + }, + "I21998:143467;20539:207001": { + "component": "NativeCoinValue", + "props": { + "noSymbol": true, + "layout": "vertical", + "rowGap": 3 + }, + "shape": "amount" + }, + "I21998:143467;20539:207002": { + "component": "TxFee", + "props": { + "accuracy": 8, + "layout": "vertical", + "rowGap": 3 + }, + "shape": "amount" + } + } +} diff --git a/tools/design-readout/calibration/entries/txs-table-item/snapshot.json b/tools/design-readout/calibration/entries/txs-table-item/snapshot.json new file mode 100644 index 00000000000..e18a3264577 --- /dev/null +++ b/tools/design-readout/calibration/entries/txs-table-item/snapshot.json @@ -0,0 +1,432 @@ +{ + "version": 1, + "fileKey": "ErLH8qySSkpprB87H0onWw", + "nodeId": "I21998:143467;20539:206951", + "capturedAt": "2026-10-08T09:19:56.695Z", + "file": { + "lastModified": "2026-10-06T08:17:32Z", + "version": "2407877869758240031" + }, + "regions": [ + "I21998:143467;20539:206952" + ], + "frameBackground": null, + "leaves": [ + { + "id": "I21998:143467;20539:206953", + "values": { + "kind": "icon", + "icon": "additionla_info", + "colors": [ + { + "role": "icon", + "hex": "#A0AEC0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 543, + "y": 621, + "width": 30, + "height": 30 + } + }, + { + "id": "I21998:143467;20539:206955", + "values": { + "kind": "text", + "text": "0x444689...39c8", + "font": { + "family": "Inter", + "weight": 700, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 585, + "y": 621, + "width": 124, + "height": 30 + } + }, + { + "id": "I21998:143467;26785:88063;13460:162892", + "values": { + "kind": "text", + "text": "10s ago", + "font": { + "family": "Inter", + "weight": 400, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 585, + "y": 651, + "width": 52, + "height": 30 + } + }, + { + "id": "I21998:143467;20539:206966", + "values": { + "kind": "box", + "colors": [ + { + "role": "background", + "hex": "#FAF5FF", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 721, + "y": 627, + "width": 87, + "height": 24 + } + }, + { + "id": "I21998:143467;20539:206966;1015:22864", + "values": { + "kind": "text", + "text": "Transaction", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#805AD5", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 725, + "y": 629, + "width": 79, + "height": 20 + } + }, + { + "id": "I21998:143467;26785:88079", + "values": { + "kind": "box", + "colors": [ + { + "role": "background", + "hex": "#F0FFF4", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 721, + "y": 657, + "width": 79, + "height": 24 + } + }, + { + "id": "I21998:143467;26785:88079;1003:19143", + "values": { + "kind": "icon", + "icon": "icon/check-circle", + "colors": [ + { + "role": "icon", + "hex": "#38A169", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 725, + "y": 664, + "width": 10, + "height": 10 + } + }, + { + "id": "I21998:143467;26785:88079;1003:19144", + "values": { + "kind": "text", + "text": "Success", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#38A169", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 739, + "y": 659, + "width": 57, + "height": 20 + } + }, + { + "id": "I21998:143467;20539:206977", + "values": { + "kind": "box", + "colors": [ + { + "role": "background", + "hex": "#101112", + "alpha": 0.019999999552965164 + } + ] + }, + "bbox": { + "x": 847, + "y": 624, + "width": 81, + "height": 24 + } + }, + { + "id": "I21998:143467;20539:206977;1003:19153", + "values": { + "kind": "text", + "text": "Withdraw", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#4A5568", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 855, + "y": 626, + "width": 65, + "height": 20 + } + }, + { + "id": "I21998:143467;20539:206981", + "values": { + "kind": "text", + "text": "1248136", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 962, + "y": 621, + "width": 72, + "height": 30 + } + }, + { + "id": "I21998:143467;20539:206992", + "values": { + "kind": "icon", + "icon": "Avatar", + "colors": [] + }, + "bbox": { + "x": 1046, + "y": 624, + "width": 24, + "height": 24 + } + }, + { + "id": "I21998:143467;20539:206993", + "values": { + "kind": "text", + "text": "0x35...4568", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": 1078, + "y": 626, + "width": 84, + "height": 20 + } + }, + { + "id": "I21998:143467;20539:206994", + "values": { + "kind": "box", + "colors": [ + { + "role": "background", + "hex": "#FFFAF0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1170, + "y": 624, + "width": 47, + "height": 24 + } + }, + { + "id": "I21998:143467;20539:206996", + "values": { + "kind": "text", + "text": "OUT", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#D69E2E", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1178, + "y": 626, + "width": 31, + "height": 20 + } + }, + { + "id": "I21998:143467;20539:206999", + "values": { + "kind": "text", + "text": "*🍐️🍐️🍐️.eth", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1257, + "y": 621, + "width": 81, + "height": 30 + } + }, + { + "id": "I21998:143467;20539:207001", + "values": { + "kind": "text", + "text": "0.25303", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2D3748", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1327, + "y": 621, + "width": 186, + "height": 30 + } + }, + { + "id": "I21998:143467;20539:207002", + "values": { + "kind": "text", + "text": "0.27646303", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2D3748", + "alpha": 1 + } + ] + }, + "bbox": { + "x": 1525, + "y": 621, + "width": 186, + "height": 30 + } + } + ] +} diff --git a/tools/design-readout/calibration/entries/user-ops-table-item/expected.json b/tools/design-readout/calibration/entries/user-ops-table-item/expected.json new file mode 100644 index 00000000000..cd29755bcfd --- /dev/null +++ b/tools/design-readout/calibration/entries/user-ops-table-item/expected.json @@ -0,0 +1,101 @@ +{ + "url": "https://www.figma.com/design/ErLH8qySSkpprB87H0onWw/?node-id=25201-111693", + "nodeId": "I25201:111693;24311:103865;24311:87534", + "component": "src/features/user-ops/pages/index/UserOpsTableItem.tsx", + "stale": false, + "cells": { + "I25201:111693;24311:103865;24311:87538": { + "component": "UserOpEntity", + "props": { + "noIcon": true, + "fontWeight": 700, + "truncation": "constant_long", + "noCopy": true + }, + "shape": "truncated-hash", + "status": "ambiguous", + "color": { + "text": "link.primary" + } + }, + "I25201:111693;24311:103865;26785:88405;13460:162892": { + "component": "TimeWithTooltip", + "props": { + "color": "text.secondary" + }, + "shape": "relative-timestamp", + "color": { + "text": "text.secondary" + } + }, + "I25201:111693;24311:103865;24311:87555;1003:19144": { + "component": "UserOpStatus", + "props": {}, + "status": "unrecognized", + "color": { + "text": "text.success" + } + }, + "I25201:111693;24311:103865;24311:87610": { + "component": "AddressStringOrParam", + "props": { + "truncation": "constant" + }, + "status": "unrecognized", + "color": { + "icon": "icon.primary" + } + }, + "I25201:111693;24311:103865;24311:87614": { + "component": "AddressStringOrParam", + "props": { + "truncation": "constant" + }, + "shape": "truncated-hash", + "color": { + "text": "link.primary" + } + }, + "I25201:111693;24311:103865;24311:87615": { + "component": "AddressStringOrParam", + "props": { + "truncation": "constant" + }, + "icon": "copy" + }, + "I25201:111693;24311:103865;24311:87568": { + "component": "TxEntity", + "props": { + "truncation": "constant", + "noIcon": true + }, + "shape": "truncated-hash", + "status": "ambiguous", + "color": { + "text": "link.primary" + } + }, + "I25201:111693;24311:103865;24311:88484": { + "component": "BlockEntity", + "props": { + "textStyle": "sm", + "noIcon": true + }, + "shape": "number", + "color": { + "text": "link.primary" + } + }, + "I25201:111693;24311:103865;24311:87660": { + "component": "NativeCoinValue", + "props": { + "layout": "vertical", + "noSymbol": true + }, + "shape": "amount", + "color": { + "text": "text.primary" + } + } + } +} diff --git a/tools/design-readout/calibration/entries/user-ops-table-item/snapshot.json b/tools/design-readout/calibration/entries/user-ops-table-item/snapshot.json new file mode 100644 index 00000000000..eff3386fc31 --- /dev/null +++ b/tools/design-readout/calibration/entries/user-ops-table-item/snapshot.json @@ -0,0 +1,277 @@ +{ + "version": 1, + "fileKey": "ErLH8qySSkpprB87H0onWw", + "nodeId": "I25201:111693;24311:103865;24311:87534", + "capturedAt": "2026-10-08T09:20:03.753Z", + "file": { + "lastModified": "2026-10-06T08:17:32Z", + "version": "2407877869758240031" + }, + "regions": [ + "I25201:111693;24311:103865;24311:87534" + ], + "frameBackground": null, + "leaves": [ + { + "id": "I25201:111693;24311:103865;24311:87538", + "values": { + "kind": "text", + "text": "0x6688a2cbaa...d887", + "font": { + "family": "Inter", + "weight": 700, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -15411, + "y": -194, + "width": 155, + "height": 20 + } + }, + { + "id": "I25201:111693;24311:103865;26785:88405;13460:162892", + "values": { + "kind": "text", + "text": "10s ago", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -15199, + "y": -199, + "width": 52, + "height": 30 + } + }, + { + "id": "I25201:111693;24311:103865;24311:87555", + "values": { + "kind": "box", + "colors": [ + { + "role": "background", + "hex": "#F0FFF4", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -15075, + "y": -196, + "width": 79, + "height": 24 + } + }, + { + "id": "I25201:111693;24311:103865;24311:87555;1003:19143", + "values": { + "kind": "icon", + "icon": "icon/check-circle", + "colors": [ + { + "role": "icon", + "hex": "#38A169", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -15071, + "y": -189, + "width": 10, + "height": 10 + } + }, + { + "id": "I25201:111693;24311:103865;24311:87555;1003:19144", + "values": { + "kind": "text", + "text": "Success", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#38A169", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -15057, + "y": -194, + "width": 57, + "height": 20 + } + }, + { + "id": "I25201:111693;24311:103865;24311:87610", + "values": { + "kind": "icon", + "icon": "Contract", + "colors": [ + { + "role": "icon", + "hex": "#718096", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -14963, + "y": -194, + "width": 20, + "height": 20 + } + }, + { + "id": "I25201:111693;24311:103865;24311:87614", + "values": { + "kind": "text", + "text": "0xd0...4567", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -14935, + "y": -199, + "width": 81, + "height": 30 + } + }, + { + "id": "I25201:111693;24311:103865;24311:87615", + "values": { + "kind": "icon", + "icon": "copy", + "colors": [ + { + "role": "icon", + "hex": "#CBD5E0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -14846, + "y": -194, + "width": 20, + "height": 20 + } + }, + { + "id": "I25201:111693;24311:103865;24311:87568", + "values": { + "kind": "text", + "text": "0xf2...151d", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -14751, + "y": -194, + "width": 72, + "height": 20 + } + }, + { + "id": "I25201:111693;24311:103865;24311:88484", + "values": { + "kind": "text", + "text": "\t21579908", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#2B6CB0", + "alpha": 1 + } + ] + }, + "bbox": { + "x": -14600.6669921875, + "y": -194, + "width": 72, + "height": 20 + } + }, + { + "id": "I25201:111693;24311:103865;24311:87660", + "values": { + "kind": "text", + "text": "0.00262618", + "font": { + "family": "Inter", + "weight": 500, + "size": 14, + "lineHeight": 20 + }, + "colors": [ + { + "role": "text", + "hex": "#101112", + "alpha": 0.800000011920929 + } + ] + }, + "bbox": { + "x": -14450.3330078125, + "y": -199, + "width": 138.33334350585938, + "height": 30 + } + } + ] +} diff --git a/tools/design-readout/calibration/index.spec.ts b/tools/design-readout/calibration/index.spec.ts new file mode 100644 index 00000000000..033ec73e05b --- /dev/null +++ b/tools/design-readout/calibration/index.spec.ts @@ -0,0 +1,326 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import type { CalibrationEntry, Expected, Snapshot } from '.'; +import { + calibrateEntry, calibrateSet, calibrationDir, EXPECTED_FILE, hasMiss, loadCalibration, loadEntry, refreshEntry, renderCalibration, SNAPSHOT_FILE, + SNAPSHOT_VERSION, +} from '.'; +import { TOKEN_ENV } from '../config'; +import type { Leaf } from '../extract/values'; +import type { NodesResponse } from '../fetch/figma'; +import { fetchNodes, FigmaFetchError } from '../fetch/figma'; +import { buildThemeColorMap } from '../recognize/colormap'; +import { loadSpriteNames } from '../recognize/signals'; + +const SPRITES = [ 'copy', 'token', 'arrows/east' ]; +const URL = 'https://www.figma.com/design/abcDEF0123456789abcDEF/Pages?node-id=1-2'; +const BLUE = { role: 'text' as const, hex: '#2B6CB0', alpha: 1 }; +const GRAY = { role: 'icon' as const, hex: '#A0AEC0', alpha: 1 }; + +function text(id: string, content: string, x: number): Leaf { + return { + id, + values: { kind: 'text', text: content, trailingGlyphs: undefined, font: { family: 'Inter', weight: 500, size: 14, lineHeight: 20 }, colors: [ BLUE ] }, + bbox: { x, y: 0, width: 80, height: 20 }, + }; +} + +function icon(id: string, name: string, x: number): Leaf { + return { id, values: { kind: 'icon', icon: name, colors: [ GRAY ] }, bbox: { x, y: 0, width: 20, height: 20 } }; +} + +// A row in reading order: a block number, a copy icon, then a from/to pair with its entity icons. +const LEAVES: ReadonlyArray<Leaf> = [ + text('1:10', '1248139', 0), + icon('1:11', 'copy', 90), + icon('1:20', 'Icons/token', 200), + text('1:21', '0x05a3…f2d1', 228), + icon('1:22', 'arrows/east', 316), + icon('1:23', 'token', 344), + text('1:24', '0xf2d1…05a3', 372), +]; + +const SNAPSHOT: Snapshot = { + version: SNAPSHOT_VERSION, + fileKey: 'abcDEF0123456789abcDEF', + nodeId: '1:2', + capturedAt: '2026-10-08T10:00:00.000Z', + file: { lastModified: '2026-10-01T00:00:00Z', version: '42' }, + regions: [ '1:2' ], + frameBackground: { hex: '#FFFFFF', alpha: 1 }, + leaves: LEAVES, +}; + +const EXPECTED: Expected = { + url: URL, + nodeId: '1:2', + component: 'src/slices/block/pages/index/BlocksTableItem.tsx', + stale: false, + cells: { + '1:10': { component: 'BlockEntity', props: { noIcon: true }, shape: 'number', color: { text: 'link.primary' } }, + '1:11': { component: 'BlockEntity', props: { noIcon: true }, icon: 'copy', color: { icon: 'icon.secondary' } }, + '1:21': { component: 'AddressFromTo', props: {}, shape: 'truncated-hash', composite: 'from-to' }, + '1:22': { component: 'AddressFromTo', props: {}, icon: 'arrows/east', composite: 'from-to' }, + '1:24': { component: 'AddressFromTo', props: {}, shape: 'truncated-hash', composite: 'from-to' }, + }, +}; + +let tmp = ''; + +afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; + fetchMock.resetMocks(); +}); + +function writeEntry(name: string, expected: unknown, snapshot: Snapshot | undefined): string { + if (!tmp) tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-calibration-')); + const dir = path.join(tmp, name); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, EXPECTED_FILE), JSON.stringify(expected, null, 2)); + if (snapshot !== undefined) fs.writeFileSync(path.join(dir, SNAPSHOT_FILE), JSON.stringify(snapshot, null, 2)); + return dir; +} + +function readJson(file: string): unknown { + return JSON.parse(fs.readFileSync(file, 'utf8')); +} + +describe('loadEntry', () => { + it('reads the expected cells and the snapshot of one folder, and an entry without a snapshot yet', () => { + const dir = writeEntry('blocks', EXPECTED, SNAPSHOT); + expect(loadEntry(dir)).toEqual({ name: 'blocks', dir, expected: EXPECTED, snapshot: SNAPSHOT }); + expect(loadEntry(writeEntry('later', EXPECTED, undefined)).snapshot).toBeUndefined(); + }); + + it('rejects a cell keyed by a node id the snapshot has no leaf for', () => { + const dir = writeEntry('blocks', { ...EXPECTED, cells: { ...EXPECTED.cells, '9:9': { component: 'X', props: {} } } }, SNAPSHOT); + expect(() => loadEntry(dir)) + .toThrow('Calibration entry blocks: cell 9:9 is not a leaf of its snapshot; the leaves are 1:10, 1:11, 1:20, 1:21, 1:22, 1:23, 1:24.'); + }); + + it('rejects a malformed cell, a snapshot of another version, and a missing expected file, naming the file and the path', () => { + const badCell = { ...EXPECTED, cells: { '1:10': { component: 'BlockEntity', props: {}, shape: 'hash' } } }; + expect(() => loadEntry(writeEntry('cell', badCell, SNAPSHOT))).toThrow(/Not a valid calibration file .*cell\/expected\.json: cells\.1:10\.shape: /); + expect(() => loadEntry(writeEntry('version', EXPECTED, { ...SNAPSHOT, version: 0 }))).toThrow(/version\/snapshot\.json: version: /); + expect(() => loadEntry(writeEntry('url', { ...EXPECTED, url: 'https://example.com' }, SNAPSHOT))).toThrow(/url: not a Figma node URL/); + const empty = path.join(writeEntry('x', EXPECTED, undefined), '..', 'empty'); + fs.mkdirSync(empty); + expect(() => loadEntry(empty)).toThrow('Calibration entry empty has no expected.json.'); + }); +}); + +describe('loadCalibration', () => { + it('loads every sub-folder in name order and ignores files at the top level', () => { + writeEntry('b', EXPECTED, SNAPSHOT); + writeEntry('a', EXPECTED, SNAPSHOT); + fs.writeFileSync(path.join(tmp, 'README.md'), 'not an entry'); + expect(loadCalibration(tmp).map((entry) => entry.name)).toEqual([ 'a', 'b' ]); + expect(() => loadCalibration(path.join(tmp, 'nowhere'))).toThrow(/No calibration set at /); + }); + + it('is under the repo root', () => { + expect(calibrationDir('/repo')).toBe(path.join('/repo', 'tools', 'design-readout', 'calibration', 'entries')); + }); +}); + +describe('calibrateEntry', () => { + const map = buildThemeColorMap(); + const entry: CalibrationEntry = { name: 'blocks', dir: '/nowhere', expected: EXPECTED, snapshot: SNAPSHOT }; + + it('checks every stated signal of every cell against recognition over the snapshot, offline', () => { + const result = calibrateEntry(entry, SPRITES, map); + expect(result).toMatchObject({ name: 'blocks', kind: 'checked', colorMode: 'light' }); + if (result.kind !== 'checked') throw new Error('unreachable'); + expect(result.cells.map((cell) => [ cell.nodeId, cell.checks.map((check) => `${ check.signal } ${ check.hit ? 'hit' : 'MISS' }`) ])).toEqual([ + [ '1:10', [ 'shape hit', 'color hit' ] ], + [ '1:11', [ 'icon hit', 'color hit' ] ], + [ '1:21', [ 'shape hit', 'composite hit' ] ], + [ '1:22', [ 'icon hit', 'composite hit' ] ], + [ '1:24', [ 'shape hit', 'composite hit' ] ], + ]); + expect(hasMiss([ result ])).toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('reports a deliberate miss per signal with what was expected and what recognition said', () => { + const cells: Expected['cells'] = { + '1:10': { component: 'BlockEntity', props: {}, shape: 'amount', color: { text: 'text.secondary' } }, + '1:11': { component: 'BlockEntity', props: {}, icon: 'copy_check' }, + '1:21': { component: 'AddressFromTo', props: {}, status: 'ambiguous' }, + '1:22': { component: 'AddressFromTo', props: {}, composite: 'amount-ticker' }, + }; + const result = calibrateEntry({ ...entry, expected: { ...EXPECTED, cells } }, SPRITES, map); + if (result.kind !== 'checked') throw new Error('unreachable'); + expect(result.cells.flatMap((cell) => cell.checks)).toEqual([ + { signal: 'shape', expected: 'amount, recognized', actual: 'number, recognized', hit: false }, + { signal: 'color', expected: 'text text.secondary', actual: 'text badge.bright.blue.fg, link.primary', hit: false }, + { signal: 'icon', expected: 'copy_check, recognized', actual: 'copy, recognized', hit: false }, + { signal: 'shape', expected: 'any, ambiguous', actual: 'truncated-hash, recognized', hit: false }, + { signal: 'composite', expected: 'amount-ticker', actual: 'from-to', hit: false }, + ]); + expect(hasMiss([ result ])).toBe(true); + }); + + it('checks a color against the tokens of that role only, and names the fill that resolved none', () => { + const cells: Expected['cells'] = { '1:10': { component: 'BlockEntity', props: {}, color: { background: 'link.primary' } } }; + const result = calibrateEntry({ ...entry, expected: { ...EXPECTED, cells } }, SPRITES, map); + if (result.kind !== 'checked') throw new Error('unreachable'); + expect(result.cells[0].checks).toEqual([ { signal: 'color', expected: 'background link.primary', actual: 'background no token', hit: false } ]); + }); + + it('lets the frame background decide the mode when no fill votes', () => { + const unmapped = { ...LEAVES[0], values: { ...LEAVES[0].values, colors: [ { role: 'text' as const, hex: '#123456', alpha: 1 } ] } }; + const snapshot: Snapshot = { ...SNAPSHOT, leaves: [ unmapped ], frameBackground: { hex: '#101112', alpha: 1 } }; + const cells: Expected['cells'] = { '1:10': { component: 'BlockEntity', props: {} } }; + expect(calibrateEntry({ ...entry, expected: { ...EXPECTED, cells }, snapshot }, SPRITES, map)).toMatchObject({ kind: 'checked', colorMode: 'dark' }); + }); + + it('fails on a cell keyed by a node id the snapshot has no leaf for', () => { + const cells: Expected['cells'] = { '9:9': { component: 'X', props: {} } }; + expect(() => calibrateEntry({ ...entry, expected: { ...EXPECTED, cells } }, SPRITES, map)).toThrow('Calibration entry blocks: cell 9:9 has no leaf.'); + }); + + it('skips a stale entry and flags one without a snapshot', () => { + expect(calibrateEntry({ ...entry, expected: { ...EXPECTED, stale: true } }, SPRITES, map)).toEqual({ name: 'blocks', kind: 'stale' }); + expect(calibrateEntry({ ...entry, snapshot: undefined }, SPRITES, map)).toEqual({ name: 'blocks', kind: 'no-snapshot' }); + expect(hasMiss([ { name: 'blocks', kind: 'stale' } ])).toBe(false); + expect(hasMiss([ { name: 'blocks', kind: 'no-snapshot' } ])).toBe(true); + }); +}); + +describe('renderCalibration', () => { + it('prints one line per entry, the misses under it, the per-signal table and the verdict', () => { + const map = buildThemeColorMap(); + const missing: Expected['cells'] = { '1:10': { component: 'BlockEntity', props: { noIcon: true }, shape: 'amount' } }; + const results = calibrateSet([ + { name: 'blocks', dir: '/a', expected: EXPECTED, snapshot: SNAPSHOT }, + { name: 'miss', dir: '/b', expected: { ...EXPECTED, cells: missing }, snapshot: SNAPSHOT }, + { name: 'gone', dir: '/c', expected: { ...EXPECTED, stale: true }, snapshot: SNAPSHOT }, + ], SPRITES, map); + expect(renderCalibration(results)).toBe([ + 'Calibration: 3 entries, 2 checked, 1 stale', + ' blocks (light): 5 cells, 10 checks, 0 misses', + ' miss (light): 1 cells, 1 checks, 1 misses', + ' MISS 1:10 BlockEntity shape: expected amount, recognized; got number, recognized', + ' gone: stale, skipped (the node is gone from Figma; --refresh gone when it is back)', + '', + 'signal hits misses', + 'shape 3 1', + 'icon 2 0', + 'color 2 0', + 'composite 3 0', + '', + 'FAIL: 1 misses', + ].join('\n')); + expect(renderCalibration(results.slice(0, 1))).toMatch(/\nPASS: 10 checks$/); + }); +}); + +describe('refreshEntry', () => { + const now = new Date('2026-10-08T12:00:00.000Z'); + const env = { [TOKEN_ENV]: 'personal-token' }; + const fetchWithToken = (ref: { fileKey: string; nodeId: string }): Promise<NodesResponse> => fetchNodes(ref, env); + + function payload(): NodesResponse { + return { + name: 'Pages', + lastModified: '2026-10-07T00:00:00Z', + version: '43', + nodes: { + '1:2': { + document: { + id: '1:2', + name: 'Row', + type: 'FRAME', + absoluteBoundingBox: { x: 0, y: 0, width: 400, height: 20 }, + fills: [ { type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 } } ], + children: [ + { id: '1:10', name: 'number', type: 'TEXT', characters: '1248140', fills: [ { type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 } } ] }, + { id: '1:11', name: 'copy', type: 'INSTANCE', fills: [ { type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 } } ] }, + ], + }, + }, + }, + }; + } + + it('re-extracts the node and overwrites the snapshot, clearing a stale mark', async() => { + const dir = writeEntry('blocks', { ...EXPECTED, stale: true, cells: { '1:10': { component: 'BlockEntity', props: {} } } }, SNAPSHOT); + fetchMock.mockResponseOnce(JSON.stringify(payload())); + const outcome = await refreshEntry(loadEntry(dir), fetchWithToken, now, buildThemeColorMap()); + expect(outcome).toEqual({ name: 'blocks', kind: 'refreshed', leaves: 3 }); + expect(fetchMock.mock.calls[0][0]).toBe('https://api.figma.com/v1/files/abcDEF0123456789abcDEF/nodes?ids=1%3A2'); + const snapshot = readJson(path.join(dir, SNAPSHOT_FILE)) as Snapshot; + expect(snapshot).toMatchObject({ + version: SNAPSHOT_VERSION, + fileKey: 'abcDEF0123456789abcDEF', + nodeId: '1:2', + capturedAt: '2026-10-08T12:00:00.000Z', + file: { lastModified: '2026-10-07T00:00:00Z', version: '43' }, + regions: [ '1:2' ], + frameBackground: { hex: '#FFFFFF', alpha: 1 }, + }); + expect(snapshot.leaves.map((leaf) => leaf.id)).toEqual([ '1:2', '1:10', '1:11' ]); + expect(readJson(path.join(dir, EXPECTED_FILE))).toMatchObject({ stale: false, cells: { '1:10': { component: 'BlockEntity' } } }); + expect(loadEntry(dir).snapshot).toEqual(snapshot); + }); + + it('marks the entry stale and keeps the old snapshot when the node is gone from the file or Figma answers 404', async() => { + const dir = writeEntry('blocks', EXPECTED, SNAPSHOT); + fetchMock.mockResponseOnce(JSON.stringify({ ...payload(), nodes: { '1:2': null } })); + expect(await refreshEntry(loadEntry(dir), fetchWithToken, now)).toEqual({ name: 'blocks', kind: 'stale', reason: 'node 1:2 is not in file "Pages"' }); + expect(readJson(path.join(dir, EXPECTED_FILE))).toMatchObject({ stale: true }); + expect(readJson(path.join(dir, SNAPSHOT_FILE))).toEqual(SNAPSHOT); + + fetchMock.mockResponseOnce('', { status: 404 }); + expect(await refreshEntry(loadEntry(dir), fetchWithToken, now)).toMatchObject({ kind: 'stale', reason: /Figma returned 404/ }); + + fetchMock.mockResponseOnce(JSON.stringify({ ...payload(), nodes: {} })); + expect(await refreshEntry(loadEntry(dir), fetchWithToken, now)).toEqual({ name: 'blocks', kind: 'stale', reason: 'node 1:2 is not in file "Pages"' }); + }); + + it('refuses an entry whose url is not a Figma node link before fetching anything', async() => { + const entry: CalibrationEntry = { name: 'blocks', dir: '/nowhere', expected: { ...EXPECTED, url: 'https://example.com' }, snapshot: SNAPSHOT }; + await expect(refreshEntry(entry, fetchWithToken, now)).rejects.toThrow('Not a Figma node URL: https://example.com'); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('stops on a rejected token or a missing one, touching nothing', async() => { + const dir = writeEntry('blocks', EXPECTED, SNAPSHOT); + fetchMock.mockResponseOnce('', { status: 403 }); + await expect(refreshEntry(loadEntry(dir), fetchWithToken, now)).rejects.toThrow(FigmaFetchError); + await expect(refreshEntry(loadEntry(dir), (ref) => fetchNodes(ref, {}), now)).rejects.toThrow('No Figma token'); + expect(readJson(path.join(dir, EXPECTED_FILE))).toEqual(EXPECTED); + }); + + it('honours the entry\'s own regions over the outline\'s content root', async() => { + const dir = writeEntry('blocks', { ...EXPECTED, regions: [ '1:11' ], cells: {} }, undefined); + fetchMock.mockResponseOnce(JSON.stringify(payload())); + expect(await refreshEntry(loadEntry(dir), fetchWithToken, now)).toEqual({ name: 'blocks', kind: 'refreshed', leaves: 1 }); + expect((readJson(path.join(dir, SNAPSHOT_FILE)) as Snapshot).regions).toEqual([ '1:11' ]); + }); + + it('records a null frame background when the root paints none', async() => { + const dir = writeEntry('blocks', { ...EXPECTED, cells: {} }, undefined); + const bare = payload(); + const { fills, ...root } = bare.nodes['1:2']?.document ?? {}; + expect(fills).toBeDefined(); + fetchMock.mockResponseOnce(JSON.stringify({ ...bare, nodes: { '1:2': { document: root } } })); + await refreshEntry(loadEntry(dir), fetchWithToken, now); + expect((readJson(path.join(dir, SNAPSHOT_FILE)) as Snapshot).frameBackground).toBeNull(); + }); +}); + +describe('the committed calibration set', () => { + it('loads, and every expected cell holds over its snapshot', () => { + const results = calibrateSet(loadCalibration(calibrationDir(path.join(__dirname, '..', '..', '..'))), loadSpriteNames()); + expect(results.length).toBeGreaterThanOrEqual(10); + expect(renderCalibration(results)).toMatch(/\nPASS: \d+ checks$/); + expect(hasMiss(results)).toBe(false); + }); +}); diff --git a/tools/design-readout/calibration/index.ts b/tools/design-readout/calibration/index.ts new file mode 100644 index 00000000000..3c197b7604a --- /dev/null +++ b/tools/design-readout/calibration/index.ts @@ -0,0 +1,385 @@ +import fs from 'fs'; +import path from 'path'; +import * as v from 'valibot'; + +import { CALIBRATION_DIR } from '../config'; +import type { Leaf } from '../extract/values'; +import { extractRegions, frameBackground } from '../extract/values'; +import type { NodeEntry, NodesResponse } from '../fetch/figma'; +import { FigmaFetchError } from '../fetch/figma'; +import type { NodeRef } from '../fetch/url'; +import { parseNodeRef } from '../fetch/url'; +import type { ColorMap, ColorRole, ColorValue } from '../recognize/colormap'; +import { buildThemeColorMap, detectColorMode } from '../recognize/colormap'; +import type { Recognition } from '../recognize/signals'; +import { COMPOSITE_RULES, recognize, TEXT_SHAPE_RULES } from '../recognize/signals'; + +export const SNAPSHOT_VERSION = 1; +export const SNAPSHOT_FILE = 'snapshot.json'; +export const EXPECTED_FILE = 'expected.json'; + +const COLOR_ROLES: ReadonlyArray<ColorRole> = [ 'text', 'background', 'border', 'icon' ]; + +const ROLE_COLOR = v.object({ role: v.picklist(COLOR_ROLES), hex: v.string(), alpha: v.number() }); + +const FONT = v.object({ + family: v.optional(v.string(), undefined), + weight: v.optional(v.number(), undefined), + size: v.optional(v.number(), undefined), + lineHeight: v.optional(v.number(), undefined), +}); + +const LEAF_VALUES = v.variant('kind', [ + v.object({ + kind: v.literal('text'), + text: v.string(), + trailingGlyphs: v.optional(v.string(), undefined), + font: v.optional(FONT, undefined), + colors: v.array(ROLE_COLOR), + }), + v.object({ kind: v.literal('icon'), icon: v.string(), colors: v.array(ROLE_COLOR) }), + v.object({ kind: v.literal('box'), colors: v.array(ROLE_COLOR) }), +]); + +const BOX = v.object({ x: v.number(), y: v.number(), width: v.number(), height: v.number() }); + +// The tool's own extraction for the node, captured by `--refresh`: never a raw Figma payload, never a hint. +const SNAPSHOT = v.object({ + version: v.literal(SNAPSHOT_VERSION), + fileKey: v.string(), + nodeId: v.string(), + capturedAt: v.string(), + file: v.object({ lastModified: v.string(), version: v.string() }), + regions: v.array(v.string()), + frameBackground: v.nullable(v.object({ hex: v.string(), alpha: v.number() })), + leaves: v.array(v.object({ id: v.string(), values: LEAF_VALUES, bbox: v.nullable(BOX) })), +}); + +export interface Snapshot { + readonly version: number; + readonly fileKey: string; + readonly nodeId: string; + readonly capturedAt: string; + readonly file: { readonly lastModified: string; readonly version: string }; + readonly regions: ReadonlyArray<string>; + readonly frameBackground: ColorValue | null; + readonly leaves: ReadonlyArray<Leaf>; +} + +const STATUSES = [ 'recognized', 'ambiguous', 'unrecognized' ] as const; + +// What recognition must say for one leaf, read off the shipped component: which repo component and +// props render the cell, and per signal what should fire. A signal left out is not checked; `status` +// alone pins a leaf the tool rightly cannot settle (an identicon is no sprite). +const EXPECTED_CELL = v.object({ + component: v.string(), + props: v.record(v.string(), v.union([ v.string(), v.number(), v.boolean() ])), + status: v.optional(v.picklist(STATUSES)), + shape: v.optional(v.picklist(TEXT_SHAPE_RULES.map((rule) => rule.signal))), + icon: v.optional(v.string()), + color: v.optional(v.partial(v.object({ text: v.string(), background: v.string(), border: v.string(), icon: v.string() }))), + composite: v.optional(v.picklist(COMPOSITE_RULES.map((rule) => rule.signal))), +}); + +export type ExpectedCell = v.InferOutput<typeof EXPECTED_CELL>; + +const EXPECTED = v.object({ + url: v.pipe(v.string(), v.check((url) => parseNodeRef(url) !== undefined, 'not a Figma node URL')), + nodeId: v.string(), + component: v.string(), + regions: v.optional(v.array(v.string())), + stale: v.boolean(), + cells: v.record(v.string(), EXPECTED_CELL), +}); + +export type Expected = v.InferOutput<typeof EXPECTED>; + +export interface CalibrationEntry { + readonly name: string; + readonly dir: string; + readonly expected: Expected; + readonly snapshot: Snapshot | undefined; +} + +export function calibrationDir(checkoutRoot: string): string { + return path.join(checkoutRoot, CALIBRATION_DIR); +} + +function readJson(file: string): unknown { + return JSON.parse(fs.readFileSync(file, 'utf8')); +} + +function parseOrThrow<TSchema extends v.GenericSchema>(schema: TSchema, input: unknown, file: string): v.InferOutput<TSchema> { + const result = v.safeParse(schema, input); + if (result.success) return result.output; + const issues = result.issues.map((issue) => `${ v.getDotPath(issue) ?? '(root)' }: ${ issue.message }`).join('; '); + throw new Error(`Not a valid calibration file ${ file }: ${ issues }`); +} + +function validateCells(entry: CalibrationEntry): void { + if (entry.snapshot === undefined) return; + const leafIds = new Set(entry.snapshot.leaves.map((leaf) => leaf.id)); + for (const nodeId of Object.keys(entry.expected.cells)) { + if (leafIds.has(nodeId)) continue; + throw new Error(`Calibration entry ${ entry.name }: cell ${ nodeId } is not a leaf of its snapshot; the leaves are ${ [ ...leafIds ].join(', ') }.`); + } +} + +// JSON drops a leaf's `undefined` keys, so the schema reads them back as optional; `Leaf` wants them +// present-and-undefined, which the same object satisfies at run time. +function readSnapshot(file: string): Snapshot { + return parseOrThrow(SNAPSHOT, readJson(file), file) as Snapshot; +} + +export function loadEntry(dir: string): CalibrationEntry { + const name = path.basename(dir); + const expectedFile = path.join(dir, EXPECTED_FILE); + if (!fs.existsSync(expectedFile)) throw new Error(`Calibration entry ${ name } has no ${ EXPECTED_FILE }.`); + const snapshotFile = path.join(dir, SNAPSHOT_FILE); + const entry: CalibrationEntry = { + name, + dir, + expected: parseOrThrow(EXPECTED, readJson(expectedFile), expectedFile), + snapshot: fs.existsSync(snapshotFile) ? readSnapshot(snapshotFile) : undefined, + }; + validateCells(entry); + return entry; +} + +// One entry per sub-folder, in name order; a file at the top level is not an entry. +export function loadCalibration(dir: string): ReadonlyArray<CalibrationEntry> { + if (!fs.existsSync(dir)) throw new Error(`No calibration set at ${ dir }.`); + return fs.readdirSync(dir, { withFileTypes: true }) + .filter((item) => item.isDirectory()) + .map((item) => item.name) + .sort() + .map((name) => loadEntry(path.join(dir, name))); +} + +export type CalibrationSignal = 'shape' | 'icon' | 'color' | 'composite'; + +export const CALIBRATION_SIGNALS: ReadonlyArray<CalibrationSignal> = [ 'shape', 'icon', 'color', 'composite' ]; + +export interface SignalCheck { + readonly signal: CalibrationSignal; + readonly expected: string; + readonly actual: string; + readonly hit: boolean; +} + +export interface CellResult { + readonly nodeId: string; + readonly component: string; + readonly checks: ReadonlyArray<SignalCheck>; +} + +export type EntryResult = + { readonly name: string; readonly kind: 'checked'; readonly colorMode: string; readonly cells: ReadonlyArray<CellResult> } | + { readonly name: string; readonly kind: 'stale' } | + { readonly name: string; readonly kind: 'no-snapshot' }; + +function signalOfLeaf(leaf: Leaf): CalibrationSignal { + switch (leaf.values.kind) { + case 'text': + return 'shape'; + case 'icon': + return 'icon'; + case 'box': + return 'color'; + } +} + +function describeDecision(recognition: Recognition): string { + const { decision } = recognition; + if (decision === null) return 'none'; + return decision.signal === 'icon' ? decision.icon : decision.signal; +} + +// Shape and icon are one check with the status folded in: a hash recognized as a hash but left +// ambiguous is not a hit for a cell that expects it settled, and a cell may expect `ambiguous`. +function checkDecision(cell: ExpectedCell, leaf: Leaf, recognition: Recognition): SignalCheck | undefined { + const expectedDecision = cell.shape ?? cell.icon; + const expectedStatus = cell.status ?? (expectedDecision === undefined ? undefined : 'recognized'); + if (expectedStatus === undefined) return undefined; + const actualDecision = describeDecision(recognition); + const decisionHit = expectedDecision === undefined || expectedDecision === actualDecision; + const statusHit = expectedStatus === recognition.status; + return { + signal: signalOfLeaf(leaf), + expected: `${ expectedDecision ?? 'any' }, ${ expectedStatus }`, + actual: `${ actualDecision }, ${ recognition.status }`, + hit: decisionHit && statusHit, + }; +} + +function checkColors(cell: ExpectedCell, recognition: Recognition): Array<SignalCheck> { + return Object.entries(cell.color ?? {}).map(([ role, token ]) => { + const resolved = recognition.tokens.filter((entry) => entry.role === role).flatMap((entry) => entry.tokens); + const actual = resolved.length === 0 ? 'no token' : resolved.join(', '); + return { signal: 'color', expected: `${ role } ${ token }`, actual: `${ role } ${ actual }`, hit: resolved.includes(token) }; + }); +} + +function checkComposite(cell: ExpectedCell, recognition: Recognition): SignalCheck | undefined { + if (cell.composite === undefined) return undefined; + const actual = recognition.composite?.signal ?? 'none'; + return { signal: 'composite', expected: cell.composite, actual, hit: actual === cell.composite }; +} + +function checkCell(nodeId: string, cell: ExpectedCell, leaf: Leaf, recognition: Recognition): CellResult { + const checks = [ checkDecision(cell, leaf, recognition), ...checkColors(cell, recognition), checkComposite(cell, recognition) ] + .filter((check) => check !== undefined); + return { nodeId, component: cell.component, checks }; +} + +export function calibrateEntry(entry: CalibrationEntry, spriteNames: ReadonlyArray<string>, map: ColorMap): EntryResult { + if (entry.expected.stale) return { name: entry.name, kind: 'stale' }; + if (entry.snapshot === undefined) return { name: entry.name, kind: 'no-snapshot' }; + const { leaves, frameBackground: background } = entry.snapshot; + const mode = detectColorMode(map, leaves.flatMap((leaf) => leaf.values.colors), background ?? undefined).mode; + const recognitions = recognize(leaves, spriteNames, map, mode); + const byId = new Map(leaves.map((leaf, index) => [ leaf.id, { leaf, recognition: recognitions[index] } ])); + const cells = Object.entries(entry.expected.cells).map(([ nodeId, cell ]) => { + const found = byId.get(nodeId); + if (found === undefined) throw new Error(`Calibration entry ${ entry.name }: cell ${ nodeId } has no leaf.`); + return checkCell(nodeId, cell, found.leaf, found.recognition); + }); + return { name: entry.name, kind: 'checked', colorMode: mode, cells }; +} + +export function calibrateSet( + entries: ReadonlyArray<CalibrationEntry>, + spriteNames: ReadonlyArray<string>, + map: ColorMap = buildThemeColorMap(), +): ReadonlyArray<EntryResult> { + return entries.map((entry) => calibrateEntry(entry, spriteNames, map)); +} + +function checksOf(results: ReadonlyArray<EntryResult>): Array<SignalCheck> { + return results.flatMap((result) => result.kind === 'checked' ? result.cells.flatMap((cell) => cell.checks) : []); +} + +// A miss is a failed check or an entry that cannot be checked at all; a stale entry is neither. +export function hasMiss(results: ReadonlyArray<EntryResult>): boolean { + return results.some((result) => result.kind === 'no-snapshot') || checksOf(results).some((check) => !check.hit); +} + +function describeMiss(check: SignalCheck): string { + return `${ check.signal }: expected ${ check.expected }; got ${ check.actual }`; +} + +function renderEntry(result: EntryResult): Array<string> { + switch (result.kind) { + case 'stale': + return [ ` ${ result.name }: stale, skipped (the node is gone from Figma; --refresh ${ result.name } when it is back)` ]; + case 'no-snapshot': + return [ ` ${ result.name }: MISS, no ${ SNAPSHOT_FILE } (run --refresh ${ result.name })` ]; + case 'checked': { + const checks = result.cells.flatMap((cell) => cell.checks); + const misses = result.cells.flatMap((cell) => cell.checks.filter((check) => !check.hit).map((check) => ({ cell, check }))); + return [ + ` ${ result.name } (${ result.colorMode }): ${ result.cells.length } cells, ${ checks.length } checks, ${ misses.length } misses`, + ...misses.map(({ cell, check }) => ` MISS ${ cell.nodeId } ${ cell.component } ${ describeMiss(check) }`), + ]; + } + } +} + +function renderSignalTable(checks: ReadonlyArray<SignalCheck>): Array<string> { + const rows = CALIBRATION_SIGNALS.map((signal) => { + const own = checks.filter((check) => check.signal === signal); + return { signal, hits: own.filter((check) => check.hit).length, misses: own.filter((check) => !check.hit).length }; + }); + const width = Math.max(...CALIBRATION_SIGNALS.map((signal) => signal.length)); + return [ + `${ 'signal'.padEnd(width) } hits misses`, + ...rows.map((row) => `${ row.signal.padEnd(width) } ${ String(row.hits).padStart(4) } ${ String(row.misses).padStart(6) }`), + ]; +} + +export function renderCalibration(results: ReadonlyArray<EntryResult>): string { + const checked = results.filter((result) => result.kind === 'checked').length; + const stale = results.filter((result) => result.kind === 'stale').length; + const checks = checksOf(results); + const misses = checks.filter((check) => !check.hit).length; + return [ + `Calibration: ${ results.length } entries, ${ checked } checked, ${ stale } stale`, + ...results.flatMap(renderEntry), + '', + ...renderSignalTable(checks), + '', + hasMiss(results) ? `FAIL: ${ misses } misses` : `PASS: ${ checks.length } checks`, + ].join('\n'); +} + +export type FetchNodes = (ref: NodeRef) => Promise<NodesResponse>; + +export type RefreshOutcome = + { readonly name: string; readonly kind: 'refreshed'; readonly leaves: number } | + { readonly name: string; readonly kind: 'stale'; readonly reason: string }; + +function writeJson(file: string, value: unknown): void { + fs.writeFileSync(file, `${ JSON.stringify(value, null, 2) }\n`); +} + +function refOf(expected: Expected): NodeRef { + const ref = parseNodeRef(expected.url); + if (ref === undefined) throw new Error(`Not a Figma node URL: ${ expected.url }`); + return { fileKey: ref.fileKey, nodeId: expected.nodeId }; +} + +type FetchedEntry = { readonly payload: NodesResponse; readonly node: NodeEntry } | { readonly gone: string }; + +async function fetchEntryNode(ref: NodeRef, fetchNodes: FetchNodes): Promise<FetchedEntry> { + try { + const payload = await fetchNodes(ref); + const node = payload.nodes[ref.nodeId]; + return node === undefined || node === null ? { gone: `node ${ ref.nodeId } is not in file "${ payload.name }"` } : { payload, node }; + } catch (error: unknown) { + if (error instanceof FigmaFetchError && error.status === 404) return { gone: error.message }; + throw error; + } +} + +function plainColor(color: ColorValue | undefined): ColorValue | null { + return color === undefined ? null : { hex: color.hex, alpha: color.alpha }; +} + +function markStale(entry: CalibrationEntry, reason: string): RefreshOutcome { + writeJson(path.join(entry.dir, EXPECTED_FILE), { ...entry.expected, stale: true }); + return { name: entry.name, kind: 'stale', reason }; +} + +// A vanished node marks its entry stale and the run goes on; a token problem or any other failure +// stops the run, since every entry after it would fail the same way. +export async function refreshEntry( + entry: CalibrationEntry, + fetchNodes: FetchNodes, + now: Date, + map: ColorMap = buildThemeColorMap(), +): Promise<RefreshOutcome> { + const ref = refOf(entry.expected); + const fetched = await fetchEntryNode(ref, fetchNodes); + if ('gone' in fetched) return markStale(entry, fetched.gone); + const { payload, node } = fetched; + const { regions, extraction } = extractRegions(node, entry.expected.regions, map); + const snapshot: Snapshot = { + version: SNAPSHOT_VERSION, + fileKey: ref.fileKey, + nodeId: ref.nodeId, + capturedAt: now.toISOString(), + file: { lastModified: payload.lastModified, version: payload.version }, + regions, + frameBackground: plainColor(frameBackground(node.document)), + leaves: extraction.leaves, + }; + writeJson(path.join(entry.dir, SNAPSHOT_FILE), snapshot); + writeJson(path.join(entry.dir, EXPECTED_FILE), { ...entry.expected, stale: false }); + return { name: entry.name, kind: 'refreshed', leaves: extraction.leaves.length }; +} + +export function describeRefresh(outcome: RefreshOutcome): string { + return outcome.kind === 'refreshed' ? + ` ${ outcome.name }: refreshed, ${ outcome.leaves } leaves` : + ` ${ outcome.name }: STALE, ${ outcome.reason }`; +} diff --git a/tools/design-readout/cli/args.spec.ts b/tools/design-readout/cli/args.spec.ts new file mode 100644 index 00000000000..a08e24a88df --- /dev/null +++ b/tools/design-readout/cli/args.spec.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from 'vitest'; + +import type { CliOptions, CorrectionRequest, OverrideRequest } from './args'; +import { parseArgs } from './args'; + +const URL = 'https://www.figma.com/design/abcDEF0123456789abcDEF/Pages?node-id=22842-174340'; + +function readout(argv: ReadonlyArray<string>): CliOptions { + const parsed = parseArgs(argv); + if (parsed.kind !== 'readout') throw new Error(`Expected a readout, got ${ parsed.kind }`); + return parsed.options; +} + +function correction(argv: ReadonlyArray<string>): CorrectionRequest { + const parsed = parseArgs(argv); + if (parsed.kind !== 'correct') throw new Error(`Expected a correction, got ${ parsed.kind }`); + return parsed.correction; +} + +function override(argv: ReadonlyArray<string>): OverrideRequest { + const parsed = parseArgs(argv); + if (parsed.kind !== 'override') throw new Error(`Expected an override, got ${ parsed.kind }`); + return parsed.override; +} + +describe('parseArgs', () => { + it('takes the node URL as the one positional and --dump in both forms', () => { + expect(parseArgs([ URL ])).toEqual({ + kind: 'readout', + options: { + dump: undefined, regions: undefined, correct: undefined, gap: undefined, stage: undefined, override: undefined, note: undefined, + calibrate: false, refresh: false, + }, + ref: { fileKey: 'abcDEF0123456789abcDEF', nodeId: '22842:174340' }, + }); + expect(readout([ URL, '--dump', 'out.json' ]).dump).toBe('out.json'); + expect(readout([ '--dump=out.json', URL ]).dump).toBe('out.json'); + }); + + it('takes --regions as comma-separated node ids in either form, nested ones included, canonicalized', () => { + expect(readout([ URL, '--regions', '1-2, 3:4,I5-6;7-8' ]).regions).toEqual([ '1:2', '3:4', 'I5:6;7:8' ]); + expect(() => parseArgs([ URL, '--regions', '1-2,abc' ])).toThrow(/Not a node id in --regions: abc\nUsage:/); + }); + + it('takes --calibrate and --refresh [<entry>] without a URL, and rejects a URL or a per-node flag with them', () => { + expect(parseArgs([ '--calibrate' ])).toEqual({ kind: 'calibrate' }); + expect(parseArgs([ '--refresh' ])).toEqual({ kind: 'refresh', entry: undefined }); + expect(parseArgs([ '--refresh', 'blocks-table-item' ])).toEqual({ kind: 'refresh', entry: 'blocks-table-item' }); + expect(() => parseArgs([ '--calibrate', URL ])).toThrow(/--calibrate takes no argument: https/); + expect(() => parseArgs([ '--refresh', 'a', 'b' ])).toThrow(/--refresh takes at most one entry name: a b/); + expect(() => parseArgs([ '--calibrate', '--refresh' ])).toThrow(/--calibrate and --refresh are separate runs/); + expect(() => parseArgs([ '--calibrate', '--dump', 'x' ])).toThrow(/--calibrate works on the calibration set and takes no per-node flag/); + expect(() => parseArgs([ '--refresh', '--gap', 'shape' ])).toThrow(/--refresh works on the calibration set and takes no per-node flag/); + expect(() => parseArgs([ '--calibrate', '--override', '1-2' ])).toThrow(/--calibrate works on the calibration set and takes no per-node flag/); + expect(() => parseArgs([ '--calibrate', '--note', 'x', '--gap', 'markup' ])).toThrow(/--calibrate works on the calibration set and takes no per-node flag/); + }); + + it('takes --note with its text and the --gap category, in either flag form', () => { + expect(parseArgs([ URL, '--note', 'the row gap is 8px, the mockup has 12px', '--gap', 'markup' ])).toEqual({ + kind: 'note', + ref: { fileKey: 'abcDEF0123456789abcDEF', nodeId: '22842:174340' }, + note: { text: 'the row gap is 8px, the mockup has 12px', gap: 'markup' }, + }); + expect(parseArgs([ '--gap=layout', '--note= cells wrap ', URL ])).toEqual({ + kind: 'note', + ref: { fileKey: 'abcDEF0123456789abcDEF', nodeId: '22842:174340' }, + note: { text: 'cells wrap', gap: 'layout' }, + }); + }); + + it('rejects --note without --gap, with blank text, with a stray word, and beside --correct or --override', () => { + expect(() => parseArgs([ URL, '--note', 'cells wrap' ])) + .toThrow(/A note is always a miss: --note needs --gap <shape\|icon\|color\|composite\|context\|layout\|convention\|markup>\nUsage:/); + expect(() => parseArgs([ URL, '--note', ' ', '--gap', 'markup' ])).toThrow(/--note needs the text of the miss, in quotes\nUsage:/); + expect(() => parseArgs([ URL, '--note', 'cells wrap', '--gap', 'markup', 'Box' ])).toThrow(/Unexpected argument: Box/); + expect(() => parseArgs([ URL, '--note', 'cells wrap', '--gap', 'markup', '--correct', '1-2', 'Box' ])) + .toThrow(/--note is its own run: a note names no node, so it goes with neither --correct nor --override\nUsage:/); + expect(() => parseArgs([ URL, '--note', 'cells wrap', '--gap', 'markup', '--override', '1-2', 'bg=x' ])).toThrow(/--note is its own run/); + }); + + it('takes --override with the node id and one or more prop=value words', () => { + expect(parseArgs([ URL, '--override', '22842-178386', 'bg=whiteAlpha.100', 'fontWeight=500' ])).toEqual({ + kind: 'override', + ref: { fileKey: 'abcDEF0123456789abcDEF', nodeId: '22842:174340' }, + override: { nodeId: '22842:178386', props: [ 'bg=whiteAlpha.100', 'fontWeight=500' ] }, + }); + expect(override([ '--override=I1:2;3:4', URL, 'color=text.primary' ])).toEqual({ nodeId: 'I1:2;3:4', props: [ 'color=text.primary' ] }); + }); + + it('rejects --override with --correct or --gap, with no word, with a word that is not prop=value, and with a bad node id', () => { + expect(() => parseArgs([ URL, '--override', '1-2', 'bg=x', '--correct', '1-2', 'Box', '--gap', 'color' ])) + .toThrow(/--override and --correct are separate runs: an override is never a miss and takes no --gap\nUsage:/); + expect(() => parseArgs([ URL, '--override', '1-2', 'bg=x', '--gap', 'color' ])).toThrow(/--override and --correct are separate runs/); + expect(() => parseArgs([ URL, '--override', '1-2', 'bg=x', '--correct', '1-2', 'Box' ])).toThrow(/--override and --correct are separate runs/); + expect(() => parseArgs([ URL, '--override', '1-2' ])).toThrow(/--override 1:2 needs at least one <prop>=<value> word, after the URL\nUsage:/); + expect(() => parseArgs([ URL, '--override', '1-2', 'noIcon' ])).toThrow(/An override is one <prop>=<value> per word, no spaces inside: noIcon\nUsage:/); + expect(() => parseArgs([ URL, '--override', '1-2', 'bg=' ])).toThrow(/An override is one <prop>=<value> per word, no spaces inside: bg=/); + expect(() => parseArgs([ URL, '--override', 'abc', 'bg=x' ])).toThrow(/Not a node id in --override: abc\nUsage:/); + }); + + it('rejects a missing, extra or malformed URL with the usage line', () => { + expect(() => parseArgs([])).toThrow(/Missing the Figma node URL\nUsage:/); + expect(() => parseArgs([ URL, URL ])).toThrow(/Unexpected argument/); + expect(() => parseArgs([ '22842:174340' ])).toThrow(/Not a Figma node URL: 22842:174340\nUsage:/); + expect(() => parseArgs([ URL, '--json' ])).toThrow(/Unknown flag: --json/); + }); + + it('takes --correct with the node id, the component and its props as words, and the --gap category', () => { + expect(parseArgs([ URL, '--correct', '22842-178386', 'BlockEntity', 'noIcon', 'size=sm', '--gap', 'context' ])).toEqual({ + kind: 'correct', + ref: { fileKey: 'abcDEF0123456789abcDEF', nodeId: '22842:174340' }, + correction: { nodeId: '22842:178386', component: 'BlockEntity', props: [ 'noIcon', 'size=sm' ], gap: 'context', stage: 'readout' }, + }); + expect(correction([ '--gap=icon', URL, '--correct=I1:2;3:4', 'IconSvg' ])) + .toEqual({ nodeId: 'I1:2;3:4', component: 'IconSvg', props: [], gap: 'icon', stage: 'readout' }); + }); + + it('takes --stage markup on a correction the developer found at the markup leaf, and rejects it anywhere else', () => { + expect(correction([ URL, '--correct', '1-2', 'BlockEntity', '--gap', 'shape', '--stage', 'markup' ]).stage).toBe('markup'); + expect(() => parseArgs([ URL, '--correct', '1-2', 'BlockEntity', '--gap', 'shape', '--stage', 'later' ])) + .toThrow(/Not a gap stage: later; --stage takes one of readout, markup\nUsage:/); + expect(() => parseArgs([ URL, '--note', 'cells wrap', '--gap', 'markup', '--stage', 'markup' ])) + .toThrow(/A note is always a markup-stage miss: --stage goes with --correct only\nUsage:/); + expect(() => parseArgs([ URL, '--override', '1-2', 'bg=x', '--stage', 'markup' ])).toThrow(/--override and --correct are separate runs/); + expect(() => parseArgs([ URL, '--stage', 'markup' ])).toThrow(/--stage goes with --correct; nothing to log without a correction\nUsage:/); + }); + + it('rejects a correction without --gap, because a correction is always a miss', () => { + expect(() => parseArgs([ URL, '--correct', '1-2', 'BlockEntity' ])) + .toThrow(/A correction is always a miss: --correct needs --gap <shape\|icon\|color\|composite\|context\|layout\|convention\|markup>\nUsage:/); + }); + + it('rejects a bad category, a correction with no component, a bad node id, and --gap on its own', () => { + expect(() => parseArgs([ URL, '--correct', '1-2', 'BlockEntity', '--gap', 'typo' ])) + .toThrow(/Not a gap category: typo; --gap takes one of shape, icon, color, composite, context, layout, convention, markup\nUsage:/); + expect(() => parseArgs([ URL, '--correct', '1-2', '--gap', 'shape' ])).toThrow(/--correct 1:2 needs the component the node is, after the URL\nUsage:/); + expect(() => parseArgs([ URL, '--correct', 'abc', 'BlockEntity', '--gap', 'shape' ])).toThrow(/Not a node id in --correct: abc\nUsage:/); + expect(() => parseArgs([ URL, '--gap', 'shape' ])).toThrow(/--gap goes with --correct/); + }); +}); diff --git a/tools/design-readout/cli/args.ts b/tools/design-readout/cli/args.ts new file mode 100644 index 00000000000..dfa0af52958 --- /dev/null +++ b/tools/design-readout/cli/args.ts @@ -0,0 +1,229 @@ +/* eslint-disable no-console -- --help prints the usage to stdout and exits */ +import type { FlagSpec } from '../../cli/flags'; +import { parseArgs as parseFlags } from '../../cli/flags'; +import { CALIBRATION_DIR, GAP_CATEGORIES, GAP_STAGES, OVERRIDE_COLOR_PROPS } from '../config'; +import type { NodeRef } from '../fetch/url'; +import { parseNodeId as parseCanonicalNodeId, parseNodeRef } from '../fetch/url'; +import type { GapStage } from '../record/gaps'; +import type { GapCategory } from '../record/sidecar'; +import { isGapCategory } from '../record/sidecar'; + +export interface CliOptions { + dump: string | undefined; + regions: ReadonlyArray<string> | undefined; + correct: string | undefined; + gap: GapCategory | undefined; + stage: GapStage | undefined; + override: string | undefined; + note: string | undefined; + calibrate: boolean; + refresh: boolean; +} + +const USAGE = `Usage: + design:readout <figma node URL> [--regions <ids>] [--dump <path>] + design:readout <figma node URL> --correct <nodeId> <component> [<props…>] --gap <category> [--stage <stage>] + design:readout <figma node URL> --override <nodeId> <prop=value> [<prop=value…>] + design:readout <figma node URL> --note "<text>" --gap <category> + design:readout --calibrate + design:readout --refresh [<entry>] + + Reads one node through the Figma REST API and prints the scoping outline to confirm, the values of + every leaf under the confirmed regions, and what it recognizes per leaf. The values go to a JSON + sidecar under the main checkout's .ai/design-readout/. A node that already has a sidecar prints a + diff against it instead; a correction or override whose values changed is carried but flagged STALE. + + One link is one screen: hidden layers are ignored, and a state or a mobile variant is its own link. + The tool names no component; a correction does. Corrections and notes are misses and go to the gap + log (.ai/design-readout/gaps.md); an override is design intent and logs nothing. --correct, + --override and --note are separate runs, offline, on the existing sidecar. + + <figma node URL> https://www.figma.com/design/<fileKey>/<name>?node-id=<A>-<B> + (the node id is accepted as A-B or A:B; a node inside a component instance + carries the instance path, I<A>:<B>;<C>:<D>) + --regions <ids> the confirmed regions, comma-separated node ids (A-B or A:B); default: the + content root the outline names + --dump <path> also write the raw REST payload to this file, e.g. to capture a test fixture + --correct <nodeId> what the leaf really is: the repo component, then any props, as words; + the same miss on another node of the same file adds no gap line: + --correct 22842-178386 BlockEntity noIcon --gap shape + --gap <category> the kind of miss a correction or note records: ${ GAP_CATEGORIES.join(', ') } + --stage <stage> where a correction's miss surfaced: ${ GAP_STAGES.join(' | ') }; default readout. A + miss the developer found in the running app against the agent's markup is + --stage markup; a note is always markup + --override <nodeId> the Chakra props the mockup adds on purpose, as <prop>=<value> words, no spaces + inside a word; replaces the node's earlier override whole. A color prop + (${ Object.keys(OVERRIDE_COLOR_PROPS).join(', ') }) must name a token the node resolved for that fill: + --override 22842-178386 bg=whiteAlpha.100 + --note "<text>" a miss found in the running app that maps to no node; the URL supplies the + file key only: --note "row gap is 8px, mockup has 12px" --gap layout + --calibrate run recognition over the committed calibration set (${ CALIBRATION_DIR }), + offline; any miss exits non-zero + --refresh [<entry>] re-capture every calibration snapshot from Figma, or one entry's; a node that + is gone marks its entry stale and --calibrate skips it + + The run needs a Figma personal access token in the environment and fails without one; it never + reads another source. Personal access tokens expire after at most 90 days, so a rejected token + usually means a new one is due.`; + +function parseNodeId(raw: string, flag: string): string { + const nodeId = parseCanonicalNodeId(raw); + if (nodeId === undefined) throw new Error(`Not a node id in ${ flag }: ${ raw.trim() }\n${ USAGE }`); + return nodeId; +} + +function parseRegionIds(value: string): Array<string> { + return value.split(',').map((raw) => parseNodeId(raw, '--regions')); +} + +function parseGapCategory(value: string): GapCategory { + if (!isGapCategory(value)) throw new Error(`Not a gap category: ${ value }; --gap takes one of ${ GAP_CATEGORIES.join(', ') }\n${ USAGE }`); + return value; +} + +function isGapStage(value: string): value is GapStage { + return (GAP_STAGES as ReadonlyArray<string>).includes(value); +} + +function parseGapStage(value: string): GapStage { + if (!isGapStage(value)) throw new Error(`Not a gap stage: ${ value }; --stage takes one of ${ GAP_STAGES.join(', ') }\n${ USAGE }`); + return value; +} + +const FLAGS: ReadonlyMap<string, FlagSpec<CliOptions>> = new Map<string, FlagSpec<CliOptions>>([ + [ '--help', { kind: 'switch', apply: () => { + console.log(USAGE); + process.exit(0); + } } ], + [ '-h', { kind: 'switch', apply: () => { + console.log(USAGE); + process.exit(0); + } } ], + [ '--dump', { kind: 'value', apply: (options, value) => { + options.dump = value; + } } ], + [ '--regions', { kind: 'value', apply: (options, value) => { + options.regions = parseRegionIds(value); + } } ], + [ '--correct', { kind: 'value', apply: (options, value) => { + options.correct = parseNodeId(value, '--correct'); + } } ], + [ '--gap', { kind: 'value', apply: (options, value) => { + options.gap = parseGapCategory(value); + } } ], + [ '--stage', { kind: 'value', apply: (options, value) => { + options.stage = parseGapStage(value); + } } ], + [ '--override', { kind: 'value', apply: (options, value) => { + options.override = parseNodeId(value, '--override'); + } } ], + [ '--note', { kind: 'value', apply: (options, value) => { + options.note = value; + } } ], + [ '--calibrate', { kind: 'switch', apply: (options) => { + options.calibrate = true; + } } ], + [ '--refresh', { kind: 'switch', apply: (options) => { + options.refresh = true; + } } ], +]); + +export interface CorrectionRequest { + readonly nodeId: string; + readonly component: string; + readonly props: ReadonlyArray<string>; + readonly gap: GapCategory; + readonly stage: GapStage; +} + +export interface OverrideRequest { + readonly nodeId: string; + readonly props: ReadonlyArray<string>; +} + +export interface NoteRequest { + readonly text: string; + readonly gap: GapCategory; +} + +export type ParsedCli = + { readonly kind: 'readout'; readonly options: CliOptions; readonly ref: NodeRef } | + { readonly kind: 'correct'; readonly ref: NodeRef; readonly correction: CorrectionRequest } | + { readonly kind: 'override'; readonly ref: NodeRef; readonly override: OverrideRequest } | + { readonly kind: 'note'; readonly ref: NodeRef; readonly note: NoteRequest } | + { readonly kind: 'calibrate' } | + { readonly kind: 'refresh'; readonly entry: string | undefined }; + +const DEFAULT_OPTIONS: CliOptions = { + dump: undefined, regions: undefined, correct: undefined, gap: undefined, stage: undefined, override: undefined, note: undefined, + calibrate: false, refresh: false, +}; + +// A note is its own run: it names no node, so it sits beside neither --correct nor --override, and +// like a correction it is always a miss. +function parseNote(options: CliOptions, words: ReadonlyArray<string>): NoteRequest | undefined { + if (options.note === undefined) return undefined; + if (options.correct !== undefined || options.override !== undefined) { + throw new Error(`--note is its own run: a note names no node, so it goes with neither --correct nor --override\n${ USAGE }`); + } + if (options.gap === undefined) throw new Error(`A note is always a miss: --note needs --gap <${ GAP_CATEGORIES.join('|') }>\n${ USAGE }`); + if (options.stage !== undefined) throw new Error(`A note is always a markup-stage miss: --stage goes with --correct only\n${ USAGE }`); + if (options.note.trim() === '') throw new Error(`--note needs the text of the miss, in quotes\n${ USAGE }`); + if (words.length > 0) throw new Error(`Unexpected argument: ${ words[0] }\n${ USAGE }`); + return { text: options.note.trim(), gap: options.gap }; +} + +function parseCorrection(options: CliOptions, words: ReadonlyArray<string>): CorrectionRequest | undefined { + if (options.correct === undefined) { + if (options.gap !== undefined) throw new Error(`--gap goes with --correct; nothing to log without a correction\n${ USAGE }`); + if (options.stage !== undefined) throw new Error(`--stage goes with --correct; nothing to log without a correction\n${ USAGE }`); + if (words.length > 0) throw new Error(`Unexpected argument: ${ words[0] }\n${ USAGE }`); + return undefined; + } + if (words.length === 0) throw new Error(`--correct ${ options.correct } needs the component the node is, after the URL\n${ USAGE }`); + if (options.gap === undefined) { + throw new Error(`A correction is always a miss: --correct needs --gap <${ GAP_CATEGORIES.join('|') }>\n${ USAGE }`); + } + return { nodeId: options.correct, component: words[0], props: words.slice(1), gap: options.gap, stage: options.stage ?? 'readout' }; +} + +// An override is not a correction: no component, no --gap, and never in the same run as --correct. +function parseOverride(options: CliOptions, words: ReadonlyArray<string>): OverrideRequest | undefined { + if (options.override === undefined) return undefined; + if (options.correct !== undefined || options.gap !== undefined || options.stage !== undefined) { + throw new Error(`--override and --correct are separate runs: an override is never a miss and takes no --gap\n${ USAGE }`); + } + if (words.length === 0) throw new Error(`--override ${ options.override } needs at least one <prop>=<value> word, after the URL\n${ USAGE }`); + const bare = words.find((word) => !/^[^=\s]+=\S+$/.test(word)); + if (bare !== undefined) throw new Error(`An override is one <prop>=<value> per word, no spaces inside: ${ bare }\n${ USAGE }`); + return { nodeId: options.override, props: words }; +} + +// --calibrate and --refresh work on the committed set, not on a node: neither takes a URL or any +// of the per-node flags. +function parseSetCommand(options: CliOptions, rest: ReadonlyArray<string>): ParsedCli { + const flag = options.calibrate ? '--calibrate' : '--refresh'; + if (options.calibrate && options.refresh) throw new Error(`--calibrate and --refresh are separate runs\n${ USAGE }`); + const perNode = [ options.dump, options.regions, options.correct, options.gap, options.override, options.note ].some((value) => value !== undefined); + if (perNode) throw new Error(`${ flag } works on the calibration set and takes no per-node flag\n${ USAGE }`); + if (options.calibrate) { + if (rest.length > 0) throw new Error(`--calibrate takes no argument: ${ rest[0] }\n${ USAGE }`); + return { kind: 'calibrate' }; + } + if (rest.length > 1) throw new Error(`--refresh takes at most one entry name: ${ rest.join(' ') }\n${ USAGE }`); + return { kind: 'refresh', entry: rest[0] }; +} + +export function parseArgs(argv: ReadonlyArray<string>): ParsedCli { + const { options, rest } = parseFlags<CliOptions>(argv, FLAGS, { ...DEFAULT_OPTIONS }, { kind: 'reject', usage: USAGE }); + if (options.calibrate || options.refresh) return parseSetCommand(options, rest); + if (rest.length === 0) throw new Error(`Missing the Figma node URL\n${ USAGE }`); + const ref = parseNodeRef(rest[0]); + if (ref === undefined) throw new Error(`Not a Figma node URL: ${ rest[0] }\n${ USAGE }`); + const note = parseNote(options, rest.slice(1)); + if (note !== undefined) return { kind: 'note', ref, note }; + const override = parseOverride(options, rest.slice(1)); + if (override !== undefined) return { kind: 'override', ref, override }; + const correction = parseCorrection(options, rest.slice(1)); + return correction === undefined ? { kind: 'readout', options, ref } : { kind: 'correct', ref, correction }; +} diff --git a/tools/design-readout/cli/commands.spec.ts b/tools/design-readout/cli/commands.spec.ts new file mode 100644 index 00000000000..80d0c21b9ce --- /dev/null +++ b/tools/design-readout/cli/commands.spec.ts @@ -0,0 +1,245 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import type { NodeEntry, NodesResponse } from '../fetch/figma'; +import { entryOf } from '../fetch/figma'; +import { loadSpriteNames } from '../recognize/signals'; +import { GAP_LOG_HEADER, gapLogPath } from '../record/gaps'; +import { buildRecord, readSidecar, sidecarPath, writeSidecar } from '../record/sidecar'; +import { dumpPayload, readoutOf, recordCorrection, recordNote, recordOverride } from './commands'; + +const DARK_PRIMARY_TEXT_TOKENS = [ + 'badge.blue_alt.fg', 'badge.gray.fg', 'badge.purple_alt.fg', 'link.menu', 'link.navigation.fg', 'tag.root.clickable.fg', 'tag.root.subtle.fg', 'text.primary', +]; + +function readFixture(file: string, nodeId: string): NodeEntry { + const payload = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'fixtures', file), 'utf8')) as NodesResponse; + return entryOf(payload, nodeId); +} + +describe('recordCorrection', () => { + const ref = { fileKey: 'KEY', nodeId: '22842:178383' }; + const request = { nodeId: '22842:178386', component: 'BlockEntity', props: [ 'noIcon' ], gap: 'context' as const, stage: 'readout' as const }; + let tmp = ''; + + afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; + }); + + function seedSidecar(): string { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-correct-')); + const entry = readFixture('22842-178383-dark.json', '22842:178383'); + const { regions, extraction, recognitions } = readoutOf(entry, undefined, loadSpriteNames()); + const target = sidecarPath(tmp, ref.fileKey, ref.nodeId); + writeSidecar(target, buildRecord({ + createdAt: '2026-10-06T10:00:00.000Z', + fileKey: ref.fileKey, + nodeId: ref.nodeId, + lastModified: '2026-10-01T00:00:00Z', + fileVersion: '42', + colorMode: extraction.colorMode.mode, + regions, + leaves: extraction.leaves, + recognitions, + })); + return target; + } + + it('writes the correction into the sidecar and appends one line to the gap log, without a fetch', () => { + const target = seedSidecar(); + const now = new Date('2026-10-07T09:30:00.000Z'); + const { record, gap } = recordCorrection(tmp, ref, request, now); + const correction = { component: 'BlockEntity', props: [ 'noIcon' ], gap: 'context', recordedAt: '2026-10-07T09:30:00.000Z', stale: false }; + expect(record.nodes.find((node) => node.id === '22842:178386')?.correction).toEqual(correction); + expect(readSidecar(target)).toEqual(record); + expect(gap.appended).toBe(true); + expect(gap.line).toBe([ + '- 2026-10-07 | KEY | 22842:178386 | context | readout | ', + 'recognized: 22842:178386 text "1248139" — Inter 700 14/20; text #63B3ED — number: block or batch or epoch | BlockEntity noIcon', + ].join('')); + expect(fs.readFileSync(gapLogPath(tmp), 'utf8')).toBe(`${ GAP_LOG_HEADER }\n${ gap.line }\n`); + }); + + it('describes the corrected node itself in the gap line, not the first node of the sidecar', () => { + seedSidecar(); + const timestamp = { ...request, nodeId: '22842:178400', component: 'TimeWithTooltip', props: [] }; + const { gap } = recordCorrection(tmp, ref, timestamp, new Date('2026-10-07T09:30:00.000Z')); + expect(gap.line).toBe([ + '- 2026-10-07 | KEY | 22842:178400 | context | readout | ', + 'recognized: 22842:178400 text "10s ago" — Inter 400 14/20; text #A0AEC0 — relative-timestamp: timestamp | TimeWithTooltip', + ].join('')); + }); + + it('fails on a missing sidecar, naming the path it expected', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-correct-')); + expect(() => recordCorrection(tmp, ref, request, new Date())).toThrow( + `No sidecar for node 22842:178383: run the readout first; it writes ${ sidecarPath(tmp, 'KEY', '22842:178383') }.`, + ); + expect(fs.existsSync(gapLogPath(tmp))).toBe(false); + }); + + it('fails on a node the sidecar does not hold, and logs no gap', () => { + seedSidecar(); + expect(() => recordCorrection(tmp, ref, { ...request, nodeId: '9:9' }, new Date())).toThrow(/Node 9:9 is not in the sidecar of 22842:178383/); + expect(fs.existsSync(gapLogPath(tmp))).toBe(false); + }); +}); + +describe('recordNote', () => { + const ref = { fileKey: 'KEY', nodeId: '22842:178383' }; + let tmp = ''; + + afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; + }); + + it('appends a markup-stage line with an empty node id, with no sidecar on disk', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-note-')); + const gap = recordNote(tmp, ref, { text: 'the row gap is 8px, the mockup has 12px', gap: 'markup' }, new Date('2026-10-09T09:30:00.000Z')); + expect(gap).toEqual({ line: '- 2026-10-09 | KEY | | markup | markup | | the row gap is 8px, the mockup has 12px', appended: true }); + expect(fs.readFileSync(gapLogPath(tmp), 'utf8')).toBe(`${ GAP_LOG_HEADER }\n${ gap.line }\n`); + expect(fs.existsSync(sidecarPath(tmp, ref.fileKey, ref.nodeId))).toBe(false); + }); + + it('adds no line for the same note again', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-note-')); + const request = { text: 'cells wrap', gap: 'layout' as const }; + const first = recordNote(tmp, ref, request, new Date('2026-10-09T09:30:00.000Z')); + const repeat = recordNote(tmp, ref, request, new Date('2026-10-10T09:30:00.000Z')); + expect(repeat).toEqual({ line: first.line.replace('2026-10-09', '2026-10-10'), appended: false }); + }); +}); + +describe('recordOverride', () => { + const ref = { fileKey: 'KEY', nodeId: '22842:178383' }; + let tmp = ''; + + afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; + }); + + function seedSidecar(): string { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-override-')); + const entry = readFixture('22842-178383-dark.json', '22842:178383'); + const { regions, extraction, recognitions } = readoutOf(entry, undefined, loadSpriteNames()); + const target = sidecarPath(tmp, ref.fileKey, ref.nodeId); + writeSidecar(target, buildRecord({ + createdAt: '2026-10-06T10:00:00.000Z', + fileKey: ref.fileKey, + nodeId: ref.nodeId, + lastModified: '2026-10-01T00:00:00Z', + fileVersion: '42', + colorMode: extraction.colorMode.mode, + regions, + leaves: extraction.leaves, + recognitions, + })); + return target; + } + + it('writes the override into the sidecar beside an untouched correction, logs no gap, and takes a non-color prop unchecked', () => { + const target = seedSidecar(); + const request = { nodeId: '22842:178386', component: 'BlockEntity', props: [ 'noIcon' ], gap: 'context' as const, stage: 'readout' as const }; + recordCorrection(tmp, ref, request, new Date('2026-10-07T09:30:00.000Z')); + fs.rmSync(gapLogPath(tmp)); + const props = [ 'color=link.primary', 'fontWeight=500' ]; + const record = recordOverride(tmp, ref, { nodeId: '22842:178386', props }, new Date('2026-10-08T09:30:00.000Z')); + const node = record.nodes.find((candidate) => candidate.id === '22842:178386'); + expect(node?.override).toEqual({ props: [ 'color=link.primary', 'fontWeight=500' ], recordedAt: '2026-10-08T09:30:00.000Z', stale: false }); + expect(node?.correction).toEqual({ component: 'BlockEntity', props: [ 'noIcon' ], gap: 'context', recordedAt: '2026-10-07T09:30:00.000Z', stale: false }); + expect(readSidecar(target)).toEqual(record); + expect(fs.existsSync(gapLogPath(tmp))).toBe(false); + }); + + it('refuses a color prop naming a token the node does not resolve for that role, listing the ones it does', () => { + const target = seedSidecar(); + const before = fs.readFileSync(target, 'utf8'); + expect(() => recordOverride(tmp, ref, { nodeId: '22842:178386', props: [ 'color=text.primary' ] }, new Date())) + .toThrow('color=text.primary names a token the mockup does not draw on 22842:178386: the node resolved text tokens link.primary.'); + expect(() => recordOverride(tmp, ref, { nodeId: '22842:178386', props: [ 'bg=whiteAlpha.100' ] }, new Date())) + .toThrow('bg=whiteAlpha.100 names a token the mockup does not draw on 22842:178386: the node resolved no background fill.'); + expect(() => recordOverride(tmp, ref, { nodeId: '22842:178400', props: [ 'color=link.primary' ] }, new Date())) + .toThrow('color=link.primary names a token the mockup does not draw on 22842:178400: ' + + 'the node resolved text tokens link.secondary, link.subtle, link.subtle.hover, text.secondary.'); + const unmapped = readSidecar(target).nodes[0]; + writeSidecar(target, { ...readSidecar(target), nodes: [ { ...unmapped, tokens: [ { role: 'background', color: '#FFFFFF/6', tokens: [] } ] } ] }); + expect(() => recordOverride(tmp, ref, { nodeId: unmapped.id, props: [ 'bg=whiteAlpha.100' ] }, new Date())) + .toThrow(`bg=whiteAlpha.100 names a token the mockup does not draw on ${ unmapped.id }: the node resolved no token for its background fill #FFFFFF/6.`); + fs.writeFileSync(target, before); + expect(fs.readFileSync(target, 'utf8')).toBe(before); + expect(fs.existsSync(gapLogPath(tmp))).toBe(false); + }); + + it('fails on a missing sidecar and on a node the sidecar does not hold', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-override-')); + expect(() => recordOverride(tmp, ref, { nodeId: '22842:178386', props: [ 'fontWeight=500' ] }, new Date())).toThrow( + `No sidecar for node 22842:178383: run the readout first; it writes ${ sidecarPath(tmp, 'KEY', '22842:178383') }.`, + ); + seedSidecar(); + expect(() => recordOverride(tmp, ref, { nodeId: '9:9', props: [ 'fontWeight=500' ] }, new Date())) + .toThrow(/Node 9:9 is not in the sidecar of 22842:178383/); + expect(() => recordOverride(tmp, ref, { nodeId: '9:9', props: [ 'color=link.primary' ] }, new Date())) + .toThrow(/Node 9:9 is not in the sidecar of 22842:178383/); + }); +}); + +describe('readoutOf', () => { + const entry = readFixture('22842-178383-dark.json', '22842:178383'); + const sprites = loadSpriteNames(); + + it('defaults the regions to the content root and extracts the leaves under it', () => { + const { regions, extraction } = readoutOf(entry, undefined, sprites); + expect(regions).toEqual([ '22842:178383' ]); + expect(extraction.leaves.map((leaf) => leaf.id)).toEqual([ '22842:178386', '22842:178400', '22842:178403', '22842:178408', '22842:178412' ]); + }); + + it('recognizes one leaf per extracted leaf in the detected dark mode: the block number and the timestamp hit, the gas values do not', () => { + const { extraction, recognitions } = readoutOf(entry, undefined, sprites); + expect(extraction.colorMode.mode).toBe('dark'); + expect(recognitions.map(({ id, status, decision, composite }) => ({ id, status, decision, composite }))).toEqual([ + { id: '22842:178386', status: 'recognized', decision: { signal: 'number', value: '1248139', entities: [ 'block', 'batch', 'epoch' ] }, composite: null }, + { id: '22842:178400', status: 'recognized', decision: { signal: 'relative-timestamp', value: '10s ago', entities: [ 'timestamp' ] }, composite: null }, + { id: '22842:178403', status: 'unrecognized', decision: null, composite: null }, + { id: '22842:178408', status: 'unrecognized', decision: null, composite: null }, + { id: '22842:178412', status: 'unrecognized', decision: null, composite: null }, + ]); + expect(recognitions.map((recognition) => recognition.tokens)).toEqual([ + [ { role: 'text', color: '#63B3ED', tokens: [ 'link.primary' ] } ], + [ { role: 'text', color: '#A0AEC0', tokens: [ 'link.secondary', 'link.subtle', 'link.subtle.hover', 'text.secondary' ] } ], + [ { role: 'text', color: '#FFFFFF/80', tokens: DARK_PRIMARY_TEXT_TOKENS } ], + [ { role: 'text', color: '#FFFFFF/80', tokens: DARK_PRIMARY_TEXT_TOKENS } ], + [ { role: 'text', color: '#FFFFFF/80', tokens: DARK_PRIMARY_TEXT_TOKENS } ], + ]); + }); + + it('extracts only under the given regions', () => { + const { regions, extraction } = readoutOf(entry, [ '22842:178399', '22842:178406' ], sprites); + expect(regions).toEqual([ '22842:178399', '22842:178406' ]); + expect(extraction.leaves.map((leaf) => leaf.id)).toEqual([ '22842:178400', '22842:178408' ]); + }); + + it('fails on a region that is not under the node', () => { + expect(() => readoutOf(entry, [ '1:1' ], sprites)).toThrow('Region 1:1 is not under node 22842:178383.'); + }); +}); + +describe('dumpPayload', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-')); + + afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }); + }); + + it('writes the payload as JSON at the path resolved from cwd, creating folders', () => { + const payload = { name: 'f', lastModified: 'm', version: 'v', nodes: {} }; + const file = dumpPayload('nested/deeper/out.json', payload, dir); + expect(file).toBe(path.join(dir, 'nested/deeper/out.json')); + expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual(payload); + }); +}); diff --git a/tools/design-readout/cli/commands.ts b/tools/design-readout/cli/commands.ts new file mode 100644 index 00000000000..031467b4450 --- /dev/null +++ b/tools/design-readout/cli/commands.ts @@ -0,0 +1,209 @@ +/* eslint-disable no-console -- this is a CLI whose entire job is to print an outline to stdout */ +import fs from 'fs'; +import path from 'path'; + +import { resolveCheckoutRoot, resolveMainCheckout } from '../../cli/checkout'; +import type { CalibrationEntry } from '../calibration'; +import { calibrateSet, calibrationDir, describeRefresh, hasMiss, loadCalibration, refreshEntry, renderCalibration } from '../calibration'; +import { OVERRIDE_COLOR_PROPS } from '../config'; +import { describeNode, renderOutline, scopeOutline, summarize } from '../extract/scope'; +import { extractRegions, renderExtraction } from '../extract/values'; +import type { Extraction } from '../extract/values'; +import type { FigmaNode, NodeEntry, NodesResponse } from '../fetch/figma'; +import { entryOf, fetchNodes } from '../fetch/figma'; +import type { NodeRef } from '../fetch/url'; +import { buildThemeColorMap } from '../recognize/colormap'; +import type { ColorTokens, Recognition } from '../recognize/signals'; +import { loadSpriteNames, recognize, renderRecognition } from '../recognize/signals'; +import type { GapAppend } from '../record/gaps'; +import { appendGap, gapLogPath, gapOfCorrection, gapOfNote } from '../record/gaps'; +import { carryCorrections, diffRecords, renderRerun } from '../record/rerun'; +import type { Correction, NodeRecord, Override, SidecarRecord } from '../record/sidecar'; +import { applyCorrection, applyOverride, buildRecord, readSidecar, sidecarPath, writeSidecar } from '../record/sidecar'; +import type { CliOptions, CorrectionRequest, NoteRequest, OverrideRequest } from './args'; + +function renderHeader(payload: NodesResponse, root: FigmaNode): string { + return [ + `File: ${ payload.name } — version ${ payload.version }, last modified ${ payload.lastModified }`, + `Node: ${ describeNode(summarize(root)) }`, + ].join('\n'); +} + +export function dumpPayload(target: string, payload: NodesResponse, cwd: string): string { + const file = path.resolve(cwd, target); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(payload, null, 2) + '\n'); + return file; +} + +export interface Readout { + readonly regions: ReadonlyArray<string>; + readonly extraction: Extraction; + readonly recognitions: ReadonlyArray<Recognition>; +} + +export function readoutOf(entry: NodeEntry, regionIds: ReadonlyArray<string> | undefined, spriteNames: ReadonlyArray<string>): Readout { + const map = buildThemeColorMap(); + const { regions, extraction } = extractRegions(entry, regionIds, map); + return { regions, extraction, recognitions: recognize(extraction.leaves, spriteNames, map, extraction.colorMode.mode) }; +} + +type OverrideColorProp = keyof typeof OVERRIDE_COLOR_PROPS; + +function isOverrideColorProp(prop: string): prop is OverrideColorProp { + return Object.hasOwn(OVERRIDE_COLOR_PROPS, prop); +} + +function describeResolved(role: string, fills: ReadonlyArray<ColorTokens>): string { + if (fills.length === 0) return `no ${ role } fill`; + const resolved = fills.flatMap((tokens) => tokens.tokens); + if (resolved.length === 0) return `no token for its ${ role } fill ${ fills.map((fill) => fill.color).join(', ') }`; + return `${ role } tokens ${ resolved.join(', ') }`; +} + +// The check reads the node's recorded tokens and nothing else: no theme lookup, so it is offline +// and the match is against what the Recognized list printed for that fill. +function checkColorProp(node: NodeRecord, prop: OverrideColorProp, value: string): void { + const role = OVERRIDE_COLOR_PROPS[prop]; + const fills = node.tokens.filter((tokens) => tokens.role === role); + const resolved = fills.flatMap((tokens) => tokens.tokens); + if (resolved.includes(value)) return; + throw new Error(`${ prop }=${ value } names a token the mockup does not draw on ${ node.id }: the node resolved ${ describeResolved(role, fills) }.`); +} + +function sidecarTarget(mainCheckout: string, ref: NodeRef): string { + const target = sidecarPath(mainCheckout, ref.fileKey, ref.nodeId); + if (!fs.existsSync(target)) throw new Error(`No sidecar for node ${ ref.nodeId }: run the readout first; it writes ${ target }.`); + return target; +} + +// Offline like a correction, and unlike one it touches the gap log not at all: the tool read the +// values right, the disagreement is design intent. +export function recordOverride(mainCheckout: string, ref: NodeRef, request: OverrideRequest, now: Date): SidecarRecord { + const target = sidecarTarget(mainCheckout, ref); + const previous = readSidecar(target); + const node = previous.nodes.find((candidate) => candidate.id === request.nodeId); + if (node !== undefined) { + for (const word of request.props) { + const [ prop, value ] = word.split('=', 2); + if (isOverrideColorProp(prop)) checkColorProp(node, prop, value); + } + } + const override: Override = { props: request.props, recordedAt: now.toISOString(), stale: false }; + const record = applyOverride(previous, request.nodeId, override); + writeSidecar(target, record); + return record; +} + +export function runOverride(ref: NodeRef, request: OverrideRequest): void { + const mainCheckout = resolveMainCheckout(process.cwd()); + recordOverride(mainCheckout, ref, request, new Date()); + console.log(`Override recorded for ${ request.nodeId } in ${ sidecarPath(mainCheckout, ref.fileKey, ref.nodeId) }: ${ request.props.join(' ') }`); + console.log('No gap logged: an override is design intent, not a miss.'); +} + +export interface CorrectionOutcome { + readonly record: SidecarRecord; + readonly gap: GapAppend; +} + +// Offline on purpose: the correction is about the sidecar the developer just read, so a fetch would +// only risk writing a correction against values they have not seen. +export function recordCorrection(mainCheckout: string, ref: NodeRef, request: CorrectionRequest, now: Date): CorrectionOutcome { + const target = sidecarTarget(mainCheckout, ref); + const recordedAt = now.toISOString(); + const correction: Correction = { component: request.component, props: request.props, gap: request.gap, recordedAt, stale: false }; + const record = applyCorrection(readSidecar(target), request.nodeId, correction); + writeSidecar(target, record); + const node = record.nodes.find((candidate) => candidate.id === request.nodeId); + // Stryker disable next-line ConditionalExpression: applyCorrection already threw for a node the sidecar lacks; this only narrows the type + if (node === undefined) throw new Error(`Node ${ request.nodeId } vanished from the sidecar while correcting it.`); + const entry = gapOfCorrection({ date: recordedAt.split('T')[0], fileKey: ref.fileKey, nodeId: request.nodeId, correction, node, stage: request.stage }); + return { record, gap: appendGap(gapLogPath(mainCheckout), entry) }; +} + +function printGap(mainCheckout: string, gap: GapAppend): void { + console.log(gap.appended ? `Gap logged in ${ gapLogPath(mainCheckout) }:` : `Same miss already in ${ gapLogPath(mainCheckout) }, no line added:`); + console.log(gap.line); +} + +export function runCorrection(ref: NodeRef, request: CorrectionRequest): void { + const mainCheckout = resolveMainCheckout(process.cwd()); + const { gap } = recordCorrection(mainCheckout, ref, request, new Date()); + console.log(`Correction recorded for ${ request.nodeId } in ${ sidecarPath(mainCheckout, ref.fileKey, ref.nodeId) }`); + printGap(mainCheckout, gap); +} + +// The URL is read for its file key and nothing else: a note needs no sidecar, so it works before a +// readout was ever run on the node. +export function recordNote(mainCheckout: string, ref: NodeRef, request: NoteRequest, now: Date): GapAppend { + const date = now.toISOString().split('T')[0]; + return appendGap(gapLogPath(mainCheckout), gapOfNote({ date, fileKey: ref.fileKey, gap: request.gap, text: request.text })); +} + +export function runNote(ref: NodeRef, request: NoteRequest): void { + const mainCheckout = resolveMainCheckout(process.cwd()); + printGap(mainCheckout, recordNote(mainCheckout, ref, request, new Date())); +} + +export async function runReadout(ref: NodeRef, options: CliOptions): Promise<void> { + const payload = await fetchNodes(ref); + if (options.dump !== undefined) console.log(`Raw payload written to ${ dumpPayload(options.dump, payload, process.cwd()) }`); + const entry = entryOf(payload, ref.nodeId); + console.log(renderHeader(payload, entry.document)); + console.log(''); + console.log(renderOutline(scopeOutline(entry.document))); + console.log(''); + const { regions, extraction, recognitions } = readoutOf(entry, options.regions, loadSpriteNames()); + console.log(`Regions: ${ regions.join(', ') }`); + const target = sidecarPath(resolveMainCheckout(process.cwd()), ref.fileKey, ref.nodeId); + const record = buildRecord({ + createdAt: new Date().toISOString(), + fileKey: ref.fileKey, + nodeId: ref.nodeId, + lastModified: payload.lastModified, + fileVersion: payload.version, + colorMode: extraction.colorMode.mode, + regions, + leaves: extraction.leaves, + recognitions, + }); + const previous = fs.existsSync(target) ? readSidecar(target) : undefined; + if (previous === undefined) { + console.log(renderExtraction(extraction)); + writeSidecar(target, record); + console.log(''); + console.log(`Sidecar written to ${ target }`); + console.log(''); + console.log(renderRecognition(extraction.leaves, recognitions)); + return; + } + const merged = carryCorrections(previous, record); + writeSidecar(target, merged); + console.log(''); + console.log(`Sidecar updated at ${ target }`); + console.log(''); + console.log(renderRerun(diffRecords(previous, merged))); +} + +export function runCalibrate(): void { + const results = calibrateSet(loadCalibration(calibrationDir(resolveCheckoutRoot(process.cwd()))), loadSpriteNames()); + console.log(renderCalibration(results)); + if (hasMiss(results)) process.exitCode = 1; +} + +function selectEntries(entries: ReadonlyArray<CalibrationEntry>, name: string | undefined): ReadonlyArray<CalibrationEntry> { + if (name === undefined) return entries; + const entry = entries.find((candidate) => candidate.name === name); + if (entry === undefined) throw new Error(`No calibration entry named ${ name }; the entries are ${ entries.map((candidate) => candidate.name).join(', ') }.`); + return [ entry ]; +} + +export async function runRefresh(name: string | undefined): Promise<void> { + const entries = selectEntries(loadCalibration(calibrationDir(resolveCheckoutRoot(process.cwd()))), name); + const map = buildThemeColorMap(); + console.log(`Refreshing ${ entries.length } calibration ${ entries.length === 1 ? 'entry' : 'entries' }:`); + for (const entry of entries) { + console.log(describeRefresh(await refreshEntry(entry, fetchNodes, new Date(), map))); + } +} diff --git a/tools/design-readout/config.ts b/tools/design-readout/config.ts new file mode 100644 index 00000000000..c873f9f5b40 --- /dev/null +++ b/tools/design-readout/config.ts @@ -0,0 +1,68 @@ +// The only place the token variable is named: an agent instruction that names it will try to set it. +export const TOKEN_ENV = 'FIGMA_API_KEY'; + +export const FIGMA_API_BASE = 'https://api.figma.com'; + +// Layer names that mark page chrome, matched as a case- and whitespace-insensitive substring. +export const CHROME_NAMES: ReadonlyArray<string> = [ 'menu', 'navigation', 'top bar', 'search header', 'footer' ]; + +// A child "spans" its parent when their edges differ by no more than this; Figma reports fractional +// boxes for auto-layout frames. +export const SPAN_TOLERANCE_PX = 1; + +// Where a run's record goes, under the main checkout. +export const SIDECAR_DIR = '.ai/design-readout'; + +// The committed calibration set, one folder per labeled node, under the repo root. +export const CALIBRATION_DIR = 'tools/design-readout/calibration/entries'; + +// The gap log beside the sidecars: one line per miss, appended by `--correct` and `--note`, never rewritten. +export const GAP_LOG_FILE = 'gaps.md'; + +// Every correction and every note is a miss of one of these kinds; `--gap` takes exactly one of them. +export const GAP_CATEGORIES = [ 'shape', 'icon', 'color', 'composite', 'context', 'layout', 'convention', 'markup' ] as const; + +// Where a miss surfaced: `readout` while confirming the tool's lists, `markup` while the developer +// verified an agent's styling in the running app. +export const GAP_STAGES = [ 'readout', 'markup' ] as const; + +// The Chakra color props an `--override` checks against the node's resolved tokens, by the fill role +// each paints. Any prop outside this map is taken as given: the tool validates no Chakra prop name. +export const OVERRIDE_COLOR_PROPS = { bg: 'background', color: 'text', borderColor: 'border' } as const; + +// What a Figma text style name claims, read off its `text-<size>` and `font-<weight>` segments. The +// pixel sizes mirror the `text.*` text styles of the theme, which this tool must not import (they +// read app config). +export const TEXT_STYLE_HINT_SIZES_PX: Readonly<Record<string, number>> = { xs: 12, sm: 14, md: 16, xl: 20 }; +export const TEXT_STYLE_HINT_WEIGHTS: Readonly<Record<string, number>> = { + thin: 100, extralight: 200, light: 300, normal: 400, regular: 400, medium: 500, semibold: 600, bold: 700, extrabold: 800, black: 900, +}; + +// Characters a designer's keyboard layout swaps in for ASCII: Cyrillic and Greek homoglyphs seen in +// hashes (`0х05…` with a Cyrillic х), plus the spacing and ellipsis variants Figma preserves. +export const LOOKALIKE_CHARACTERS: Readonly<Record<string, string>> = { + х: 'x', Х: 'X', о: 'o', О: 'O', а: 'a', А: 'A', е: 'e', Е: 'E', с: 'c', С: 'C', р: 'p', Р: 'P', + у: 'y', В: 'B', Н: 'H', К: 'K', М: 'M', Т: 'T', ο: 'o', Ο: 'O', α: 'a', ' ': ' ', '․': '.', +}; + +// The sprite name list the icon rule matches against; generated by `svg:build-sprite`, tracked. +export const SPRITE_NAMES_FILE = 'public/icons/name.d.ts'; + +// An icon is "beside" a text when their boxes overlap vertically and the horizontal gap is at most +// this; the shipped entity rows put `gap: 2` (8px) between the icon and the hash. +export const ICON_ADJACENCY_GAP_PX = 16; + +// Members of a composite (a hash and the arrow to the next hash, an amount and its ticker) sit this +// close at most; the shipped from/to and value cells put `gap: 2` or `3` (8–12px) between them. +export const COMPOSITE_ADJACENCY_GAP_PX = 16; + +// A readout role narrows a color lookup to the semantic tokens these patterns name. A link token is +// a text color unless its path says it paints a background (`link.navigation.bg.group`). The badge +// and tag families keep their `bg` / `fg` / `border` leaves, which is what the skill's badge and tag +// fingerprints read the color scheme from. +export const COLOR_ROLE_PATTERNS = { + text: [ /^text\./, /^link\.(?!.*\.bg\b)/, /^(?:badge|tag)\..*\.fg$/ ], + background: [ /^bg\./, /^(?:badge|tag)\..*\.bg$/ ], + border: [ /^border\./, /^(?:badge|tag)\..*\.border$/ ], + icon: [ /^icon\./ ], +} as const; diff --git a/tools/design-readout/extract/scope.spec.ts b/tools/design-readout/extract/scope.spec.ts new file mode 100644 index 00000000000..03e7177b02b --- /dev/null +++ b/tools/design-readout/extract/scope.spec.ts @@ -0,0 +1,213 @@ +import fs from 'fs'; +import path from 'path'; + +import { describe, expect, it } from 'vitest'; + +import type { FigmaNode, NodesResponse } from '../fetch/figma'; +import { rootOf } from '../fetch/figma'; +import { renderOutline, scopeOutline } from './scope'; + +function readFixture(file: string, nodeId: string): FigmaNode { + const payload = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'fixtures', file), 'utf8')) as NodesResponse; + return rootOf(payload, nodeId); +} + +interface Box { + readonly width: number; + readonly height: number; +} + +function node(name: string, box: Box, extra: Partial<FigmaNode> = {}, children: Array<FigmaNode> = []): FigmaNode { + return { + id: `${ name }#${ box.width }x${ box.height }`, + name, + type: 'FRAME', + absoluteBoundingBox: { x: 0, y: 0, width: box.width, height: box.height }, + children, + ...extra, + }; +} + +const PAGE: Box = { width: 1440, height: 3000 }; + +describe('scopeOutline over the captured fixtures', () => { + it.each([ + [ '22842-174340-light.json', '22842:174340' ], + [ '22842-178383-dark.json', '22842:178383' ], + ])('%s: a table row is its own content root; its two hidden cells are not counted', (file, nodeId) => { + const outline = scopeOutline(readFixture(file, nodeId)); + expect(outline.contentRoot.id).toBe(nodeId); + expect(outline.contentRoot.name).toBe('Holders_1st_line_public name'); + expect(outline.contentChildren).toBe(5); + expect(outline.wrappers).toEqual([]); + expect(outline.chrome).toEqual([]); + }); + + it('prints the root, the path and the dropped chrome, and nothing about hidden layers', () => { + const text = renderOutline(scopeOutline(readFixture('22842-174340-light.json', '22842:174340'))); + expect(text).toBe([ + 'Content root: 22842:174340 "Holders_1st_line_public name" FRAME 1114×46, 5 content children', + ' via: (the node itself)', + 'Chrome dropped:', + ' (none)', + ].join('\n')); + }); +}); + +describe('scopeOutline descent', () => { + it('descends single-content-child wrappers and stops at two content children', () => { + const content = node('Content', { width: 1114, height: 2800 }, {}, [ + node('Header', { width: 1114, height: 60 }), + node('Table', { width: 1114, height: 2700 }), + ]); + const root = node('Page', PAGE, {}, [ node('Wrapper', PAGE, {}, [ content ]) ]); + const outline = scopeOutline(root); + expect(outline.contentRoot.id).toBe(content.id); + expect(outline.contentChildren).toBe(2); + expect(outline.wrappers.map((wrapper) => wrapper.name)).toEqual([ 'Page', 'Wrapper' ]); + }); + + it('a node without content children is the content root itself', () => { + const leaf = node('Leaf', { width: 100, height: 20 }, { type: 'TEXT', children: undefined }); + expect(scopeOutline(leaf)).toEqual({ + contentRoot: expect.objectContaining({ id: leaf.id }), + contentChildren: 0, + wrappers: [], + chrome: [], + }); + }); + + it('ignores hidden layers: they neither stop the descent nor count as content', () => { + const hiddenScreen = node('Error state', PAGE, { visible: false }, [ node('Only', PAGE) ]); + const hiddenBadge = node('Group 185', { width: 166, height: 40 }, { visible: false }); + const content = node('Content', PAGE, {}, [ + node('A', { width: 1, height: 1 }), + node('B', { width: 1, height: 1 }), + node('C', PAGE, { visible: false }), + ]); + const outline = scopeOutline(node('Page', PAGE, {}, [ hiddenScreen, hiddenBadge, content ])); + expect(outline.contentRoot.id).toBe(content.id); + expect(outline.contentChildren).toBe(2); + expect(renderOutline(outline)).not.toMatch(/Error state|Group 185|"C"/); + }); + + it('drops chrome by name, ignoring case, whitespace and underscores, and does not count it', () => { + const table = node('Table', { width: 1114, height: 2700 }); + const root = node('Page', PAGE, {}, [ + node('Search_header', { width: 1114, height: 60 }), + node(' TOP bar ', { width: 1114, height: 60 }), + node('Left Menu', { width: 200, height: 3000 }), + node('Footer-main', { width: 1114, height: 60 }), + table, + ]); + const outline = scopeOutline(root); + expect(outline.contentRoot.id).toBe(table.id); + expect(outline.chrome.map((chrome) => chrome.rule)).toEqual([ + { kind: 'name', matched: 'search header' }, + { kind: 'name', matched: 'top bar' }, + { kind: 'name', matched: 'menu' }, + { kind: 'name', matched: 'footer' }, + ]); + }); + + it('drops a sealed library instance spanning the screen width or height, within tolerance, at any depth', () => { + const table = node('Table', { width: 1114, height: 2700 }); + const inner = node('Inner', { width: 1114, height: 3000 }, {}, [ + node('Rail', { width: 80, height: 3000 }, { type: 'INSTANCE', exposedInstances: [] }), + table, + ]); + const root = node('Page', { width: 1114, height: 3000 }, {}, [ + node('Banner', { width: 1113.4, height: 60 }, { type: 'INSTANCE' }), + inner, + ]); + const outline = scopeOutline(root); + expect(outline.contentRoot.id).toBe(table.id); + expect(outline.chrome.map((chrome) => chrome.rule)).toEqual([ + { kind: 'structural', spans: 'width' }, + { kind: 'structural', spans: 'height' }, + ]); + }); + + it('spans at exactly the tolerance, and never when the instance or the screen has no box', () => { + const content = node('Content', { width: 1114, height: 2800 }, {}, [ node('A', { width: 1, height: 1 }), node('B', { width: 1, height: 1 }) ]); + const edge = node('Banner', { width: 1113, height: 60 }, { type: 'INSTANCE' }); + expect(scopeOutline(node('Page', { width: 1114, height: 3000 }, {}, [ edge, content ])).chrome.map((chrome) => chrome.rule)) + .toEqual([ { kind: 'structural', spans: 'width' } ]); + const boxless = node('Rail', PAGE, { type: 'INSTANCE', absoluteBoundingBox: null }); + expect(scopeOutline(node('Page', PAGE, {}, [ boxless, content ])).chrome).toEqual([]); + const sealed = node('Rail', PAGE, { type: 'INSTANCE' }); + expect(scopeOutline(node('Page', PAGE, { absoluteBoundingBox: null }, [ sealed, content ])).chrome).toEqual([]); + const outline = scopeOutline(node('Page', PAGE, { absoluteBoundingBox: undefined }, [ sealed, content ])); + expect(outline.chrome).toEqual([]); + expect(renderOutline(outline)).toContain('Content root: Page#1440x3000 "Page" FRAME no box'); + }); + + it('keeps a sealed instance that fills its column but not the screen, and descends into it', () => { + const emptyState = node('Verify_empty', { width: 1114, height: 440 }, { type: 'INSTANCE' }, [ + node('Icon', { width: 40, height: 40 }), + node('Text', { width: 300, height: 20 }), + ]); + const column = node('Column', { width: 1114, height: 568 }, {}, [ node('Search_header', { width: 1114, height: 60 }, { type: 'INSTANCE' }), emptyState ]); + const outline = scopeOutline(node('Page', PAGE, {}, [ node('Menu', { width: 229, height: 832 }), column ])); + expect(outline.contentRoot.id).toBe(emptyState.id); + expect(outline.contentChildren).toBe(2); + }); + + it('drops a plain frame that holds nothing but chrome, naming what was inside', () => { + const sidebar = node('Frame 151', { width: 230, height: 832 }, {}, [ + node('Menu', { width: 229, height: 832 }), + node('Hide_menu_bar', { width: 1, height: 832 }, { type: 'INSTANCE' }), + node('Divider', { width: 1, height: 832 }, { visible: false }), + ]); + const content = node('Content', { width: 1114, height: 568 }, {}, [ node('A', { width: 1, height: 1 }), node('B', { width: 1, height: 1 }) ]); + const outline = scopeOutline(node('Page', PAGE, {}, [ sidebar, content ])); + expect(outline.contentRoot.id).toBe(content.id); + expect(outline.chrome).toEqual([ expect.objectContaining({ name: 'Frame 151', rule: { kind: 'wrapper', inside: [ 'Menu', 'Hide_menu_bar' ] } }) ]); + expect(renderOutline(outline)).toContain('— holds only chrome (Menu, Hide_menu_bar)'); + }); + + it('matches a chrome name across separators, so topbar_desktop meets "top bar"', () => { + const content = node('Content', PAGE, {}, [ node('A', { width: 1, height: 1 }), node('B', { width: 1, height: 1 }) ]); + const outline = scopeOutline(node('Page', PAGE, {}, [ node('topbar_desktop', { width: 1440, height: 32 }, { type: 'INSTANCE' }), content ])); + expect(outline.chrome.map((chrome) => chrome.rule)).toEqual([ { kind: 'name', matched: 'top bar' } ]); + }); + + it('keeps a spanning instance that exposes children, and a spanning plain frame', () => { + const root = node('Page', { width: 1114, height: 3000 }, {}, [ + node('Card', { width: 1114, height: 60 }, { type: 'INSTANCE', exposedInstances: [ '1:1' ] }), + node('Section', { width: 1114, height: 2000 }), + ]); + const outline = scopeOutline(root); + expect(outline.contentRoot.id).toBe(root.id); + expect(outline.contentChildren).toBe(2); + expect(outline.chrome).toEqual([]); + }); + + it('keeps dropping named chrome inside the content root, but not spanning instances there', () => { + const search = node('Search_header', { width: 1283, height: 40 }, { type: 'INSTANCE' }); + const title = node('Tittle/H2', { width: 1283, height: 40 }, { type: 'INSTANCE' }); + const header = node('Frame 567', { width: 1283, height: 104 }, {}, [ search, title ]); + const table = node('table', { width: 1282, height: 610 }, {}, [ + node('Footer', { width: 1282, height: 20 }), + node('row', { width: 1282, height: 46 }, { type: 'INSTANCE' }), + ]); + const content = node('Content', { width: 1347, height: 858 }, {}, [ header, table ]); + const outline = scopeOutline(node('Page', PAGE, {}, [ node('Menu', { width: 93, height: 858 }), content ])); + expect(outline.contentRoot.id).toBe(content.id); + expect(outline.chrome.map((chrome) => [ chrome.name, chrome.under.name ])).toEqual([ + [ 'Menu', 'Page' ], + [ 'Search_header', 'Frame 567' ], + [ 'Footer', 'table' ], + ]); + }); + + it('prints each dropped chrome with the level it was dropped at and the rule', () => { + const content = node('Content', { width: 1114, height: 2800 }, {}, [ node('A', { width: 1, height: 1 }), node('B', { width: 1, height: 1 }) ]); + const inner = node('Inner', { width: 1114, height: 2947 }, {}, [ node('Search_header', { width: 1114, height: 60 }, { type: 'INSTANCE' }), content ]); + const text = renderOutline(scopeOutline(node('Page', PAGE, {}, [ node('Top bar', { width: 1440, height: 60 }), inner ]))); + expect(text).toContain('via: Page#1440x3000 "Page" FRAME 1440×3000 > Inner#1114x2947 "Inner" FRAME 1114×2947'); + expect(text).toContain('Chrome dropped:\n' + + ' - Top bar#1440x60 "Top bar" FRAME 1440×60 under Page#1440x3000 — name contains "top bar"\n' + + ' - Search_header#1114x60 "Search_header" INSTANCE 1114×60 under Inner#1114x2947 — name contains "search header"'); + }); +}); diff --git a/tools/design-readout/extract/scope.ts b/tools/design-readout/extract/scope.ts new file mode 100644 index 00000000000..b71be9af983 --- /dev/null +++ b/tools/design-readout/extract/scope.ts @@ -0,0 +1,147 @@ +import { CHROME_NAMES, SPAN_TOLERANCE_PX } from '../config'; +import type { BoundingBox, FigmaNode } from '../fetch/figma'; + +export interface NodeSummary { + readonly id: string; + readonly name: string; + readonly type: string; + readonly box: BoundingBox | undefined; +} + +export type ChromeRule = + { readonly kind: 'name'; readonly matched: string } | + { readonly kind: 'structural'; readonly spans: 'width' | 'height' } | + { readonly kind: 'wrapper'; readonly inside: ReadonlyArray<string> }; + +export interface DroppedChrome extends NodeSummary { + readonly rule: ChromeRule; + readonly under: NodeSummary; +} + +// Hidden layers (visibility off) are not part of the screen and never appear here. +export interface Outline { + readonly contentRoot: NodeSummary; + readonly contentChildren: number; + // The wrappers descended through, outermost first; empty when the linked node is the content root. + readonly wrappers: ReadonlyArray<NodeSummary>; + readonly chrome: ReadonlyArray<DroppedChrome>; +} + +export function summarize(node: FigmaNode): NodeSummary { + return { id: node.id, name: node.name, type: node.type, box: node.absoluteBoundingBox ?? undefined }; +} + +// Separators are dropped rather than collapsed so `topbar_desktop` meets the list's `top bar`. +function normalizeName(name: string): string { + return name.toLowerCase().replace(/[\s_-]+/g, ''); +} + +function visibleChildren(node: FigmaNode): Array<FigmaNode> { + return (node.children ?? []).filter((child) => child.visible !== false); +} + +function spans(child: FigmaNode, screen: FigmaNode, side: 'width' | 'height'): boolean { + const childBox = child.absoluteBoundingBox; + const screenBox = screen.absoluteBoundingBox; + if (childBox === undefined || childBox === null || screenBox === undefined || screenBox === null) return false; + return childBox[side] >= screenBox[side] - SPAN_TOLERANCE_PX; +} + +function nameRuleOf(child: FigmaNode): ChromeRule | undefined { + const name = normalizeName(child.name); + const matched = CHROME_NAMES.find((chrome) => name.includes(normalizeName(chrome))); + return matched === undefined ? undefined : { kind: 'name', matched }; +} + +// Measured against the linked screen, not the immediate parent: an empty-state or a table instance +// fills its column but not the screen, a top bar or a side rail fills the screen. +function structuralRuleOf(child: FigmaNode, screen: FigmaNode): ChromeRule | undefined { + const isSealedInstance = child.type === 'INSTANCE' && (child.exposedInstances ?? []).length === 0; + if (!isSealedInstance) return undefined; + if (spans(child, screen, 'width')) return { kind: 'structural', spans: 'width' }; + if (spans(child, screen, 'height')) return { kind: 'structural', spans: 'height' }; + return undefined; +} + +type OwnRule = (child: FigmaNode) => ChromeRule | undefined; + +// A node is chrome by its own rule, or because everything visible inside it is chrome (a sidebar +// frame holding the menu and its collapse bar). +function chromeRuleOf(child: FigmaNode, ownRule: OwnRule): ChromeRule | undefined { + const own = ownRule(child); + if (own !== undefined) return own; + const inside = visibleChildren(child); + if (inside.length === 0 || inside.some((node) => chromeRuleOf(node, ownRule) === undefined)) return undefined; + return { kind: 'wrapper', inside: inside.map((node) => node.name) }; +} + +interface Split { + readonly chrome: ReadonlyArray<DroppedChrome>; + readonly content: ReadonlyArray<FigmaNode>; +} + +function splitChildren(node: FigmaNode, ownRule: OwnRule): Split { + const chrome: Array<DroppedChrome> = []; + const content: Array<FigmaNode> = []; + for (const child of visibleChildren(node)) { + const rule = chromeRuleOf(child, ownRule); + if (rule === undefined) content.push(child); + else chrome.push({ ...summarize(child), rule, under: summarize(node) }); + } + return { chrome, content }; +} + +// Inside the content only the name list applies: a spanning instance there is a title or a table. +function chromeWithin(node: FigmaNode): Array<DroppedChrome> { + const { chrome, content } = splitChildren(node, nameRuleOf); + return [ ...chrome, ...content.flatMap(chromeWithin) ]; +} + +// Descend through single-content-child wrappers, dropping chrome at each level, until a node with two +// or more content children (or none); then keep dropping named chrome anywhere inside it. +export function scopeOutline(screen: FigmaNode): Outline { + const descentRule: OwnRule = (child) => nameRuleOf(child) ?? structuralRuleOf(child, screen); + const wrappers: Array<NodeSummary> = []; + const chrome: Array<DroppedChrome> = []; + let node = screen; + for (;;) { + const split = splitChildren(node, descentRule); + chrome.push(...split.chrome); + if (split.content.length !== 1) { + return { contentRoot: summarize(node), contentChildren: split.content.length, wrappers, chrome: [ ...chrome, ...split.content.flatMap(chromeWithin) ] }; + } + wrappers.push(summarize(node)); + node = split.content[0]; + } +} + +function describeBox(box: BoundingBox | undefined): string { + return box === undefined ? 'no box' : `${ Math.round(box.width) }×${ Math.round(box.height) }`; +} + +export function describeNode(node: NodeSummary): string { + return `${ node.id } "${ node.name }" ${ node.type } ${ describeBox(node.box) }`; +} + +function describeRule(rule: ChromeRule): string { + switch (rule.kind) { + case 'name': + return `name contains "${ rule.matched }"`; + case 'structural': + return `sealed instance spanning the screen's ${ rule.spans }`; + case 'wrapper': + return `holds only chrome (${ rule.inside.join(', ') })`; + } +} + +export function renderOutline(outline: Outline): string { + const { wrappers, chrome } = outline; + return [ + `Content root: ${ describeNode(outline.contentRoot) }, ${ outline.contentChildren } content children`, + ` via: ${ wrappers.length === 0 ? '(the node itself)' : wrappers.map(describeNode).join(' > ') }`, + 'Chrome dropped:', + ...(chrome.length === 0 ? + [ ' (none)' ] : + chrome.map((dropped) => ` - ${ describeNode(dropped) } under ${ dropped.under.id } — ${ describeRule(dropped.rule) }`)), + ].join('\n'); +} diff --git a/tools/design-readout/extract/values.spec.ts b/tools/design-readout/extract/values.spec.ts new file mode 100644 index 00000000000..80ddae6b86f --- /dev/null +++ b/tools/design-readout/extract/values.spec.ts @@ -0,0 +1,354 @@ +import fs from 'fs'; +import path from 'path'; + +import { describe, expect, it } from 'vitest'; + +import type { FigmaNode, NodeEntry, NodesResponse } from '../fetch/figma'; +import { entryOf } from '../fetch/figma'; +import { buildThemeColorMap } from '../recognize/colormap'; +import type { Extraction, Leaf } from './values'; +import { describeLeaf, extractValues, findNode, renderExtraction } from './values'; + +const DARK_PRIMARY_TEXT_TOKENS = [ + 'badge.blue_alt.fg', 'badge.gray.fg', 'badge.purple_alt.fg', 'link.menu', 'link.navigation.fg', 'tag.root.clickable.fg', 'tag.root.subtle.fg', 'text.primary', +].join(', '); + +const MAP = buildThemeColorMap(); +const NONE: ReadonlySet<string> = new Set(); + +function readFixture(file: string, nodeId: string): NodeEntry { + const payload = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'fixtures', file), 'utf8')) as NodesResponse; + return entryOf(payload, nodeId); +} + +const DARK_ROW = readFixture('22842-178383-dark.json', '22842:178383'); + +function solid(hex: string, opacity = 1): FigmaNode['fills'] { + const channel = (offset: number): number => parseInt(hex.slice(offset, offset + 2), 16) / 255; + return [ { type: 'SOLID', opacity, color: { r: channel(1), g: channel(3), b: channel(5), a: 1 } } ]; +} + +function node(id: string, type: string, extra: Partial<FigmaNode> = {}, children: Array<FigmaNode> = []): FigmaNode { + return { id, name: id, type, absoluteBoundingBox: { x: 0, y: 0, width: 10, height: 10 }, children, ...extra }; +} + +function entryWith(document: FigmaNode, styles: NodeEntry['styles'] = {}, components: NodeEntry['components'] = {}): NodeEntry { + return { document, styles, components }; +} + +function extract(entry: NodeEntry, excluded: ReadonlySet<string> = NONE): Extraction { + return extractValues(entry, [ entry.document ], excluded, MAP); +} + +describe('extractValues', () => { + it('reads a text node from the fixture: content, font, fill per role and box', () => { + const { leaves } = extract(DARK_ROW); + expect(leaves.find((leaf) => leaf.id === '22842:178386')).toEqual({ + id: '22842:178386', + bbox: { x: 1473, y: 869, width: 60, height: 20 }, + values: { + kind: 'text', + text: '1248139', + trailingGlyphs: undefined, + font: { family: 'Inter', weight: 700, size: 14, lineHeight: 20 }, + colors: [ { role: 'text', hex: '#63B3ED', alpha: 1 } ], + }, + }); + }); + + it('folds the paint opacity into the alpha of a text fill', () => { + const { leaves } = extract(DARK_ROW); + const leaf = leaves.find((entry) => entry.id === '22842:178403'); + expect(leaf?.values.colors[0].hex).toBe('#FFFFFF'); + expect(leaf?.values.colors[0].alpha).toBeCloseTo(0.8); + }); + + it('excludes a hidden node and everything under it', () => { + const { leaves, hints } = extract(DARK_ROW); + const ids = leaves.map((leaf) => leaf.id); + expect(ids).not.toContain('22842:178391'); + expect(ids).not.toContain('22842:178390'); + expect(ids).not.toContain('22842:178395'); + expect(hints.map((hint) => hint.nodeId)).not.toContain('22842:178391'); + expect(ids).toEqual([ '22842:178386', '22842:178400', '22842:178403', '22842:178408', '22842:178412' ]); + }); + + it('skips an excluded id and its subtree', () => { + const { leaves } = extract(DARK_ROW, new Set([ '22842:178401' ])); + expect(leaves.map((leaf) => leaf.id)).not.toContain('22842:178403'); + }); + + it('records a filled and bordered frame as a box with background and border roles, then walks into it', () => { + const frame = node('frame', 'FRAME', { fills: solid('#1A202C'), strokes: solid('#2D3748') }, [ + node('label', 'TEXT', { characters: 'Hi', fills: solid('#FFFFFF') }), + ]); + const { leaves } = extract(entryWith(frame)); + expect(leaves.map((leaf) => leaf.id)).toEqual([ 'frame', 'label' ]); + expect(leaves[0].values).toEqual({ + kind: 'box', + colors: [ { role: 'background', hex: '#1A202C', alpha: 1 }, { role: 'border', hex: '#2D3748', alpha: 1 } ], + }); + }); + + it('records a plain structural frame as nothing but walks its children', () => { + const frame = node('wrap', 'FRAME', { fills: [] }, [ node('label', 'TEXT', { characters: 'x', fills: solid('#000000') }) ]); + expect(extract(entryWith(frame)).leaves.map((leaf) => leaf.id)).toEqual([ 'label' ]); + }); + + it('records an icon instance by its instance name with the first fill inside as the icon color', () => { + const icon = node('inst', 'INSTANCE', { name: 'Icons/arrows/east', componentId: 'c1', fills: [] }, [ + node('v', 'VECTOR', { fills: solid('#718096') }), + ]); + const { leaves, hints } = extract(entryWith(icon, {}, { c1: { name: 'arrows/east' } })); + expect(leaves).toEqual([ { + id: 'inst', + bbox: { x: 0, y: 0, width: 10, height: 10 }, + values: { kind: 'icon', icon: 'Icons/arrows/east', colors: [ { role: 'icon', hex: '#718096', alpha: 1 } ] }, + } ]); + expect(hints).toEqual([ { + nodeId: 'inst', + layer: 'Icons/arrows/east', + source: 'component', + name: 'arrows/east', + verdict: { kind: 'unchecked', reason: 'a component name is a label, not a value' }, + } ]); + }); + + it('walks into an instance that carries text instead of treating it as an icon', () => { + const button = node('btn', 'INSTANCE', { name: 'Button', fills: solid('#3182CE') }, [ node('t', 'TEXT', { characters: 'Go', fills: solid('#FFFFFF') }) ]); + const { leaves } = extract(entryWith(button)); + expect(leaves.map((leaf) => [ leaf.id, leaf.values.kind ])).toEqual([ [ 'btn', 'box' ], [ 't', 'text' ] ]); + }); + + it('splits a trailing glyph off the text content', () => { + const text = node('t', 'TEXT', { characters: 'Contract ↗', fills: solid('#000000') }); + const { leaves } = extract(entryWith(text)); + expect(leaves[0].values).toMatchObject({ kind: 'text', text: 'Contract ↗', trailingGlyphs: '↗' }); + const truncated = node('h', 'TEXT', { characters: '0x05a3…', fills: solid('#000000') }); + expect(extract(entryWith(truncated)).leaves[0].values).toMatchObject({ trailingGlyphs: '…' }); + const percent = node('p', 'TEXT', { characters: '10.81%', fills: solid('#000000') }); + expect(extract(entryWith(percent)).leaves[0].values).toMatchObject({ trailingGlyphs: undefined }); + }); + + it('reads only a visible solid paint with a color, and scales its alpha by the paint and the node opacity', () => { + const fills: FigmaNode['fills'] = [ + { type: 'GRADIENT_LINEAR', color: { r: 1, g: 0, b: 0, a: 1 } }, + { type: 'SOLID', visible: false, color: { r: 1, g: 0, b: 0, a: 1 } }, + { type: 'SOLID' }, + ...solid('#000000', 0.8) ?? [], + ]; + const text = node('t', 'TEXT', { characters: 'x', fills, opacity: 0.5 }); + const { colors } = extract(entryWith(text)).leaves[0].values; + expect(colors).toHaveLength(1); + expect(colors[0]).toMatchObject({ role: 'text', hex: '#000000' }); + expect(colors[0].alpha).toBeCloseTo(0.4); + }); + + it('takes the icon color from the first visible fill inside, past an unpainted child, and ignores hidden text', () => { + const icon = node('inst', 'INSTANCE', { name: 'Icons/x', fills: [] }, [ + node('wrap', 'FRAME', { fills: [] }), + node('hidden', 'VECTOR', { visible: false, fills: solid('#FF0000') }), + node('label', 'TEXT', { visible: false, characters: 'x', fills: solid('#000000') }), + node('v', 'VECTOR', { fills: solid('#0000FF') }), + ]); + const { leaves } = extract(entryWith(icon)); + expect(leaves).toHaveLength(1); + expect(leaves[0].values).toEqual({ kind: 'icon', icon: 'Icons/x', colors: [ { role: 'icon', hex: '#0000FF', alpha: 1 } ] }); + }); + + it('gives a free-standing vector the icon role', () => { + const vector = node('v', 'VECTOR', { fills: solid('#F44336') }); + expect(extract(entryWith(vector)).leaves[0].values).toEqual({ kind: 'box', colors: [ { role: 'icon', hex: '#F44336', alpha: 1 } ] }); + }); +}); + +describe('hints', () => { + function textWithFillStyle(styleName: string, hex: string, opacity = 1): NodeEntry { + const text = node('t', 'TEXT', { characters: 'x', fills: solid(hex, opacity), styles: { fill: 's1' } }); + return entryWith(text, { s1: { name: styleName, styleType: 'FILL' } }); + } + + it('agrees when the dark-mode text.primary hint sits over a whiteAlpha fill', () => { + const { hints } = extract(textWithFillStyle('🖤 Dark/text.primary', '#FFFFFF', 0.8)); + expect(hints).toEqual([ { nodeId: 't', layer: 't', source: 'fill style', name: '🖤 Dark/text.primary', verdict: { kind: 'agrees' } } ]); + }); + + it('reports a disagreement with both sides when the hint names a token the value does not serve in the run mode', () => { + const { hints } = extract(textWithFillStyle('🖤 Dark/text.secondary', '#FFFFFF', 0.8)); + expect(hints[0].verdict).toEqual({ kind: 'disagrees', value: `#FFFFFF/80 → dark: ${ DARK_PRIMARY_TEXT_TOKENS }` }); + }); + + it('reports a hint stated for the other mode as a disagreement, whatever token it names', () => { + const { hints, colorMode } = extract(textWithFillStyle('🤍 Light/text.primary', '#FFFFFF', 0.8)); + expect(colorMode.mode).toBe('dark'); + expect(hints[0].verdict).toEqual({ + kind: 'disagrees', + value: `stated for light, the run reads dark; #FFFFFF/80 → dark: ${ DARK_PRIMARY_TEXT_TOKENS }`, + }); + }); + + it('flags the dark button hint over the light-mode link blue of the Details row, a token the theme does not know', () => { + const { hints, colorMode } = extract(readFixture('22842-169552-light.json', '22842:169552')); + expect(colorMode).toMatchObject({ mode: 'light', decidedBy: 'majority' }); + expect(hints.find((hint) => hint.nodeId === '22842:169555' && hint.source === 'fill style')).toEqual({ + nodeId: '22842:169555', + layer: 'Asset Name Copy 2', + source: 'fill style', + name: '🖤 Dark/button.primary', + verdict: { kind: 'disagrees', value: 'stated for dark, the run reads light; #2B6CB0 → light: badge.bright.blue.fg, link.primary' }, + }); + expect(hints.filter((hint) => hint.verdict.kind === 'disagrees')).toHaveLength(1); + }); + + it('reads the mode past an emoji-only segment, and a name that is only a mode carries no token', () => { + expect(extract(textWithFillStyle('🖤/Dark/text.primary', '#FFFFFF', 0.8)).hints[0].verdict).toEqual({ kind: 'agrees' }); + expect(extract(textWithFillStyle('🖤 Dark', '#FFFFFF', 0.8)).hints[0].verdict).toEqual({ kind: 'unchecked', reason: 'the style name carries no token' }); + }); + + it('says the role has no token when the fill serves none in the run mode', () => { + const { hints, colorMode } = extract(textWithFillStyle('Dark/text.primary', '#123456')); + expect(colorMode.mode).toBe('light'); + expect(hints[0].verdict).toEqual({ kind: 'disagrees', value: 'stated for dark, the run reads light; #123456 → light: no text token' }); + }); + + it('checks a mode-free hint in the run mode', () => { + expect(extract(textWithFillStyle('gray/400', '#A0AEC0')).hints[0].verdict).toEqual({ kind: 'agrees' }); + const { hints } = extract(textWithFillStyle('gray/500', '#A0AEC0')); + expect(hints[0].verdict).toMatchObject({ kind: 'disagrees', value: expect.stringMatching(/^#A0AEC0 → (light|dark): /) }); + }); + + it('leaves a hint unchecked when it names no theme token or the node paints nothing', () => { + const foreign = extract(textWithFillStyle('💙 Selected options/selected.option.bg', '#3182CE')).hints[0]; + expect(foreign.verdict).toEqual({ kind: 'unchecked', reason: '"Selected options.selected.option.bg" is not a theme token' }); + const unpainted = node('t', 'TEXT', { characters: 'x', fills: [], styles: { fill: 's1' } }); + const { hints } = extract(entryWith(unpainted, { s1: { name: 'Dark/text.primary', styleType: 'FILL' } })); + expect(hints[0].verdict).toEqual({ kind: 'unchecked', reason: 'the node paints no solid color' }); + }); + + it('judges the fixture fill hints in the mode the fills voted for', () => { + const { hints, colorMode } = extract(DARK_ROW); + expect(colorMode).toEqual({ mode: 'dark', decidedBy: 'majority', votes: { light: 0, dark: 5 } }); + const fills = hints.filter((hint) => hint.source === 'fill style').map((hint) => [ hint.nodeId, hint.name, hint.verdict.kind ]); + expect(fills).toEqual([ + [ '22842:178386', '🖤 Dark/link.primary', 'agrees' ], + [ '22842:178400', '🖤 Dark/text.secondary', 'agrees' ], + [ '22842:178403', '🖤 Dark/text.primary', 'agrees' ], + [ '22842:178408', '🖤 Dark/text.primary', 'agrees' ], + [ '22842:178412', '🖤 Dark/text.primary', 'agrees' ], + ]); + }); + + it('compares a text style hint to the font values', () => { + const { hints } = extract(DARK_ROW); + expect(hints.find((hint) => hint.nodeId === '22842:178386' && hint.source === 'text style')).toEqual({ + nodeId: '22842:178386', layer: 'Asset Name Copy 2', source: 'text style', name: '🔠 Text - Inter/text-sm/font-bold', verdict: { kind: 'agrees' }, + }); + const text = node('t', 'TEXT', { + characters: 'x', + fills: solid('#000000'), + style: { fontFamily: 'Inter', fontWeight: 400, fontSize: 16, lineHeightPx: 24 }, + styles: { text: 's1' }, + }); + const mismatch = extract(entryWith(text, { s1: { name: 'Text - Inter/text-sm/font-bold', styleType: 'TEXT' } })).hints[0]; + expect(mismatch.verdict).toEqual({ kind: 'disagrees', value: 'size 14px vs 16px, weight 700 vs 400' }); + const unknown = extract(entryWith(text, { s1: { name: 'Heading/h1', styleType: 'TEXT' } })).hints[0]; + expect(unknown.verdict).toEqual({ kind: 'unchecked', reason: 'the style name claims no size or weight the tool knows' }); + }); + + it('checks a text style that claims only a size or only a weight, and leaves one unchecked on a node without a text style', () => { + const styled = (name: string, style: FigmaNode['style']): NodeEntry => entryWith( + node('t', 'TEXT', { characters: 'x', fills: solid('#000000'), style, styles: { text: 's1' } }), + { s1: { name, styleType: 'TEXT' } }, + ); + const font = { fontFamily: 'Inter', fontWeight: 700, fontSize: 14, lineHeightPx: 20 }; + expect(extract(styled('text-sm', font)).hints[0].verdict).toEqual({ kind: 'agrees' }); + expect(extract(styled('font-bold', font)).hints[0].verdict).toEqual({ kind: 'agrees' }); + expect(extract(styled('text-sm', { ...font, fontSize: 16 })).hints[0].verdict).toEqual({ kind: 'disagrees', value: 'size 14px vs 16px' }); + expect(extract(styled('text-sm/font-bold', undefined)).hints[0].verdict).toEqual({ kind: 'unchecked', reason: 'the node has no text style' }); + }); + + it('checks a stroke style against the border color, not the fill', () => { + const frame = node('f', 'FRAME', { fills: solid('#FFFFFF'), strokes: solid('#E2E8F0'), styles: { stroke: 's1' } }, []); + const { hints } = extract(entryWith(frame, { s1: { name: 'gray/200', styleType: 'FILL' } })); + expect(hints).toEqual([ { nodeId: 'f', layer: 'f', source: 'stroke style', name: 'gray/200', verdict: { kind: 'agrees' } } ]); + }); + + it('checks a fill style against the icon color of an instance and the background of a frame', () => { + const icon = node('i', 'INSTANCE', { name: 'Icons/x', fills: [], styles: { fill: 's1' } }, [ node('v', 'VECTOR', { fills: solid('#718096') }) ]); + expect(extract(entryWith(icon, { s1: { name: 'gray/500', styleType: 'FILL' } })).hints[0].verdict).toEqual({ kind: 'agrees' }); + const frame = node('f', 'FRAME', { fills: solid('#EDF2F7'), styles: { fill: 's1' } }, []); + expect(extract(entryWith(frame, { s1: { name: 'gray/100', styleType: 'FILL' } })).hints[0].verdict).toEqual({ kind: 'agrees' }); + }); +}); + +describe('color mode', () => { + const paletteOnlyText = node('t', 'TEXT', { characters: 'x', fills: solid('#000000') }); + + it('breaks a tie between the fills with the linked node\'s own background, even when the regions sit below it', () => { + const page = node('page', 'FRAME', { fills: solid('#101112') }, [ paletteOnlyText ]); + const entry = entryWith(page); + expect(extractValues(entry, [ paletteOnlyText ], NONE, MAP).colorMode) + .toEqual({ mode: 'dark', decidedBy: 'frame-background', votes: { light: 0, dark: 0 } }); + expect(extract(entry).colorMode).toMatchObject({ mode: 'dark', decidedBy: 'majority' }); + }); + + it('reads the light tx row light although its grays paint dark-mode backgrounds: each fill votes with its own role', () => { + const { colorMode } = extract(readFixture('13983-116369-light.json', '13983:116369')); + expect(colorMode).toMatchObject({ mode: 'light', decidedBy: 'majority' }); + expect(colorMode.votes.light).toBeGreaterThan(colorMode.votes.dark); + }); + + it('falls back to light when neither the fills nor the linked node\'s background lean either way', () => { + const extraction = extract(entryWith(paletteOnlyText)); + expect(extraction.colorMode).toEqual({ mode: 'light', decidedBy: 'default', votes: { light: 0, dark: 0 } }); + expect(renderExtraction(extraction)).toContain('Color mode: light (no vote, the default; 0 light, 0 dark)'); + }); +}); + +describe('findNode', () => { + it('finds a node by id anywhere under the root, or nothing', () => { + expect(findNode(DARK_ROW.document, '22842:178403')?.name).toBe('Asset Name Copy 2'); + expect(findNode(DARK_ROW.document, '22842:178383')?.id).toBe('22842:178383'); + expect(findNode(DARK_ROW.document, '1:1')).toBeUndefined(); + }); +}); + +describe('renderExtraction', () => { + it('lists the leaves, then the hints with their verdicts and a disagreement count', () => { + const entry = textWithTwoHints(); + const rendered = renderExtraction(extract(entry)); + expect(rendered).toBe([ + 'Color mode: dark (by majority; 0 light, 1 dark)', + 'Values: 1 leaves', + ' - t text "Hi ↗" +"↗" — Inter 700 14/20; text #FFFFFF/80', + 'Figma hints (not stored): 2, 1 disagreeing', + ' - t "t" fill style "Light/text.primary": DISAGREES with value stated for light, the run reads dark; ' + + `#FFFFFF/80 → dark: ${ DARK_PRIMARY_TEXT_TOKENS }`, + ' - t "t" text style "text-sm/font-bold": agrees', + ].join('\n')); + }); + + it('counts no disagreement when every hint agrees', () => { + const frame = node('f', 'FRAME', { strokes: solid('#E2E8F0'), styles: { stroke: 's1' } }, []); + const rendered = renderExtraction(extract(entryWith(frame, { s1: { name: 'gray/200', styleType: 'FILL' } }))); + expect(rendered).toContain('Figma hints (not stored): 1, 0 disagreeing'); + }); + + it('describes an icon and a box leaf', () => { + expect(describeLeaf({ id: 'i', bbox: null, values: { kind: 'icon', icon: 'Icons/x', colors: [] } })).toBe('i icon "Icons/x" — '); + const box: Leaf = { id: 'b', bbox: null, values: { kind: 'box', colors: [ { role: 'border', hex: '#000000', alpha: 0.5 } ] } }; + expect(describeLeaf(box)).toBe('b box — border #000000/50'); + const bare: Leaf = { id: 't', bbox: null, values: { kind: 'text', text: 'x', trailingGlyphs: undefined, font: undefined, colors: [] } }; + expect(describeLeaf(bare)).toBe('t text "x" — no font; '); + }); + + function textWithTwoHints(): NodeEntry { + const text = node('t', 'TEXT', { + characters: 'Hi ↗', + fills: solid('#FFFFFF', 0.8), + style: { fontFamily: 'Inter', fontWeight: 700, fontSize: 14, lineHeightPx: 20 }, + styles: { fill: 's1', text: 's2' }, + }); + return entryWith(text, { s1: { name: 'Light/text.primary', styleType: 'FILL' }, s2: { name: 'text-sm/font-bold', styleType: 'TEXT' } }); + } +}); diff --git a/tools/design-readout/extract/values.ts b/tools/design-readout/extract/values.ts new file mode 100644 index 00000000000..45dfa84eaf0 --- /dev/null +++ b/tools/design-readout/extract/values.ts @@ -0,0 +1,376 @@ +import { TEXT_STYLE_HINT_SIZES_PX, TEXT_STYLE_HINT_WEIGHTS } from '../config'; +import type { BoundingBox, FigmaNode, FigmaPaint, NodeEntry } from '../fetch/figma'; +import type { ColorMap, ColorMode, ColorRole, ColorValue, ModeDetection } from '../recognize/colormap'; +import { colorKey, detectColorMode, lookupTokens } from '../recognize/colormap'; +import { scopeOutline } from './scope'; + +export interface RoleColor extends ColorValue { + readonly role: ColorRole; +} + +export interface FontValues { + readonly family: string | undefined; + readonly weight: number | undefined; + readonly size: number | undefined; + readonly lineHeight: number | undefined; +} + +// `text`: a text layer. `icon`: a library instance with no text inside, named by the instance. +// `box`: anything else that paints — a filled or bordered frame, a vector, a shape. +export type LeafValues = + { + readonly kind: 'text'; + readonly text: string; + readonly trailingGlyphs: string | undefined; + readonly font: FontValues | undefined; + readonly colors: ReadonlyArray<RoleColor>; + } | + { readonly kind: 'icon'; readonly icon: string; readonly colors: ReadonlyArray<RoleColor> } | + { readonly kind: 'box'; readonly colors: ReadonlyArray<RoleColor> }; + +export interface Leaf { + readonly id: string; + readonly values: LeafValues; + readonly bbox: BoundingBox | null; +} + +export type HintVerdict = + { readonly kind: 'agrees' } | + { readonly kind: 'disagrees'; readonly value: string } | + { readonly kind: 'unchecked'; readonly reason: string }; + +export type HintSource = 'fill style' | 'stroke style' | 'text style' | 'component'; + +// What Figma says about a node beside its values. Printed for the developer, never stored. +export interface Hint { + readonly nodeId: string; + readonly layer: string; + readonly source: HintSource; + readonly name: string; + readonly verdict: HintVerdict; +} + +export interface Extraction { + readonly leaves: ReadonlyArray<Leaf>; + readonly hints: ReadonlyArray<Hint>; + readonly colorMode: ModeDetection; +} + +const ICON_SHAPES: ReadonlySet<string> = new Set([ 'VECTOR', 'BOOLEAN_OPERATION', 'STAR', 'POLYGON', 'LINE' ]); +const BOX_SHAPES: ReadonlySet<string> = new Set([ 'RECTANGLE', 'ELLIPSE' ]); +const MODES: ReadonlyArray<ColorMode> = [ 'light', 'dark' ]; +const CHANNEL_MAX = 255; + +// Arrows, check marks, an ellipsis: what a designer appends to a value rather than part of it. `%` +// and currency signs are punctuation of the value itself and stay in the text. +const TRAILING_GLYPHS = /([\p{So}\p{Sm}…]+)\s*$/u; + +function channelHex(channel: number): string { + return Math.round(channel * CHANNEL_MAX).toString(16).padStart(2, '0').toUpperCase(); +} + +function solidColor(paint: FigmaPaint, nodeOpacity: number): ColorValue | undefined { + if (paint.type !== 'SOLID' || paint.visible === false || paint.color === undefined) return undefined; + const { r, g, b, a } = paint.color; + return { hex: `#${ channelHex(r) }${ channelHex(g) }${ channelHex(b) }`, alpha: a * (paint.opacity ?? 1) * nodeOpacity }; +} + +function roleColors(paints: ReadonlyArray<FigmaPaint> | undefined, role: ColorRole, nodeOpacity: number): Array<RoleColor> { + return (paints ?? []).flatMap((paint) => { + const color = solidColor(paint, nodeOpacity); + return color === undefined ? [] : [ { role, ...color } ]; + }); +} + +function visibleChildren(node: FigmaNode): ReadonlyArray<FigmaNode> { + return (node.children ?? []).filter((child) => child.visible !== false); +} + +function hasVisibleText(node: FigmaNode): boolean { + return visibleChildren(node).some((child) => child.type === 'TEXT' || hasVisibleText(child)); +} + +// The first solid fill painted anywhere inside an icon instance is what the icon shows in. +function iconColors(node: FigmaNode): Array<RoleColor> { + const own = roleColors(node.fills, 'icon', node.opacity ?? 1); + if (own.length > 0) return own; + for (const child of visibleChildren(node)) { + const inside = iconColors(child); + if (inside.length > 0) return inside; + } + return []; +} + +function fontOf(node: FigmaNode): FontValues | undefined { + const style = node.style; + if (style === undefined) return undefined; + return { family: style.fontFamily, weight: style.fontWeight, size: style.fontSize, lineHeight: style.lineHeightPx }; +} + +function textValues(node: FigmaNode): LeafValues { + const text = node.characters ?? ''; + const glyphs = TRAILING_GLYPHS.exec(text); + return { + kind: 'text', + text, + trailingGlyphs: glyphs === null ? undefined : glyphs[1], + font: fontOf(node), + colors: roleColors(node.fills, 'text', node.opacity ?? 1), + }; +} + +function paintedValues(node: FigmaNode, fillRole: ColorRole): LeafValues | undefined { + const opacity = node.opacity ?? 1; + const colors = [ ...roleColors(node.fills, fillRole, opacity), ...roleColors(node.strokes, 'border', opacity) ]; + return colors.length === 0 ? undefined : { kind: 'box', colors }; +} + +function leafValuesOf(node: FigmaNode): LeafValues | undefined { + if (node.type === 'TEXT') return textValues(node); + if (node.type === 'INSTANCE' && !hasVisibleText(node)) return { kind: 'icon', icon: node.name, colors: iconColors(node) }; + if (ICON_SHAPES.has(node.type)) return paintedValues(node, 'icon'); + return paintedValues(node, 'background'); +} + +function isWalkedInto(node: FigmaNode, values: LeafValues | undefined): boolean { + // Stryker disable next-line ConditionalExpression: a TEXT node carries no children in the REST payload, so walking into one is a no-op either way + return values?.kind !== 'text' && values?.kind !== 'icon' && !ICON_SHAPES.has(node.type) && !BOX_SHAPES.has(node.type); +} + +interface StyleHintName { + readonly mode: ColorMode | undefined; + readonly token: string | undefined; +} + +// `🖤 Dark/text.primary` → dark `text.primary`; `gray/200` → `gray.200` in either mode. +function parseStyleHintName(name: string): StyleHintName { + const segments = name.replace(/[^\x20-\x7E]/g, '').split('/').map((segment) => segment.trim()).filter((segment) => segment !== ''); + const head = segments[0]?.toLowerCase(); + const mode = head === 'light' || head === 'dark' ? head : undefined; + const rest = mode === undefined ? segments : segments.slice(1); + return { mode, token: rest.length === 0 ? undefined : rest.join('.') }; +} + +function isKnownToken(map: ColorMap, token: string): boolean { + const serves = (index: Record<string, Array<string>>): boolean => Object.values(index).some((tokens) => tokens.includes(token)); + return serves(map.palette) || MODES.some((mode) => serves(map.semantic[mode])); +} + +function describeTokens(map: ColorMap, value: RoleColor, mode: ColorMode): string { + const tokens = lookupTokens(map, value, mode, value.role); + return `${ colorKey(value) } → ${ mode }: ${ tokens.length === 0 ? `no ${ value.role } token` : tokens.join(', ') }`; +} + +// A hint stated for the other mode disagrees before its token is looked at: the file mixes light and +// dark styles, and a dark style on a light screen is the designer's slip whatever token it names. +function colorHintVerdict(map: ColorMap, runMode: ColorMode, name: string, value: RoleColor | undefined): HintVerdict { + if (value === undefined) return { kind: 'unchecked', reason: 'the node paints no solid color' }; + const { mode, token } = parseStyleHintName(name); + if (mode !== undefined && mode !== runMode) { + return { kind: 'disagrees', value: `stated for ${ mode }, the run reads ${ runMode }; ${ describeTokens(map, value, runMode) }` }; + } + if (token === undefined) return { kind: 'unchecked', reason: 'the style name carries no token' }; + if (!isKnownToken(map, token)) return { kind: 'unchecked', reason: `"${ token }" is not a theme token` }; + if (lookupTokens(map, value, runMode).includes(token)) return { kind: 'agrees' }; + return { kind: 'disagrees', value: describeTokens(map, value, runMode) }; +} + +interface TextHintClaim { + readonly size: number | undefined; + readonly weight: number | undefined; +} + +function parseTextHintName(name: string): TextHintClaim { + const size = /\btext-(\w+)/.exec(name)?.[1]; + const weight = /\bfont-(\w+)/.exec(name)?.[1]; + return { + size: size === undefined ? undefined : TEXT_STYLE_HINT_SIZES_PX[size.toLowerCase()], + weight: weight === undefined ? undefined : TEXT_STYLE_HINT_WEIGHTS[weight.toLowerCase()], + }; +} + +function textHintVerdict(name: string, font: FontValues | undefined): HintVerdict { + const claim = parseTextHintName(name); + if (claim.size === undefined && claim.weight === undefined) return { kind: 'unchecked', reason: 'the style name claims no size or weight the tool knows' }; + if (font === undefined) return { kind: 'unchecked', reason: 'the node has no text style' }; + const mismatches: Array<string> = []; + if (claim.size !== undefined && claim.size !== font.size) mismatches.push(`size ${ claim.size }px vs ${ font.size ?? '?' }px`); + if (claim.weight !== undefined && claim.weight !== font.weight) mismatches.push(`weight ${ claim.weight } vs ${ font.weight ?? '?' }`); + return mismatches.length === 0 ? { kind: 'agrees' } : { kind: 'disagrees', value: mismatches.join(', ') }; +} + +// A hint with the value it is judged against; the verdict waits for the run's color mode, which the +// leaves decide only once they are all collected. +interface PendingHint { + readonly nodeId: string; + readonly layer: string; + readonly source: HintSource; + readonly name: string; + readonly against: + { readonly kind: 'color'; readonly value: RoleColor | undefined } | + { readonly kind: 'font'; readonly font: FontValues | undefined } | + { readonly kind: 'label' }; +} + +interface WalkContext { + readonly entry: NodeEntry; + readonly excluded: ReadonlySet<string>; + readonly leaves: Array<Leaf>; + readonly pending: Array<PendingHint>; +} + +function styleName(entry: NodeEntry, node: FigmaNode, property: string): string | undefined { + const id = node.styles?.[property]; + // Stryker disable next-line ConditionalExpression: an undefined id indexes nothing; the guard only types the lookup + return id === undefined ? undefined : entry.styles?.[id]?.name; +} + +function firstColor(values: LeafValues | undefined, role: ColorRole): RoleColor | undefined { + return values?.colors.find((color) => color.role === role); +} + +function fillRoleOf(node: FigmaNode, values: LeafValues | undefined): ColorRole { + if (values?.kind === 'text') return 'text'; + if (values?.kind === 'icon' || ICON_SHAPES.has(node.type)) return 'icon'; + return 'background'; +} + +function collectHints(node: FigmaNode, values: LeafValues | undefined, context: WalkContext): void { + const { entry, pending } = context; + const hint = (source: HintSource, name: string | undefined, against: PendingHint['against']): void => { + if (name !== undefined) pending.push({ nodeId: node.id, layer: node.name, source, name, against }); + }; + hint('fill style', styleName(entry, node, 'fill'), { kind: 'color', value: firstColor(values, fillRoleOf(node, values)) }); + hint('stroke style', styleName(entry, node, 'stroke'), { kind: 'color', value: firstColor(values, 'border') }); + hint('text style', styleName(entry, node, 'text'), { kind: 'font', font: fontOf(node) }); + // Stryker disable next-line ConditionalExpression: an undefined id indexes nothing; the guard only types the lookup + const component = node.componentId === undefined ? undefined : entry.components?.[node.componentId]?.name; + hint('component', component, { kind: 'label' }); +} + +function judgeHint(pending: PendingHint, map: ColorMap, mode: ColorMode): Hint { + const { against, ...hint } = pending; + switch (against.kind) { + case 'color': + return { ...hint, verdict: colorHintVerdict(map, mode, hint.name, against.value) }; + case 'font': + return { ...hint, verdict: textHintVerdict(hint.name, against.font) }; + case 'label': + return { ...hint, verdict: { kind: 'unchecked', reason: 'a component name is a label, not a value' } }; + } +} + +// The linked node's own fill is the screen background. It is also a leaf when the node is a region, +// so the tiebreak only matters for regions narrower than the node. +export function frameBackground(root: FigmaNode): ColorValue | undefined { + return roleColors(root.fills, 'background', root.opacity ?? 1)[0]; +} + +function walk(node: FigmaNode, context: WalkContext): void { + if (node.visible === false || context.excluded.has(node.id)) return; + const values = leafValuesOf(node); + collectHints(node, values, context); + if (values !== undefined) context.leaves.push({ id: node.id, values, bbox: node.absoluteBoundingBox ?? null }); + if (!isWalkedInto(node, values)) return; + for (const child of node.children ?? []) walk(child, context); +} + +export function findNode(root: FigmaNode, id: string): FigmaNode | undefined { + if (root.id === id) return root; + for (const child of root.children ?? []) { + const found = findNode(child, id); + if (found !== undefined) return found; + } + return undefined; +} + +// Values per leaf under each region, in document order; hidden layers and excluded ids (dropped +// chrome) are skipped with their subtrees. Every fill of every leaf votes on the color mode, and +// the hints are judged in the mode the vote settled on. +export function extractValues(entry: NodeEntry, regions: ReadonlyArray<FigmaNode>, excluded: ReadonlySet<string>, map: ColorMap): Extraction { + const context: WalkContext = { entry, excluded, leaves: [], pending: [] }; + for (const region of regions) walk(region, context); + const { leaves, pending } = context; + const colorMode = detectColorMode(map, leaves.flatMap((leaf) => leaf.values.colors), frameBackground(entry.document)); + return { leaves, hints: pending.map((hint) => judgeHint(hint, map, colorMode.mode)), colorMode }; +} + +export interface RegionExtraction { + readonly regions: ReadonlyArray<string>; + readonly extraction: Extraction; +} + +// The regions default to the outline's content root; chrome the outline dropped is excluded either way. +export function extractRegions(entry: NodeEntry, regionIds: ReadonlyArray<string> | undefined, map: ColorMap): RegionExtraction { + const root = entry.document; + const outline = scopeOutline(root); + const regions = regionIds ?? [ outline.contentRoot.id ]; + const nodes = regions.map((id) => { + const node = findNode(root, id); + if (node === undefined) throw new Error(`Region ${ id } is not under node ${ root.id }.`); + return node; + }); + const excluded = new Set(outline.chrome.map((dropped) => dropped.id)); + return { regions, extraction: extractValues(entry, nodes, excluded, map) }; +} + +function describeColors(colors: ReadonlyArray<RoleColor>): string { + return colors.map((color) => `${ color.role } ${ colorKey(color) }`).join(', '); +} + +function describeFont(font: FontValues | undefined): string { + if (font === undefined) return 'no font'; + return `${ font.family ?? '?' } ${ font.weight ?? '?' } ${ font.size ?? '?' }/${ font.lineHeight ?? '?' }`; +} + +export function describeLeaf(leaf: Leaf): string { + const { values } = leaf; + switch (values.kind) { + case 'text': { + const glyphs = values.trailingGlyphs === undefined ? '' : ` +"${ values.trailingGlyphs }"`; + return `${ leaf.id } text ${ JSON.stringify(values.text) }${ glyphs } — ${ describeFont(values.font) }; ${ describeColors(values.colors) }`; + } + case 'icon': + return `${ leaf.id } icon "${ values.icon }" — ${ describeColors(values.colors) }`; + case 'box': + return `${ leaf.id } box — ${ describeColors(values.colors) }`; + } +} + +function describeVerdict(verdict: HintVerdict): string { + switch (verdict.kind) { + case 'agrees': + return 'agrees'; + case 'disagrees': + return `DISAGREES with value ${ verdict.value }`; + case 'unchecked': + return `unchecked (${ verdict.reason })`; + } +} + +function describeDecidedBy(decidedBy: ModeDetection['decidedBy']): string { + switch (decidedBy) { + case 'majority': + return 'by majority'; + case 'frame-background': + return 'a tie, by the frame background'; + case 'default': + return 'no vote, the default'; + } +} + +export function describeColorMode({ mode, decidedBy, votes }: ModeDetection): string { + return `Color mode: ${ mode } (${ describeDecidedBy(decidedBy) }; ${ votes.light } light, ${ votes.dark } dark)`; +} + +export function renderExtraction(extraction: Extraction): string { + const { leaves, hints, colorMode } = extraction; + const disagreements = hints.filter((hint) => hint.verdict.kind === 'disagrees').length; + return [ + describeColorMode(colorMode), + `Values: ${ leaves.length } leaves`, + ...leaves.map((leaf) => ` - ${ describeLeaf(leaf) }`), + `Figma hints (not stored): ${ hints.length }, ${ disagreements } disagreeing`, + ...hints.map((hint) => ` - ${ hint.nodeId } "${ hint.layer }" ${ hint.source } "${ hint.name }": ${ describeVerdict(hint.verdict) }`), + ].join('\n'); +} diff --git a/tools/design-readout/fetch/figma.spec.ts b/tools/design-readout/fetch/figma.spec.ts new file mode 100644 index 00000000000..3dcefa8b285 --- /dev/null +++ b/tools/design-readout/fetch/figma.spec.ts @@ -0,0 +1,49 @@ +import { beforeEach, describe, expect, it } from 'vitest'; + +import { TOKEN_ENV } from '../config'; +import { entryOf, fetchNodes, rootOf } from './figma'; + +const REF = { fileKey: 'abcDEF0123456789abcDEF', nodeId: '22842:174340' }; + +describe('fetchNodes', () => { + beforeEach(() => { + fetchMock.resetMocks(); + }); + + it('fails without a token, naming no other source, and never calls Figma', async() => { + await expect(fetchNodes(REF, {})).rejects.toThrow('No Figma token'); + await expect(fetchNodes(REF, { [TOKEN_ENV]: ' ' })).rejects.toThrow('No Figma token'); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('reports a rejected token as the reason and mentions the 90-day expiry', async() => { + fetchMock.mockResponseOnce('', { status: 403 }); + await expect(fetchNodes(REF, { [TOKEN_ENV]: 'expired' })).rejects + .toThrow('Figma rejected the token (HTTP 403); personal access tokens expire after at most 90 days.'); + fetchMock.mockResponseOnce('', { status: 401 }); + await expect(fetchNodes(REF, { [TOKEN_ENV]: 'expired' })).rejects + .toThrow('Figma rejected the token (HTTP 401); personal access tokens expire after at most 90 days.'); + }); + + it('tells a missing file apart from any other failure, keeping the status', async() => { + fetchMock.mockResponseOnce('', { status: 404 }); + await expect(fetchNodes(REF, { [TOKEN_ENV]: 'personal-token' })).rejects + .toThrow('Figma returned 404: the file key is wrong or the token has no access to the file.'); + fetchMock.mockResponseOnce('', { status: 500 }); + await expect(fetchNodes(REF, { [TOKEN_ENV]: 'personal-token' })).rejects.toThrow('Figma nodes request failed with HTTP 500.'); + }); + + it('asks the nodes endpoint for the one node with the token in the header', async() => { + const document = { id: '22842:174340', name: 'n', type: 'FRAME' }; + fetchMock.mockResponseOnce(JSON.stringify({ name: 'f', lastModified: 'm', version: 'v', nodes: { '22842:174340': { document } } })); + const payload = await fetchNodes(REF, { [TOKEN_ENV]: 'personal-token' }); + expect(fetchMock.mock.calls[0][0]).toBe('https://api.figma.com/v1/files/abcDEF0123456789abcDEF/nodes?ids=22842%3A174340'); + expect(fetchMock.mock.calls[0][1]).toEqual({ headers: { 'X-Figma-Token': 'personal-token' } }); + expect(rootOf(payload, '22842:174340').name).toBe('n'); + }); + + it('names the node when the file does not contain it, whether the entry is null or absent', () => { + expect(() => rootOf({ name: 'f', lastModified: 'm', version: 'v', nodes: { '1:2': null } }, '1:2')).toThrow('Node 1:2 is not in file "f".'); + expect(() => entryOf({ name: 'f', lastModified: 'm', version: 'v', nodes: {} }, '1:2')).toThrow('Node 1:2 is not in file "f".'); + }); +}); diff --git a/tools/design-readout/fetch/figma.ts b/tools/design-readout/fetch/figma.ts new file mode 100644 index 00000000000..046a35de24d --- /dev/null +++ b/tools/design-readout/fetch/figma.ts @@ -0,0 +1,120 @@ +import { FIGMA_API_BASE, TOKEN_ENV } from '../config'; +import type { NodeRef } from './url'; + +export interface BoundingBox { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +export interface FigmaColor { + readonly r: number; + readonly g: number; + readonly b: number; + readonly a: number; +} + +export interface FigmaPaint { + readonly type: string; + readonly visible?: boolean; + readonly opacity?: number; + readonly color?: FigmaColor; +} + +export interface FigmaTextStyle { + readonly fontFamily?: string; + readonly fontWeight?: number; + readonly fontSize?: number; + readonly lineHeightPx?: number; +} + +// The subset of a REST node this tool reads; the payload carries far more and is dumped verbatim. +export interface FigmaNode { + readonly id: string; + readonly name: string; + readonly type: string; + readonly visible?: boolean; + readonly opacity?: number; + readonly children?: ReadonlyArray<FigmaNode>; + readonly absoluteBoundingBox?: BoundingBox | null; + readonly exposedInstances?: ReadonlyArray<string>; + readonly fills?: ReadonlyArray<FigmaPaint>; + readonly strokes?: ReadonlyArray<FigmaPaint>; + readonly characters?: string; + readonly style?: FigmaTextStyle; + readonly componentId?: string; + // Property (`fill`, `text`, `stroke`, …) → style id, resolved by the entry's `styles` map. + readonly styles?: Readonly<Record<string, string>>; +} + +export interface FigmaStyle { + readonly name: string; + readonly styleType: string; +} + +export interface FigmaComponent { + readonly name: string; +} + +export interface NodeEntry { + readonly document: FigmaNode; + readonly styles?: Readonly<Record<string, FigmaStyle>>; + readonly components?: Readonly<Record<string, FigmaComponent>>; +} + +// `GET /v1/files/:key/nodes`: file metadata plus one entry per requested id, `null` when the id is +// not in the file. +export interface NodesResponse { + readonly name: string; + readonly lastModified: string; + readonly version: string; + readonly nodes: Readonly<Record<string, NodeEntry | null>>; +} + +// `status` is the HTTP status the request failed with; undefined when the run never reached Figma. +export class FigmaFetchError extends Error { + readonly status: number | undefined; + + constructor(message: string, status?: number) { + super(message); + this.status = status; + } +} + +export type Env = Readonly<Record<string, string | undefined>>; + +function readToken(env: Env): string { + const token = env[TOKEN_ENV]?.trim(); + if (token === undefined || token === '') { + throw new FigmaFetchError(`No Figma token: export ${ TOKEN_ENV } (a personal access token) and run again.`); + } + return token; +} + +function describeFailure(status: number): string { + if (status === 401 || status === 403) { + return `Figma rejected the token (HTTP ${ status }); personal access tokens expire after at most 90 days.`; + } + if (status === 404) return 'Figma returned 404: the file key is wrong or the token has no access to the file.'; + return `Figma nodes request failed with HTTP ${ status }.`; +} + +// eslint-disable-next-line no-restricted-properties -- Node CLI reading its own token from the shell, not an app env var +export async function fetchNodes(ref: NodeRef, env: Env = process.env): Promise<NodesResponse> { + const token = readToken(env); + const url = `${ FIGMA_API_BASE }/v1/files/${ ref.fileKey }/nodes?ids=${ encodeURIComponent(ref.nodeId) }`; + const response = await fetch(url, { headers: { 'X-Figma-Token': token } }); + if (!response.ok) throw new FigmaFetchError(describeFailure(response.status), response.status); + return await response.json() as NodesResponse; +} + +export function entryOf(payload: NodesResponse, nodeId: string): NodeEntry { + const entry = payload.nodes[nodeId]; + if (entry === undefined || entry === null) throw new FigmaFetchError(`Node ${ nodeId } is not in file "${ payload.name }".`); + return entry; +} + +export function rootOf(payload: NodesResponse, nodeId: string): FigmaNode { + return entryOf(payload, nodeId).document; +} diff --git a/tools/design-readout/fetch/url.spec.ts b/tools/design-readout/fetch/url.spec.ts new file mode 100644 index 00000000000..c97d84be29e --- /dev/null +++ b/tools/design-readout/fetch/url.spec.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'vitest'; + +import { fileSafeNodeId, parseNodeId, parseNodeRef } from './url'; + +describe('parseNodeRef', () => { + it('reads the file key and a dashed node id from a design link', () => { + expect(parseNodeRef('https://www.figma.com/design/abcDEF0123456789abcDEF/Pages?node-id=22842-174340&t=abc-4')) + .toEqual({ fileKey: 'abcDEF0123456789abcDEF', nodeId: '22842:174340' }); + }); + + it('accepts the canonical colon form of the node id, encoded or not', () => { + expect(parseNodeRef('https://www.figma.com/design/abcDEF0123456789abcDEF/?node-id=22842:174340')?.nodeId).toBe('22842:174340'); + expect(parseNodeRef('https://www.figma.com/design/abcDEF0123456789abcDEF/?node-id=22842%3A174340')?.nodeId).toBe('22842:174340'); + }); + + it('accepts the older file/ path and a link without a file name segment', () => { + expect(parseNodeRef('https://www.figma.com/file/abcDEF0123456789abcDEF/Pages?node-id=1-2')).toEqual({ fileKey: 'abcDEF0123456789abcDEF', nodeId: '1:2' }); + expect(parseNodeRef('https://figma.com/design/abcDEF0123456789abcDEF?node-id=1-2')).toEqual({ fileKey: 'abcDEF0123456789abcDEF', nodeId: '1:2' }); + }); + + it('returns the branch key of a branch link, since the REST API serves branch content under it alone', () => { + expect(parseNodeRef('https://www.figma.com/design/abcDEF0123456789abcDEF/branch/brKEY0123456789/Pages?node-id=1-2')) + .toEqual({ fileKey: 'brKEY0123456789', nodeId: '1:2' }); + }); + + it('rejects anything that is not a figma node link', () => { + expect(parseNodeRef('22842:174340')).toBeUndefined(); + expect(parseNodeRef('https://notfigma.com/design/abcDEF0123456789abcDEF?node-id=1-2')).toBeUndefined(); + expect(parseNodeRef('https://www.figma.com/design/abcDEF0123456789abcDEF/Pages')).toBeUndefined(); + expect(parseNodeRef('https://www.figma.com/design/abcDEF0123456789abcDEF/Pages?node-id=abc')).toBeUndefined(); + expect(parseNodeRef('https://example.com/design/abcDEF0123456789abcDEF?node-id=1-2')).toBeUndefined(); + expect(parseNodeRef('https://www.figma.com/board/abcDEF0123456789abcDEF?node-id=1-2')).toBeUndefined(); + expect(parseNodeRef('not a url')).toBeUndefined(); + }); +}); + +describe('parseNodeId', () => { + it('canonicalizes a plain id from either form', () => { + expect(parseNodeId('22842-174340')).toBe('22842:174340'); + expect(parseNodeId(' 22842:174340 ')).toBe('22842:174340'); + }); + + it('keeps the instance path of a nested id and adds the I prefix the REST API keys it by', () => { + expect(parseNodeId('I21998:159259;20539:210205;20534:197023')).toBe('I21998:159259;20539:210205;20534:197023'); + expect(parseNodeId('I21998-159259;20539-210205')).toBe('I21998:159259;20539:210205'); + expect(parseNodeId('21998-159259;20539-210205')).toBe('I21998:159259;20539:210205'); + }); + + it('rejects anything else', () => { + expect([ 'abc', '1', '1:2;', ';1:2', 'I;1:2', '1:2;x:y', '' ].map(parseNodeId)).toEqual(Array(7).fill(undefined)); + }); + + it('reads a nested id from a link', () => { + expect(parseNodeRef('https://www.figma.com/design/abcDEF0123456789abcDEF/Pages?node-id=I21998-159259%3B20539-210205')?.nodeId) + .toBe('I21998:159259;20539:210205'); + }); +}); + +describe('fileSafeNodeId', () => { + it('turns the separators into file-name characters, keeping plain ids as before', () => { + expect(fileSafeNodeId('22842:174340')).toBe('22842-174340'); + expect(fileSafeNodeId('I21998:159259;20539:210205')).toBe('I21998-159259_20539-210205'); + }); +}); diff --git a/tools/design-readout/fetch/url.ts b/tools/design-readout/fetch/url.ts new file mode 100644 index 00000000000..16dfcfa8204 --- /dev/null +++ b/tools/design-readout/fetch/url.ts @@ -0,0 +1,50 @@ +export interface NodeRef { + readonly fileKey: string; + readonly nodeId: string; +} + +const FILE_PATH = /^\/(?:design|file)\/([A-Za-z0-9]+)(?:\/branch\/([A-Za-z0-9]+))?(?:\/|$)/; +const NODE_ID_SEGMENT = '\\d+[-:]\\d+'; +const NODE_ID = new RegExp(`^I?(${ NODE_ID_SEGMENT }(?:;${ NODE_ID_SEGMENT })*)$`); +const SEGMENT_SEPARATOR = /[-:]/; + +// A node id is `A:B` for a node placed on the page and `I<A:B>;<C:D>…` for a node inside a +// component instance: the instance's id, then the internal ids down to the node. The URL form +// writes `-` for `:`; the canonical form is what the REST API keys its response by. +export function parseNodeId(raw: string): string | undefined { + const match = NODE_ID.exec(raw.trim()); + if (match === null) return undefined; + const segments = match[1].split(';').map((segment) => segment.split(SEGMENT_SEPARATOR).join(':')); + return `${ segments.length > 1 ? 'I' : '' }${ segments.join(';') }`; +} + +// The id in a form a file name can carry: `I1:2;3:4` → `I1-2_3-4`. +export function fileSafeNodeId(nodeId: string): string { + return nodeId.replace(/:/g, '-').replace(/;/g, '_'); +} + +function parseUrl(input: string): URL | undefined { + try { + return new URL(input); + } catch { + return undefined; + } +} + +function isFigmaHost(hostname: string): boolean { + return hostname === 'figma.com' || hostname.endsWith('.figma.com'); +} + +// A Figma node link: `https://www.figma.com/design/<fileKey>/<name>?node-id=<A>-<B>`. The node id is +// accepted in its URL form (`A-B`) and its canonical form (`A:B`), and is always returned canonical. +// A branch link carries `/branch/<branchKey>/` after the file key, and the REST API serves the +// branch's content under the branch key only, so that is the key returned. +export function parseNodeRef(input: string): NodeRef | undefined { + const url = parseUrl(input); + if (url === undefined || !isFigmaHost(url.hostname)) return undefined; + const [ , mainKey, branchKey ] = FILE_PATH.exec(url.pathname) ?? []; + const fileKey = branchKey ?? mainKey; + const nodeId = parseNodeId(url.searchParams.get('node-id') ?? ''); + if (fileKey === undefined || nodeId === undefined) return undefined; + return { fileKey, nodeId }; +} diff --git a/tools/design-readout/fixtures/13983-116369-light.json b/tools/design-readout/fixtures/13983-116369-light.json new file mode 100644 index 00000000000..8c084806469 --- /dev/null +++ b/tools/design-readout/fixtures/13983-116369-light.json @@ -0,0 +1,3399 @@ +{ + "name": "🖥️ Blockscout desktop pages", + "lastModified": "2026-10-06T08:17:31Z", + "thumbnailUrl": "https://s3-alpha.figma.com/thumbnails/ea6b2cdf-f674-4e71-99cf-ef63e39eac15?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQ4GOSFWCQPXYJSOJ%2F20261004%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20261004T120000Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=ffa90a523f6cfdd45a7f6b040d90fa1f1184904ac9b40504f76eb1d0308a1fab", + "version": "2407163522197879133", + "role": "viewer", + "editorType": "figma", + "linkAccess": "view", + "nodes": { + "13983:116369": { + "document": { + "id": "13983:116369", + "name": "1st_line", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "13983:116370", + "name": "Frame 155", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "14080:318015", + "name": "Chakra icons / Linear/Txn20", + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "14076:263650", + "overrides": [ + { + "id": "14080:318015", + "overriddenFields": [ + "height", + "width" + ] + } + ], + "children": [ + { + "id": "I14080:318015;14076:263657", + "name": "Subtract", + "type": "BOOLEAN_OPERATION", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "I14080:318015;14076:263656", + "name": "Union", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.29019609093666077, + "g": 0.3333333432674408, + "b": 0.40784314274787903, + "a": 1 + } + }, + { + "opacity": 0.20000000298023224, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0, + "g": 0, + "b": 0, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0.30000001192092896, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:424" + }, + "absoluteBoundingBox": { + "x": 4455.74365234375, + "y": 530.7362670898438, + "width": 20.51282501220703, + "height": 16.527286529541016 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I14080:318015;14076:263655", + "name": "Union (Stroke)", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.29019609093666077, + "g": 0.3333333432674408, + "b": 0.40784314274787903, + "a": 1 + } + }, + { + "opacity": 0.20000000298023224, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0, + "g": 0, + "b": 0, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0.30000001192092896, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:424" + }, + "absoluteBoundingBox": { + "x": 4455.74365234375, + "y": 530.7362670898438, + "width": 20.51282501220703, + "height": 16.527286529541016 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0.30000001192092896, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:423" + }, + "booleanOperation": "SUBTRACT", + "absoluteBoundingBox": { + "x": 4456, + "y": 530.9999389648438, + "width": 20, + "height": 16 + }, + "absoluteRenderBounds": { + "x": 4456, + "y": 530.9999389648438, + "width": 20, + "height": 16 + }, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "effects": [], + "interactions": [] + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 4456, + "y": 529, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 4456, + "y": 529, + "width": 20, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116372", + "name": "Frame 205", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "13983:116373", + "name": "Asset Name Copy 8", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.16862745583057404, + "g": 0.42352941632270813, + "b": 0.6901960968971252, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "1:474" + }, + "absoluteBoundingBox": { + "x": 4484, + "y": 529, + "width": 288, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 4484.701171875, + "y": 533.3408813476562, + "width": 230.33349609375, + "height": 10.8828125 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "characters": "0xf3ef9ef04d0d5dd73f58...e333", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Bold", + "fontStyle": "Bold", + "fontWeight": 700, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "counterAxisSizingMode": "FIXED", + "primaryAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "itemSpacing": 12, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 4484, + "y": 524, + "width": 288, + "height": 30 + }, + "absoluteRenderBounds": { + "x": 4484, + "y": 524, + "width": 288, + "height": 30 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "FILL", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "counterAxisSizingMode": "FIXED", + "primaryAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 4456, + "y": 524, + "width": 316, + "height": 30 + }, + "absoluteRenderBounds": { + "x": 4456, + "y": 524, + "width": 316, + "height": 30 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FILL", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116374", + "name": "Asset Name Copy 2", + "visible": false, + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.16862745583057404, + "g": 0.42352941632270813, + "b": 0.6901960968971252, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "1:474" + }, + "absoluteBoundingBox": { + "x": 4744, + "y": 529, + "width": 294, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "characters": "0xf3ef9ef04d0d5dd73f58e6dad54...e333", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Bold", + "fontStyle": "Bold", + "fontWeight": 700, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116375", + "name": "Frame 150", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "13983:116376", + "name": "Loaders/Circular-Progress", + "visible": false, + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "624:9148", + "componentProperties": { + "Label": { + "value": "False", + "type": "VARIANT", + "boundVariables": {} + } + }, + "overrides": [ + { + "id": "13983:116376", + "overriddenFields": [ + "fills", + "height", + "preserveRatio", + "width" + ] + }, + { + "id": "I13983:116376;623:9319", + "overriddenFields": [ + "visible" + ] + }, + { + "id": "I13983:116376;624:9145", + "overriddenFields": [ + "arcData", + "inheritFillStyleId" + ] + }, + { + "id": "I13983:116376;624:9149", + "overriddenFields": [ + "visible" + ] + } + ], + "children": [ + { + "id": "I13983:116376;623:9319", + "name": "Width", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.886274516582489, + "g": 0.9098039269447327, + "b": 0.9411764740943909, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:420" + }, + "absoluteBoundingBox": { + "x": 4784, + "y": 524, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "isMask": true, + "maskType": "ALPHA", + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116376;624:9149", + "name": "Bar", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.929411768913269, + "g": 0.9490196108818054, + "b": 0.9686274528503418, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:419" + }, + "absoluteBoundingBox": { + "x": 4784, + "y": 524, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116376;624:9145", + "name": "Progress", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.1921568661928177, + "g": 0.5098039507865906, + "b": 0.8078431487083435, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:473" + }, + "absoluteBoundingBox": { + "x": 4784, + "y": 524, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 4.71238899230957, + "endingAngle": 9.676105499267578, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 4784, + "y": 524, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116377", + "name": "10s ago", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "1:423" + }, + "absoluteBoundingBox": { + "x": 4784, + "y": 524, + "width": 177, + "height": 30 + }, + "absoluteRenderBounds": { + "x": 4784.85498046875, + "y": 533.678955078125, + "width": 49.7109375, + "height": 13.34375 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FILL", + "characters": "10s ago", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": null, + "fontStyle": "Regular", + "fontWeight": 400, + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "counterAxisSizingMode": "FIXED", + "primaryAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "itemSpacing": 5, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 4784, + "y": 524, + "width": 182, + "height": 30 + }, + "absoluteRenderBounds": { + "x": 4784, + "y": 524, + "width": 182, + "height": 30 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116378", + "name": "from/to", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "13983:116380", + "name": "Avatar", + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "404:174", + "componentProperties": { + "Size": { + "value": "xs", + "type": "VARIANT", + "boundVariables": {} + }, + "Variant": { + "value": "Image", + "type": "VARIANT", + "boundVariables": {} + }, + "Badge": { + "value": "False", + "type": "VARIANT", + "boundVariables": {} + } + }, + "overrides": [ + { + "id": "I13983:116380;913:15436", + "overriddenFields": [ + "visible" + ] + } + ], + "children": [ + { + "id": "I13983:116380;14096:340456", + "name": "ENS", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "I13983:116380;14096:340457", + "name": "Layer 1", + "type": "GROUP", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "I13983:116380;14096:340458", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fillOverrideTable": { + "2": null + }, + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:417" + }, + "absoluteBoundingBox": { + "x": 4983.6953125, + "y": 532.8888549804688, + "width": 4.105994701385498, + "height": 5.713266849517822 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;14096:340459", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fillOverrideTable": { + "2": null + }, + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:417" + }, + "absoluteBoundingBox": { + "x": 4982.5, + "y": 536.7102661132812, + "width": 5.296664714813232, + "height": 8.400794982910156 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;14096:340460", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fillOverrideTable": { + "2": null + }, + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:417" + }, + "absoluteBoundingBox": { + "x": 4988.19970703125, + "y": 539.3978881835938, + "width": 4.10634708404541, + "height": 5.713266849517822 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;14096:340461", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fillOverrideTable": { + "2": null + }, + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:417" + }, + "absoluteBoundingBox": { + "x": 4988.2041015625, + "y": 532.8888549804688, + "width": 5.295840263366699, + "height": 8.400795936584473 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;14096:340462", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "COLOR", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fillOverrideTable": { + "2": null + }, + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:417" + }, + "absoluteBoundingBox": { + "x": 4982.5, + "y": 532.8888549804688, + "width": 11, + "height": 12.222222328186035 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 4982.5, + "y": 532.8888549804688, + "width": 11, + "height": 12.222286224365234 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "type": "GRADIENT_LINEAR", + "gradientHandlePositions": [ + { + "x": 0.4583333611177924, + "y": 0.18749999060916284 + }, + { + "x": 0.7708333990691915, + "y": 0.9375000502138122 + }, + { + "x": 0.08333333131546772, + "y": 0.34375000958486235 + } + ], + "gradientStops": [ + { + "color": { + "r": 0.501960813999176, + "g": 0.5960784554481506, + "b": 0.9803921580314636, + "a": 1 + }, + "position": 0 + }, + { + "color": { + "r": 0.3607843220233917, + "g": 0.658823549747467, + "b": 0.95686274766922, + "a": 1 + }, + "position": 0.6161859035491943 + }, + { + "color": { + "r": 0.3019607961177826, + "g": 0.7098039388656616, + "b": 0.9490196108818054, + "a": 1 + }, + "position": 0.9572147727012634 + } + ] + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "type": "GRADIENT_LINEAR", + "gradientHandlePositions": [ + { + "x": 0.4583333611177924, + "y": 0.18749999060916284 + }, + { + "x": 0.7708333990691915, + "y": 0.9375000502138122 + }, + { + "x": 0.08333333131546772, + "y": 0.34375000958486235 + } + ], + "gradientStops": [ + { + "color": { + "r": 0.501960813999176, + "g": 0.5960784554481506, + "b": 0.9803921580314636, + "a": 1 + }, + "position": 0 + }, + { + "color": { + "r": 0.3607843220233917, + "g": 0.658823549747467, + "b": 0.95686274766922, + "a": 1 + }, + "position": 0.6161859035491943 + }, + { + "color": { + "r": 0.3019607961177826, + "g": 0.7098039388656616, + "b": 0.9490196108818054, + "a": 1 + }, + "position": 0.9572147727012634 + } + ] + } + ], + "strokes": [], + "cornerRadius": 4, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "counterAxisSizingMode": "FIXED", + "primaryAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "primaryAxisAlignItems": "CENTER", + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 4977, + "y": 528, + "width": 22, + "height": 22 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;16687:155232", + "name": "ENS 20px", + "visible": false, + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "13818:186569", + "overrides": [], + "children": [ + { + "id": "I13983:116380;16687:155232;13818:186562", + "name": "Group", + "type": "GROUP", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "I13983:116380;16687:155232;13818:186563", + "name": "Layer 1", + "type": "GROUP", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "I13983:116380;16687:155232;13818:186564", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "fillOverrideTable": { + "1": null + }, + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:423" + }, + "absoluteBoundingBox": { + "x": 4980.7890625, + "y": 529, + "width": 6.718900203704834, + "height": 9.348981857299805 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;16687:155232;13818:186565", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "fillOverrideTable": { + "1": null + }, + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:423" + }, + "absoluteBoundingBox": { + "x": 4978.83349609375, + "y": 535.2532958984375, + "width": 8.667268753051758, + "height": 13.746755599975586 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;16687:155232;13818:186566", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "fillOverrideTable": { + "1": null + }, + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:423" + }, + "absoluteBoundingBox": { + "x": 4988.16015625, + "y": 539.6510009765625, + "width": 6.719476699829102, + "height": 9.348979949951172 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;16687:155232;13818:186567", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "fillOverrideTable": { + "1": null + }, + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:423" + }, + "absoluteBoundingBox": { + "x": 4988.16748046875, + "y": 529, + "width": 8.66592025756836, + "height": 13.746757507324219 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;16687:155232;13818:186568", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "COLOR", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "fillOverrideTable": { + "1": null + }, + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "1:423" + }, + "absoluteBoundingBox": { + "x": 4978.83349609375, + "y": 529, + "width": 18, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 4978.83349609375, + "y": 529, + "width": 18, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 4978.83349609375, + "y": 529, + "width": 18, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": true, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 4978, + "y": 529, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;19812:67668", + "name": "Jazzicon", + "visible": false, + "type": "RECTANGLE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "IMAGE", + "scaleMode": "STRETCH", + "imageRef": "dc045a38e8cab6db94c631f6fbc1d32c7287b0ec", + "imageTransform": [ + [ + 0.16233766078948975, + 0, + 0.33441558480262756 + ], + [ + 0, + 0.158439502120018, + 0.5055732727050781 + ] + ] + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "cornerRadius": 1000, + "cornerSmoothing": 0, + "absoluteBoundingBox": { + "x": 4978, + "y": 529, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;19812:67669", + "name": "Blockies", + "visible": false, + "type": "RECTANGLE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "IMAGE", + "scaleMode": "FILL", + "imageRef": "949ea01c378d530b1f3720a4a9568f72a636932b" + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": 4978, + "y": 529, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;19812:67670", + "name": "Github", + "visible": false, + "type": "RECTANGLE", + "scrollBehavior": "SCROLLS", + "rotation": -5.721188916458728e-18, + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "IMAGE", + "scaleMode": "FILL", + "imageRef": "8ab27f27dca2c975987dbbb61e52c19163e2c141" + }, + { + "opacity": 0.10000000149011612, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.5490196347236633, + "g": 0.7215686440467834, + "b": 0.501960813999176, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "cornerRadius": 100, + "cornerSmoothing": 0, + "absoluteBoundingBox": { + "x": 4978, + "y": 529, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116380;19812:67671", + "name": "gradient", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "GRADIENT_LINEAR", + "gradientHandlePositions": [ + { + "x": 0.17499998513609133, + "y": 0.3500000095739959 + }, + { + "x": 1.1249999852851023, + "y": 1.0000000366941095 + }, + { + "x": -0.15000002842396554, + "y": 0.8250000096485015 + } + ], + "gradientStops": [ + { + "color": { + "r": 0.16173996031284332, + "g": 0.3623785972595215, + "b": 0.793017566204071, + "a": 1 + }, + "position": 0 + }, + { + "color": { + "r": 0.7145012617111206, + "g": 0.5022146105766296, + "b": 0.9846842288970947, + "a": 1 + }, + "position": 1 + } + ] + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": 4978, + "y": 529, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 4978, + "y": 529, + "width": 20, + "height": 20 + }, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "effects": [], + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": true, + "background": [], + "fills": [], + "strokes": [], + "cornerRadius": 9999, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 4978, + "y": 529, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 4978, + "y": 529, + "width": 20, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116382", + "name": "0xd0...4567", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.16862745583057404, + "g": 0.42352941632270813, + "b": 0.6901960968971252, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "1:474" + }, + "absoluteBoundingBox": { + "x": 5006, + "y": 524, + "width": 81, + "height": 30 + }, + "absoluteRenderBounds": { + "x": 5006.79052734375, + "y": 533.678955078125, + "width": 79.0830078125, + "height": 10.49005126953125 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "characters": "0xd0...4567", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116383", + "name": "copy", + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "868:9765", + "overrides": [ + { + "id": "13983:116383", + "overriddenFields": [ + "height", + "width" + ] + }, + { + "id": "I13983:116383;868:9764", + "overriddenFields": [ + "inheritFillStyleId", + "strokes" + ] + } + ], + "children": [ + { + "id": "I13983:116383;868:9764", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.6274510025978088, + "g": 0.6823529601097107, + "b": 0.7529411911964417, + "a": 1 + } + } + ], + "strokes": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.6274510025978088, + "g": 0.6823529601097107, + "b": 0.7529411911964417, + "a": 1 + } + } + ], + "strokeWeight": 0.30000001192092896, + "strokeAlign": "CENTER", + "styles": { + "fill": "1:422", + "stroke": "1:422" + }, + "absoluteBoundingBox": { + "x": 5095, + "y": 532, + "width": 11.666666984558105, + "height": 14 + }, + "absoluteRenderBounds": { + "x": 5095, + "y": 531.8499755859375, + "width": 11.81689453125, + "height": 14.300048828125 + }, + "constraints": { + "vertical": "CENTER", + "horizontal": "LEFT" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": true, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 5095, + "y": 529, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 5095, + "y": 529, + "width": 20, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "counterAxisSizingMode": "FIXED", + "primaryAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 4978, + "y": 524, + "width": 234, + "height": 30 + }, + "absoluteRenderBounds": { + "x": 4978, + "y": 524, + "width": 234, + "height": 30 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116384", + "name": "transactions_tags", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "13983:116385", + "name": "TagCC", + "visible": false, + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "1015:22857", + "componentProperties": { + "Skin": { + "value": "Light", + "type": "VARIANT", + "boundVariables": {} + } + }, + "overrides": [ + { + "id": "13983:116385", + "overriddenFields": [ + "height", + "width" + ] + } + ], + "children": [ + { + "id": "I13983:116385;1015:22858", + "name": "Text", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.1921568661928177, + "g": 0.5098039507865906, + "b": 0.8078431487083435, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "1:473" + }, + "absoluteBoundingBox": { + "x": 5228, + "y": 529, + "width": 86, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "Contract call", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "TOP", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.9215686321258545, + "g": 0.9725490212440491, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.9215686321258545, + "g": 0.9725490212440491, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "cornerRadius": 4, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0.9215686321258545, + "g": 0.9725490212440491, + "b": 1, + "a": 1 + }, + "styles": { + "fills": "1:468", + "fill": "1:468" + }, + "layoutMode": "HORIZONTAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "paddingLeft": 4, + "paddingRight": 4, + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 5224, + "y": 527, + "width": 102, + "height": 24 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116386", + "name": "TagTnx", + "visible": false, + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "1015:22865", + "componentProperties": { + "Skin": { + "value": "txn_light", + "type": "VARIANT", + "boundVariables": {} + } + }, + "overrides": [ + { + "id": "13983:116386", + "overriddenFields": [ + "height", + "width" + ] + }, + { + "id": "I13983:116386;1015:22864", + "overriddenFields": [ + "characterStyleOverrides", + "characters", + "lineIndentations", + "lineTypes", + "styleOverrideTable" + ] + } + ], + "children": [ + { + "id": "I13983:116386;1015:22864", + "name": "Text", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.501960813999176, + "g": 0.3529411852359772, + "b": 0.8352941274642944, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "1:493" + }, + "absoluteBoundingBox": { + "x": 5228, + "y": 529, + "width": 79, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "CommitHash", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "TOP", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.9803921580314636, + "g": 0.9607843160629272, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.9803921580314636, + "g": 0.9607843160629272, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "cornerRadius": 4, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0.9803921580314636, + "g": 0.9607843160629272, + "b": 1, + "a": 1 + }, + "styles": { + "fills": "1:488", + "fill": "1:488" + }, + "layoutMode": "HORIZONTAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "paddingLeft": 4, + "paddingRight": 4, + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 5224, + "y": 527, + "width": 95, + "height": 24 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116387", + "name": "TagTT", + "visible": false, + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "1007:23080", + "overrides": [ + { + "id": "13983:116387", + "overriddenFields": [ + "height", + "width" + ] + }, + { + "id": "I13983:116387;24:1153", + "overriddenFields": [ + "characterStyleOverrides", + "characters", + "inheritTextStyleId", + "lineIndentations", + "lineTypes", + "styleOverrideTable", + "text" + ] + } + ], + "children": [ + { + "id": "I13983:116387;24:1153", + "name": "Text", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.8208333253860474, + "g": 0.5700687766075134, + "b": 0.3385937809944153, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "absoluteBoundingBox": { + "x": 5345, + "y": 534, + "width": 81, + "height": 16 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "Token transfer", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-SemiBold", + "fontStyle": "Semi Bold", + "fontWeight": 600, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "TOP", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "opacity": 0.10000000149011612, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.8208333253860474, + "g": 0.6858062744140625, + "b": 0.3385937809944153, + "a": 1 + } + } + ], + "fills": [ + { + "opacity": 0.10000000149011612, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.8208333253860474, + "g": 0.6858062744140625, + "b": 0.3385937809944153, + "a": 1 + } + } + ], + "strokes": [], + "cornerRadius": 4, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0.8208333253860474, + "g": 0.6858062744140625, + "b": 0.3385937809944153, + "a": 0.10000000149011612 + }, + "layoutMode": "HORIZONTAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "paddingLeft": 8, + "paddingRight": 8, + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 5337, + "y": 527, + "width": 95, + "height": 24 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116388", + "name": "TagTT", + "visible": false, + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "1007:23080", + "overrides": [ + { + "id": "13983:116388", + "overriddenFields": [ + "height", + "inheritFillStyleId", + "width" + ] + }, + { + "id": "I13983:116388;24:1153", + "overriddenFields": [ + "characterStyleOverrides", + "characters", + "inheritFillStyleId", + "inheritTextStyleId", + "lineIndentations", + "lineTypes", + "styleOverrideTable", + "text" + ] + } + ], + "children": [ + { + "id": "I13983:116388;24:1153", + "name": "Text", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.1921568661928177, + "g": 0.5921568870544434, + "b": 0.5843137502670288, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "1:463" + }, + "absoluteBoundingBox": { + "x": 5232, + "y": 574, + "width": 81, + "height": 16 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "Multicall", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "TOP", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.9019607901573181, + "g": 1, + "b": 0.9803921580314636, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.9019607901573181, + "g": 1, + "b": 0.9803921580314636, + "a": 1 + } + } + ], + "strokes": [], + "cornerRadius": 4, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0.9019607901573181, + "g": 1, + "b": 0.9803921580314636, + "a": 1 + }, + "styles": { + "fills": "1:458", + "fill": "1:458" + }, + "layoutMode": "HORIZONTAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "paddingLeft": 8, + "paddingRight": 8, + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 5224, + "y": 567, + "width": 72, + "height": 24 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "13983:116389", + "name": "Tag/Method", + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "1003:19151", + "overrides": [ + { + "id": "13983:116389", + "overriddenFields": [ + "height", + "width" + ] + }, + { + "id": "I13983:116389;1003:19153", + "overriddenFields": [ + "characterStyleOverrides", + "characters", + "lineIndentations", + "lineTypes", + "styleOverrideTable" + ] + } + ], + "children": [ + { + "id": "I13983:116389;1003:19152", + "name": "icon/code", + "visible": false, + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "1001:17604", + "overrides": [], + "children": [ + { + "id": "I13983:116389;1003:19152;101:1708", + "name": "brackets", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.29019609093666077, + "g": 0.3333333432674408, + "b": 0.40784314274787903, + "a": 1 + } + }, + { + "opacity": 0.20000000298023224, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0, + "g": 0, + "b": 0, + "a": 1 + } + } + ], + "fillOverrideTable": { + "1": { + "inheritFillStyleId": "1001:17917", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0, + "g": 0, + "b": 0, + "a": 1 + } + } + ] + } + }, + "strokes": [], + "strokeWeight": 2, + "strokeAlign": "CENTER", + "strokeJoin": "ROUND", + "strokeCap": "ROUND", + "styles": { + "fill": "1:424" + }, + "absoluteBoundingBox": { + "x": 5232, + "y": 535.875, + "width": 10.000000953674316, + "height": 6.25 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": true, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 5232, + "y": 534, + "width": 10, + "height": 10 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I13983:116389;1003:19153", + "name": "MethodName", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.29019609093666077, + "g": 0.3333333432674408, + "b": 0.40784314274787903, + "a": 1 + } + }, + { + "opacity": 0.20000000298023224, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0, + "g": 0, + "b": 0, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "1:424" + }, + "absoluteBoundingBox": { + "x": 5232, + "y": 529, + "width": 122, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 5233.11865234375, + "y": 533.3408813476562, + "width": 119.86767578125, + "height": 10.828125 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "Unknown function", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "TOP", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 5, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.9686274528503418, + "g": 0.9803921580314636, + "b": 0.9882352948188782, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.9686274528503418, + "g": 0.9803921580314636, + "b": 0.9882352948188782, + "a": 1 + } + } + ], + "strokes": [], + "cornerRadius": 4, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0.9686274528503418, + "g": 0.9803921580314636, + "b": 0.9882352948188782, + "a": 1 + }, + "styles": { + "fills": "1:418", + "fill": "1:418" + }, + "layoutMode": "HORIZONTAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "paddingLeft": 8, + "paddingRight": 8, + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 5224, + "y": 527, + "width": 81, + "height": 24 + }, + "absoluteRenderBounds": { + "x": 5224, + "y": 527, + "width": 128.986328125, + "height": 24 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 16, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 5224, + "y": 527, + "width": 138, + "height": 24 + }, + "absoluteRenderBounds": { + "x": 5224, + "y": 527, + "width": 138, + "height": 24 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "cornerRadius": 12, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "primaryAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "paddingLeft": 12, + "paddingRight": 12, + "paddingTop": 16, + "paddingBottom": 16, + "itemSpacing": 12, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 4444, + "y": 508, + "width": 1115, + "height": 62 + }, + "absoluteRenderBounds": { + "x": 4444, + "y": 508, + "width": 1115, + "height": 62 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 0, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + "components": { + "14076:263650": { + "key": "3b7a24a3675d03d1017318746c057b9aab423b70", + "name": "Chakra icons / Linear/Txn20", + "description": "", + "remote": false, + "documentationLinks": [] + }, + "624:9148": { + "key": "4fcc730f3142eb773929752c05d1585cacef4888", + "name": "Label=False", + "description": "", + "remote": false, + "componentSetId": "624:9218", + "documentationLinks": [] + }, + "404:174": { + "key": "9f6234f1204c7c3cbdc738a3019ec73a0028edf3", + "name": "Size=xs, Variant=Image, Badge=False", + "description": "", + "remote": false, + "componentSetId": "404:173", + "documentationLinks": [] + }, + "13818:186569": { + "key": "55416c80a5d559b73a432b074ff8e9b4ed05545f", + "name": "ENS name", + "description": "", + "remote": false, + "documentationLinks": [] + }, + "868:9765": { + "key": "a988a8cb982b081ef7748aea91263f8a5a4b87f1", + "name": "copy", + "description": "", + "remote": false, + "documentationLinks": [] + }, + "1015:22857": { + "key": "5da6c922f211f4aa85d5770fe57f7ecc18973ab2", + "name": "Skin=Light", + "description": "", + "remote": false, + "componentSetId": "11542:133267", + "documentationLinks": [] + }, + "1015:22865": { + "key": "21f0a772dcc9c716cbd3511ff35091c1884b891e", + "name": "Skin=txn_light", + "description": "", + "remote": false, + "componentSetId": "11524:133339", + "documentationLinks": [] + }, + "1007:23080": { + "key": "2e20904d563be9da6c185044be1f518f95a1d83c", + "name": "TagTT", + "description": "", + "remote": true, + "documentationLinks": [] + }, + "1003:19151": { + "key": "18fe85e0d22abcf259557e74e89103e6b9be4408", + "name": "Tag/Method", + "description": "", + "remote": false, + "documentationLinks": [] + }, + "1001:17604": { + "key": "1442830b812b4a69599cf6cdada56d9770c3f96e", + "name": "icon/code", + "description": "", + "remote": true, + "documentationLinks": [] + } + }, + "componentSets": { + "624:9218": { + "key": "68c6063447338956d79f089246847bd0c97454bc", + "name": "Loaders/Circular-Progress", + "description": "The CircularProgress component is used to indicate the progress for determinate and indeterminate processes.", + "remote": false + }, + "404:173": { + "key": "0111930ecda9b64def345dd0967aaf218ec8605a", + "name": "Avatar", + "description": "The Avatar component is used to represent a user, and displays the profile picture, initials or fallback icon.", + "remote": false + }, + "11542:133267": { + "key": "ea2e0a2e7b63347286e2bdaf5dbfd2d0d5debd0f", + "name": "TagCC", + "description": "", + "remote": false + }, + "11524:133339": { + "key": "c5c703c512a48112a2b2325626ffbe94c2220d18", + "name": "TagTnx", + "description": "", + "remote": false + } + }, + "schemaVersion": 0, + "styles": { + "1:424": { + "key": "ac59f131e571df84a886813e7dd3dfc3aa62c4df", + "name": "gray/600", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:423": { + "key": "62e866747c55a96d48cfd3484ff5d6239fbb4512", + "name": "Text-Links-Icons/500", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:474": { + "key": "4770be3bf0bc1b1a2eb5812d9733ce94626831cf", + "name": "Text-Links-Icons/600", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:420": { + "key": "d95302dc9d2bf2abddb2679aa8b43176e49c5de2", + "name": "gray/200", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:419": { + "key": "d7997e3afda1401ec5c0dca1ade8d864781e5f6e", + "name": "gray/100", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:473": { + "key": "5cb9aca59341b1001286cd6074353ffa61e8cc92", + "name": "blue/500", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:417": { + "key": "01d57a817c0ee8324a8cd60783685490af5b914f", + "name": "🎨 Background for themes/white", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:422": { + "key": "d56cf8235f497c87f61de907f2f3c607aa77ab16", + "name": "Text-Links-Icons/400", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:468": { + "key": "11f6e637fd28bc74916968327dfbf41e2bd2dde6", + "name": "blue/50", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:493": { + "key": "0cf153beb5608fb56361e3962cf8a3a1a56f8497", + "name": "purple/500", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:488": { + "key": "200c1dcf1ca3b4c31e00732101ce1a528c77f679", + "name": "purple/50", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:463": { + "key": "2ad603029baa131c67d9c2109957a21d3160c63f", + "name": "teal/500", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1:458": { + "key": "75189a754357e1e957ee14e3a9cc60c8f28691b7", + "name": "teal/50", + "styleType": "FILL", + "remote": false, + "description": "" + }, + "1001:17917": { + "key": "671020aca383841eedb75d797e3df5e5fecd709d", + "name": "Black", + "styleType": "FILL", + "remote": true, + "description": "" + }, + "1:418": { + "key": "38a59f4d0ca49b8b964c624b5bc754caf6baac4b", + "name": "gray/50", + "styleType": "FILL", + "remote": false, + "description": "" + } + } + } + } +} diff --git a/tools/design-readout/fixtures/22842-169552-light.json b/tools/design-readout/fixtures/22842-169552-light.json new file mode 100644 index 00000000000..f702b6741c7 --- /dev/null +++ b/tools/design-readout/fixtures/22842-169552-light.json @@ -0,0 +1,1986 @@ +{ + "name": "🖥️ Blockscout desktop pages", + "lastModified": "2026-10-06T08:17:31Z", + "thumbnailUrl": "https://s3-alpha.figma.com/thumbnails/ea6b2cdf-f674-4e71-99cf-ef63e39eac15?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQ4GOSFWCQPXYJSOJ%2F20261004%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20261004T120000Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=ffa90a523f6cfdd45a7f6b040d90fa1f1184904ac9b40504f76eb1d0308a1fab", + "version": "2407163522197879133", + "role": "viewer", + "editorType": "figma", + "linkAccess": "view", + "nodes": { + "22842:169552": { + "document": { + "id": "22842:169552", + "name": "Holders_1st_line_public name", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169553", + "name": "rank", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169554", + "name": "balance", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169555", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.16862745583057404, + "g": 0.42352941632270813, + "b": 0.6901960968971252, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:24008", + "text": "26350:73382" + }, + "absoluteBoundingBox": { + "x": -1922, + "y": -272, + "width": 60, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1921.2890625, + "y": -267.32598876953125, + "width": 58.1365966796875, + "height": 10.465179443359375 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "1248139", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Bold", + "fontStyle": "Bold", + "fontWeight": 700, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "TOP", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169556", + "name": "total", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169557", + "name": "total", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1854, + "y": -272, + "width": 118, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169558", + "name": "Frame 150", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169559", + "name": "Loaders/Circular-Progress", + "visible": false, + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "28663:36787", + "componentProperties": { + "Label": { + "value": "False", + "type": "VARIANT", + "boundVariables": {} + }, + "Skin": { + "value": "Light", + "type": "VARIANT", + "boundVariables": {} + } + }, + "overrides": [ + { + "id": "22842:169559", + "overriddenFields": [ + "fills", + "height", + "preserveRatio", + "width" + ] + }, + { + "id": "I22842:169559;623:9319", + "overriddenFields": [ + "visible" + ] + }, + { + "id": "I22842:169559;624:9145", + "overriddenFields": [ + "arcData", + "inheritFillStyleId" + ] + }, + { + "id": "I22842:169559;624:9149", + "overriddenFields": [ + "visible" + ] + } + ], + "children": [ + { + "id": "I22842:169559;623:9319", + "name": "Width", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.886274516582489, + "g": 0.9098039269447327, + "b": 0.9411764740943909, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "28663:36784" + }, + "absoluteBoundingBox": { + "x": -1854, + "y": -272, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "isMask": true, + "maskType": "ALPHA", + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I22842:169559;624:9149", + "name": "Bar", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.929411768913269, + "g": 0.9490196108818054, + "b": 0.9686274528503418, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "28663:36785" + }, + "absoluteBoundingBox": { + "x": -1854, + "y": -272, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I22842:169559;624:9145", + "name": "Progress", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.1921568661928177, + "g": 0.5098039507865906, + "b": 0.8078431487083435, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "27942:23987" + }, + "absoluteBoundingBox": { + "x": -1854, + "y": -272, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 4.71238899230957, + "endingAngle": 9.676105499267578, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": -1854, + "y": -272, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169560", + "name": "10s ago", + "visible": false, + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "27942:23657", + "text": "26326:30496" + }, + "absoluteBoundingBox": { + "x": -1854, + "y": -272, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "characters": "10s ago", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": null, + "fontStyle": "Regular", + "fontWeight": 400, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "itemSpacing": 5, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1854, + "y": -272, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1854, + "y": -272, + "width": 52, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1854, + "y": -272, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1854, + "y": -272, + "width": 52, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1922, + "y": -272, + "width": 120, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1922, + "y": -272, + "width": 120, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "primaryAxisSizingMode": "FIXED", + "primaryAxisAlignItems": "CENTER", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1922, + "y": -277, + "width": 85, + "height": 30 + }, + "absoluteRenderBounds": { + "x": -1922, + "y": -277, + "width": 120, + "height": 30 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169561", + "name": "728972_gold_medal_award_badge_prize_icon 1", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169562", + "name": "Group", + "type": "GROUP", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169563", + "name": "Group", + "type": "GROUP", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169564", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.95686274766922, + "g": 0.26274511218070984, + "b": 0.21176470816135406, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": -1858.75, + "y": -261, + "width": 17.49999237060547, + "height": 6.726093769073486 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": -1858.75, + "y": -261, + "width": 17.49999237060547, + "height": 6.726093769073486 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": -1858.75, + "y": -261, + "width": 17.49999237060547, + "height": 6.726093769073486 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169565", + "name": "Vector", + "visible": false, + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 0.7568627595901489, + "b": 0.027450980618596077, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": -1855, + "y": -253.5, + "width": 10, + "height": 10 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169566", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 0.6549019813537598, + "b": 0.14901961386203766, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": -1857.5, + "y": -256, + "width": 15, + "height": 15 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169567", + "name": "Ellipse 1", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 0.6549019813537598, + "b": 0.14901961386203766, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": -1855, + "y": -253.5, + "width": 10, + "height": 10 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": true, + "background": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": -1860, + "y": -261, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169568", + "name": "addreess", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169569", + "name": "10s ago", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "27942:23657", + "text": "26326:30496" + }, + "absoluteBoundingBox": { + "x": -1825, + "y": -272, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1824.1448974609375, + "y": -267.3210144042969, + "width": 49.7109375, + "height": 13.343734741210938 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "10s ago", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": null, + "fontStyle": "Regular", + "fontWeight": 400, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1825, + "y": -272, + "width": 321, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1825, + "y": -272, + "width": 321, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169570", + "name": "Frame 573", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169571", + "name": "publictag", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169572", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": -1452, + "y": -272, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1333.417236328125, + "y": -267.5894775390625, + "width": 52.6204833984375, + "height": 10.74359130859375 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "22 Gwei", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1452, + "y": -272, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1452, + "y": -272, + "width": 172, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169573", + "name": "publictag", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169574", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": -1492, + "y": -248, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "10.81%", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1492, + "y": -248, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "MAX", + "primaryAxisAlignItems": "CENTER", + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1492, + "y": -272, + "width": 212, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1492, + "y": -272, + "width": 212, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169575", + "name": "Frame 574", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169576", + "name": "publictag", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169577", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": -1228, + "y": -272, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1109.772705078125, + "y": -267.5894775390625, + "width": 52.9759521484375, + "height": 10.74359130859375 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "24 Gwei", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1228, + "y": -272, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1228, + "y": -272, + "width": 172, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169578", + "name": "publictag", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:169579", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": -1268, + "y": -248, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "10.81%", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1268, + "y": -248, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "MAX", + "primaryAxisAlignItems": "CENTER", + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1268, + "y": -272, + "width": 212, + "height": 20 + }, + "absoluteRenderBounds": { + "x": -1268, + "y": -272, + "width": 212, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169580", + "name": "%", + "visible": false, + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.1764705926179886, + "g": 0.21568627655506134, + "b": 0.2823529541492462, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "28663:36411", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": -1180, + "y": -269, + "width": 168.5, + "height": 44 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 1, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "characters": "13.16943790%", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:169581", + "name": "txn", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": -1044, + "y": -277, + "width": 212, + "height": 30 + }, + "absoluteRenderBounds": { + "x": -885.731689453125, + "y": -267.5894775390625, + "width": 52.93499755859375, + "height": 10.74359130859375 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "FILL", + "characters": "26 Gwei", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "cornerRadius": 12, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "primaryAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "paddingLeft": 12, + "paddingRight": 12, + "paddingTop": 8, + "paddingBottom": 8, + "itemSpacing": 12, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": -1934, + "y": -285, + "width": 1114, + "height": 46 + }, + "absoluteRenderBounds": { + "x": -1934, + "y": -285, + "width": 1114, + "height": 46 + }, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 0, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + "components": { + "28663:36787": { + "key": "e866e0a5cc5940dd32387da0dd9546d84d6eba2e", + "name": "Label=False, Skin=Light", + "description": "", + "remote": true, + "componentSetId": "28663:36786", + "documentationLinks": [] + } + }, + "componentSets": { + "28663:36786": { + "key": "31f14819149d5456f07456844a5e8062f39c19ea", + "name": "Loaders/Circular-Progress", + "description": "The CircularProgress component is used to indicate the progress for determinate and indeterminate processes.", + "remote": true + } + }, + "schemaVersion": 0, + "styles": { + "27942:24008": { + "key": "e1032c365345e677b2587560f576cf77437d18ef", + "name": "🖤 Dark/button.primary", + "styleType": "FILL", + "remote": true, + "description": "" + }, + "26350:73382": { + "key": "499c0b67945e223f17b26495a360c3e14fb1d178", + "name": "🔠 Text - Inter/text-sm/font-bold", + "styleType": "TEXT", + "remote": true, + "description": "" + }, + "28663:36784": { + "key": "b24a3e9219f29aec38d96317c5fb48390b799b7c", + "name": "gray/200", + "styleType": "FILL", + "remote": true, + "description": "" + }, + "28663:36785": { + "key": "b75000e4bbe3cf3f6a10c6b0c505d4ed943065af", + "name": "gray/100", + "styleType": "FILL", + "remote": true, + "description": "" + }, + "27942:23987": { + "key": "96c81a841ef5448be7e26d2155a0ff048c7fc22e", + "name": "💙 Selected options/selected.option.bg", + "styleType": "FILL", + "remote": true, + "description": "500" + }, + "27942:23657": { + "key": "c431efd0bd868714880ae8c6ab25aa6f7714249b", + "name": "🤍 Light/text.secondary", + "styleType": "FILL", + "remote": true, + "description": "Gray 500 for text/icons\nLight theme" + }, + "26326:30496": { + "key": "1b455e9d05f7eb0b8a3b60e04ba2c03fe511bcfe", + "name": "🔠 Text - Inter/text-sm/font-normal", + "styleType": "TEXT", + "remote": true, + "description": "" + }, + "27942:23926": { + "key": "614d9ff84c0606312c40a5b492fab62943fdacc3", + "name": "🤍 Light/text.primary", + "styleType": "FILL", + "remote": true, + "description": "text for light theme" + }, + "26350:73312": { + "key": "8b3e2d6905a225484227b582a4028e78a967789a", + "name": "🔠 Text - Inter/text-sm/font-medium", + "styleType": "TEXT", + "remote": true, + "description": "" + }, + "28663:36411": { + "key": "e673d9fbc07f41d8f26354565c966615c926f0e1", + "name": "gray/700", + "styleType": "FILL", + "remote": true, + "description": "" + } + } + } + } +} diff --git a/tools/design-readout/fixtures/22842-174340-light.json b/tools/design-readout/fixtures/22842-174340-light.json new file mode 100644 index 00000000000..1ea7eb02019 --- /dev/null +++ b/tools/design-readout/fixtures/22842-174340-light.json @@ -0,0 +1,1986 @@ +{ + "name": "🖥️ Blockscout desktop pages", + "lastModified": "2026-09-30T06:27:22Z", + "thumbnailUrl": "https://s3-alpha.figma.com/thumbnails/9426e8c7-5f2c-4b82-bd43-d73a3f4b5b2b?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQ4GOSFWCQPXYJSOJ%2F20261004%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20261004T120000Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=27a4792ffc53b65478919980e26efa1215fa79716838a0dec3c4aabb087ea335", + "version": "2405407072828039987", + "role": "viewer", + "editorType": "figma", + "linkAccess": "view", + "nodes": { + "22842:174340": { + "document": { + "id": "22842:174340", + "name": "Holders_1st_line_public name", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174341", + "name": "rank", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174342", + "name": "balance", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174343", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.16862745583057404, + "g": 0.42352941632270813, + "b": 0.6901960968971252, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:24008", + "text": "26350:73382" + }, + "absoluteBoundingBox": { + "x": 34, + "y": 891, + "width": 60, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 34.7109375, + "y": 895.6740112304688, + "width": 58.13654327392578, + "height": 10.4652099609375 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "1248139", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Bold", + "fontStyle": "Bold", + "fontWeight": 700, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "TOP", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174344", + "name": "total", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174345", + "name": "total", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 102, + "y": 891, + "width": 118, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174346", + "name": "Frame 150", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174347", + "name": "Loaders/Circular-Progress", + "visible": false, + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "28663:36787", + "componentProperties": { + "Label": { + "value": "False", + "type": "VARIANT", + "boundVariables": {} + }, + "Skin": { + "value": "Light", + "type": "VARIANT", + "boundVariables": {} + } + }, + "overrides": [ + { + "id": "22842:174347", + "overriddenFields": [ + "fills", + "height", + "preserveRatio", + "width" + ] + }, + { + "id": "I22842:174347;623:9319", + "overriddenFields": [ + "visible" + ] + }, + { + "id": "I22842:174347;624:9145", + "overriddenFields": [ + "arcData", + "inheritFillStyleId" + ] + }, + { + "id": "I22842:174347;624:9149", + "overriddenFields": [ + "visible" + ] + } + ], + "children": [ + { + "id": "I22842:174347;623:9319", + "name": "Width", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.886274516582489, + "g": 0.9098039269447327, + "b": 0.9411764740943909, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "28663:36784" + }, + "absoluteBoundingBox": { + "x": 102, + "y": 891, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "isMask": true, + "maskType": "ALPHA", + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I22842:174347;624:9149", + "name": "Bar", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.929411768913269, + "g": 0.9490196108818054, + "b": 0.9686274528503418, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "28663:36785" + }, + "absoluteBoundingBox": { + "x": 102, + "y": 891, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I22842:174347;624:9145", + "name": "Progress", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.1921568661928177, + "g": 0.5098039507865906, + "b": 0.8078431487083435, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "27942:23987" + }, + "absoluteBoundingBox": { + "x": 102, + "y": 891, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 4.71238899230957, + "endingAngle": 9.676105499267578, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 102, + "y": 891, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174348", + "name": "10s ago", + "visible": false, + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "27942:23657", + "text": "26326:30496" + }, + "absoluteBoundingBox": { + "x": 102, + "y": 891, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "characters": "10s ago", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": null, + "fontStyle": "Regular", + "fontWeight": 400, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "itemSpacing": 5, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 102, + "y": 891, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 102, + "y": 891, + "width": 52, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 102, + "y": 891, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 102, + "y": 891, + "width": 52, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 34, + "y": 891, + "width": 120, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 34, + "y": 891, + "width": 120, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "primaryAxisSizingMode": "FIXED", + "primaryAxisAlignItems": "CENTER", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 34, + "y": 886, + "width": 85, + "height": 30 + }, + "absoluteRenderBounds": { + "x": 34, + "y": 886, + "width": 120, + "height": 30 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174349", + "name": "728972_gold_medal_award_badge_prize_icon 1", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174350", + "name": "Group", + "type": "GROUP", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174351", + "name": "Group", + "type": "GROUP", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174352", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.95686274766922, + "g": 0.26274511218070984, + "b": 0.21176470816135406, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": 97.25003814697266, + "y": 902, + "width": 17.49999237060547, + "height": 6.726093769073486 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 97.25003814697266, + "y": 902, + "width": 17.49999237060547, + "height": 6.726093769073486 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 97.25003814697266, + "y": 902, + "width": 17.49999237060547, + "height": 6.726093769073486 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174353", + "name": "Vector", + "visible": false, + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 0.7568627595901489, + "b": 0.027450980618596077, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": 101, + "y": 909.5, + "width": 10, + "height": 10 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174354", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 0.6549019813537598, + "b": 0.14901961386203766, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": 98.5, + "y": 907, + "width": 15, + "height": 15 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174355", + "name": "Ellipse 1", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 0.6549019813537598, + "b": 0.14901961386203766, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": 101, + "y": 909.5, + "width": 10, + "height": 10 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": true, + "background": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 96, + "y": 902, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174356", + "name": "addreess", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174357", + "name": "10s ago", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "27942:23657", + "text": "26326:30496" + }, + "absoluteBoundingBox": { + "x": 131, + "y": 891, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 131.85511779785156, + "y": 895.678955078125, + "width": 49.7109375, + "height": 13.34375 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "10s ago", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": null, + "fontStyle": "Regular", + "fontWeight": 400, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 131, + "y": 891, + "width": 321, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 131, + "y": 891, + "width": 321, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174358", + "name": "Frame 573", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174359", + "name": "publictag", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174360", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 504, + "y": 891, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 637.6553344726562, + "y": 894.5454711914062, + "width": 37.51318359375, + "height": 12.72723388671875 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "$0.56", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 504, + "y": 891, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 504, + "y": 891, + "width": 172, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174361", + "name": "publictag", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174362", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 464, + "y": 915, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "10.81%", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 464, + "y": 915, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "MAX", + "primaryAxisAlignItems": "CENTER", + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 464, + "y": 891, + "width": 212, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 464, + "y": 891, + "width": 212, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174363", + "name": "Frame 574", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174364", + "name": "publictag", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174365", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 728, + "y": 891, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 861.5186157226562, + "y": 894.5454711914062, + "width": 37.64990234375, + "height": 12.72723388671875 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "$0.36", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 728, + "y": 891, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 728, + "y": 891, + "width": 172, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174366", + "name": "publictag", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:174367", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 688, + "y": 915, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "10.81%", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 688, + "y": 915, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "MAX", + "primaryAxisAlignItems": "CENTER", + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 688, + "y": 891, + "width": 212, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 688, + "y": 891, + "width": 212, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174368", + "name": "%", + "visible": false, + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.1764705926179886, + "g": 0.21568627655506134, + "b": 0.2823529541492462, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "28663:36411", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 776, + "y": 894, + "width": 168.5, + "height": 44 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 1, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "characters": "13.16943790%", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:174369", + "name": "txn", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 912, + "y": 886, + "width": 212, + "height": 30 + }, + "absoluteRenderBounds": { + "x": 1085.6553955078125, + "y": 894.5454711914062, + "width": 37.5130615234375, + "height": 12.72723388671875 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "FILL", + "characters": "$0.56", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 5, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "cornerRadius": 12, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "primaryAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "paddingLeft": 12, + "paddingRight": 12, + "paddingTop": 8, + "paddingBottom": 8, + "itemSpacing": 12, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 22, + "y": 878, + "width": 1114, + "height": 46 + }, + "absoluteRenderBounds": { + "x": 22, + "y": 878, + "width": 1114, + "height": 46 + }, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 0, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + "components": { + "28663:36787": { + "key": "e866e0a5cc5940dd32387da0dd9546d84d6eba2e", + "name": "Label=False, Skin=Light", + "description": "", + "remote": true, + "componentSetId": "28663:36786", + "documentationLinks": [] + } + }, + "componentSets": { + "28663:36786": { + "key": "31f14819149d5456f07456844a5e8062f39c19ea", + "name": "Loaders/Circular-Progress", + "description": "The CircularProgress component is used to indicate the progress for determinate and indeterminate processes.", + "remote": true + } + }, + "schemaVersion": 0, + "styles": { + "27942:24008": { + "key": "e1032c365345e677b2587560f576cf77437d18ef", + "name": "🖤 Dark/button.primary", + "styleType": "FILL", + "remote": true, + "description": "" + }, + "26350:73382": { + "key": "499c0b67945e223f17b26495a360c3e14fb1d178", + "name": "🔠 Text - Inter/text-sm/font-bold", + "styleType": "TEXT", + "remote": true, + "description": "" + }, + "28663:36784": { + "key": "b24a3e9219f29aec38d96317c5fb48390b799b7c", + "name": "gray/200", + "styleType": "FILL", + "remote": true, + "description": "" + }, + "28663:36785": { + "key": "b75000e4bbe3cf3f6a10c6b0c505d4ed943065af", + "name": "gray/100", + "styleType": "FILL", + "remote": true, + "description": "" + }, + "27942:23987": { + "key": "96c81a841ef5448be7e26d2155a0ff048c7fc22e", + "name": "💙 Selected options/selected.option.bg", + "styleType": "FILL", + "remote": true, + "description": "500" + }, + "27942:23657": { + "key": "c431efd0bd868714880ae8c6ab25aa6f7714249b", + "name": "🤍 Light/text.secondary", + "styleType": "FILL", + "remote": true, + "description": "Gray 500 for text/icons\nLight theme" + }, + "26326:30496": { + "key": "1b455e9d05f7eb0b8a3b60e04ba2c03fe511bcfe", + "name": "🔠 Text - Inter/text-sm/font-normal", + "styleType": "TEXT", + "remote": true, + "description": "" + }, + "27942:23926": { + "key": "614d9ff84c0606312c40a5b492fab62943fdacc3", + "name": "🤍 Light/text.primary", + "styleType": "FILL", + "remote": true, + "description": "text for light theme" + }, + "26350:73312": { + "key": "8b3e2d6905a225484227b582a4028e78a967789a", + "name": "🔠 Text - Inter/text-sm/font-medium", + "styleType": "TEXT", + "remote": true, + "description": "" + }, + "28663:36411": { + "key": "e673d9fbc07f41d8f26354565c966615c926f0e1", + "name": "gray/700", + "styleType": "FILL", + "remote": true, + "description": "" + } + } + } + } +} diff --git a/tools/design-readout/fixtures/22842-178383-dark.json b/tools/design-readout/fixtures/22842-178383-dark.json new file mode 100644 index 00000000000..dbbb6484e20 --- /dev/null +++ b/tools/design-readout/fixtures/22842-178383-dark.json @@ -0,0 +1,2000 @@ +{ + "name": "🖥️ Blockscout desktop pages", + "lastModified": "2026-09-30T06:27:22Z", + "thumbnailUrl": "https://s3-alpha.figma.com/thumbnails/9426e8c7-5f2c-4b82-bd43-d73a3f4b5b2b?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQ4GOSFWCQPXYJSOJ%2F20261004%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20261004T120000Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=27a4792ffc53b65478919980e26efa1215fa79716838a0dec3c4aabb087ea335", + "version": "2405407072828039987", + "role": "viewer", + "editorType": "figma", + "linkAccess": "view", + "nodes": { + "22842:178383": { + "document": { + "id": "22842:178383", + "name": "Holders_1st_line_public name", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178384", + "name": "rank", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178385", + "name": "balance", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178386", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.38823530077934265, + "g": 0.7019608020782471, + "b": 0.929411768913269, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27945:55652", + "text": "26350:73382" + }, + "absoluteBoundingBox": { + "x": 1473, + "y": 869, + "width": 60, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 1473.7109375, + "y": 873.6740112304688, + "width": 58.1365966796875, + "height": 10.4652099609375 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "1248139", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Bold", + "fontStyle": "Bold", + "fontWeight": 700, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "TOP", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178387", + "name": "total", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178388", + "name": "total", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 1541, + "y": 869, + "width": 118, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178389", + "name": "Frame 150", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178390", + "name": "Loaders/Circular-Progress", + "visible": false, + "type": "INSTANCE", + "scrollBehavior": "SCROLLS", + "componentId": "28663:36787", + "componentProperties": { + "Label": { + "value": "False", + "type": "VARIANT", + "boundVariables": {} + }, + "Skin": { + "value": "Light", + "type": "VARIANT", + "boundVariables": {} + } + }, + "overrides": [ + { + "id": "22842:178390", + "overriddenFields": [ + "fills", + "height", + "preserveRatio", + "width" + ] + }, + { + "id": "I22842:178390;623:9319", + "overriddenFields": [ + "visible" + ] + }, + { + "id": "I22842:178390;624:9145", + "overriddenFields": [ + "arcData", + "inheritFillStyleId" + ] + }, + { + "id": "I22842:178390;624:9149", + "overriddenFields": [ + "visible" + ] + } + ], + "children": [ + { + "id": "I22842:178390;623:9319", + "name": "Width", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.886274516582489, + "g": 0.9098039269447327, + "b": 0.9411764740943909, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "28663:36784" + }, + "absoluteBoundingBox": { + "x": 1541, + "y": 869, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "isMask": true, + "maskType": "ALPHA", + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I22842:178390;624:9149", + "name": "Bar", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.929411768913269, + "g": 0.9490196108818054, + "b": 0.9686274528503418, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "28663:36785" + }, + "absoluteBoundingBox": { + "x": 1541, + "y": 869, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "I22842:178390;624:9145", + "name": "Progress", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.1921568661928177, + "g": 0.5098039507865906, + "b": 0.8078431487083435, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "styles": { + "fill": "27942:23987" + }, + "absoluteBoundingBox": { + "x": 1541, + "y": 869, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 4.71238899230957, + "endingAngle": 9.676105499267578, + "innerRadius": 0.800000011920929 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 1541, + "y": 869, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178391", + "name": "10s ago", + "visible": false, + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.4431372582912445, + "g": 0.501960813999176, + "b": 0.5882353186607361, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "27942:23657", + "text": "26326:30496" + }, + "absoluteBoundingBox": { + "x": 1541, + "y": 869, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "characters": "10s ago", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": null, + "fontStyle": "Regular", + "fontWeight": 400, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "itemSpacing": 5, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 1541, + "y": 869, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 1541, + "y": 869, + "width": 52, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 1541, + "y": 869, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 1541, + "y": 869, + "width": 52, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 1473, + "y": 869, + "width": 120, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 1473, + "y": 869, + "width": 120, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "primaryAxisSizingMode": "FIXED", + "primaryAxisAlignItems": "CENTER", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 1473, + "y": 864, + "width": 85, + "height": 30 + }, + "absoluteRenderBounds": { + "x": 1473, + "y": 864, + "width": 120, + "height": 30 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178392", + "name": "728972_gold_medal_award_badge_prize_icon 1", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178393", + "name": "Group", + "type": "GROUP", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178394", + "name": "Group", + "type": "GROUP", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178395", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.95686274766922, + "g": 0.26274511218070984, + "b": 0.21176470816135406, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": 1536.25, + "y": 880, + "width": 17.49999237060547, + "height": 6.726093769073486 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 1536.25, + "y": 880, + "width": 17.49999237060547, + "height": 6.726093769073486 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 1536.25, + "y": 880, + "width": 17.49999237060547, + "height": 6.726093769073486 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178396", + "name": "Vector", + "visible": false, + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 0.7568627595901489, + "b": 0.027450980618596077, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": 1540, + "y": 887.5, + "width": 10, + "height": 10 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178397", + "name": "Vector", + "type": "VECTOR", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 0.6549019813537598, + "b": 0.14901961386203766, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": 1537.5, + "y": 885, + "width": 15, + "height": 15 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178398", + "name": "Ellipse 1", + "type": "ELLIPSE", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 0.6549019813537598, + "b": 0.14901961386203766, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "absoluteBoundingBox": { + "x": 1540, + "y": 887.5, + "width": 10, + "height": 10 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "SCALE", + "horizontal": "SCALE" + }, + "effects": [], + "arcData": { + "startingAngle": 0, + "endingAngle": 6.2831854820251465, + "innerRadius": 0 + }, + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": true, + "background": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "fills": [ + { + "blendMode": "NORMAL", + "visible": false, + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "absoluteBoundingBox": { + "x": 1535, + "y": 880, + "width": 20, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178399", + "name": "addreess", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178400", + "name": "10s ago", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.6274510025978088, + "g": 0.6823529601097107, + "b": 0.7529411911964417, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "27942:23658", + "text": "26326:30496" + }, + "absoluteBoundingBox": { + "x": 1570, + "y": 869, + "width": 52, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 1570.8551025390625, + "y": 873.678955078125, + "width": 49.7109375, + "height": 13.34375 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "characters": "10s ago", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": null, + "fontStyle": "Regular", + "fontWeight": 400, + "textAutoResize": "WIDTH_AND_HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "LEFT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 3, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "itemSpacing": 8, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 1570, + "y": 869, + "width": 321, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 1570, + "y": 869, + "width": 321, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178401", + "name": "Frame 573", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178402", + "name": "publictag", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178403", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23927", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 1943.3333740234375, + "y": 869, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 2076.98876953125, + "y": 872.5454711914062, + "width": 37.51318359375, + "height": 12.72723388671875 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "$0.56", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 1943.3333740234375, + "y": 869, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 1943.3333740234375, + "y": 869, + "width": 172.0001220703125, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178404", + "name": "publictag", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178405", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 1903, + "y": 893, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "10.81%", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 1903, + "y": 893, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "MAX", + "primaryAxisAlignItems": "CENTER", + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 1903, + "y": 869, + "width": 212.3333282470703, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 1903, + "y": 869, + "width": 212.33349609375, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178406", + "name": "Frame 574", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178407", + "name": "publictag", + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178408", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23927", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 2167.66650390625, + "y": 869, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 2301.18505859375, + "y": 872.5454711914062, + "width": 37.64990234375, + "height": 12.72723388671875 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "$0.36", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 2167.66650390625, + "y": 869, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 2167.66650390625, + "y": 869, + "width": 172, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178409", + "name": "publictag", + "visible": false, + "type": "FRAME", + "scrollBehavior": "SCROLLS", + "children": [ + { + "id": "22842:178410", + "name": "Asset Name Copy 2", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.062745101749897, + "g": 0.06666667014360428, + "b": 0.07058823853731155, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 0, + "strokeAlign": "CENTER", + "styles": { + "fill": "27942:23926", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 2127.333251953125, + "y": 893, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "HUG", + "characters": "10.81%", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "textAutoResize": "HEIGHT", + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "itemSpacing": 10, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 2127.333251953125, + "y": 893, + "width": 172, + "height": 20 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 0, + "layoutSizingHorizontal": "HUG", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "VERTICAL", + "counterAxisSizingMode": "FIXED", + "counterAxisAlignItems": "MAX", + "primaryAxisAlignItems": "CENTER", + "itemSpacing": 4, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 2127.333251953125, + "y": 869, + "width": 212.33334350585938, + "height": 20 + }, + "absoluteRenderBounds": { + "x": 2127.333251953125, + "y": 869, + "width": 212.33334350585938, + "height": 20 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "INHERIT", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178411", + "name": "%", + "visible": false, + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 0.1764705926179886, + "g": 0.21568627655506134, + "b": 0.2823529541492462, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "28663:36411", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 2215, + "y": 872, + "width": 168.5, + "height": 44 + }, + "absoluteRenderBounds": null, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 1, + "layoutSizingHorizontal": "FIXED", + "layoutSizingVertical": "FIXED", + "characters": "13.16943790%", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + { + "id": "22842:178412", + "name": "txn", + "type": "TEXT", + "scrollBehavior": "SCROLLS", + "blendMode": "PASS_THROUGH", + "fills": [ + { + "opacity": 0.800000011920929, + "blendMode": "NORMAL", + "type": "SOLID", + "color": { + "r": 1, + "g": 1, + "b": 1, + "a": 1 + } + } + ], + "strokes": [], + "strokeWeight": 1, + "strokeAlign": "OUTSIDE", + "styles": { + "fill": "27942:23927", + "text": "26350:73312" + }, + "absoluteBoundingBox": { + "x": 2351.66650390625, + "y": 864, + "width": 212.33334350585938, + "height": 30 + }, + "absoluteRenderBounds": { + "x": 2525.6552734375, + "y": 872.5454711914062, + "width": 37.51318359375, + "height": 12.72723388671875 + }, + "constraints": { + "vertical": "TOP", + "horizontal": "LEFT" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 1, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "FILL", + "characters": "$0.56", + "characterStyleOverrides": [], + "styleOverrideTable": {}, + "lineTypes": [ + "NONE" + ], + "lineIndentations": [ + 0 + ], + "style": { + "fontFamily": "Inter", + "fontPostScriptName": "Inter-Medium", + "fontStyle": "Medium", + "fontWeight": 500, + "fontSize": 14, + "textAlignHorizontal": "RIGHT", + "textAlignVertical": "CENTER", + "letterSpacing": 0, + "lineHeightPx": 20, + "lineHeightPercent": 118.04158782958984, + "lineHeightPercentFontSize": 142.85714721679688, + "lineHeightUnit": "PIXELS" + }, + "layoutVersion": 4, + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + } + ], + "blendMode": "PASS_THROUGH", + "clipsContent": false, + "background": [], + "fills": [], + "strokes": [], + "cornerRadius": 12, + "cornerSmoothing": 0, + "strokeWeight": 1, + "strokeAlign": "INSIDE", + "backgroundColor": { + "r": 0, + "g": 0, + "b": 0, + "a": 0 + }, + "layoutMode": "HORIZONTAL", + "primaryAxisSizingMode": "FIXED", + "counterAxisAlignItems": "CENTER", + "paddingLeft": 12, + "paddingRight": 12, + "paddingTop": 8, + "paddingBottom": 8, + "itemSpacing": 12, + "layoutWrap": "NO_WRAP", + "absoluteBoundingBox": { + "x": 1461, + "y": 856, + "width": 1115, + "height": 46 + }, + "absoluteRenderBounds": { + "x": 1461, + "y": 856, + "width": 1115, + "height": 46 + }, + "constraints": { + "vertical": "CENTER", + "horizontal": "CENTER" + }, + "layoutAlign": "STRETCH", + "layoutGrow": 0, + "layoutSizingHorizontal": "FILL", + "layoutSizingVertical": "HUG", + "effects": [], + "interactions": [], + "complexStrokeProperties": { + "strokeType": "BASIC" + } + }, + "components": { + "28663:36787": { + "key": "e866e0a5cc5940dd32387da0dd9546d84d6eba2e", + "name": "Label=False, Skin=Light", + "description": "", + "remote": true, + "componentSetId": "28663:36786", + "documentationLinks": [] + } + }, + "componentSets": { + "28663:36786": { + "key": "31f14819149d5456f07456844a5e8062f39c19ea", + "name": "Loaders/Circular-Progress", + "description": "The CircularProgress component is used to indicate the progress for determinate and indeterminate processes.", + "remote": true + } + }, + "schemaVersion": 0, + "styles": { + "27945:55652": { + "key": "97453f8cee4d797c9faf735ebb2f185f2918798f", + "name": "🖤 Dark/link.primary", + "styleType": "FILL", + "remote": true, + "description": "" + }, + "26350:73382": { + "key": "499c0b67945e223f17b26495a360c3e14fb1d178", + "name": "🔠 Text - Inter/text-sm/font-bold", + "styleType": "TEXT", + "remote": true, + "description": "" + }, + "28663:36784": { + "key": "b24a3e9219f29aec38d96317c5fb48390b799b7c", + "name": "gray/200", + "styleType": "FILL", + "remote": true, + "description": "" + }, + "28663:36785": { + "key": "b75000e4bbe3cf3f6a10c6b0c505d4ed943065af", + "name": "gray/100", + "styleType": "FILL", + "remote": true, + "description": "" + }, + "27942:23987": { + "key": "96c81a841ef5448be7e26d2155a0ff048c7fc22e", + "name": "💙 Selected options/selected.option.bg", + "styleType": "FILL", + "remote": true, + "description": "500" + }, + "27942:23657": { + "key": "c431efd0bd868714880ae8c6ab25aa6f7714249b", + "name": "🤍 Light/text.secondary", + "styleType": "FILL", + "remote": true, + "description": "Gray 500 for text/icons\nLight theme" + }, + "26326:30496": { + "key": "1b455e9d05f7eb0b8a3b60e04ba2c03fe511bcfe", + "name": "🔠 Text - Inter/text-sm/font-normal", + "styleType": "TEXT", + "remote": true, + "description": "" + }, + "27942:23658": { + "key": "96caacc999ed614827c7aebf3a96d68f844ebd78", + "name": "🖤 Dark/text.secondary", + "styleType": "FILL", + "remote": true, + "description": "Gray 400 text/icons\nDark theme" + }, + "27942:23927": { + "key": "19b75fefccd1a81eaabeb4d81ba33f6f97dfb030", + "name": "🖤 Dark/text.primary", + "styleType": "FILL", + "remote": true, + "description": "text for dark theme" + }, + "26350:73312": { + "key": "8b3e2d6905a225484227b582a4028e78a967789a", + "name": "🔠 Text - Inter/text-sm/font-medium", + "styleType": "TEXT", + "remote": true, + "description": "" + }, + "27942:23926": { + "key": "614d9ff84c0606312c40a5b492fab62943fdacc3", + "name": "🤍 Light/text.primary", + "styleType": "FILL", + "remote": true, + "description": "text for light theme" + }, + "28663:36411": { + "key": "e673d9fbc07f41d8f26354565c966615c926f0e1", + "name": "gray/700", + "styleType": "FILL", + "remote": true, + "description": "" + } + } + } + } +} diff --git a/tools/design-readout/index.ts b/tools/design-readout/index.ts new file mode 100644 index 00000000000..27cfaa39d68 --- /dev/null +++ b/tools/design-readout/index.ts @@ -0,0 +1,44 @@ +/* eslint-disable no-console -- the entry point reports a failed run on stderr */ +import { parseArgs } from './cli/args'; +import { runCalibrate, runCorrection, runNote, runOverride, runReadout, runRefresh } from './cli/commands'; +import { FigmaFetchError } from './fetch/figma'; + +async function main(): Promise<void> { + const parsed = parseArgs(process.argv.slice(2)); + switch (parsed.kind) { + case 'correct': + runCorrection(parsed.ref, parsed.correction); + return; + case 'override': + runOverride(parsed.ref, parsed.override); + return; + case 'note': + runNote(parsed.ref, parsed.note); + return; + case 'calibrate': + runCalibrate(); + return; + case 'refresh': + await runRefresh(parsed.entry); + return; + case 'readout': + await runReadout(parsed.ref, parsed.options); + } +} + +// run.sh always executes the compiled `tools/design-readout/dist/tools/design-readout/index.js`, so that path +// is what marks this module as the process entry point; under vitest the entry is vitest's own binary. +const CLI_ENTRY_PATH = 'design-readout/dist/tools/design-readout/index.js'; + +function isProcessEntryPoint(): boolean { + const entry = process.argv[1]?.replace(/\\/g, '/'); + return entry !== undefined && entry.endsWith(CLI_ENTRY_PATH); +} + +if (isProcessEntryPoint()) { + main().catch((error: unknown) => { + const message = error instanceof Error ? error.message : String(error); + console.error(error instanceof FigmaFetchError ? message : `design:readout failed: ${ message }`); + process.exitCode = 1; + }); +} diff --git a/tools/design-readout/layout-conventions.md b/tools/design-readout/layout-conventions.md new file mode 100644 index 00000000000..aba1a9e43fb --- /dev/null +++ b/tools/design-readout/layout-conventions.md @@ -0,0 +1,6 @@ +| What the mockup shows / the question | Convention | Unless | Code home | +| --- | --- | --- | --- | +| a list on mobile drawn as cards, or as a table narrower than its columns | a horizontally scrollable table, never a card variant | | `src/toolkit/chakra/table.tsx` | +| pagination controls anywhere on the screen | pagination sits in the `ActionBar` | the mockup puts it in the tabs row | `src/shell/page/action-bar/ActionBar.tsx`, `src/shared/pagination/` | +| a price-like cell (fiat, gas price, fee) in a table column | right-aligned, under an `isNumeric` column header | | `src/toolkit/chakra/table.tsx` | +| a row divider drawn as its own layer (a line or a "divider" icon) between table rows | the row's bottom border from the `line` table variant; no separate divider element | | `src/toolkit/chakra/table.tsx` | diff --git a/tools/design-readout/recognize/colormap.spec.ts b/tools/design-readout/recognize/colormap.spec.ts new file mode 100644 index 00000000000..038abe36665 --- /dev/null +++ b/tools/design-readout/recognize/colormap.spec.ts @@ -0,0 +1,201 @@ +import { describe, expect, it } from 'vitest'; + +import type { ColorMap, ColorValue } from './colormap'; +import { buildColorMap, buildThemeColorMap, colorKey, detectColorMode, lookupTokens, parseColorLiteral } from './colormap'; + +// Built inside each test, not at module level: Stryker activates a mutant only once the tests start. +const themeMap = (): ColorMap => buildThemeColorMap(); + +const opaque = (hex: string): ColorValue => ({ hex, alpha: 1 }); + +describe('parseColorLiteral and colorKey', () => { + it.each([ + [ '#ffffff', '#FFFFFF' ], + [ '#FFF', '#FFFFFF' ], + [ 'RGBA(255, 255, 255, 0.80)', '#FFFFFF/80' ], + [ 'rgba(144, 205, 244, 0.3)', '#90CDF4/30' ], + [ 'rgba(144, 205, 244, 0)', '#90CDF4/0' ], + [ 'rgb(16, 17, 18)', '#101112' ], + ])('%s is keyed as %s', (literal, key) => { + const value = parseColorLiteral(literal); + expect(value).toBeDefined(); + expect(colorKey(value as ColorValue)).toBe(key); + }); + + it('keys a Figma float alpha by its whole percent and treats 1 as opaque', () => { + expect(colorKey({ hex: '#ffffff', alpha: 0.800000011920929 })).toBe('#FFFFFF/80'); + expect(colorKey({ hex: '#ffffff', alpha: 0.999 })).toBe('#FFFFFF'); + }); + + it('rejects anything that is not a hex or rgb(a) literal', () => { + expect(parseColorLiteral('{colors.blue.500}')).toBeUndefined(); + expect(parseColorLiteral('transparent')).toBeUndefined(); + }); +}); + +describe('buildColorMap', () => { + const palette = { + blue: { '500': { value: '#3182CE' }, '300': { value: '#63B3ED' } }, + whiteAlpha: { '800': { value: 'RGBA(255, 255, 255, 0.80)' } }, + orange: { '800': { value: '#7B341E' } }, + white: { value: '#ffffff' }, + transparent: { value: 'transparent' }, + list: [ { value: '#111111' } ], + nothing: null, + }; + const themeDefaults = { + text: { primary: { _light: { value: '{colors.blue.500}' }, _dark: { value: '{colors.whiteAlpha.800}' } } }, + link: { primary: { _light: { value: '{colors.blue.500}' }, _dark: { value: '{colors.blue.300}' } } }, + stats: { bg: { _light: { value: '#F7FAFC' }, _dark: { value: '{colors.whiteAlpha.800}' } }, border: { value: '#222222' } }, + ghost: { bg: { _light: { value: 'transparent' } } }, + }; + const semanticColors = { + text: { primary: { value: { _light: '{colors.theme.text.primary._light}', _dark: '{colors.theme.text.primary._dark}' } } }, + link: { primary: { DEFAULT: { value: { _light: '{colors.theme.link.primary._light}', _dark: '{colors.theme.link.primary._dark}' } } } }, + heading: { DEFAULT: { value: '{colors.text.primary}' } }, + tooltip: { DEFAULT: { fg: { value: '{colors.white}' } } }, + global: { selection: { bg: { value: { _light: '#E3CFE7', _dark: '#754B7D' } } } }, + alert: { bg: { warning: { value: { _light: '{colors.orange.800}', _dark: '{colors.orange.800/44}' } } } }, + nav: { hover: { value: { _light: '{colors.blue.300}' } } }, + viaDefault: { value: '{colors.link.primary}' }, + viaMode: { value: '{colors.theme.stats.bg}' }, + missing: { value: '{colors.nope.deeper.more}' }, + loopA: { value: '{colors.loopB}' }, + loopB: { value: '{colors.loopA}' }, + ...Object.fromEntries(Array.from({ length: 10 }, (_, hop) => [ `chain${ hop }`, { value: `{colors.${ hop === 9 ? 'white' : `chain${ hop + 1 }` }}` } ])), + chain10: { value: '{colors.chain0}' }, + }; + const build = (): ColorMap => buildColorMap({ palette, themeDefaults, semanticColors }); + const allNames = (map: ColorMap): Array<string> => [ map.palette, map.semantic.light, map.semantic.dark ].flatMap((section) => Object.values(section).flat()); + + it('names every palette color by its path, mode-free', () => { + const map = build(); + expect(map.palette).toEqual({ + '#3182CE': [ 'blue.500' ], + '#63B3ED': [ 'blue.300' ], + '#7B341E': [ 'orange.800' ], + '#FFFFFF': [ 'white' ], + '#FFFFFF/80': [ 'whiteAlpha.800' ], + }); + }); + + it('resolves references through the theme defaults and other semantic tokens down to hex and alpha, per mode', () => { + const map = build(); + expect(map.semantic.light['#3182CE']).toEqual([ 'heading', 'link.primary', 'text.primary', 'theme.link.primary', 'theme.text.primary', 'viaDefault' ]); + expect(map.semantic.dark['#FFFFFF/80']).toEqual([ 'heading', 'text.primary', 'theme.stats.bg', 'theme.text.primary', 'viaMode' ]); + expect(map.semantic.dark['#63B3ED']).toEqual([ 'link.primary', 'theme.link.primary', 'viaDefault' ]); + expect(map.semantic.light['#F7FAFC']).toEqual([ 'theme.stats.bg', 'viaMode' ]); + }); + + it('follows a reference chain ten hops deep and gives up on the eleventh, so a cycle resolves to nothing', () => { + const map = build(); + expect(map.semantic.light['#FFFFFF']).toEqual([ ...Array.from({ length: 10 }, (_, hop) => `chain${ hop }`), 'tooltip.fg' ]); + expect(allNames(map)).not.toContain('chain10'); + expect(allNames(map)).not.toContain('loopA'); + expect(allNames(map)).not.toContain('loopB'); + }); + + it('leaves out a leaf that resolves to no color, a dangling reference, a theme default with no mode, and anything that is not a token tree', () => { + const names = allNames(build()); + expect(names).not.toContain('transparent'); + expect(names).not.toContain('missing'); + expect(names).not.toContain('theme.stats.border'); + expect(names).not.toContain('theme.ghost.bg'); + expect(names.filter((name) => name.startsWith('list'))).toEqual([]); + expect(names).not.toContain('nothing'); + }); + + it('drops DEFAULT segments, keeps literal hex values and applies a /alpha suffix on a reference', () => { + const map = build(); + expect(map.semantic.light['#FFFFFF']).toContain('tooltip.fg'); + expect(map.semantic.light['#E3CFE7']).toEqual([ 'global.selection.bg' ]); + expect(map.semantic.dark['#754B7D']).toEqual([ 'global.selection.bg' ]); + expect(map.semantic.light['#7B341E']).toEqual([ 'alert.bg.warning' ]); + expect(map.semantic.dark['#7B341E/44']).toEqual([ 'alert.bg.warning' ]); + }); + + it('leaves a token out of a mode it has no value for', () => { + const map = build(); + expect(map.semantic.light['#63B3ED']).toEqual([ 'nav.hover' ]); + expect(map.semantic.dark['#63B3ED']).not.toContain('nav.hover'); + }); +}); + +describe('lookupTokens over the real theme', () => { + it('returns every token a hex serves, semantic tokens before palette names', () => { + const tokens = lookupTokens(themeMap(), opaque('#ffffff'), 'light'); + expect(tokens[0]).toBe('bg.primary'); + expect(tokens).toContain('button.solid.text'); + expect(tokens.at(-1)).toBe('white'); + }); + + it('resolves the dark-mode rgba(255,255,255,0.8) to whiteAlpha.800 and text.primary', () => { + const value = parseColorLiteral('rgba(255,255,255,0.8)') as ColorValue; + const tokens = lookupTokens(themeMap(), value, 'dark'); + expect(tokens).toContain('text.primary'); + expect(tokens).toContain('whiteAlpha.800'); + expect(lookupTokens(themeMap(), value, 'light')).toEqual([ 'whiteAlpha.800' ]); + }); + + it('narrows by role through the token path prefix and misses when the role has no token at that hex', () => { + expect(lookupTokens(themeMap(), opaque('#ffffff'), 'light', 'background')).toEqual([ 'bg.primary' ]); + expect(lookupTokens(themeMap(), opaque('#ffffff'), 'light', 'text')).toEqual([]); + expect(lookupTokens(themeMap(), opaque('#718096'), 'light', 'text')).toEqual([ 'link.secondary', 'text.secondary' ]); + expect(lookupTokens(themeMap(), opaque('#718096'), 'light', 'icon')).toEqual([ 'icon.primary' ]); + }); + + it('keeps the badge and tag families in the role their leaf names, so a badge fill resolves its color scheme', () => { + expect(lookupTokens(themeMap(), opaque('#F0FFF4'), 'light', 'background')).toContain('badge.green.bg'); + expect(lookupTokens(themeMap(), opaque('#38A169'), 'light', 'text')).toContain('badge.green.fg'); + expect(lookupTokens(themeMap(), opaque('#38A169'), 'light', 'background')).not.toContain('badge.green.fg'); + expect(lookupTokens(themeMap(), parseColorLiteral('rgba(16,17,18,0.04)') as ColorValue, 'light', 'border')).toContain('tag.root.select.border'); + }); + + it('counts a link as a text color unless its path paints a background', () => { + expect(lookupTokens(themeMap(), opaque('#63B3ED'), 'dark', 'text')).toEqual([ 'link.primary' ]); + expect(lookupTokens(themeMap(), opaque('#ffffff'), 'light')).toContain('link.navigation.bg.group'); + }); + + it('returns nothing for a hex no token serves', () => { + expect(lookupTokens(themeMap(), opaque('#123456'), 'dark')).toEqual([]); + }); +}); + +describe('detectColorMode over the real theme', () => { + const darkText = parseColorLiteral('rgba(255,255,255,0.8)') as ColorValue; + const lightText = parseColorLiteral('rgba(16,17,18,0.8)') as ColorValue; + const lightBackground = opaque('#FFFFFF'); + const darkBackground = opaque('#101112'); + const paletteOnly = opaque('#000000'); + const sharedOnly = parseColorLiteral('rgba(144, 205, 244, 0.3)') as ColorValue; + const balanced = opaque('#6B46C1'); + + it('lets the majority of mode-leaning values decide', () => { + expect(detectColorMode(themeMap(), [ darkText, darkText, lightText ], undefined)) + .toEqual({ mode: 'dark', decidedBy: 'majority', votes: { light: 1, dark: 2 } }); + expect(detectColorMode(themeMap(), [ lightText, lightText, darkText ], lightBackground)).toMatchObject({ mode: 'light', decidedBy: 'majority' }); + }); + + it('does not count a color whose exclusive tokens balance, or that serves only shared tokens, palette names, or nothing', () => { + expect(detectColorMode(themeMap(), [ paletteOnly, sharedOnly, balanced, opaque('#123456'), darkText ], undefined)) + .toMatchObject({ mode: 'dark', votes: { light: 0, dark: 1 } }); + }); + + it('lets a fill with a role vote only with that role\'s tokens', () => { + const gray600 = opaque('#4A5568'); + expect(detectColorMode(themeMap(), [ gray600 ], undefined)).toMatchObject({ mode: 'dark', decidedBy: 'majority' }); + expect(detectColorMode(themeMap(), [ { ...gray600, role: 'text' } ], undefined)).toMatchObject({ mode: 'light', votes: { light: 1, dark: 0 } }); + expect(detectColorMode(themeMap(), [ { ...opaque('#718096'), role: 'text' } ], undefined)).toMatchObject({ mode: 'light', votes: { light: 1, dark: 0 } }); + }); + + it('breaks a tie with the frame background', () => { + expect(detectColorMode(themeMap(), [ darkText, lightText ], darkBackground)) + .toEqual({ mode: 'dark', decidedBy: 'frame-background', votes: { light: 1, dark: 1 } }); + expect(detectColorMode(themeMap(), [], lightBackground)).toMatchObject({ mode: 'light', decidedBy: 'frame-background' }); + }); + + it('falls back to light when neither the values nor the background decide', () => { + expect(detectColorMode(themeMap(), [ paletteOnly ], undefined)).toEqual({ mode: 'light', decidedBy: 'default', votes: { light: 0, dark: 0 } }); + expect(detectColorMode(themeMap(), [], paletteOnly)).toMatchObject({ decidedBy: 'default' }); + }); +}); diff --git a/tools/design-readout/recognize/colormap.ts b/tools/design-readout/recognize/colormap.ts new file mode 100644 index 00000000000..bee3de566c0 --- /dev/null +++ b/tools/design-readout/recognize/colormap.ts @@ -0,0 +1,235 @@ +import { DEFAULT_THEME_COLORS, PALETTE_COLORS } from '../../../src/toolkit/theme/foundations/colorsDefault'; +import { SEMANTIC_TOKENS_DEFAULT } from '../../../src/toolkit/theme/foundations/semanticTokensDefault'; +import { COLOR_ROLE_PATTERNS } from '../config'; + +export type ColorMode = 'light' | 'dark'; +export type ColorRole = keyof typeof COLOR_ROLE_PATTERNS; + +// A resolved color: six upper-case hex digits plus an alpha in [0, 1], where 1 is opaque. +export interface ColorValue { + readonly hex: string; + readonly alpha: number; +} + +// hex (with alpha) → token names. Palette names (`blue.500`, `whiteAlpha.800`) are the same in both +// modes; semantic names (`text.primary`, `button.solid.bg`) resolve per mode. +export interface ColorMap { + readonly palette: Record<string, Array<string>>; + readonly semantic: Record<ColorMode, Record<string, Array<string>>>; +} + +type TokenTree = Record<string, unknown>; + +const MODES: ReadonlyArray<ColorMode> = [ 'light', 'dark' ]; + +// Alpha is keyed as a whole percent: the theme writes two decimals, Figma reports floats like 0.800000011. +const ALPHA_PERCENT = 100; +const OPAQUE_PERCENT = 100; + +// `{colors.a.b}` chains are short; the limit only stops a reference cycle from recursing forever. +const MAX_REFERENCE_DEPTH = 10; + +function channelHex(channel: number): string { + return Math.round(channel).toString(16).padStart(2, '0').toUpperCase(); +} + +export function parseColorLiteral(literal: string): ColorValue | undefined { + const text = literal.trim(); + const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text); + if (hex !== null) { + const digits = hex[1].length === 3 ? hex[1].split('').map((digit) => digit + digit).join('') : hex[1]; + return { hex: `#${ digits.toUpperCase() }`, alpha: 1 }; + } + const rgba = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec(text); + if (rgba !== null) { + const [ , red, green, blue, alpha ] = rgba; + return { hex: `#${ channelHex(Number(red)) }${ channelHex(Number(green)) }${ channelHex(Number(blue)) }`, alpha: alpha === undefined ? 1 : Number(alpha) }; + } + return undefined; +} + +export function colorKey(value: ColorValue): string { + const percent = Math.round(value.alpha * ALPHA_PERCENT); + return percent >= OPAQUE_PERCENT ? value.hex.toUpperCase() : `${ value.hex.toUpperCase() }/${ percent }`; +} + +function isRecord(value: unknown): value is TokenTree { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function walkPath(tree: TokenTree, segments: ReadonlyArray<string>): unknown { + let node: unknown = tree; + for (const segment of segments) { + if (!isRecord(node)) return undefined; + node = node[segment]; + } + return node; +} + +interface TokenReference { + readonly segments: ReadonlyArray<string>; + readonly alphaScale: number; +} + +function parseReference(text: string): TokenReference | undefined { + const match = /^\{colors\.([^}/]+)(?:\/(\d+))?\}$/.exec(text.trim()); + if (match === null) return undefined; + return { segments: match[1].split('.'), alphaScale: match[2] === undefined ? 1 : Number(match[2]) / ALPHA_PERCENT }; +} + +// Where a path lands in the tree: a leaf's `value`, a group's `DEFAULT`, or a theme group keyed by mode. +function valueAt(node: unknown, mode: ColorMode): unknown { + if (!isRecord(node)) return undefined; + if ('value' in node) return node.value; + if (isRecord(node.DEFAULT) && 'value' in node.DEFAULT) return node.DEFAULT.value; + const forMode = node[`_${ mode }`]; + return isRecord(forMode) ? forMode.value : undefined; +} + +function resolveValue(tree: TokenTree, value: unknown, mode: ColorMode, depth: number): ColorValue | undefined { + if (isRecord(value)) return resolveValue(tree, value[`_${ mode }`], mode, depth); + if (typeof value !== 'string') return undefined; + const reference = parseReference(value); + if (reference === undefined) return parseColorLiteral(value); + if (depth >= MAX_REFERENCE_DEPTH) return undefined; + const resolved = resolveValue(tree, valueAt(walkPath(tree, reference.segments), mode), mode, depth + 1); + return resolved === undefined ? undefined : { hex: resolved.hex, alpha: resolved.alpha * reference.alphaScale }; +} + +export function resolveToken(tree: TokenTree, value: unknown, mode: ColorMode): ColorValue | undefined { + return resolveValue(tree, value, mode, 0); +} + +interface TokenLeaf { + readonly name: string; + readonly value: unknown; +} + +// Every `{ value }` leaf under the tree, named by its path the way Chakra names the token: `DEFAULT` +// segments are not part of the name (`tooltip.DEFAULT.bg` is `tooltip.bg`). +function collectLeaves(node: unknown, path: ReadonlyArray<string>, into: Array<TokenLeaf>): void { + if (!isRecord(node)) return; + if ('value' in node) { + into.push({ name: path.filter((segment) => segment !== 'DEFAULT').join('.'), value: node.value }); + return; + } + for (const [ key, child ] of Object.entries(node)) { + collectLeaves(child, [ ...path, key ], into); + } +} + +function addEntry(section: Record<string, Array<string>>, key: string, name: string): void { + section[key] = [ ...(section[key] ?? []), name ]; +} + +function sortSection(section: Record<string, Array<string>>): Record<string, Array<string>> { + return Object.fromEntries(Object.keys(section).sort().map((key) => [ key, [ ...section[key] ].sort() ])); +} + +export interface ThemeSources { + readonly palette: TokenTree; + readonly themeDefaults: TokenTree; + readonly semanticColors: TokenTree; +} + +// A theme default is mode-keyed by its own path (`theme.stats.bg._light`), so the leaf's last segment +// says which mode it belongs to and the token keeps the rest of the path. +function themeLeafMode(leaf: TokenLeaf): { readonly name: string; readonly mode: ColorMode } | undefined { + const mode = MODES.find((candidate) => leaf.name.endsWith(`._${ candidate }`)); + return mode === undefined ? undefined : { name: leaf.name.slice(0, -`._${ mode }`.length), mode }; +} + +export function buildColorMap({ palette, themeDefaults, semanticColors }: ThemeSources): ColorMap { + const tree: TokenTree = { ...palette, theme: themeDefaults, ...semanticColors }; + + const paletteSection: Record<string, Array<string>> = {}; + const paletteLeaves: Array<TokenLeaf> = []; + collectLeaves(palette, [], paletteLeaves); + for (const leaf of paletteLeaves) { + const resolved = resolveToken(tree, leaf.value, 'light'); + if (resolved !== undefined) addEntry(paletteSection, colorKey(resolved), leaf.name); + } + + const semantic = { light: {}, dark: {} } as Record<ColorMode, Record<string, Array<string>>>; + + const themeLeaves: Array<TokenLeaf> = []; + collectLeaves(themeDefaults, [ 'theme' ], themeLeaves); + for (const leaf of themeLeaves) { + const keyed = themeLeafMode(leaf); + if (keyed === undefined) continue; + const resolved = resolveToken(tree, leaf.value, keyed.mode); + if (resolved !== undefined) addEntry(semantic[keyed.mode], colorKey(resolved), keyed.name); + } + + const semanticLeaves: Array<TokenLeaf> = []; + collectLeaves(semanticColors, [], semanticLeaves); + for (const mode of MODES) { + for (const leaf of semanticLeaves) { + const resolved = resolveToken(tree, leaf.value, mode); + if (resolved !== undefined) addEntry(semantic[mode], colorKey(resolved), leaf.name); + } + semantic[mode] = sortSection(semantic[mode]); + } + + return { palette: sortSection(paletteSection), semantic }; +} + +// The map of the shipped theme. Built from the config-free defaults, so an instance's runtime color +// overrides are never in it. +export function buildThemeColorMap(): ColorMap { + return buildColorMap({ palette: PALETTE_COLORS, themeDefaults: DEFAULT_THEME_COLORS, semanticColors: SEMANTIC_TOKENS_DEFAULT.colors }); +} + +const NO_TOKENS: ReadonlyArray<string> = []; + +function semanticTokensFor(map: ColorMap, value: ColorValue, mode: ColorMode): ReadonlyArray<string> { + return map.semantic[mode][colorKey(value)] ?? NO_TOKENS; +} + +// Every token the color serves in the mode, semantic first; a role keeps only the tokens its patterns name. +export function lookupTokens(map: ColorMap, value: ColorValue, mode: ColorMode, role?: ColorRole): Array<string> { + const all = [ ...semanticTokensFor(map, value, mode), ...(map.palette[colorKey(value)] ?? NO_TOKENS) ]; + if (role === undefined) return all; + const patterns: ReadonlyArray<RegExp> = COLOR_ROLE_PATTERNS[role]; + return all.filter((name) => patterns.some((pattern) => pattern.test(name))); +} + +export interface ModeDetection { + readonly mode: ColorMode; + readonly decidedBy: 'majority' | 'frame-background' | 'default'; + readonly votes: Record<ColorMode, number>; +} + +// A fill that votes on the mode; with a role, only that role's tokens count for it. +export interface VotingColor extends ColorValue { + readonly role?: ColorRole; +} + +// The mode a color leans to: the one where it serves more semantic tokens that the other mode does not +// share. A token the color serves in both modes says nothing, and neither do palette names, which are +// mode-free. The role matters: `gray.600` is a light-mode text and a dark-mode background, so a +// text fill of it must not be read as a dark vote. +function leaningMode(map: ColorMap, value: VotingColor): ColorMode | undefined { + const inLight = lookupTokens(map, value, 'light', value.role); + const inDark = lookupTokens(map, value, 'dark', value.role); + const lightOnly = inLight.filter((name) => !inDark.includes(name)).length; + const darkOnly = inDark.filter((name) => !inLight.includes(name)).length; + if (lightOnly === darkOnly) return undefined; + // Stryker disable next-line EqualityOperator: a tie returned above, so > and >= cannot differ here + return lightOnly > darkOnly ? 'light' : 'dark'; +} + +export function detectColorMode(map: ColorMap, values: ReadonlyArray<VotingColor>, frameBackground: VotingColor | undefined): ModeDetection { + const votes: Record<ColorMode, number> = { light: 0, dark: 0 }; + for (const value of values) { + const mode = leaningMode(map, value); + if (mode !== undefined) votes[mode] += 1; + } + // Stryker disable next-line EqualityOperator: inside the tie guard, so > and >= cannot differ here + if (votes.light !== votes.dark) return { mode: votes.light > votes.dark ? 'light' : 'dark', decidedBy: 'majority', votes }; + + const background = frameBackground === undefined ? undefined : leaningMode(map, frameBackground); + if (background !== undefined) return { mode: background, decidedBy: 'frame-background', votes }; + + return { mode: 'light', decidedBy: 'default', votes }; +} diff --git a/tools/design-readout/recognize/signals.spec.ts b/tools/design-readout/recognize/signals.spec.ts new file mode 100644 index 00000000000..a5e98a419a3 --- /dev/null +++ b/tools/design-readout/recognize/signals.spec.ts @@ -0,0 +1,329 @@ +import fs from 'fs'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import type { Leaf, RoleColor } from '../extract/values'; +import { buildThemeColorMap } from './colormap'; +import type { Recognition } from './signals'; +import { + applyComposites, COMPOSITE_RULES, loadSpriteNames, matchIconName, matchTextShape, normalizeIconName, normalizeLookalikes, orderByBox, + parseSpriteNames, recognize, renderRecognition, TEXT_SHAPE_RULES, +} from './signals'; + +const SPRITES: ReadonlyArray<string> = [ 'arrows/east', 'apps_list', 'clock-light', 'gas_xl', 'gas', 'status/success', 'contracts/verified' ]; +const MAP = buildThemeColorMap(); +const NO_COLORS: ReadonlyArray<RoleColor> = []; + +function text(id: string, characters: string, x = 0, y = 0, colors = NO_COLORS): Leaf { + return { + id, + bbox: { x, y, width: 60, height: 20 }, + values: { kind: 'text', text: characters, trailingGlyphs: undefined, font: undefined, colors }, + }; +} + +function icon(id: string, name: string, x = 0, y = 0): Leaf { + return { id, bbox: { x, y, width: 20, height: 20 }, values: { kind: 'icon', icon: name, colors: [] } }; +} + +function box(id: string, colors: ReadonlyArray<RoleColor>, x = 0, y = 0): Leaf { + return { id, bbox: { x, y, width: 40, height: 20 }, values: { kind: 'box', colors } }; +} + +function recognizeDark(leaves: ReadonlyArray<Leaf>): ReadonlyArray<Recognition> { + return recognize(leaves, SPRITES, MAP, 'dark'); +} + +describe('normalizeLookalikes', () => { + it('maps Cyrillic and Greek homoglyphs to ASCII and leaves ASCII alone', () => { + expect(normalizeLookalikes('0х05а3…')).toBe('0x05a3…'); + expect(normalizeLookalikes('ЕТН')).toBe('ETH'); + expect(normalizeLookalikes('0x05a3')).toBe('0x05a3'); + }); + + it('folds three dots into an ellipsis and drops zero-width and non-breaking spacing', () => { + expect(normalizeLookalikes('0x05a3...f2d1')).toBe('0x05a3…f2d1'); + expect(normalizeLookalikes('10s ago​')).toBe('10s ago'); + }); +}); + +describe('TEXT_SHAPE_RULES', () => { + it('documents each rule with an example its own pattern matches and no earlier rule claims', () => { + const claimed = TEXT_SHAPE_RULES.map((rule) => [ rule.signal, rule.pattern.test(rule.example), matchTextShape(rule.example)?.signal ]); + expect(claimed).toEqual(TEXT_SHAPE_RULES.map((rule) => [ rule.signal, true, rule.signal ])); + }); +}); + +describe('matchTextShape', () => { + it('tells an address, a transaction hash and a method id apart by length', () => { + expect(matchTextShape('0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D')).toMatchObject({ signal: 'address', entities: [ 'address' ] }); + expect(matchTextShape(`0x${ 'ab'.repeat(32) }`)).toMatchObject({ signal: 'transaction-hash', entities: [ 'transaction' ] }); + expect(matchTextShape('0xa9059cbb')).toMatchObject({ signal: 'method-id', entities: [ 'method' ] }); + }); + + it('reads a truncated hash as an address or a transaction, in either ellipsis form', () => { + expect(matchTextShape('0x05a3…f2d1')).toMatchObject({ signal: 'truncated-hash', entities: [ 'address', 'transaction' ] }); + expect(matchTextShape('0x05a3f2d1…')?.signal).toBe('truncated-hash'); + expect(matchTextShape('0x05a3...f2d1')?.signal).toBe('truncated-hash'); + }); + + it('matches through a lookalike character and records the normalized value', () => { + expect(matchTextShape('0х05а3…f2d1')).toEqual({ signal: 'truncated-hash', entities: [ 'address', 'transaction' ], value: '0x05a3…f2d1' }); + }); + + it('reads a bare or grouped integer as a block, batch or epoch number and a # id as an NFT id', () => { + expect(matchTextShape('1248139')).toMatchObject({ signal: 'number', entities: [ 'block', 'batch', 'epoch' ] }); + expect(matchTextShape('1,248,139')?.signal).toBe('number'); + expect(matchTextShape('0.5612')).toMatchObject({ signal: 'amount', entities: [ 'amount' ] }); + expect(matchTextShape('1,234.56')?.signal).toBe('amount'); + expect(matchTextShape('#1234')).toMatchObject({ signal: 'nft-id', entities: [ 'nft' ] }); + expect(matchTextShape('#1234…890')?.signal).toBe('nft-id'); + }); + + it('reads relative and absolute timestamps', () => { + expect(matchTextShape('10s ago')).toMatchObject({ signal: 'relative-timestamp', entities: [ 'timestamp' ] }); + expect(matchTextShape('1d 4h ago')?.signal).toBe('relative-timestamp'); + expect(matchTextShape('2 hours ago')?.signal).toBe('relative-timestamp'); + expect(matchTextShape('Oct 6, 2026 12:34:56')).toMatchObject({ signal: 'absolute-timestamp' }); + expect(matchTextShape('2026-10-06 12:34')?.signal).toBe('absolute-timestamp'); + expect(matchTextShape('Jul 17 2023 16:50:24 PM')?.signal).toBe('absolute-timestamp'); + }); + + it('reads a short upper-case word as a ticker', () => { + expect(matchTextShape('USDT')).toMatchObject({ signal: 'ticker', entities: [ 'ticker' ] }); + expect(matchTextShape('Eth')).toBeUndefined(); + }); + + it('ignores the trailing glyphs and matches nothing for prose or an amount', () => { + expect(matchTextShape('0xa9059cbb ↗')?.signal).toBe('method-id'); + expect(matchTextShape('$0.56')).toBeUndefined(); + expect(matchTextShape('Contract')).toBeUndefined(); + expect(matchTextShape('0x05a3')).toBeUndefined(); + }); +}); + +describe('parseSpriteNames / loadSpriteNames', () => { + it('reads the quoted members of the generated union', () => { + expect(parseSpriteNames('export type IconName =\n\t| "ABI"\n\t| "arrows/east";\n')).toEqual([ 'ABI', 'arrows/east' ]); + }); + + it('loads the tracked sprite list of this repo, and no two of its names normalize alike', () => { + const names = loadSpriteNames(); + expect(names).toContain('arrows/east'); + expect(names.length).toBeGreaterThan(100); + expect(new Set(names.map(normalizeIconName)).size).toBe(names.length); + }); + + describe('without a sprite list above this module', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('fails naming the file it looked for instead of walking past the file system root', () => { + vi.spyOn(fs, 'existsSync').mockReturnValue(false); + expect(() => loadSpriteNames()).toThrow(/^Cannot find public\/icons\/name\.d\.ts above /); + }); + }); +}); + +describe('matchIconName', () => { + it('hits an instance named exactly like a sprite', () => { + expect(matchIconName('arrows/east', SPRITES)).toBe('arrows/east'); + expect(matchIconName('gas_xl', SPRITES)).toBe('gas_xl'); + }); + + it('hits through case, separators, the Icons/ group and a trailing size or variant', () => { + expect(matchIconName('Icons/Arrows East', SPRITES)).toBe('arrows/east'); + expect(matchIconName('Apps list', SPRITES)).toBe('apps_list'); + expect(matchIconName('clock_light', SPRITES)).toBe('clock-light'); + expect(matchIconName('arrows/east-20', SPRITES)).toBe('arrows/east'); + expect(matchIconName('status/success, Size=sm', SPRITES)).toBe('status/success'); + expect(matchIconName('gas xl', SPRITES)).toBe('gas_xl'); + expect(matchIconName('gas/xl', SPRITES)).toBe('gas_xl'); + }); + + it('misses a name no sprite carries', () => { + expect(matchIconName('Icons/Sparkle', SPRITES)).toBeUndefined(); + expect(matchIconName('arrows', SPRITES)).toBeUndefined(); + }); +}); + +describe('recognize', () => { + it('runs text shapes first and icon names second, recording the signal on each decision', () => { + const leaves = [ text('t', '1248139'), icon('i', 'Icons/contracts/verified', 100, 100), text('p', '$0.56') ]; + expect(recognizeDark(leaves)).toEqual<Array<Recognition>>([ + { id: 't', status: 'recognized', decision: { signal: 'number', value: '1248139', entities: [ 'block', 'batch', 'epoch' ] }, tokens: [], composite: null }, + { id: 'i', status: 'recognized', decision: { signal: 'icon', icon: 'contracts/verified' }, tokens: [], composite: null }, + { id: 'p', status: 'unrecognized', decision: null, tokens: [], composite: null }, + ]); + }); + + it('marks a truncated hash ambiguous when no icon sits beside it, recognized when one does', () => { + const alone = recognizeDark([ text('h', '0x05a3…f2d1') ]); + expect(alone[0]).toMatchObject({ status: 'ambiguous', decision: { signal: 'truncated-hash' } }); + const beside = recognizeDark([ icon('i', 'contracts/verified', 0, 0), text('h', '0x05a3…f2d1', 28, 0) ]); + expect(beside.map((recognition) => recognition.status)).toEqual([ 'recognized', 'recognized' ]); + const farAway = recognizeDark([ icon('i', 'contracts/verified', 0, 0), text('h', '0x05a3…f2d1', 60, 0) ]); + expect(farAway[1].status).toBe('ambiguous'); + const otherRow = recognizeDark([ icon('i', 'contracts/verified', 0, 0), text('h', '0x05a3…f2d1', 28, 40) ]); + expect(otherRow[1].status).toBe('ambiguous'); + }); + + it('counts an icon beside a hash up to the adjacency gap, overlapping it vertically by more than a shared edge', () => { + const statusAt = (iconX: number, iconY: number, hashX: number, hashY: number): string => + recognizeDark([ icon('i', 'contracts/verified', iconX, iconY), text('h', '0x05a3…f2d1', hashX, hashY) ])[1].status; + expect(statusAt(0, 0, 36, 0)).toBe('recognized'); + expect(statusAt(0, 0, 37, 0)).toBe('ambiguous'); + expect(statusAt(0, 0, 28, 19)).toBe('recognized'); + expect(statusAt(0, 0, 28, 20)).toBe('ambiguous'); + expect(statusAt(0, 19, 28, 0)).toBe('recognized'); + expect(statusAt(0, 20, 28, 0)).toBe('ambiguous'); + }); + + it('counts an icon the sprite list does not know as an entity icon, and no box at all as not beside', () => { + expect(recognizeDark([ icon('i', 'Icons/Sparkle', 0, 0), text('h', '0x05a3…f2d1', 28, 0) ])[1].status).toBe('recognized'); + const hashWithoutBox = { ...text('h', '0x05a3…f2d1', 28, 0), bbox: null }; + expect(recognizeDark([ icon('i', 'contracts/verified', 0, 0), hashWithoutBox ])[1].status).toBe('ambiguous'); + const iconWithoutBox = { ...icon('i', 'contracts/verified', 0, 0), bbox: null }; + expect(recognizeDark([ iconWithoutBox, text('h', '0x05a3…f2d1', 28, 0) ])[1].status).toBe('ambiguous'); + }); + + it('leaves an icon no sprite matches unrecognized', () => { + expect(recognizeDark([ icon('i', 'Icons/Sparkle') ])).toEqual([ { id: 'i', status: 'unrecognized', decision: null, tokens: [], composite: null } ]); + }); + + it('resolves every fill to the tokens of its role in the run mode, several when the hex serves several', () => { + const primary = text('t', 'Hi', 0, 0, [ { role: 'text', hex: '#FFFFFF', alpha: 0.8 } ]); + expect(recognize([ primary ], SPRITES, MAP, 'dark')[0].tokens).toEqual([ + { + role: 'text', + color: '#FFFFFF/80', + tokens: [ + 'badge.blue_alt.fg', 'badge.gray.fg', 'badge.purple_alt.fg', 'link.menu', 'link.navigation.fg', + 'tag.root.clickable.fg', 'tag.root.subtle.fg', 'text.primary', + ], + }, + ]); + expect(recognize([ primary ], SPRITES, MAP, 'light')[0].tokens).toEqual([ { role: 'text', color: '#FFFFFF/80', tokens: [] } ]); + }); + + it('recognizes a painted box when every fill is a token and leaves it unrecognized with the unmapped hex otherwise', () => { + const card = box('c', [ { role: 'background', hex: '#101112', alpha: 1 }, { role: 'border', hex: '#FFFFFF', alpha: 0.06 } ]); + const [ recognized ] = recognizeDark([ card ]); + expect(recognized).toMatchObject({ status: 'recognized', decision: { signal: 'color' } }); + expect(recognized.tokens[0]).toEqual({ role: 'background', color: '#101112', tokens: [ 'bg.primary' ] }); + expect(recognized.tokens[1]).toMatchObject({ role: 'border', color: '#FFFFFF/6', tokens: expect.arrayContaining([ 'border.divider' ]) }); + const stray = box('s', [ { role: 'background', hex: '#123456', alpha: 1 }, { role: 'border', hex: '#FFFFFF', alpha: 0.06 } ]); + expect(recognizeDark([ stray ])[0]).toMatchObject({ + status: 'unrecognized', + decision: null, + tokens: [ { color: '#123456', tokens: [] }, { color: '#FFFFFF/6' } ], + }); + expect(recognizeDark([ box('e', []) ])[0]).toEqual({ id: 'e', status: 'unrecognized', decision: null, tokens: [], composite: null }); + }); +}); + +describe('COMPOSITE_RULES', () => { + it('is a table of two rules in reading order: hash, arrow, hash and amount, ticker', () => { + expect(COMPOSITE_RULES.map((rule) => [ rule.signal, rule.parts.map((part) => part.part) ])).toEqual([ + [ 'from-to', [ 'from', 'arrow', 'to' ] ], + [ 'amount-ticker', [ 'amount', 'ticker' ] ], + ]); + }); +}); + +describe('orderByBox', () => { + it('orders rows of overlapping boxes top to bottom and each row left to right, dropping unboxed items', () => { + const items = [ text('c', '', 100, 2), text('d', '', 0, 40), text('a', '', 0, 0), { id: 'n', bbox: null }, text('b', '', 50, 10) ]; + expect(orderByBox(items).map((item) => item.id)).toEqual([ 'a', 'b', 'c', 'd' ]); + }); + + it('grows a row to the lowest box in it, and starts a new row at a box that only touches the row\'s bottom edge', () => { + const grown = [ text('a', '', 0, 0), text('b', '', 50, 10), text('e', '', 10, 25), text('d', '', 0, 50) ]; + expect(orderByBox(grown).map((item) => item.id)).toEqual([ 'a', 'e', 'b', 'd' ]); + const touching = [ text('a', '', 100, 0), text('b', '', 0, 20) ]; + expect(orderByBox(touching).map((item) => item.id)).toEqual([ 'a', 'b' ]); + }); +}); + +describe('composites', () => { + const fromTo = [ + icon('fi', 'contracts/verified', 0, 0), text('from', '0x05a3…f2d1', 28, 0), icon('arrow', 'arrows/east', 96, 0), + icon('ti', 'contracts/verified', 124, 0), text('to', '0x9b1c…0a77', 152, 0), + ]; + + it('joins hash, arrow, hash into a from/to pair over the entity icons between them, in box order not layer order', () => { + const recognitions = recognizeDark([ ...fromTo ].reverse()); + const members = { from: 'from', arrow: 'arrow', to: 'to' }; + expect(recognitions.find((entry) => entry.id === 'from')?.composite).toEqual({ signal: 'from-to', part: 'from', members }); + expect(recognitions.find((entry) => entry.id === 'arrow')?.composite).toEqual({ signal: 'from-to', part: 'arrow', members }); + expect(recognitions.find((entry) => entry.id === 'to')?.composite).toEqual({ signal: 'from-to', part: 'to', members }); + expect(recognitions.find((entry) => entry.id === 'fi')?.composite).toBeNull(); + }); + + it('does not fire when a member is only ambiguous, missing, out of order or too far away', () => { + const head = fromTo.slice(0, 3); + const noIcon = recognizeDark([ ...head, text('to', '0x9b1c…0a77', 124, 0) ]); + expect(noIcon.find((entry) => entry.id === 'to')?.status).toBe('ambiguous'); + expect(noIcon.every((entry) => entry.composite === null)).toBe(true); + const noArrow = recognizeDark(fromTo.filter((leaf) => leaf.id !== 'arrow')); + expect(noArrow.every((entry) => entry.composite === null)).toBe(true); + const twoArrows = recognizeDark([ + ...head, icon('arrow2', 'arrows/east', 124, 0), icon('ti', 'contracts/verified', 152, 0), text('to', '0x9b1c…0a77', 180, 0), + ]); + expect(twoArrows.every((entry) => entry.composite === null)).toBe(true); + const farApart = recognizeDark([ ...head, icon('ti', 'contracts/verified', 200, 0), text('to', '0x9b1c…0a77', 228, 0) ]); + expect(farApart.every((entry) => entry.composite === null)).toBe(true); + }); + + it('joins an amount or a bare number with the ticker beside it, once per leaf', () => { + const recognitions = recognizeDark([ text('v', '0.5612', 0, 0), text('c', 'ETH', 64, 0), text('n', '1248139', 0, 30), text('c2', 'USDT', 64, 30) ]); + expect(recognitions.map((entry) => entry.composite)).toEqual([ + { signal: 'amount-ticker', part: 'amount', members: { amount: 'v', ticker: 'c' } }, + { signal: 'amount-ticker', part: 'ticker', members: { amount: 'v', ticker: 'c' } }, + { signal: 'amount-ticker', part: 'amount', members: { amount: 'n', ticker: 'c2' } }, + { signal: 'amount-ticker', part: 'ticker', members: { amount: 'n', ticker: 'c2' } }, + ]); + const label = recognizeDark([ text('v', '0.5612', 0, 0), text('l', 'Value', 64, 0), text('c', 'ETH', 128, 0) ]); + expect(label.map((entry) => entry.composite?.part ?? null)).toEqual([ 'amount', null, 'ticker' ]); + const twoAmounts = recognizeDark([ text('v', '0.5612', 0, 0), text('n', '1248139', 64, 0) ]); + expect(twoAmounts.every((entry) => entry.composite === null)).toBe(true); + }); + + it('refuses a recognition list that does not cover the leaves', () => { + expect(() => applyComposites([ text('t', '1248139') ], [])).toThrow('Leaf t has no recognition.'); + }); +}); + +describe('renderRecognition', () => { + it('lists the recognized items with tokens and composites, then the ambiguous and unrecognized items with id, values and box', () => { + const leaves = [ + text('t', '1248139', 10, 20, [ { role: 'text', hex: '#63B3ED', alpha: 1 } ]), text('h', '0x05a3…f2d1', 80, 20), icon('i', 'Icons/Sparkle', 180, 20), + text('p', '$0.56', 220, 20), text('v', '0.5612', 10, 50), text('c', 'ETH', 80, 50), + box('b', [ { role: 'background', hex: '#123456', alpha: 1 }, { role: 'border', hex: '#FFFFFF', alpha: 0.06 } ], 10, 80), + box('k', [ { role: 'background', hex: '#101112', alpha: 1 } ], 60, 80), + box('e', [], 110, 80), + { ...text('q', 'Contract'), bbox: null }, + ]; + expect(renderRecognition(leaves, recognizeDark(leaves))).toBe([ + 'Recognized: 4 of 10', + ' - t text "1248139" — no font; text #63B3ED; at 10,20 60×20 — number: block or batch or epoch; tokens: text #63B3ED → link.primary', + ' - v text "0.5612" — no font; ; at 10,50 60×20 — amount: amount; tokens: no fill; amount of amount-ticker (amount v, ticker c)', + ' - c text "ETH" — no font; ; at 80,50 60×20 — ticker: ticker; tokens: no fill; ticker of amount-ticker (amount v, ticker c)', + ' - k box — background #101112; at 60,80 40×20 — every fill is a theme token; tokens: background #101112 → bg.primary', + 'Ambiguous: 1', + ' - h text "0x05a3…f2d1" — no font; ; at 80,20 60×20 — truncated-hash: address or transaction, no icon beside it; tokens: no fill', + 'Unrecognized: 5', + ' - i icon "Icons/Sparkle" — ; at 180,20 20×20 — no sprite icon is named like "Icons/Sparkle"; tokens: no fill', + ' - p text "$0.56" — no font; ; at 220,20 60×20 — no text-shape rule matches; tokens: no fill', + ' - b box — background #123456, border #FFFFFF/6; at 10,80 40×20 — no token serves background #123456; ' + + 'tokens: background #123456 → no token; border #FFFFFF/6 → border.divider, tag.root.select.border', + ' - e box — ; at 110,80 40×20 — a painted box has no text or icon to read; tokens: no fill', + ' - q text "Contract" — no font; ; no box — no text-shape rule matches; tokens: no fill', + ].join('\n')); + }); + + it('refuses a recognition whose leaf is missing', () => { + expect(() => renderRecognition([], recognizeDark([ text('t', '1248139') ]))).toThrow('Recognition t has no leaf.'); + }); +}); diff --git a/tools/design-readout/recognize/signals.ts b/tools/design-readout/recognize/signals.ts new file mode 100644 index 00000000000..70e49095ee6 --- /dev/null +++ b/tools/design-readout/recognize/signals.ts @@ -0,0 +1,404 @@ +import fs from 'fs'; +import path from 'path'; + +import { COMPOSITE_ADJACENCY_GAP_PX, ICON_ADJACENCY_GAP_PX, LOOKALIKE_CHARACTERS, SPRITE_NAMES_FILE } from '../config'; +import type { Leaf, RoleColor } from '../extract/values'; +import { describeLeaf } from '../extract/values'; +import type { BoundingBox } from '../fetch/figma'; +import { colorKey, lookupTokens } from './colormap'; +import type { ColorMap, ColorMode, ColorRole } from './colormap'; + +export type Entity = 'address' | 'transaction' | 'method' | 'block' | 'batch' | 'epoch' | 'nft' | 'timestamp' | 'ticker' | 'amount'; + +export type TextShapeSignal = + 'address' | 'transaction-hash' | 'method-id' | 'truncated-hash' | 'number' | 'amount' | 'nft-id' | 'relative-timestamp' | 'absolute-timestamp' | + 'ticker'; + +export interface TextShapeRule { + readonly signal: TextShapeSignal; + readonly entities: ReadonlyArray<Entity>; + readonly pattern: RegExp; + readonly example: string; +} + +const RELATIVE_TIME_UNIT_LETTERS: ReadonlyArray<string> = [ 's', 'm', 'h', 'd', 'w', 'y' ]; +const RELATIVE_TIME_UNIT_WORDS: ReadonlyArray<string> = [ + 'sec', 'secs', 'second', 'seconds', 'min', 'mins', 'minute', 'minutes', 'hr', 'hrs', 'hour', 'hours', + 'day', 'days', 'week', 'weeks', 'mo', 'month', 'months', 'year', 'years', +]; +const RELATIVE_TIME_UNIT = `(?:[${ RELATIVE_TIME_UNIT_LETTERS.join('') }]|${ RELATIVE_TIME_UNIT_WORDS.join('|') })`; + +// Each rule matches the whole text after lookalike normalization and with the trailing glyphs cut +// off. The first rule that matches wins, so the specific shapes sit above the general ones; a rule +// with several entities names what the ticket's context must choose between. +export const TEXT_SHAPE_RULES: ReadonlyArray<TextShapeRule> = [ + { signal: 'address', entities: [ 'address' ], pattern: /^0x[0-9a-f]{40}$/i, example: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' }, + { + signal: 'transaction-hash', + entities: [ 'transaction' ], + pattern: /^0x[0-9a-f]{64}$/i, + example: '0x6c7d1e0a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6', + }, + { signal: 'method-id', entities: [ 'method' ], pattern: /^0x[0-9a-f]{8}$/i, example: '0xa9059cbb' }, + { signal: 'truncated-hash', entities: [ 'address', 'transaction' ], pattern: /^0x[0-9a-f]{2,}…(?:[0-9a-f]{2,})?$/i, example: '0x05a3…f2d1' }, + { signal: 'nft-id', entities: [ 'nft' ], pattern: /^#\d+(?:…\d+)?$/, example: '#1234' }, + { signal: 'number', entities: [ 'block', 'batch', 'epoch' ], pattern: /^(?:\d{1,3}(?:,\d{3})+|\d+)$/, example: '1248139' }, + { signal: 'amount', entities: [ 'amount' ], pattern: /^(?:\d{1,3}(?:,\d{3})+|\d+)\.\d+$/, example: '0.5612' }, + { + signal: 'relative-timestamp', + entities: [ 'timestamp' ], + pattern: new RegExp(`^(?:\\d+\\s*${ RELATIVE_TIME_UNIT }\\s*)+ago$`, 'i'), + example: '10s ago', + }, + { + signal: 'absolute-timestamp', + entities: [ 'timestamp' ], + pattern: new RegExp([ + '^(?:', + '\\d{4}-\\d{2}-\\d{2}(?:[T ]\\d{2}:\\d{2}(?::\\d{2})?)?', + '|[A-Z][a-z]{2} \\d{1,2},? \\d{4}(?: \\d{1,2}:\\d{2}(?::\\d{2})?(?: ?[AP]M)?)?', + '|\\d{1,2}/\\d{1,2}/\\d{4}(?: \\d{1,2}:\\d{2}(?::\\d{2})?)?', + ')$', + ].join('')), + example: 'Oct 6, 2026 12:34:56', + }, + { signal: 'ticker', entities: [ 'ticker' ], pattern: /^[A-Z][A-Z0-9]{1,5}$/, example: 'USDT' }, +]; + +const ZERO_WIDTH = /[\u200b-\u200d\ufeff]/g; +const THREE_DOTS = /\.{3}/g; +const TRAILING_SYMBOLS = /[\p{So}\p{Sm}\s]+$/u; + +export function normalizeLookalikes(text: string): string { + return Array.from(text.replace(ZERO_WIDTH, '').replace(THREE_DOTS, '…')) + .map((character) => LOOKALIKE_CHARACTERS[character] ?? character) + .join(''); +} + +export interface TextShapeMatch { + readonly signal: TextShapeSignal; + readonly entities: ReadonlyArray<Entity>; + readonly value: string; +} + +export function matchTextShape(text: string): TextShapeMatch | undefined { + const value = normalizeLookalikes(text).replace(TRAILING_SYMBOLS, '').trim(); + const rule = TEXT_SHAPE_RULES.find((candidate) => candidate.pattern.test(value)); + return rule === undefined ? undefined : { signal: rule.signal, entities: rule.entities, value }; +} + +const SPRITE_NAME = /"([^"]+)"/g; + +export function parseSpriteNames(source: string): ReadonlyArray<string> { + return Array.from(source.matchAll(SPRITE_NAME), (match) => match[1]); +} + +function findRepoRoot(start: string): string { + let dir = start; + while (!fs.existsSync(path.join(dir, SPRITE_NAMES_FILE))) { + const parent = path.dirname(dir); + if (parent === dir) throw new Error(`Cannot find ${ SPRITE_NAMES_FILE } above ${ start }`); + dir = parent; + } + return dir; +} + +// Walks up from this module: the compiled copy runs from `dist/tools/design-readout/recognize/`, the +// specs from `tools/design-readout/recognize/`, and the repo root is the first ancestor holding the sprite list. +export function loadSpriteNames(): ReadonlyArray<string> { + return parseSpriteNames(fs.readFileSync(path.join(findRepoRoot(__dirname), SPRITE_NAMES_FILE), 'utf8')); +} + +const ICON_GROUP_PREFIX = /^icons?-/; +const VARIANT_PROPERTIES = /,.*$/; +const SIZE_SUFFIX = /-(?:\d+(?:px)?|xs|sm|md|lg|xl|2xl)$/; +const SEPARATORS = /[\s_/-]+/g; + +// Lower case, one separator, no `Icons/` group: "Icons/Arrows East" and "arrows/east" are one name. +// The sprite list stays injective under this (`recognize.spec.ts` checks), so no two sprites collide. +export function normalizeIconName(name: string): string { + return name.trim().toLowerCase().replace(VARIANT_PROPERTIES, '').replace(SEPARATORS, '-').replace(ICON_GROUP_PREFIX, ''); +} + +export function matchIconName(instanceName: string, spriteNames: ReadonlyArray<string>): string | undefined { + const bySprite = new Map(spriteNames.map((sprite) => [ normalizeIconName(sprite), sprite ])); + const normalized = normalizeIconName(instanceName); + return bySprite.get(normalized) ?? bySprite.get(normalized.replace(SIZE_SUFFIX, '')); +} + +// `recognized`: a signal fired and settles the shape. `ambiguous`: a signal fired but the shape alone +// cannot settle it (a truncated hash with no entity icon beside it). `unrecognized`: nothing fired; +// the values are listed, never a guess. +export type RecognitionStatus = 'recognized' | 'ambiguous' | 'unrecognized'; + +// What the signal says the node is: for a text, its shape and the entities that shape can be; for an +// icon, the sprite name its instance name resolved to; for a painted box, that every fill is a theme +// token. Never a component. +export type Decision = + { readonly signal: TextShapeSignal; readonly value: string; readonly entities: ReadonlyArray<Entity> } | + { readonly signal: 'icon'; readonly icon: string } | + { readonly signal: 'color' }; + +// One fill resolved through the reverse map in the run's mode: the tokens it serves under its role, +// empty when none does. +export interface ColorTokens { + readonly role: ColorRole; + readonly color: string; + readonly tokens: ReadonlyArray<string>; +} + +export type CompositeSignal = 'from-to' | 'amount-ticker'; + +// A node's place in a composite: which rule fired, which part it plays, and the ids of every part. +export interface CompositeMembership { + readonly signal: CompositeSignal; + readonly part: string; + readonly members: Readonly<Record<string, string>>; +} + +export interface Recognition { + readonly id: string; + readonly status: RecognitionStatus; + readonly decision: Decision | null; + readonly tokens: ReadonlyArray<ColorTokens>; + readonly composite: CompositeMembership | null; +} + +function isBeside(a: BoundingBox | null, b: BoundingBox | null, maxGap: number): boolean { + if (a === null || b === null) return false; + const overlapsVertically = a.y < b.y + b.height && b.y < a.y + a.height; + const gap = Math.max(a.x - (b.x + b.width), b.x - (a.x + a.width)); + return overlapsVertically && gap <= maxGap; +} + +const ARROW_ICON = /^arrows\//; + +function isEntityIcon(leaf: Leaf, spriteNames: ReadonlyArray<string>): boolean { + if (leaf.values.kind !== 'icon') return false; + const sprite = matchIconName(leaf.values.icon, spriteNames); + // Stryker disable next-line ConditionalExpression: the undefined check narrows the type; an unmatched name is not an arrow either way + return sprite === undefined || !ARROW_ICON.test(sprite); +} + +function hasEntityIconBeside(leaf: Leaf, context: RecognitionContext): boolean { + return context.leaves.some((other) => isEntityIcon(other, context.spriteNames) && isBeside(leaf.bbox, other.bbox, ICON_ADJACENCY_GAP_PX)); +} + +type ShapeRecognition = Pick<Recognition, 'status' | 'decision'>; + +// A truncated hash stands for an entity only with the entity's icon beside it; alone, or with just +// the arrow to the next hash, nothing says whether the designer meant an address or a transaction. +function recognizeText(leaf: Leaf, text: string, context: RecognitionContext): ShapeRecognition { + const match = matchTextShape(text); + if (match === undefined) return { status: 'unrecognized', decision: null }; + const ambiguous = match.signal === 'truncated-hash' && !hasEntityIconBeside(leaf, context); + return { status: ambiguous ? 'ambiguous' : 'recognized', decision: match }; +} + +function recognizeIcon(instanceName: string, spriteNames: ReadonlyArray<string>): ShapeRecognition { + const icon = matchIconName(instanceName, spriteNames); + if (icon === undefined) return { status: 'unrecognized', decision: null }; + return { status: 'recognized', decision: { signal: 'icon', icon } }; +} + +// A painted box has no text or icon to read: its fills are all it says, so it is recognized when +// every one of them is a theme token. +function recognizeBox(tokens: ReadonlyArray<ColorTokens>): ShapeRecognition { + const everyFillIsAToken = tokens.length > 0 && tokens.every((entry) => entry.tokens.length > 0); + return everyFillIsAToken ? { status: 'recognized', decision: { signal: 'color' } } : { status: 'unrecognized', decision: null }; +} + +export function resolveTokens(colors: ReadonlyArray<RoleColor>, map: ColorMap, mode: ColorMode): ReadonlyArray<ColorTokens> { + return colors.map((color) => ({ role: color.role, color: colorKey(color), tokens: lookupTokens(map, color, mode, color.role) })); +} + +interface RecognitionContext { + readonly leaves: ReadonlyArray<Leaf>; + readonly spriteNames: ReadonlyArray<string>; + readonly map: ColorMap; + readonly mode: ColorMode; +} + +function recognizeLeaf(leaf: Leaf, context: RecognitionContext): Recognition { + const { values } = leaf; + const tokens = resolveTokens(values.colors, context.map, context.mode); + const shape = ((): ShapeRecognition => { + switch (values.kind) { + case 'text': + return recognizeText(leaf, values.text, context); + case 'icon': + return recognizeIcon(values.icon, context.spriteNames); + case 'box': + return recognizeBox(tokens); + } + })(); + return { id: leaf.id, ...shape, tokens, composite: null }; +} + +export interface CompositePart { + readonly part: string; + readonly matches: (decision: Decision) => boolean; +} + +export interface CompositeRule { + readonly signal: CompositeSignal; + readonly parts: ReadonlyArray<CompositePart>; +} + +const HASH_SIGNALS: ReadonlyArray<string> = [ 'address', 'transaction-hash', 'truncated-hash' ]; +const AMOUNT_SIGNALS: ReadonlyArray<string> = [ 'amount', 'number' ]; + +const isHash = (decision: Decision): boolean => HASH_SIGNALS.includes(decision.signal); +// Stryker disable next-line ConditionalExpression: the signal check narrows the type; a decision without an icon is not an arrow either way +const isArrow = (decision: Decision): boolean => decision.signal === 'icon' && ARROW_ICON.test(decision.icon); +const isAmount = (decision: Decision): boolean => AMOUNT_SIGNALS.includes(decision.signal); +const isTicker = (decision: Decision): boolean => decision.signal === 'ticker'; + +// The parts in reading order. A rule fires over recognized leaves that sit within the composite gap +// of each other; a leaf that matches none of the parts (the entity icon beside a hash) may sit +// between two parts, a leaf that matches a part out of order ends the attempt, and a part whose +// leaf is only ambiguous blocks the rule — a composite never promotes what the shape could not settle. +export const COMPOSITE_RULES: ReadonlyArray<CompositeRule> = [ + { signal: 'from-to', parts: [ { part: 'from', matches: isHash }, { part: 'arrow', matches: isArrow }, { part: 'to', matches: isHash } ] }, + { signal: 'amount-ticker', parts: [ { part: 'amount', matches: isAmount }, { part: 'ticker', matches: isTicker } ] }, +]; + +interface Member { + readonly leaf: Leaf; + readonly recognition: Recognition; +} + +// Bounding-box order, not layer order: rows of vertically overlapping boxes top to bottom, left to +// right inside a row. A leaf with no box takes no part in a composite. +export function orderByBox<TItem extends { readonly bbox: BoundingBox | null }>(items: ReadonlyArray<TItem>): Array<TItem> { + const boxed = items.filter((item) => item.bbox !== null).sort((a, b) => (a.bbox?.y ?? 0) - (b.bbox?.y ?? 0)); + const rows: Array<{ bottom: number; items: Array<TItem> }> = []; + for (const item of boxed) { + const box = item.bbox as BoundingBox; + const row = rows[rows.length - 1]; + if (row !== undefined && box.y < row.bottom) { + row.items.push(item); + row.bottom = Math.max(row.bottom, box.y + box.height); + } else { + rows.push({ bottom: box.y + box.height, items: [ item ] }); + } + } + return rows.flatMap((row) => row.items.sort((a, b) => (a.bbox?.x ?? 0) - (b.bbox?.x ?? 0))); +} + +type PartHit = { readonly kind: 'next' } | { readonly kind: 'foreign' } | { readonly kind: 'blocked' }; + +function classifyMember(member: Member, rule: CompositeRule, nextPart: number, taken: ReadonlySet<string>): PartHit { + const { decision, status } = member.recognition; + if (decision === null) return { kind: 'foreign' }; + if (!rule.parts.some((part) => part.matches(decision))) return { kind: 'foreign' }; + const fitsNext = rule.parts[nextPart].matches(decision) && status === 'recognized' && !taken.has(member.leaf.id); + return fitsNext ? { kind: 'next' } : { kind: 'blocked' }; +} + +function matchRuleAt(ordered: ReadonlyArray<Member>, start: number, rule: CompositeRule, taken: ReadonlySet<string>): Record<string, string> | undefined { + const members: Record<string, string> = {}; + let nextPart = 0; + for (let index = start; index < ordered.length; index++) { + const member = ordered[index]; + if (index > start && !isBeside(ordered[index - 1].leaf.bbox, member.leaf.bbox, COMPOSITE_ADJACENCY_GAP_PX)) return undefined; + const hit = classifyMember(member, rule, nextPart, taken); + if (hit.kind === 'blocked') return undefined; + if (hit.kind === 'foreign') continue; + members[rule.parts[nextPart].part] = member.leaf.id; + nextPart += 1; + if (nextPart === rule.parts.length) return members; + } + return undefined; +} + +function withComposite(recognition: Recognition, signal: CompositeSignal, members: Record<string, string>): Recognition { + const part = Object.keys(members).find((key) => members[key] === recognition.id); + // Stryker disable next-line ConditionalExpression: called only for the ids in members, so the part is always found + return part === undefined ? recognition : { ...recognition, composite: { signal, part, members } }; +} + +// Composites run after every leaf has its own recognition, each rule once over the ordered leaves, +// and a leaf joins at most one composite. +export function applyComposites(leaves: ReadonlyArray<Leaf>, recognitions: ReadonlyArray<Recognition>): ReadonlyArray<Recognition> { + const byId = new Map(recognitions.map((recognition) => [ recognition.id, recognition ])); + const ordered = orderByBox(leaves).map((leaf): Member => { + const recognition = byId.get(leaf.id); + if (recognition === undefined) throw new Error(`Leaf ${ leaf.id } has no recognition.`); + return { leaf, recognition }; + }); + const taken = new Set<string>(); + for (const rule of COMPOSITE_RULES) { + // Stryker disable next-line EqualityOperator: a pass starting past the last leaf matches nothing + for (let start = 0; start < ordered.length; start++) { + const members = matchRuleAt(ordered, start, rule, taken); + if (members === undefined) continue; + for (const id of Object.values(members)) { + taken.add(id); + byId.set(id, withComposite(byId.get(id) as Recognition, rule.signal, members)); + } + } + } + return recognitions.map((recognition) => byId.get(recognition.id) as Recognition); +} + +// One recognition per leaf, in leaf order: text-shape rules first, icon names second, every fill +// resolved to its tokens in the run's mode, and the composite rules last over what is recognized. +export function recognize(leaves: ReadonlyArray<Leaf>, spriteNames: ReadonlyArray<string>, map: ColorMap, mode: ColorMode): ReadonlyArray<Recognition> { + const context: RecognitionContext = { leaves, spriteNames, map, mode }; + return applyComposites(leaves, leaves.map((leaf) => recognizeLeaf(leaf, context))); +} + +function describeBox(bbox: BoundingBox | null): string { + return bbox === null ? 'no box' : `at ${ bbox.x },${ bbox.y } ${ bbox.width }×${ bbox.height }`; +} + +function describeUnmapped(tokens: ReadonlyArray<ColorTokens>): string { + const unmapped = tokens.filter((entry) => entry.tokens.length === 0); + if (unmapped.length === 0) return 'a painted box has no text or icon to read'; + return `no token serves ${ unmapped.map((entry) => `${ entry.role } ${ entry.color }`).join(', ') }`; +} + +export function describeWhy(leaf: Leaf, recognition: Pick<Recognition, 'decision' | 'status' | 'tokens'>): string { + const { decision } = recognition; + if (decision === null) { + if (leaf.values.kind === 'icon') return `no sprite icon is named like "${ leaf.values.icon }"`; + return leaf.values.kind === 'text' ? 'no text-shape rule matches' : describeUnmapped(recognition.tokens); + } + if (decision.signal === 'icon') return `icon "${ decision.icon }"`; + if (decision.signal === 'color') return 'every fill is a theme token'; + return `${ decision.signal }: ${ decision.entities.join(' or ') }${ recognition.status === 'ambiguous' ? ', no icon beside it' : '' }`; +} + +export function describeTokens(tokens: ReadonlyArray<ColorTokens>): string { + if (tokens.length === 0) return 'no fill'; + return tokens.map((entry) => `${ entry.role } ${ entry.color } → ${ entry.tokens.length === 0 ? 'no token' : entry.tokens.join(', ') }`).join('; '); +} + +export function describeComposite(composite: CompositeMembership | null): string { + if (composite === null) return ''; + const others = Object.entries(composite.members).map(([ part, id ]) => `${ part } ${ id }`).join(', '); + return `; ${ composite.part } of ${ composite.signal } (${ others })`; +} + +function renderList(title: string, leaves: ReadonlyArray<Leaf>, recognitions: ReadonlyArray<Recognition>, status: RecognitionStatus): Array<string> { + const byId = new Map(leaves.map((leaf) => [ leaf.id, leaf ])); + const items = recognitions.filter((recognition) => recognition.status === status); + const detail = (recognition: Recognition): string => `; tokens: ${ describeTokens(recognition.tokens) }${ describeComposite(recognition.composite) }`; + return [ + `${ title }: ${ items.length }${ status === 'recognized' ? ` of ${ recognitions.length }` : '' }`, + ...items.map((recognition) => { + const leaf = byId.get(recognition.id); + if (leaf === undefined) throw new Error(`Recognition ${ recognition.id } has no leaf.`); + return ` - ${ describeLeaf(leaf) }; ${ describeBox(leaf.bbox) } — ${ describeWhy(leaf, recognition) }${ detail(recognition) }`; + }), + ]; +} + +export function renderRecognition(leaves: ReadonlyArray<Leaf>, recognitions: ReadonlyArray<Recognition>): string { + return [ + ...renderList('Recognized', leaves, recognitions, 'recognized'), + ...renderList('Ambiguous', leaves, recognitions, 'ambiguous'), + ...renderList('Unrecognized', leaves, recognitions, 'unrecognized'), + ].join('\n'); +} diff --git a/tools/design-readout/record/gaps.spec.ts b/tools/design-readout/record/gaps.spec.ts new file mode 100644 index 00000000000..27c7761e8e6 --- /dev/null +++ b/tools/design-readout/record/gaps.spec.ts @@ -0,0 +1,140 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import { appendGap, formatGapLine, GAP_LOG_HEADER, gapLogPath, gapOfCorrection, gapOfNote } from './gaps'; +import type { Correction, NodeRecord } from './sidecar'; + +let tmp = ''; + +afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; +}); + +const NODE: NodeRecord = { + id: '22842:178386', + values: { + kind: 'text', + text: '1248139', + trailingGlyphs: undefined, + font: { family: 'Inter', weight: 500, size: 14, lineHeight: 20 }, + colors: [ { role: 'text', hex: '#63B3ED', alpha: 1 } ], + }, + bbox: null, + decision: { signal: 'number', value: '1248139', entities: [ 'block', 'batch', 'epoch' ] }, + status: 'recognized', + tokens: [ { role: 'text', color: '#63B3ED', tokens: [ 'link.primary' ] } ], + composite: null, + correction: null, + override: null, +}; + +const CORRECTION: Correction = { + component: 'BlockEntity', + props: [ 'noIcon', 'size=sm' ], + gap: 'context', + recordedAt: '2026-10-07T09:30:00.000Z', + stale: false, +}; + +const CORRECTION_GAP = { date: '2026-10-07', fileKey: 'KEY', nodeId: '22842:178386', correction: CORRECTION, node: NODE, stage: 'readout' as const }; +const ENTRY = gapOfCorrection(CORRECTION_GAP); +const NOTE = gapOfNote({ date: '2026-10-09', fileKey: 'KEY', gap: 'markup', text: 'the row gap is 8px in the app, 12px in the mockup' }); + +describe('gapLogPath', () => { + it('sits beside the sidecars under the main checkout', () => { + expect(gapLogPath('/repo')).toBe(path.join('/repo', '.ai', 'design-readout', 'gaps.md')); + }); +}); + +describe('gapOfCorrection', () => { + it('is a readout-stage miss on the corrected node, in the tool\'s words against the developer\'s', () => { + expect(ENTRY).toEqual({ + date: '2026-10-07', + fileKey: 'KEY', + nodeId: '22842:178386', + gap: 'context', + stage: 'readout', + toolSaid: 'recognized: 22842:178386 text "1248139" — Inter 500 14/20; text #63B3ED — number: block or batch or epoch', + developerSaid: 'BlockEntity noIcon size=sm', + }); + }); + + it('writes a bare component when the correction has no props', () => { + expect(gapOfCorrection({ ...CORRECTION_GAP, correction: { ...CORRECTION, props: [] } }).developerSaid).toBe('BlockEntity'); + expect(gapOfCorrection({ ...CORRECTION_GAP, stage: 'markup' }).stage).toBe('markup'); + }); +}); + +describe('gapOfNote', () => { + it('is a markup-stage miss with no node and nothing the tool said', () => { + expect(NOTE).toEqual({ + date: '2026-10-09', + fileKey: 'KEY', + nodeId: '', + gap: 'markup', + stage: 'markup', + toolSaid: '', + developerSaid: 'the row gap is 8px in the app, 12px in the mockup', + }); + }); +}); + +describe('formatGapLine', () => { + it('is one line: date, file key, node id, category, stage, what the tool said, what the developer said', () => { + expect(formatGapLine(ENTRY)).toBe([ + '- 2026-10-07 | KEY | 22842:178386 | context | readout | ', + 'recognized: 22842:178386 text "1248139" — Inter 500 14/20; text #63B3ED — number: block or batch or epoch | BlockEntity noIcon size=sm', + ].join('')); + }); + + it('leaves the node id and the tool column empty on a note', () => { + expect(formatGapLine(NOTE)).toBe('- 2026-10-09 | KEY | | markup | markup | | the row gap is 8px in the app, 12px in the mockup'); + }); +}); + +describe('appendGap', () => { + it('creates the file with the header line on first write and only appends afterwards', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-gaps-')); + const target = gapLogPath(tmp); + const first = appendGap(target, ENTRY); + const second = appendGap(target, gapOfCorrection({ ...CORRECTION_GAP, date: '2026-10-08', nodeId: '1:1', correction: { ...CORRECTION, gap: 'shape' } })); + const third = appendGap(target, NOTE); + expect(fs.readFileSync(target, 'utf8')).toBe(`${ GAP_LOG_HEADER }\n${ first.line }\n${ second.line }\n${ third.line }\n`); + expect(second).toEqual({ line: expect.stringMatching(/^- 2026-10-08 \| KEY \| 1:1 \| shape \| readout \| /), appended: true }); + expect(third).toEqual({ line: expect.stringMatching(/^- 2026-10-09 \| KEY \| {2}\| markup \| markup \| {2}\| the row gap/), appended: true }); + }); + + it('adds no line for the same miss on another node of the same file, whatever its stage', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-gaps-')); + const target = gapLogPath(tmp); + const first = appendGap(target, ENTRY); + const repeat = appendGap(target, gapOfCorrection({ ...CORRECTION_GAP, date: '2026-10-09', nodeId: '1:1', node: { ...NODE, id: '1:1' } })); + const otherStage = appendGap(target, { ...ENTRY, date: '2026-10-10', stage: 'markup' }); + expect(repeat.appended).toBe(false); + expect(otherStage.appended).toBe(false); + expect(fs.readFileSync(target, 'utf8')).toBe(`${ GAP_LOG_HEADER }\n${ first.line }\n`); + }); + + it('adds no line for the same note text under the same file key and category', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-gaps-')); + const target = gapLogPath(tmp); + const first = appendGap(target, NOTE); + expect(appendGap(target, { ...NOTE, date: '2026-10-10' }).appended).toBe(false); + expect(appendGap(target, { ...NOTE, gap: 'layout' }).appended).toBe(true); + expect(fs.readFileSync(target, 'utf8')).toBe(`${ GAP_LOG_HEADER }\n${ first.line }\n${ formatGapLine({ ...NOTE, gap: 'layout' }) }\n`); + }); + + it('keeps a line for the same values under another file key, category or correction', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-gaps-')); + const target = gapLogPath(tmp); + appendGap(target, ENTRY); + expect(appendGap(target, { ...ENTRY, fileKey: 'OTHER' }).appended).toBe(true); + expect(appendGap(target, gapOfCorrection({ ...CORRECTION_GAP, correction: { ...CORRECTION, gap: 'shape' } })).appended).toBe(true); + expect(appendGap(target, gapOfCorrection({ ...CORRECTION_GAP, correction: { ...CORRECTION, props: [] } })).appended).toBe(true); + expect(fs.readFileSync(target, 'utf8').split('\n').filter((line) => line.startsWith('- '))).toHaveLength(4); + }); +}); diff --git a/tools/design-readout/record/gaps.ts b/tools/design-readout/record/gaps.ts new file mode 100644 index 00000000000..9d075343476 --- /dev/null +++ b/tools/design-readout/record/gaps.ts @@ -0,0 +1,91 @@ +import fs from 'fs'; +import path from 'path'; + +import type { GAP_STAGES } from '../config'; +import { GAP_LOG_FILE, SIDECAR_DIR } from '../config'; +import { describeLeaf } from '../extract/values'; +import { describeWhy } from '../recognize/signals'; +import type { Correction, GapCategory, NodeRecord } from './sidecar'; + +export type GapStage = typeof GAP_STAGES[number]; + +export interface GapEntry { + readonly date: string; + readonly fileKey: string; + readonly nodeId: string; + readonly gap: GapCategory; + readonly stage: GapStage; + readonly toolSaid: string; + readonly developerSaid: string; +} + +export const GAP_LOG_HEADER = '# Design readout gap log — one line per miss: date | file key | node id | category | stage | the tool said | the developer said'; + +export function gapLogPath(mainCheckout: string): string { + return path.join(mainCheckout, SIDECAR_DIR, GAP_LOG_FILE); +} + +function describeToolSaid(node: NodeRecord): string { + return `${ node.status }: ${ describeLeaf(node) } — ${ describeWhy(node, node) }`; +} + +function describeDeveloperSaid(correction: Correction): string { + return correction.props.length === 0 ? correction.component : `${ correction.component } ${ correction.props.join(' ') }`; +} + +export interface CorrectionGap { + readonly date: string; + readonly fileKey: string; + readonly nodeId: string; + readonly correction: Correction; + readonly node: NodeRecord; + readonly stage: GapStage; +} + +// A correction names a node, so it can surface at either stage: while settling the readout, or at +// the markup leaf when the developer's fix maps back to a leaf the sidecar holds. +export function gapOfCorrection({ date, fileKey, nodeId, correction, node, stage }: CorrectionGap): GapEntry { + return { date, fileKey, nodeId, gap: correction.gap, stage, toolSaid: describeToolSaid(node), developerSaid: describeDeveloperSaid(correction) }; +} + +export interface NoteGap { + readonly date: string; + readonly fileKey: string; + readonly gap: GapCategory; + readonly text: string; +} + +// A note maps to no node: the miss surfaced in the running app, against the agent's markup, and the +// developer could not pin it to one leaf the sidecar holds. +export function gapOfNote({ date, fileKey, gap, text }: NoteGap): GapEntry { + return { date, fileKey, nodeId: '', gap, stage: 'markup', toolSaid: '', developerSaid: text }; +} + +export function formatGapLine({ date, fileKey, nodeId, gap, stage, toolSaid, developerSaid }: GapEntry): string { + return `- ${ date } | ${ fileKey } | ${ nodeId } | ${ gap } | ${ stage } | ${ toolSaid } | ${ developerSaid }`; +} + +// A miss is the kind of thing the tool got wrong, not the node it got it wrong on or the stage it +// surfaced at: the same cell repeated down eight rows of a mockup is one miss, so the phase 2 count +// reads kinds. The key is the line without its date, node id and stage. +function missOf(line: string): string { + const [ , fileKey, nodeId, category, , ...rest ] = line.replace(/^- /, '').split(' | '); + const said = rest.join(' | '); + // Stryker disable next-line ConditionalExpression: with no node id the replace strips the one leading space every note line shares, so every key moves alike + return `${ fileKey } | ${ category } | ${ nodeId === '' ? said : said.replace(`${ nodeId } `, '') }`; +} + +export interface GapAppend { + readonly line: string; + readonly appended: boolean; +} + +export function appendGap(filePath: string, entry: GapEntry): GapAppend { + const line = formatGapLine(entry); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8').split('\n') : undefined; + if (existing?.some((candidate) => candidate.startsWith('- ') && missOf(candidate) === missOf(line))) return { line, appended: false }; + const prefix = existing === undefined ? `${ GAP_LOG_HEADER }\n` : ''; + fs.appendFileSync(filePath, `${ prefix }${ line }\n`); + return { line, appended: true }; +} diff --git a/tools/design-readout/record/rerun.spec.ts b/tools/design-readout/record/rerun.spec.ts new file mode 100644 index 00000000000..bb7e883686b --- /dev/null +++ b/tools/design-readout/record/rerun.spec.ts @@ -0,0 +1,210 @@ +import { describe, expect, it } from 'vitest'; + +import { carryCorrections, diffRecords, renderRerun } from './rerun'; +import type { Correction, NodeRecord, Override, SidecarRecord } from './sidecar'; + +const TEXT: NodeRecord = { + id: '1:2', + values: { + kind: 'text', + text: '1248139', + trailingGlyphs: undefined, + font: { family: 'Inter', weight: 500, size: 14, lineHeight: 20 }, + colors: [ { role: 'text', hex: '#63B3ED', alpha: 1 } ], + }, + bbox: { x: 0, y: 0, width: 60, height: 20 }, + decision: { signal: 'number', value: '1248139', entities: [ 'block', 'batch', 'epoch' ] }, + status: 'recognized', + tokens: [ { role: 'text', color: '#63B3ED', tokens: [ 'link.primary' ] } ], + composite: null, + correction: null, + override: null, +}; + +const ICON: NodeRecord = { + id: '1:3', + values: { kind: 'icon', icon: 'Icons/block', colors: [] }, + bbox: { x: 70, y: 0, width: 20, height: 20 }, + decision: null, + status: 'unrecognized', + tokens: [], + composite: null, + correction: null, + override: null, +}; + +const CORRECTION: Correction = { component: 'BlockEntity', props: [ 'noIcon' ], gap: 'context', recordedAt: '2026-10-06T12:00:00.000Z', stale: false }; +const OVERRIDE: Override = { props: [ 'bg=whiteAlpha.100', 'fontWeight=500' ], recordedAt: '2026-10-06T12:30:00.000Z', stale: false }; + +function record(nodes: ReadonlyArray<NodeRecord>, overrides: Partial<SidecarRecord> = {}): SidecarRecord { + return { + version: 2, + createdAt: '2026-10-06T10:00:00.000Z', + fileKey: 'KEY', + nodeId: '1:1', + file: { lastModified: '2026-10-01T00:00:00Z', version: '42' }, + colorMode: 'light', + regions: [ '1:1' ], + nodes, + ...overrides, + }; +} + +const LATER: Partial<SidecarRecord> = { createdAt: '2026-10-07T10:00:00.000Z', file: { lastModified: '2026-10-07T00:00:00Z', version: '43' } }; + +function withText(node: NodeRecord, text: string): NodeRecord { + if (node.values.kind !== 'text') throw new Error('not a text node'); + return { ...node, values: { ...node.values, text } }; +} + +describe('diffRecords', () => { + it('reports an identical node as unchanged, and a box move alone as unchanged too', () => { + const moved = { ...TEXT, bbox: { x: 5, y: 5, width: 60, height: 20 } }; + expect(diffRecords(record([ TEXT ]), record([ moved ], LATER)).changes).toEqual([ { kind: 'unchanged', node: moved } ]); + }); + + it('reports a node whose only difference is a key JSON dropped on the way to disk as unchanged', () => { + const fromDisk = JSON.parse(JSON.stringify(TEXT)) as NodeRecord; + expect(fromDisk.values).not.toHaveProperty('trailingGlyphs'); + expect(diffRecords(record([ fromDisk ]), record([ TEXT ], LATER)).changes).toEqual([ { kind: 'unchanged', node: TEXT } ]); + expect(carryCorrections(record([ { ...fromDisk, correction: CORRECTION } ]), record([ TEXT ], LATER)).nodes[0].correction).toEqual(CORRECTION); + }); + + it('reports changed values, a changed decision, and both, naming which', () => { + const newText = withText(TEXT, '1248140'); + const newDecision: NodeRecord = { ...TEXT, status: 'ambiguous' }; + const both: NodeRecord = { ...withText(TEXT, 'abc'), decision: null, status: 'unrecognized' }; + expect(diffRecords(record([ TEXT ]), record([ newText ], LATER)).changes).toEqual([ + { kind: 'changed', previous: TEXT, next: newText, values: true, decision: false }, + ]); + expect(diffRecords(record([ TEXT ]), record([ newDecision ], LATER)).changes).toEqual([ + { kind: 'changed', previous: TEXT, next: newDecision, values: false, decision: true }, + ]); + expect(diffRecords(record([ TEXT ]), record([ both ], LATER)).changes).toEqual([ + { kind: 'changed', previous: TEXT, next: both, values: true, decision: true }, + ]); + }); + + it('lists new nodes in the new order and vanished nodes after them', () => { + const { changes } = diffRecords(record([ TEXT ]), record([ ICON ], LATER)); + expect(changes).toEqual([ { kind: 'new', node: ICON }, { kind: 'vanished', node: TEXT } ]); + }); + + it('carries both runs\' identity for the header', () => { + const diff = diffRecords(record([]), record([], LATER)); + expect(diff.previous).toEqual({ createdAt: '2026-10-06T10:00:00.000Z', file: { lastModified: '2026-10-01T00:00:00Z', version: '42' }, colorMode: 'light' }); + expect(diff.next).toEqual({ createdAt: '2026-10-07T10:00:00.000Z', file: { lastModified: '2026-10-07T00:00:00Z', version: '43' }, colorMode: 'light' }); + }); +}); + +describe('carryCorrections', () => { + const corrected: NodeRecord = { ...TEXT, correction: CORRECTION }; + + it('keeps a correction on an unchanged node as it was', () => { + const merged = carryCorrections(record([ corrected ]), record([ TEXT ], LATER)); + expect(merged.nodes[0].correction).toEqual(CORRECTION); + expect(merged.createdAt).toBe('2026-10-07T10:00:00.000Z'); + }); + + it('keeps a correction on a node whose values changed, flagged stale', () => { + const merged = carryCorrections(record([ corrected ]), record([ withText(TEXT, '1248140') ], LATER)); + expect(merged.nodes[0].correction).toEqual({ ...CORRECTION, stale: true }); + }); + + it('keeps a correction unflagged when only the tool\'s decision changed', () => { + const merged = carryCorrections(record([ corrected ]), record([ { ...TEXT, status: 'ambiguous' } ], LATER)); + expect(merged.nodes[0].correction).toEqual(CORRECTION); + }); + + it('never un-flags a stale correction on its own', () => { + const stale = { ...corrected, correction: { ...CORRECTION, stale: true } }; + expect(carryCorrections(record([ stale ]), record([ TEXT ], LATER)).nodes[0].correction).toEqual({ ...CORRECTION, stale: true }); + }); + + it('gives a new node no correction and drops the one of a vanished node', () => { + const merged = carryCorrections(record([ corrected ]), record([ ICON ], LATER)); + expect(merged.nodes).toEqual([ ICON ]); + }); + + it('leaves a node that had no correction or override without one when its values change', () => { + const merged = carryCorrections(record([ TEXT ]), record([ withText(TEXT, '1248140') ], LATER)); + expect(merged.nodes[0].correction).toBeNull(); + expect(merged.nodes[0].override).toBeNull(); + }); + + describe('override', () => { + const overridden: NodeRecord = { ...TEXT, correction: CORRECTION, override: OVERRIDE }; + + it('keeps an override on an unchanged node as it was, beside the correction', () => { + const merged = carryCorrections(record([ overridden ]), record([ TEXT ], LATER)); + expect(merged.nodes[0]).toEqual(overridden); + }); + + it('keeps an override on a node whose values changed, flagged stale', () => { + const merged = carryCorrections(record([ overridden ]), record([ withText(TEXT, '1248140') ], LATER)); + expect(merged.nodes[0].override).toEqual({ ...OVERRIDE, stale: true }); + expect(merged.nodes[0].correction).toEqual({ ...CORRECTION, stale: true }); + }); + + it('keeps an override unflagged when only the tool\'s decision changed, and never un-flags a stale one', () => { + expect(carryCorrections(record([ overridden ]), record([ { ...TEXT, status: 'ambiguous' } ], LATER)).nodes[0].override).toEqual(OVERRIDE); + const stale = { ...TEXT, override: { ...OVERRIDE, stale: true } }; + expect(carryCorrections(record([ stale ]), record([ TEXT ], LATER)).nodes[0].override).toEqual({ ...OVERRIDE, stale: true }); + }); + + it('gives a new node no override and drops the one of a vanished node', () => { + const merged = carryCorrections(record([ overridden ]), record([ ICON ], LATER)); + expect(merged.nodes).toEqual([ ICON ]); + }); + }); +}); + +describe('renderRerun', () => { + it('prints the header, the counts with corrections, and only the changed, new and vanished nodes', () => { + const corrected: NodeRecord = { ...TEXT, correction: CORRECTION }; + const previous = record([ corrected, ICON, { ...ICON, id: '1:4' } ]); + const recognizedIcon: NodeRecord = { ...ICON, id: '1:5', decision: { signal: 'icon', icon: 'block' }, status: 'recognized' }; + const next = carryCorrections(previous, record([ withText(TEXT, '1248140'), ICON, recognizedIcon ], { ...LATER, colorMode: 'dark' })); + expect(renderRerun(diffRecords(previous, next))).toBe([ + 'Re-run against the sidecar of 2026-10-06T10:00:00.000Z: file version 42 → 43, color mode light → dark', + 'Unchanged: 1 (0 recognized by correction)', + 'Changed: 3', + ' ~ 1:2 changed values; correction BlockEntity noIcon (context) is now STALE, re-confirm it', + ' was 1:2 text "1248139" — Inter 500 14/20; text #63B3ED — number: block or batch or epoch', + ' now 1:2 text "1248140" — Inter 500 14/20; text #63B3ED — number: block or batch or epoch', + ' + new 1:5 icon "Icons/block" — — icon "block"', + ' - vanished 1:4', + ].join('\n')); + }); + + it('counts an unchanged corrected node as recognized by correction and says a kept correction is kept', () => { + const corrected: NodeRecord = { ...TEXT, correction: CORRECTION }; + const previous = record([ corrected, { ...ICON, correction: { ...CORRECTION, component: 'IconSvg', props: [] } } ]); + const next = carryCorrections(previous, record([ TEXT, { ...ICON, status: 'ambiguous' } ], LATER)); + expect(renderRerun(diffRecords(previous, next))).toContain(', color mode light\nUnchanged: 1 (1 recognized by correction)'); + expect(renderRerun(diffRecords(previous, next))).toContain(' ~ 1:3 changed decision; correction IconSvg (context) kept'); + }); + + it('says when a vanished node takes its correction with it', () => { + const previous = record([ { ...TEXT, correction: CORRECTION } ]); + const next = carryCorrections(previous, record([], LATER)); + expect(renderRerun(diffRecords(previous, next))).toContain(' - vanished 1:2; its correction BlockEntity noIcon (context) is dropped'); + }); + + it('names an override on a changed line, stale or kept, after the correction when both exist', () => { + const previous = record([ { ...TEXT, correction: CORRECTION, override: OVERRIDE }, { ...ICON, override: OVERRIDE } ]); + const next = carryCorrections(previous, record([ withText(TEXT, '1248140'), { ...ICON, status: 'ambiguous' } ], LATER)); + const text = renderRerun(diffRecords(previous, next)); + expect(text).toContain([ + ' ~ 1:2 changed values; correction BlockEntity noIcon (context) is now STALE, re-confirm it', + '; override bg=whiteAlpha.100 fontWeight=500 is now STALE, re-confirm it', + ].join('')); + expect(text).toContain(' ~ 1:3 changed decision; override bg=whiteAlpha.100 fontWeight=500 kept'); + }); + + it('says when a vanished node takes its override with it, and marks an already stale one', () => { + const previous = record([ { ...TEXT, override: { ...OVERRIDE, stale: true } } ]); + const next = carryCorrections(previous, record([], LATER)); + expect(renderRerun(diffRecords(previous, next))).toContain(' - vanished 1:2; its override bg=whiteAlpha.100 fontWeight=500 (STALE) is dropped'); + }); +}); diff --git a/tools/design-readout/record/rerun.ts b/tools/design-readout/record/rerun.ts new file mode 100644 index 00000000000..ee7c09f9183 --- /dev/null +++ b/tools/design-readout/record/rerun.ts @@ -0,0 +1,151 @@ +import { isEqual } from 'es-toolkit'; + +import { describeLeaf } from '../extract/values'; +import { describeWhy } from '../recognize/signals'; +import type { Correction, NodeRecord, Override, SidecarRecord } from './sidecar'; + +export type NodeChange = + { readonly kind: 'unchanged'; readonly node: NodeRecord } | + { readonly kind: 'changed'; readonly previous: NodeRecord; readonly next: NodeRecord; readonly values: boolean; readonly decision: boolean } | + { readonly kind: 'new'; readonly node: NodeRecord } | + { readonly kind: 'vanished'; readonly node: NodeRecord }; + +type RunIdentity = Pick<SidecarRecord, 'createdAt' | 'file' | 'colorMode'>; + +export interface RerunDiff { + readonly previous: RunIdentity; + readonly next: RunIdentity; + readonly changes: ReadonlyArray<NodeChange>; +} + +type DecisionSlice = Pick<NodeRecord, 'decision' | 'status' | 'tokens' | 'composite'>; + +function decisionOf({ decision, status, tokens, composite }: NodeRecord): DecisionSlice { + return { decision, status, tokens, composite }; +} + +// The previous record came back through JSON, which drops a key whose value is `undefined` +// (`trailingGlyphs`), so the fresh extraction is put through the same round trip before comparing. +function stored<T>(value: T): T { + return JSON.parse(JSON.stringify(value)) as T; +} + +function changeOf(previous: NodeRecord, next: NodeRecord): NodeChange { + const values = !isEqual(stored(previous.values), stored(next.values)); + const decision = !isEqual(stored(decisionOf(previous)), stored(decisionOf(next))); + if (!values && !decision) return { kind: 'unchanged', node: next }; + return { kind: 'changed', previous, next, values, decision }; +} + +function identityOf({ createdAt, file, colorMode }: SidecarRecord): RunIdentity { + return { createdAt, file, colorMode }; +} + +// The new record's nodes in their order, then the vanished ones in the old record's order. A box +// move alone is neither a value nor a decision change: the box is layout, which the readout leaves +// to the developer, so a nudged row prints nothing. +export function diffRecords(previous: SidecarRecord, next: SidecarRecord): RerunDiff { + const before = new Map(previous.nodes.map((node) => [ node.id, node ])); + const after = new Set(next.nodes.map((node) => node.id)); + const changes: Array<NodeChange> = next.nodes.map((node) => { + const old = before.get(node.id); + return old === undefined ? { kind: 'new', node } : changeOf(old, node); + }); + for (const node of previous.nodes) { + if (!after.has(node.id)) changes.push({ kind: 'vanished', node }); + } + return { previous: identityOf(previous), next: identityOf(next), changes }; +} + +// A correction is the developer's word on the values they saw: it holds while the values hold, and +// a decision change alone (a new rule in the tool) does not unsettle it. Once the values differ the +// correction is kept but marked stale, for the developer to re-confirm with a new `--correct`. An +// override is carried under the same rule. +function valuesChanged(old: NodeRecord, next: NodeRecord): boolean { + const change = changeOf(old, next); + // Stryker disable next-line ConditionalExpression: the kind check narrows the union; an unchanged node has no values flag to read + return change.kind === 'changed' && change.values; +} + +function carriedCorrection(old: NodeRecord, next: NodeRecord): Correction | null { + if (old.correction === null) return null; + return valuesChanged(old, next) ? { ...old.correction, stale: true } : old.correction; +} + +function carriedOverride(old: NodeRecord, next: NodeRecord): Override | null { + if (old.override === null) return null; + return valuesChanged(old, next) ? { ...old.override, stale: true } : old.override; +} + +export function carryCorrections(previous: SidecarRecord, next: SidecarRecord): SidecarRecord { + const before = new Map(previous.nodes.map((node) => [ node.id, node ])); + return { + ...next, + nodes: next.nodes.map((node) => { + const old = before.get(node.id); + if (old === undefined) return { ...node, correction: null, override: null }; + return { ...node, correction: carriedCorrection(old, node), override: carriedOverride(old, node) }; + }), + }; +} + +export function describeCorrection(correction: Correction): string { + const props = correction.props.length === 0 ? '' : ` ${ correction.props.join(' ') }`; + return `${ correction.component }${ props } (${ correction.gap }${ correction.stale ? ', STALE' : '' })`; +} + +export function describeOverride(override: Override): string { + return `${ override.props.join(' ') }${ override.stale ? ' (STALE)' : '' }`; +} + +function describeRecord(node: NodeRecord): string { + return `${ describeLeaf(node) } — ${ describeWhy(node, node) }`; +} + +function describeChanged(change: Extract<NodeChange, { kind: 'changed' }>): Array<string> { + const what = [ change.values ? 'values' : undefined, change.decision ? 'decision' : undefined ].filter((part) => part !== undefined).join(' and '); + const fate = change.values ? 'is now STALE, re-confirm it' : 'kept'; + const { correction, override } = change.previous; + const carried = [ + correction === null ? '' : `; correction ${ describeCorrection(correction) } ${ fate }`, + override === null ? '' : `; override ${ describeOverride(override) } ${ fate }`, + ].join(''); + return [ + ` ~ ${ change.next.id } changed ${ what }${ carried }`, + ` was ${ describeRecord(change.previous) }`, + ` now ${ describeRecord(change.next) }`, + ]; +} + +function renderChange(change: NodeChange): Array<string> { + switch (change.kind) { + case 'unchanged': + return []; + case 'new': + return [ ` + new ${ describeRecord(change.node) }` ]; + case 'vanished': { + const { correction, override } = change.node; + const dropped = [ + correction === null ? '' : `; its correction ${ describeCorrection(correction) } is dropped`, + override === null ? '' : `; its override ${ describeOverride(override) } is dropped`, + ].join(''); + return [ ` - vanished ${ change.node.id }${ dropped }` ]; + } + case 'changed': + return describeChanged(change); + } +} + +export function renderRerun(diff: RerunDiff): string { + const unchanged = diff.changes.filter((change) => change.kind === 'unchanged'); + const corrected = unchanged.filter((change) => change.node.correction !== null).length; + const changed = diff.changes.filter((change) => change.kind !== 'unchanged'); + const mode = diff.previous.colorMode === diff.next.colorMode ? diff.next.colorMode : `${ diff.previous.colorMode } → ${ diff.next.colorMode }`; + const version = `${ diff.previous.file.version } → ${ diff.next.file.version }`; + return [ + `Re-run against the sidecar of ${ diff.previous.createdAt }: file version ${ version }, color mode ${ mode }`, + `Unchanged: ${ unchanged.length } (${ corrected } recognized by correction)`, + `Changed: ${ changed.length }`, + ...changed.flatMap(renderChange), + ].join('\n'); +} diff --git a/tools/design-readout/record/sidecar.spec.ts b/tools/design-readout/record/sidecar.spec.ts new file mode 100644 index 00000000000..318929b8fdc --- /dev/null +++ b/tools/design-readout/record/sidecar.spec.ts @@ -0,0 +1,197 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import type { Leaf } from '../extract/values'; +import type { Recognition } from '../recognize/signals'; +import { applyCorrection, applyOverride, buildRecord, isGapCategory, readSidecar, sidecarPath, writeSidecar } from './sidecar'; + +let tmp = ''; + +afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; +}); + +const LEAVES: ReadonlyArray<Leaf> = [ + { + id: '1:2', + bbox: { x: 1, y: 2, width: 3, height: 4 }, + values: { + kind: 'text', + text: 'Hi', + trailingGlyphs: undefined, + font: { family: 'Inter', weight: 500, size: 14, lineHeight: 20 }, + colors: [ { role: 'text', hex: '#FFFFFF', alpha: 0.8 } ], + }, + }, + { id: '1:3', bbox: null, values: { kind: 'icon', icon: 'Icons/x', colors: [] } }, +]; + +const TOKENS: Recognition['tokens'] = [ { role: 'text', color: '#FFFFFF/80', tokens: [ 'text.primary' ] } ]; +const COMPOSITE: Recognition['composite'] = { signal: 'from-to', part: 'arrow', members: { from: '1:1', arrow: '1:3', to: '1:4' } }; + +const RECOGNITIONS: ReadonlyArray<Recognition> = [ + { id: '1:2', status: 'unrecognized', decision: null, tokens: TOKENS, composite: null }, + { id: '1:3', status: 'recognized', decision: { signal: 'icon', icon: 'x' }, tokens: [], composite: COMPOSITE }, +]; + +function record(): ReturnType<typeof buildRecord> { + return buildRecord({ + createdAt: '2026-10-06T10:00:00.000Z', + fileKey: 'KEY', + nodeId: '22842:178383', + lastModified: '2026-10-01T00:00:00Z', + fileVersion: '42', + colorMode: 'dark', + regions: [ '22842:178383' ], + leaves: LEAVES, + recognitions: RECOGNITIONS, + }); +} + +describe('sidecarPath', () => { + it('is one file per file key and node under the main checkout, with a file-safe node id', () => { + expect(sidecarPath('/repo', 'KEY', '22842:178383')).toBe(path.join('/repo', '.ai', 'design-readout', 'KEY-22842-178383.json')); + }); +}); + +describe('buildRecord', () => { + it('carries the file identity, the color mode and one node per leaf with its status, decision, tokens, composite and empty developer slots', () => { + expect(record()).toEqual({ + version: 2, + createdAt: '2026-10-06T10:00:00.000Z', + fileKey: 'KEY', + nodeId: '22842:178383', + file: { lastModified: '2026-10-01T00:00:00Z', version: '42' }, + colorMode: 'dark', + regions: [ '22842:178383' ], + nodes: [ + { + id: '1:2', + values: LEAVES[0].values, + bbox: { x: 1, y: 2, width: 3, height: 4 }, + decision: null, + status: 'unrecognized', + tokens: TOKENS, + composite: null, + correction: null, + override: null, + }, + { + id: '1:3', + values: LEAVES[1].values, + bbox: null, + decision: { signal: 'icon', icon: 'x' }, + status: 'recognized', + tokens: [], + composite: COMPOSITE, + correction: null, + override: null, + }, + ], + }); + }); + + it('fails on a leaf with no recognition rather than writing a half-filled record', () => { + expect(() => buildRecord({ + createdAt: '2026-10-06T10:00:00.000Z', + fileKey: 'KEY', + nodeId: '22842:178383', + lastModified: '2026-10-01T00:00:00Z', + fileVersion: '42', + colorMode: 'dark', + regions: [ '22842:178383' ], + leaves: LEAVES, + recognitions: RECOGNITIONS.slice(0, 1), + })).toThrow('Leaf 1:3 has no recognition.'); + }); + + it('stores no Figma hint, style name, component name or layer name', () => { + const built = record(); + expect(Object.keys(built).sort()).toEqual([ 'colorMode', 'createdAt', 'file', 'fileKey', 'nodeId', 'nodes', 'regions', 'version' ]); + for (const node of built.nodes) { + expect(Object.keys(node).sort()).toEqual([ 'bbox', 'composite', 'correction', 'decision', 'id', 'override', 'status', 'tokens', 'values' ]); + } + expect(JSON.stringify(built)).not.toMatch(/hint|style|component|layer|name/i); + }); +}); + +describe('isGapCategory', () => { + it('accepts exactly the seven categories', () => { + for (const category of [ 'shape', 'icon', 'color', 'composite', 'context', 'layout', 'convention' ]) expect(isGapCategory(category)).toBe(true); + expect(isGapCategory('Shape')).toBe(false); + expect(isGapCategory('typo')).toBe(false); + }); +}); + +describe('applyCorrection', () => { + const correction = { component: 'IconSvg', props: [ 'name=x' ], gap: 'icon' as const, recordedAt: '2026-10-07T09:30:00.000Z', stale: false }; + + it('sets the correction on the named node and leaves the rest of the record alone', () => { + const corrected = applyCorrection(record(), '1:3', correction); + expect(corrected.nodes[1]).toEqual({ ...record().nodes[1], correction }); + expect({ ...corrected, nodes: undefined }).toEqual({ ...record(), nodes: undefined }); + expect(corrected.nodes[0]).toEqual(record().nodes[0]); + }); + + it('replaces an earlier correction on the same node', () => { + const twice = applyCorrection(applyCorrection(record(), '1:3', { ...correction, stale: true }), '1:3', correction); + expect(twice.nodes[1].correction).toEqual(correction); + }); + + it('rejects a node that is not in the record, naming the ones that are', () => { + expect(() => applyCorrection(record(), '9:9', correction)).toThrow('Node 9:9 is not in the sidecar of 22842:178383; its nodes are 1:2, 1:3.'); + }); +}); + +describe('applyOverride', () => { + const override = { props: [ 'bg=whiteAlpha.100', 'fontWeight=500' ], recordedAt: '2026-10-08T09:30:00.000Z', stale: false }; + const correction = { component: 'IconSvg', props: [ 'name=x' ], gap: 'icon' as const, recordedAt: '2026-10-07T09:30:00.000Z', stale: false }; + + it('sets the override on the named node, beside its correction, and leaves the rest of the record alone', () => { + const corrected = applyCorrection(record(), '1:3', correction); + const overridden = applyOverride(corrected, '1:3', override); + expect(overridden.nodes[1]).toEqual({ ...record().nodes[1], correction, override }); + expect({ ...overridden, nodes: undefined }).toEqual({ ...record(), nodes: undefined }); + expect(overridden.nodes[0]).toEqual(record().nodes[0]); + }); + + it('replaces an earlier override on the same node whole', () => { + const twice = applyOverride(applyOverride(record(), '1:3', { ...override, props: [ 'color=text.primary' ], stale: true }), '1:3', override); + expect(twice.nodes[1].override).toEqual(override); + }); + + it('rejects a node that is not in the record, naming the ones that are', () => { + expect(() => applyOverride(record(), '9:9', override)).toThrow('Node 9:9 is not in the sidecar of 22842:178383; its nodes are 1:2, 1:3.'); + }); +}); + +describe('writeSidecar / readSidecar', () => { + it('writes pretty JSON, creating the folder, and reads the same record back', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-sidecar-')); + const target = sidecarPath(tmp, 'KEY', '22842:178383'); + writeSidecar(target, record()); + expect(fs.readFileSync(target, 'utf8')).toMatch(/^\{\n {2}"version": 2,\n/); + expect(readSidecar(target)).toEqual(record()); + }); + + it('reads a version-2 record written before the override slot with every override null', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-sidecar-')); + const target = path.join(tmp, 'old.json'); + const legacy = { ...record(), nodes: record().nodes.map(({ override: _, ...node }) => node) }; + fs.writeFileSync(target, JSON.stringify(legacy)); + expect(readSidecar(target)).toEqual(record()); + }); + + it('rejects a file that is not a sidecar of the current version', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'design-readout-sidecar-')); + const target = path.join(tmp, 'x.json'); + fs.writeFileSync(target, JSON.stringify({ version: 99 })); + expect(() => readSidecar(target)).toThrow('Not a design-readout sidecar (version 2)'); + fs.writeFileSync(target, JSON.stringify(null)); + expect(() => readSidecar(target)).toThrow('Not a design-readout sidecar'); + }); +}); diff --git a/tools/design-readout/record/sidecar.ts b/tools/design-readout/record/sidecar.ts new file mode 100644 index 00000000000..54a4a30f9a1 --- /dev/null +++ b/tools/design-readout/record/sidecar.ts @@ -0,0 +1,140 @@ +import fs from 'fs'; +import path from 'path'; + +import { GAP_CATEGORIES, SIDECAR_DIR } from '../config'; +import type { Leaf, LeafValues } from '../extract/values'; +import type { BoundingBox } from '../fetch/figma'; +import { fileSafeNodeId } from '../fetch/url'; +import type { ColorMode } from '../recognize/colormap'; +import type { ColorTokens, CompositeMembership, Decision, Recognition, RecognitionStatus } from '../recognize/signals'; + +export const SIDECAR_VERSION = 2; + +export type GapCategory = typeof GAP_CATEGORIES[number]; + +// What the developer said a node is, against what the tool said: the repo component, its props as +// given, and the kind of miss. `stale` is set by a re-run whose values for the node differ from the +// ones the correction was given on; the correction stays until the developer re-confirms it. +export interface Correction { + readonly component: string; + readonly props: ReadonlyArray<string>; + readonly gap: GapCategory; + readonly recordedAt: string; + readonly stale: boolean; +} + +// What the mockup styles on purpose, on a node whose component the tool read right: Chakra props as +// `<prop>=<value>` words, over the shipped component's own. Not a miss: it names no component and logs +// no gap. `stale` follows the correction's rule — set by a re-run whose values differ. +export interface Override { + readonly props: ReadonlyArray<string>; + readonly recordedAt: string; + readonly stale: boolean; +} + +// Per node: the values and box this run extracted, what recognition decided (the signal that fired +// and what it says the node is; `null` when nothing fired) with its status, the tokens each fill +// resolved to in the run's mode, the composite the node is part of (`null` when none fired), and +// the slots for the developer's correction and style override, each `null` until given. +export interface NodeRecord { + readonly id: string; + readonly values: LeafValues; + readonly bbox: BoundingBox | null; + readonly decision: Decision | null; + readonly status: RecognitionStatus; + readonly tokens: ReadonlyArray<ColorTokens>; + readonly composite: CompositeMembership | null; + readonly correction: Correction | null; + readonly override: Override | null; +} + +export interface SidecarRecord { + readonly version: number; + readonly createdAt: string; + readonly fileKey: string; + readonly nodeId: string; + readonly file: { + readonly lastModified: string; + readonly version: string; + }; + readonly colorMode: ColorMode; + readonly regions: ReadonlyArray<string>; + readonly nodes: ReadonlyArray<NodeRecord>; +} + +export interface SidecarInputs { + readonly createdAt: string; + readonly fileKey: string; + readonly nodeId: string; + readonly lastModified: string; + readonly fileVersion: string; + readonly colorMode: ColorMode; + readonly regions: ReadonlyArray<string>; + readonly leaves: ReadonlyArray<Leaf>; + readonly recognitions: ReadonlyArray<Recognition>; +} + +function nodeRecordOf(leaf: Leaf, recognitions: ReadonlyMap<string, Recognition>): NodeRecord { + const recognition = recognitions.get(leaf.id); + if (recognition === undefined) throw new Error(`Leaf ${ leaf.id } has no recognition.`); + const { decision, status, tokens, composite } = recognition; + return { id: leaf.id, values: leaf.values, bbox: leaf.bbox, decision, status, tokens, composite, correction: null, override: null }; +} + +export function buildRecord(inputs: SidecarInputs): SidecarRecord { + const recognitions = new Map(inputs.recognitions.map((recognition) => [ recognition.id, recognition ])); + return { + version: SIDECAR_VERSION, + createdAt: inputs.createdAt, + fileKey: inputs.fileKey, + nodeId: inputs.nodeId, + file: { lastModified: inputs.lastModified, version: inputs.fileVersion }, + colorMode: inputs.colorMode, + regions: inputs.regions, + nodes: inputs.leaves.map((leaf) => nodeRecordOf(leaf, recognitions)), + }; +} + +export function isGapCategory(value: string): value is GapCategory { + return (GAP_CATEGORIES as ReadonlyArray<string>).includes(value); +} + +function assertNode(record: SidecarRecord, nodeId: string): void { + if (!record.nodes.some((node) => node.id === nodeId)) { + throw new Error(`Node ${ nodeId } is not in the sidecar of ${ record.nodeId }; its nodes are ${ record.nodes.map((node) => node.id).join(', ') }.`); + } +} + +export function applyCorrection(record: SidecarRecord, nodeId: string, correction: Correction): SidecarRecord { + assertNode(record, nodeId); + return { ...record, nodes: record.nodes.map((node) => node.id === nodeId ? { ...node, correction } : node) }; +} + +// Replaces the node's override whole, as `applyCorrection` does; the correction slot is untouched. +export function applyOverride(record: SidecarRecord, nodeId: string, override: Override): SidecarRecord { + assertNode(record, nodeId); + return { ...record, nodes: record.nodes.map((node) => node.id === nodeId ? { ...node, override } : node) }; +} + +export function sidecarPath(mainCheckout: string, fileKey: string, nodeId: string): string { + return path.join(mainCheckout, SIDECAR_DIR, `${ fileKey }-${ fileSafeNodeId(nodeId) }.json`); +} + +export function writeSidecar(filePath: string, record: SidecarRecord): void { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, `${ JSON.stringify(record, null, 2) }\n`); +} + +function isRecord(value: unknown): value is Record<string, unknown> { + // Stryker disable next-line ConditionalExpression: a primitive reads `version` as undefined and fails the same check; the typeof only narrows the type + return typeof value === 'object' && value !== null; +} + +export function readSidecar(filePath: string): SidecarRecord { + const parsed: unknown = JSON.parse(fs.readFileSync(filePath, 'utf8')); + if (!isRecord(parsed) || parsed.version !== SIDECAR_VERSION) throw new Error(`Not a design-readout sidecar (version ${ SIDECAR_VERSION }): ${ filePath }`); + // Only this tool writes the folder; the version is the one field an edited file could drift on. The + // override slot came after version 2 was cut, so a record written before it reads back with `null`. + const record = parsed as unknown as SidecarRecord; + return { ...record, nodes: record.nodes.map((node) => ({ ...node, override: node.override ?? null })) }; +} diff --git a/tools/design-readout/run.sh b/tools/design-readout/run.sh new file mode 100755 index 00000000000..35df6ca794b --- /dev/null +++ b/tools/design-readout/run.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# Usage: tools/design-readout/run.sh <figma node URL> [--regions <ids>] [--dump <path>] + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" + +# The tool imports the shared flag parser from ../cli and the theme defaults from ../../src, so tsc's +# rootDir is the repo root and the entry point lands two levels deeper than the outDir. +# A module that moved or was renamed leaves its old .js in dist, and Node would still resolve it. +rm -rf "$DIR/dist" +"$ROOT/node_modules/.bin/tsc" -p "$DIR/tsconfig.json" +node "$DIR/dist/tools/design-readout/index.js" "$@" diff --git a/tools/design-readout/tsconfig.json b/tools/design-readout/tsconfig.json new file mode 100644 index 00000000000..23eaee50e27 --- /dev/null +++ b/tools/design-readout/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "node16", + "target": "es2022", + "moduleResolution": "node16", + "resolveJsonModule": true, + "isolatedModules": false, + "noEmit": false, + "incremental": false, + "rootDir": "../..", + "outDir": "./dist" + }, + "include": [ + "./index.ts" + ], + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/tools/dev-server/CONTEXT.md b/tools/dev-server/CONTEXT.md index ac618e89788..7040691903e 100644 --- a/tools/dev-server/CONTEXT.md +++ b/tools/dev-server/CONTEXT.md @@ -1,6 +1,7 @@ # Dev server - context -How the local dev server **and** the demo (review) deploy get their `NEXT_PUBLIC_*` +Everything that runs the app **on this machine** — the dev server, a local production build, the +locally built docker image — and how it **and** the demo (review) deploy get their `NEXT_PUBLIC_*` env vars. The model: instead of committing a per-instance preset file for every chain, we **fetch a live instance's public config over HTTP at startup** and write it to a throwaway `.env.tmp`. This directory owns the registry, the fetch logic, and the run @@ -32,10 +33,18 @@ its name. | `dev.preset.sh` | `pnpm dev:preset <alias> [--port <number>]` — fetch + run `next dev`. | | `dev.local.sh` | `pnpm dev:local [--port <number>]` — run against a local backend using `.env.localhost` (no fetch). Skips the multichain config: a local backend serves a single chain. | | `prod.preset.sh` | `pnpm prod:preset <alias> [--port <number>] [--skip-build]` — fetch + `next build` + `next start` (production build, e.g. for performance measurements); `--skip-build` restarts from the existing `.next` output. `--profile` builds the React-profileable variant (see `tools/profiling/CONTEXT.md`). | -| `run_steps.sh` | Sourced by all three run scripts: env layering (`build_port_args`, `build_env_args`), asset regeneration (`prepare_assets`), and the launch wrapper (`run_with_envs`). What stays in a run script is its argument parsing and the command it finally runs. | +| `docker.build.sh` | `pnpm build:docker` — build the production image locally as `blockscout-frontend:local`. | +| `docker.preset.sh` | `pnpm start:docker:preset <alias>` — fetch + run that image; the docker counterpart of `dev.preset.sh`. | +| `docker.local.sh` | `pnpm start:docker:local` — run that image against a local backend using `.env.localhost`; the docker counterpart of `dev.local.sh`. | +| `run_steps.sh` | Sourced by every entry point: env layering (`build_port_args`, `build_env_args`, `build_docker_env_args`), asset cleanup / regeneration (`clean_assets`, `prepare_assets`), and the launch wrapper (`run_with_envs`). What stays in an entry point is its argument parsing and the command it finally runs. | | `.env.localhost` | Committed base config for local-backend dev. | +<<<<<<< HEAD | `sync-preset-lists.mjs` | Regenerates / checks the alias dropdowns from `registry.json`. | | `fetch.js`, `tsconfig.tsbuildinfo` | Build artifacts - git-ignored, regenerated on run. | +======= +| `sync-presets/` | Regenerates / checks the alias dropdowns from `registry.json`; `run.sh` is its compile-on-run wrapper. | +| `fetch.js`, `sync-presets/dist/`, `tsconfig.tsbuildinfo` | Build artifacts — git-ignored, regenerated on run. | +>>>>>>> v2.13.0 ## Dropped envs: `ignoredEnvs` vs `deprecatedEnvs` @@ -73,11 +82,20 @@ lives here): - **`--omit-local-envs` is the dev/container switch.** Dev mode applies `localEnvs` (so APP_HOST etc. point at `localhost`); the container passes `--omit-local-envs` so those keys are absent and the deployment's own APP_* values survive (this replaced the old entrypoint blacklist). +- **`tools/dev-server/tsconfig.json` must never get an `outDir`.** `fetch.js` has to emit beside + `fetch.ts` — the Dockerfile `COPY`s it from there and `fetch.sh` runs it from there. That is why the + sync tool has its own `sync-presets/tsconfig.json` emitting to `sync-presets/dist/`. ## Env layering (highest → lowest priority) - `dev:preset` / `prod:preset`: `--port` flag → `.env.local` → `.env.extra` → `.env.secrets` → `.env.tmp` (fetched instance) - `dev:local`: `--port` flag → `.env.local` → `.env.extra` → `.env.secrets` → `.env.localhost` +- `start:docker:preset`: `.env.local` → `.env.extra` → `.env.secrets` → `.env.tmp` (no `--port` flag) +- `start:docker:local`: `.env.local` → `.env.extra` → `.env.secrets` → `.env.localhost` (no `--port` flag) + +The docker entries pass the same files as `docker run --env-file`s, whose precedence is the **reverse** +of dotenv-cli's (last file wins) — `build_docker_env_args` lists them lowest-priority-first for that +reason. The `--port` flag sets `NEXT_PUBLIC_APP_PORT` via dotenv-cli's `-v` (applied AFTER all `-e` files, so it beats every env file). It overrides the env var rather than just `next dev -p` @@ -90,7 +108,7 @@ that's what lets a `--skip-build` restart move to a different port. | File | Committed? | Purpose | |---|---|---| | `.env.local` | git-ignored | Personal, local-only overrides (Next convention). | -| `.env.extra` | **committed** (empty on main) | Branch/feature ENVs that must also reach the **demo deploy**. No secrets. | +| `.env.extra` | **committed** (empty on main) | Branch/feature ENVs that must also reach the **demo deploy**. No secrets. **Lives at the repo root** | | `.env.secrets` | git-ignored (repo root) | Local secret overrides; optional (fetched config already carries public keys). | | `.env.tmp` | git-ignored | The fetched instance config; overwritten each start, left on disk for inspection. | @@ -116,6 +134,6 @@ retain runtime preset injection for upstream deployments that consume them: 3. Commit. CI runs `pnpm presets:lint` (in `checks.yml`) and **fails the PR if the dropdowns drift** from the registry. -Other consumers (`tools/scripts/{sitemap,og-image}-generator.dev.sh`, the essential-dapps / -feature-reporter / llms-txt generators, `docker.preset.sh`) all fetch via `fetch.sh <alias>` and -run against the resulting `.env.tmp`. +Other consumers (the `dev.sh` / `pnpm dev` of each `deploy/tools/*` generator that needs an instance +config, `docker.preset.sh`) all fetch via `fetch.sh <alias>` and run against the resulting +`.env.tmp`, written to the caller's cwd. diff --git a/tools/dev-server/docker.build.sh b/tools/dev-server/docker.build.sh new file mode 100755 index 00000000000..b3d98666848 --- /dev/null +++ b/tools/dev-server/docker.build.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# Builds the production image locally as blockscout-frontend:local, tagged with the current git +# sha / tag. Run it with docker.preset.sh or docker.local.sh. + +source ./tools/dev-server/run_steps.sh + +# the Dockerfile COPYs public/ into the image, so a stale local run must not leak into it +clean_assets + +docker build \ + --progress=plain \ + --build-arg GIT_COMMIT_SHA=$(git rev-parse --short HEAD) \ + --build-arg GIT_TAG=$(git describe --tags --abbrev=0) \ + -t blockscout-frontend:local ./ diff --git a/tools/dev-server/docker.local.sh b/tools/dev-server/docker.local.sh new file mode 100755 index 00000000000..e39c3a09b7b --- /dev/null +++ b/tools/dev-server/docker.local.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +# Runs the locally built image (see docker.build.sh) against a LOCAL backend using the committed +# tools/dev-server/.env.localhost config — the docker counterpart of dev.local.sh, with the same +# env layering. + +source ./tools/dev-server/run_steps.sh + +usage="Usage: pnpm start:docker:local" + +while [ "$#" -gt 0 ]; do + case "$1" in + --) + shift ;; + *) + echo "🚨 Unknown argument \"$1\"." + echo "$usage" + exit 1 ;; + esac +done + +build_docker_env_args ./tools/dev-server/.env.localhost + +docker run -p 3000:3000 "${docker_env_args[@]}" blockscout-frontend:local | pino-pretty diff --git a/tools/dev-server/docker.preset.sh b/tools/dev-server/docker.preset.sh new file mode 100755 index 00000000000..edaad4a6468 --- /dev/null +++ b/tools/dev-server/docker.preset.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +# Runs the locally built image (see docker.build.sh) against a live instance's config, fetched over +# HTTP at startup — the docker counterpart of dev.preset.sh, with the same env layering. + +source ./tools/dev-server/run_steps.sh + +usage="Usage: pnpm start:docker:preset <instance_alias>" + +positional=() +while [ "$#" -gt 0 ]; do + case "$1" in + --) + # `pnpm start:docker:preset -- eth` forwards the separator into the script; drop it + shift ;; + *) + positional+=( "$1" ); shift ;; + esac +done + +if [ "${#positional[@]}" -ne 1 ]; then + echo "$usage" + exit 1 +fi + +preset_name="${positional[0]}" + +# Fetch the instance config into ./.env.tmp (raw KEY=value, docker --env-file compatible) +./tools/dev-server/fetch.sh "$preset_name" || exit 1 + +build_docker_env_args ./.env.tmp + +docker run -p 3000:3000 "${docker_env_args[@]}" blockscout-frontend:local | pino-pretty diff --git a/tools/dev-server/prod.preset.sh b/tools/dev-server/prod.preset.sh index fe983094401..b2e627c1eeb 100755 --- a/tools/dev-server/prod.preset.sh +++ b/tools/dev-server/prod.preset.sh @@ -71,7 +71,7 @@ if [ "$skip_build" = false ]; then prepare_assets "$preset_name" # build the app - run_with_envs "source ./deploy/scripts/export_pro_api_flag.sh && next build${build_flags}" || exit 1 + run_with_envs "source ./deploy/scripts/export_pro_api_flag.sh && pnpm lint:tsc && next build${build_flags}" || exit 1 echo "" else if [ ! -f ./.env.tmp ]; then diff --git a/tools/dev-server/registry.json b/tools/dev-server/registry.json index 69172bd29a7..dc6d440beb4 100644 --- a/tools/dev-server/registry.json +++ b/tools/dev-server/registry.json @@ -10,7 +10,7 @@ "eth": "https://eth.blockscout.com", "eth_sepolia": "https://eth-sepolia.blockscout.com", "filecoin": "https://filecoin.blockscout.com", - "garnet": "https://explorer.garnetchain.com", + "fuse": "https://explorer.fuse.io", "gnosis": "https://gnosis.blockscout.com", "gnosis_chiado": "https://gnosis-chiado.blockscout.com", "hpp": "https://explorer.hpp.io", @@ -25,7 +25,6 @@ "rootstock": "https://rootstock.blockscout.com", "rootstock_testnet": "https://rootstock-testnet.blockscout.com", "robinhood": "https://robinhoodchain.blockscout.com", - "scroll_sepolia": "https://scroll-sepolia.blockscout.com", "shibarium": "https://www.shibariumscan.io", "stability_testnet": "https://stability-testnet.blockscout.com", "staging": "https://eth-sepolia.k8s-dev.blockscout.com", @@ -35,6 +34,5 @@ "zetachain": "https://zetascan.com", "zetachain_testnet": "https://testnet.zetascan.com", "zilliqa": "https://zilliqa.blockscout.com", - "zksync": "https://zksync.blockscout.com", - "zora": "https://explorer.zora.energy" + "zksync": "https://zksync.blockscout.com" } diff --git a/tools/dev-server/run_steps.sh b/tools/dev-server/run_steps.sh index 863e8e9996d..33996a77989 100644 --- a/tools/dev-server/run_steps.sh +++ b/tools/dev-server/run_steps.sh @@ -2,7 +2,7 @@ # The steps every local run script performs, in the order they perform them: # layer the env files, regenerate what the app reads from disk at boot, launch. -# Shared by dev.preset.sh, dev.local.sh and prod.preset.sh — what stays in those scripts is +# Shared by the dev.*, prod.* and docker.* entry points — what stays in those scripts is # their argument parsing and the command they finally run. # # Must be SOURCED, not executed: prepare_assets sources deploy/scripts/build_sprite.sh so the @@ -21,6 +21,7 @@ set -o pipefail port_args=() env_args=() +docker_env_args=() # --port overrides NEXT_PUBLIC_APP_PORT (dotenv-cli applies -v variables AFTER the -e files, # so this beats every env file). Overriding the env var — not just `next dev -p` — keeps the @@ -65,6 +66,31 @@ build_env_args() { env_args+=( -e "$1" ) } +# The same files in `docker run --env-file` order. Docker's precedence is the REVERSE of +# dotenv-cli's: the LAST --env-file wins, so the list is lowest priority first. +# +# Usage: build_docker_env_args <base_env_file> +# Sets: docker_env_args +build_docker_env_args() { + docker_env_args=( --env-file "$1" ) + if [ -f ./.env.secrets ]; then + docker_env_args+=( --env-file ./.env.secrets ) + fi + docker_env_args+=( --env-file ./.env.extra ) + if [ -f ./.env.local ]; then + docker_env_args+=( --env-file ./.env.local ) + fi +} + +# Removes everything a previous run generated under public/, so neither a dev server nor a docker +# build (which COPYs public/ into the image) picks up stale assets. +clean_assets() { + rm -rf ./public/assets/configs + rm -rf ./public/assets/multichain + rm -rf ./public/assets/essential-dapps + rm -rf ./public/assets/envs.js +} + # Regenerates everything the app reads off disk at boot: the downloaded instance assets, the # generated configs, the icon sprite and the route map. # @@ -75,11 +101,7 @@ build_env_args() { prepare_assets() { local preset_name="$1" - # remove previous assets - rm -rf ./public/assets/configs - rm -rf ./public/assets/multichain - rm -rf ./public/assets/essential-dapps - rm -rf ./public/assets/envs.js + clean_assets # download assets for the running instance dotenv \ diff --git a/tools/dev-server/sync-presets/cli.spec.ts b/tools/dev-server/sync-presets/cli.spec.ts new file mode 100644 index 00000000000..fa96cb7d986 --- /dev/null +++ b/tools/dev-server/sync-presets/cli.spec.ts @@ -0,0 +1,142 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; + +import type { CliPaths } from './cli'; +import { DRIFT_MESSAGE, runSync } from './cli'; +import { TARGETS, buildBlock } from './sync'; + +const [ WORKFLOW_TARGET, TASKS_TARGET ] = TARGETS; + +const REGISTRY = '{"eth":"https://eth.example","gnosis":"https://gnosis.example"}'; +const ALIASES = [ 'eth', 'gnosis' ]; + +let paths: CliPaths; + +function writeTarget(file: string, blockLines: ReadonlyArray<string>): void { + const absPath = path.join(paths.root, file); + fs.mkdirSync(path.dirname(absPath), { recursive: true }); + fs.writeFileSync(absPath, [ 'before', ...blockLines, 'after', '' ].join('\n')); +} + +function readTarget(file: string): string { + return fs.readFileSync(path.join(paths.root, file), 'utf8'); +} + +function inSyncBlock(target: typeof WORKFLOW_TARGET): Array<string> { + return buildBlock(target, ALIASES).split('\n'); +} + +function driftedBlock(target: typeof WORKFLOW_TARGET): Array<string> { + return buildBlock(target, [ 'eth' ]).split('\n'); +} + +function writeBothTargets(blockOf: (target: typeof WORKFLOW_TARGET) => Array<string>): void { + writeTarget(WORKFLOW_TARGET.file, blockOf(WORKFLOW_TARGET)); + writeTarget(TASKS_TARGET.file, blockOf(TASKS_TARGET)); +} + +beforeEach(() => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'sync-presets-')); + paths = { root, registryPath: path.join(root, 'registry.json') }; + fs.writeFileSync(paths.registryPath, REGISTRY); +}); + +afterEach(() => { + fs.rmSync(paths.root, { recursive: true, force: true }); +}); + +describe('check mode', () => { + it('exits 0 and prints a tick per target when both are in sync', () => { + writeBothTargets(inSyncBlock); + + const result = runSync(paths, false); + + expect(result.exitCode).toBe(0); + expect(result.output).toEqual([ + { stream: 'out', text: `✓ ${ WORKFLOW_TARGET.file }` }, + { stream: 'out', text: `✓ ${ TASKS_TARGET.file }` }, + ]); + }); + + it('exits 1, names the drifted file on stderr and appends the hint', () => { + writeTarget(WORKFLOW_TARGET.file, driftedBlock(WORKFLOW_TARGET)); + writeTarget(TASKS_TARGET.file, inSyncBlock(TASKS_TARGET)); + + const result = runSync(paths, false); + + expect(result.exitCode).toBe(1); + expect(result.output).toEqual([ + { stream: 'err', text: `✗ out of sync: ${ WORKFLOW_TARGET.file }` }, + { stream: 'out', text: `✓ ${ TASKS_TARGET.file }` }, + { stream: 'err', text: DRIFT_MESSAGE }, + ]); + }); + + it('leaves a drifted file untouched', () => { + writeBothTargets(driftedBlock); + const before = readTarget(WORKFLOW_TARGET.file); + + runSync(paths, false); + + expect(readTarget(WORKFLOW_TARGET.file)).toBe(before); + }); +}); + +describe('write mode', () => { + it('exits 0 and reports "ok" per target when nothing needs rewriting', () => { + writeBothTargets(inSyncBlock); + + const result = runSync(paths, true); + + expect(result.exitCode).toBe(0); + expect(result.output).toEqual([ + { stream: 'out', text: `✓ ok ${ WORKFLOW_TARGET.file }` }, + { stream: 'out', text: `✓ ok ${ TASKS_TARGET.file }` }, + ]); + }); + + it('rewrites a drifted file, reports "updated" and still exits 0', () => { + writeBothTargets(driftedBlock); + + const result = runSync(paths, true); + + expect(result.exitCode).toBe(0); + expect(result.output).toEqual([ + { stream: 'out', text: `✏️ updated ${ WORKFLOW_TARGET.file }` }, + { stream: 'out', text: `✏️ updated ${ TASKS_TARGET.file }` }, + ]); + expect(readTarget(WORKFLOW_TARGET.file)).toContain(' - gnosis'); + expect(readTarget(TASKS_TARGET.file)).toContain(' "gnosis",'); + }); + + it('preserves the lines around the block', () => { + writeBothTargets(driftedBlock); + + runSync(paths, true); + + const lines = readTarget(WORKFLOW_TARGET.file).split('\n'); + expect(lines[0]).toBe('before'); + expect(lines.at(-2)).toBe('after'); + }); + + it('leaves the tree in a state a following check passes', () => { + writeBothTargets(driftedBlock); + + runSync(paths, true); + + expect(runSync(paths, false).exitCode).toBe(0); + }); +}); + +describe('malformed markers', () => { + it('throws naming the target file rather than reporting drift', () => { + writeTarget(WORKFLOW_TARGET.file, [ ' # presets:end' ]); + writeTarget(TASKS_TARGET.file, inSyncBlock(TASKS_TARGET)); + + expect(() => runSync(paths, false)) + .toThrow(`Missing or malformed presets:start/presets:end markers in ${ WORKFLOW_TARGET.file }`); + }); +}); diff --git a/tools/dev-server/sync-presets/cli.ts b/tools/dev-server/sync-presets/cli.ts new file mode 100644 index 00000000000..7ba57894daf --- /dev/null +++ b/tools/dev-server/sync-presets/cli.ts @@ -0,0 +1,60 @@ +import fs from 'fs'; +import path from 'path'; + +import type { PresetTarget } from './sync'; +import { TARGETS, parseAliases, syncTarget } from './sync'; + +export const DRIFT_MESSAGE = + '\nPreset dropdowns are out of sync with tools/dev-server/registry.json. Run `pnpm presets:sync`.'; + +export interface CliPaths { + readonly root: string; + readonly registryPath: string; +} + +export interface OutputLine { + readonly stream: 'out' | 'err'; + readonly text: string; +} + +export interface CliResult { + readonly output: ReadonlyArray<OutputLine>; + readonly exitCode: number; +} + +function formatOutcome(target: PresetTarget, changed: boolean, write: boolean): OutputLine { + if (write) { + return { stream: 'out', text: `${ changed ? '✏️ updated ' : '✓ ok ' } ${ target.file }` }; + } + if (changed) { + return { stream: 'err', text: `✗ out of sync: ${ target.file }` }; + } + return { stream: 'out', text: `✓ ${ target.file }` }; +} + +export function runSync(paths: CliPaths, write: boolean): CliResult { + const aliases = parseAliases(fs.readFileSync(paths.registryPath, 'utf8')); + const output: Array<OutputLine> = []; + let drift = false; + + for (const target of TARGETS) { + const absPath = path.join(paths.root, target.file); + const { next, changed } = syncTarget(target, fs.readFileSync(absPath, 'utf8'), aliases); + + if (write && changed) { + fs.writeFileSync(absPath, next); + } + if (!write && changed) { + drift = true; + } + + output.push(formatOutcome(target, changed, write)); + } + + if (drift) { + output.push({ stream: 'err', text: DRIFT_MESSAGE }); + return { output, exitCode: 1 }; + } + + return { output, exitCode: 0 }; +} diff --git a/tools/dev-server/sync-presets/index.ts b/tools/dev-server/sync-presets/index.ts new file mode 100644 index 00000000000..21ae725ea0c --- /dev/null +++ b/tools/dev-server/sync-presets/index.ts @@ -0,0 +1,26 @@ +/* eslint-disable no-console -- this is a CLI whose entire job is to print a per-target status line */ +import path from 'path'; + +import { runSync } from './cli'; + +// Regenerates / checks the alias dropdowns from tools/dev-server/registry.json. +// +// node dist/index.js # check mode (CI) — exits 1 on drift +// node dist/index.js --write # rewrite the lists from the registry +// +// This file is only ever run as the compiled ./dist/index.js (see run.sh), which is the directory +// the hops below count from. It declares no functions of its own: everything worth a test lives in +// ./cli.ts. + +const DEV_SERVER_DIR = path.resolve(__dirname, '../..'); + +const result = runSync({ + root: path.resolve(DEV_SERVER_DIR, '../..'), + registryPath: path.join(DEV_SERVER_DIR, 'registry.json'), +}, process.argv.includes('--write')); + +for (const line of result.output) { + (line.stream === 'err' ? console.error : console.log)(line.text); +} + +process.exitCode = result.exitCode; diff --git a/tools/dev-server/sync-presets/run.sh b/tools/dev-server/sync-presets/run.sh new file mode 100755 index 00000000000..1590500a7df --- /dev/null +++ b/tools/dev-server/sync-presets/run.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# Compile-on-run wrapper for the preset-list sync tool. +# Resolves its own location, so it can be called from any working directory. +# +# Usage: tools/dev-server/sync-presets/run.sh [--write] + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../../.." && pwd)" + +# Use the repo-local TypeScript so the wrapper is self-contained (no global tsc needed). +"$ROOT/node_modules/.bin/tsc" -p "$DIR/tsconfig.json" +node "$DIR/dist/index.js" "$@" diff --git a/tools/dev-server/sync-presets/sync.spec.ts b/tools/dev-server/sync-presets/sync.spec.ts new file mode 100644 index 00000000000..3d9ff75c1a8 --- /dev/null +++ b/tools/dev-server/sync-presets/sync.spec.ts @@ -0,0 +1,144 @@ +import { describe, it, expect } from 'vitest'; + +import type { PresetTarget } from './sync'; +import { TARGETS, parseAliases, buildBlock, spliceBlock, syncTarget } from './sync'; + +const [ WORKFLOW_TARGET, TASKS_TARGET ] = TARGETS; + +const ALIASES = [ 'eth', 'gnosis', 'zksync' ]; + +function workflowFile(aliasLines: ReadonlyArray<string>): string { + return [ + 'on:', + ' workflow_dispatch:', + ' inputs:', + ' preset:', + ' options:', + ' # presets:start — generated from tools/dev-server/registry.json (run `pnpm presets:sync`)', + ...aliasLines, + ' # presets:end', + ' variant:', + ' type: choice', + '', + ].join('\n'); +} + +describe('parseAliases', () => { + it('reads the registry keys in file order', () => { + expect(parseAliases('{"zora":"https://a","eth":"https://b","base":"https://c"}')) + .toEqual([ 'zora', 'eth', 'base' ]); + }); + + it('is empty for an empty registry', () => { + expect(parseAliases('{}')).toEqual([]); + }); +}); + +describe('buildBlock', () => { + it('brackets YAML sequence items with hash-comment markers at the target indent', () => { + expect(buildBlock(WORKFLOW_TARGET, ALIASES).split('\n')).toEqual([ + ' # presets:start — generated from tools/dev-server/registry.json (run `pnpm presets:sync`)', + ' - eth', + ' - gnosis', + ' - zksync', + ' # presets:end', + ]); + }); + + it('brackets quoted JSON array items with slash-comment markers at the target indent', () => { + expect(buildBlock(TASKS_TARGET, ALIASES).split('\n')).toEqual([ + ' // presets:start — generated from tools/dev-server/registry.json (run `pnpm presets:sync`)', + ' "eth",', + ' "gnosis",', + ' "zksync",', + ' // presets:end', + ]); + }); + + it('emits markers with no body for an empty alias list', () => { + const lines = buildBlock(WORKFLOW_TARGET, []).split('\n'); + expect(lines).toHaveLength(2); + expect(lines[0]).toContain('presets:start'); + expect(lines[1]).toContain('presets:end'); + }); +}); + +describe('spliceBlock', () => { + it('replaces the bracketed lines and leaves the rest of the file byte-identical', () => { + const before = workflowFile([ ' - eth', ' - gnosis' ]); + const after = spliceBlock(WORKFLOW_TARGET, before, ALIASES); + + expect(after).toBe(workflowFile([ ' - eth', ' - gnosis', ' - zksync' ])); + }); + + it('drops aliases the registry no longer lists', () => { + const before = workflowFile([ ' - eth', ' - dropped_chain' ]); + + expect(spliceBlock(WORKFLOW_TARGET, before, [ 'eth' ])).not.toContain('dropped_chain'); + }); + + it('rewrites a hand-edited block back to the registry order', () => { + const scrambled = workflowFile([ ' - zksync', ' - eth', ' - gnosis' ]); + + expect(spliceBlock(WORKFLOW_TARGET, scrambled, ALIASES)) + .toBe(workflowFile(ALIASES.map((alias) => ` - ${ alias }`))); + }); + + it('throws naming the target file when the start marker is missing', () => { + const content = [ 'options:', ' - eth', ' # presets:end' ].join('\n'); + + expect(() => spliceBlock(WORKFLOW_TARGET, content, ALIASES)) + .toThrow(`Missing or malformed presets:start/presets:end markers in ${ WORKFLOW_TARGET.file }`); + }); + + it('throws naming the target file when the end marker is missing', () => { + const content = [ 'options:', ' # presets:start', ' - eth' ].join('\n'); + + expect(() => spliceBlock(WORKFLOW_TARGET, content, ALIASES)) + .toThrow(`Missing or malformed presets:start/presets:end markers in ${ WORKFLOW_TARGET.file }`); + }); + + it('throws when one line carries both markers, bracketing no block', () => { + const content = [ 'options:', ' # presets:start — ... # presets:end', ' - eth' ].join('\n'); + + expect(() => spliceBlock(WORKFLOW_TARGET, content, ALIASES)) + .toThrow(`Missing or malformed presets:start/presets:end markers in ${ WORKFLOW_TARGET.file }`); + }); + + it('throws when the markers are inverted', () => { + const content = [ + 'options:', + ' # presets:end', + ' - eth', + ' # presets:start', + ].join('\n'); + + expect(() => spliceBlock(TASKS_TARGET, content, ALIASES)) + .toThrow(`Missing or malformed presets:start/presets:end markers in ${ TASKS_TARGET.file }`); + }); +}); + +describe('syncTarget', () => { + it('reports no change when the block already matches the registry', () => { + const content = workflowFile(ALIASES.map((alias) => ` - ${ alias }`)); + const result = syncTarget(WORKFLOW_TARGET, content, ALIASES); + + expect(result.changed).toBe(false); + expect(result.next).toBe(content); + }); + + it('reports drift and carries the rewritten content when an alias is missing', () => { + const content = workflowFile([ ' - eth', ' - gnosis' ]); + const result = syncTarget(WORKFLOW_TARGET, content, ALIASES); + + expect(result.changed).toBe(true); + expect(result.next).toContain(' - zksync'); + }); +}); + +describe('TARGETS', () => { + it('covers the workflow dropdown and the VS Code task list', () => { + expect(TARGETS.map((target: PresetTarget) => target.file)) + .toEqual([ '.github/workflows/deploy-review.yml', '.vscode/tasks.json' ]); + }); +}); diff --git a/tools/dev-server/sync-presets/sync.ts b/tools/dev-server/sync-presets/sync.ts new file mode 100644 index 00000000000..2493960bc68 --- /dev/null +++ b/tools/dev-server/sync-presets/sync.ts @@ -0,0 +1,59 @@ +// Keeps the preset/alias dropdowns in the GitHub workflows and .vscode/tasks.json in sync with +// tools/dev-server/registry.json (the single source of truth). Each target file brackets its +// registry-managed aliases with `presets:start` / `presets:end` marker comments; only the lines +// between the markers are touched, so the rest of the file and its formatting survive untouched. +// +// Kept free of fs and process access so the specs can exercise block building and splicing without +// a working tree; ./cli.ts is what reads and writes the files. + +const START = 'presets:start'; +const END = 'presets:end'; + +export interface PresetTarget { + readonly file: string; + readonly indent: number; + readonly comment: string; + readonly line: (alias: string) => string; +} + +export const TARGETS: ReadonlyArray<PresetTarget> = [ + { file: '.github/workflows/deploy-review.yml', indent: 12, comment: '#', line: (alias) => `- ${ alias }` }, + { file: '.vscode/tasks.json', indent: 14, comment: '//', line: (alias) => `"${ alias }",` }, +]; + +export function parseAliases(registryJson: string): Array<string> { + return Object.keys(JSON.parse(registryJson) as Record<string, string>); +} + +export function buildBlock(target: PresetTarget, aliases: ReadonlyArray<string>): string { + const pad = ' '.repeat(target.indent); + const header = `${ pad }${ target.comment } ${ START } — generated from tools/dev-server/registry.json (run \`pnpm presets:sync\`)`; + const footer = `${ pad }${ target.comment } ${ END }`; + const body = aliases.map((alias) => `${ pad }${ target.line(alias) }`); + return [ header, ...body, footer ].join('\n'); +} + +export function spliceBlock(target: PresetTarget, content: string, aliases: ReadonlyArray<string>): string { + const lines = content.split('\n'); + const startIndex = lines.findIndex((line) => line.includes(START)); + const endIndex = lines.findIndex((line) => line.includes(END)); + + // A missing end marker leaves endIndex at -1, so `<=` rejects that too; equal indexes mean one line + // carries both markers and brackets no block. + if (startIndex === -1 || endIndex <= startIndex) { + throw new Error(`Missing or malformed ${ START }/${ END } markers in ${ target.file }`); + } + + const block = buildBlock(target, aliases).split('\n'); + return [ ...lines.slice(0, startIndex), ...block, ...lines.slice(endIndex + 1) ].join('\n'); +} + +export interface SyncResult { + readonly next: string; + readonly changed: boolean; +} + +export function syncTarget(target: PresetTarget, content: string, aliases: ReadonlyArray<string>): SyncResult { + const next = spliceBlock(target, content, aliases); + return { next, changed: next !== content }; +} diff --git a/tools/dev-server/sync-presets/tsconfig.json b/tools/dev-server/sync-presets/tsconfig.json new file mode 100644 index 00000000000..8f4d9580e53 --- /dev/null +++ b/tools/dev-server/sync-presets/tsconfig.json @@ -0,0 +1,22 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "module": "node16", + "target": "es2022", + "moduleResolution": "node16", + "resolveJsonModule": false, + "isolatedModules": false, + "noEmit": false, + // Disable incremental (inherited from the root config): dist/ is git-ignored and compiled on + // demand, so a stale .tsbuildinfo must never short-circuit the emit. + "incremental": false, + "rootDir": ".", + "outDir": "./dist" + }, + "include": [ + "./index.ts" + ], + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/tools/doc-links/CONTEXT.md b/tools/doc-links/CONTEXT.md new file mode 100644 index 00000000000..37d8a5bde90 --- /dev/null +++ b/tools/doc-links/CONTEXT.md @@ -0,0 +1,39 @@ +# Doc-link checker — context + +`pnpm lint:doc-links` resolves the cross-references in the agent instruction surface — markdown links, +heading anchors, and the file and directory paths written in backticks. A CI check in +`.github/workflows/checks.yml`. + +## Files + +| File | Role | +|---|---| +| `surface.ts` | Which files are checked: the walked config roots, the exclusions, and every markdown file in and below a directory that carries a `CONTEXT.md`, taken from the tracked-file list. Widening the check surface happens here. | +| `strip.ts` | Blanks the regions of a line that are not references — fenced blocks, and the illustration marks. | +| `resolve.ts` | Turns a written reference into the file it names, and judges when a path that resolves nowhere is a break (shorthand, neighbour, top-level segment) rather than prose that looks like one. | +| `check.ts` | One file in, its findings out. The two reference forms — backtick path, markdown link — are checked here. | +| `report.ts` | Findings to output lines and an exit code. Free of `console` so a spec can assert both. | +| `index.ts` | CLI entry: repo root, tracked files, the loop, the printing. | +| `run.sh`, `tsconfig.json` | Compile-on-run wrapper; the compiled output is git-ignored. | + +## What an editor here must keep true + +- **`ILLUSTRATION_FORMS` is the only statement of the exemption marks**, and it is printed on failure. + Teaching the checker a new mark without amending that string leaves authors reading a footer that + contradicts the tool. +- **The repo root comes from git, not from hops counted off the entry file.** The entry runs compiled, one + directory deeper than its source, so a relative count is right in a spec and wrong in production. +- **Every path this directory's own docs write is checked by the tool they document.** A rename here that + misses `CONTEXT.md` fails the run. + +## Gotchas (these bit us; don't re-learn them) + +- **An `e.g.` is not an exemption.** Prose introducing a real file as an example is the common case, and + exempting it would leave exactly those references unprotected against a rename. An example naming no real + file takes a `<placeholder>` segment instead. +- **A false positive is more expensive than a miss.** Noise trains everyone to stop reading the output, so a + path that names a shape rather than a location (`types/api.ts`, `hooks/`) is deliberately not reported — + the judgements in `resolve.ts` exist to keep it that way. +- **`.cursor/rules/*.mdc` and `.claude/CLAUDE.md` are symlinks onto files under `.agents`.** Both the + de-duplication and the realpath-relative resolution depend on that; drop either and every finding in a + symlinked file is reported twice, or its relative links resolve from the wrong directory. diff --git a/tools/doc-links/check.spec.ts b/tools/doc-links/check.spec.ts new file mode 100644 index 00000000000..cb1ae839d25 --- /dev/null +++ b/tools/doc-links/check.spec.ts @@ -0,0 +1,137 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; + +import { checkFile } from './check'; +import type { RepoIndex } from './resolve'; +import { buildRepoIndex } from './resolve'; + +const DOC = '.agents/AGENTS.md'; + +const TRACKED = [ + '.agents/AGENTS.md', + '.agents/rules/docs.md', + 'src/api/types.ts', + 'src/toolkit/theme/theme.ts', + 'src/slices/token/types/api.ts', + 'src/slices/block/types/api.ts', +]; + +let root: string; +let repo: RepoIndex; + +function write(rel: string, body = ''): void { + const absPath = path.join(root, rel); + fs.mkdirSync(path.dirname(absPath), { recursive: true }); + fs.writeFileSync(absPath, body); +} + +async function messagesFor(...lines: ReadonlyArray<string>): Promise<Array<string>> { + write(DOC, lines.join('\n')); + return (await checkFile(repo, DOC)).map((finding) => finding.message); +} + +beforeEach(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'doc-links-'))); + repo = buildRepoIndex(root, TRACKED); + for (const rel of TRACKED) { + write(rel); + } +}); + +afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); +}); + +describe('the four reported classes', () => { + it('reports a backtick path that resolves nowhere', async() => { + expect(await messagesFor('See `src/api/gone.ts`.')).toEqual([ 'path reference does not exist: src/api/gone.ts' ]); + }); + + it('reports a link target that resolves nowhere', async() => { + expect(await messagesFor('See [docs](./rules/gone.md).')).toEqual([ 'link target does not exist: ./rules/gone.md' ]); + }); + + it('reports an anchor missing from a target that does resolve', async() => { + write('.agents/rules/docs.md', '# What earns a line'); + + expect(await messagesFor('See [docs](./rules/docs.md#gone).')) + .toEqual([ 'heading anchor not found in target: ./rules/docs.md#gone' ]); + }); + + it('accepts an anchor that matches a heading, case-insensitively', async() => { + write('.agents/rules/docs.md', '# What earns a line'); + + expect(await messagesFor('See [docs](./rules/docs.md#What-Earns-A-Line).')).toEqual([]); + }); + + it('reports a sibling link written without a slash', async() => { + expect(await messagesFor('See [docs](gone.md).')).toEqual([ 'link target does not exist: gone.md' ]); + }); + + it('accepts a link to a markdown file with no anchor', async() => { + expect(await messagesFor('See [docs](./rules/docs.md).')).toEqual([]); + }); + + it('leaves an anchor on a target that is not markdown unchecked', async() => { + expect(await messagesFor('See [the type](../src/api/types.ts#L20).')).toEqual([]); + }); + + it('reports a shorthand path in full', async() => { + expect(await messagesFor('See `toolkit/theme/theme.ts`.')) + .toEqual([ 'toolkit/theme/theme.ts is shorthand; write it in full: src/toolkit/theme/theme.ts' ]); + }); +}); + +describe('what is not a reference', () => { + it.each([ + [ 'a fenced block', [ '```', '`src/api/gone.ts`', '[docs](./rules/gone.md)', '```' ] ], + [ 'a placeholder segment', [ 'See `src/slices/<entity>/index.ts` and [spec](./tasks/<n>/spec.md).' ] ], + [ 'a table-row arrow', [ '| Pattern | Output |', '| --- | --- |', '| `src/api/types.ts` | → `src/api/gone.ts` |' ] ], + [ 'a backtick span that is not a path', [ 'Set `someConfigKey`, `a.b.c` and `no-slash-here`.' ] ], + [ 'bracket text without a slash or an extension', [ 'See [just prose](notafile).' ] ], + [ 'a protocol or in-page link', [ '[web](https://example.com), [mail](mailto:a@b.c), [top](#heading)' ] ], + [ 'a backtick span containing whitespace', [ 'Run `node src/api/gone.ts --flag`.' ] ], + [ 'a slash-bearing span with no file extension', [ 'The request runs through `src/api/resources`.' ] ], + [ 'a path naming a shape rather than a location', [ 'Every slice has a `types/api.ts`.' ] ], + [ 'a bare directory naming a convention', [ 'Each slice keeps a `hooks/` folder.' ] ], + ])('exempts %s', async(_name, lines) => { + expect(await messagesFor(...lines)).toEqual([]); + }); + + it('still checks a real reference standing beside an illustration', async() => { + expect(await messagesFor('See `src/slices/<entity>/index.ts` and `src/api/gone.ts`.')) + .toEqual([ 'path reference does not exist: src/api/gone.ts' ]); + }); + + it('does not read a markdown-link example inside a code span as a link', async() => { + expect(await messagesFor('Write it as `[Link Text](./rules/gone.md)`.')).toEqual([]); + }); +}); + +describe('finding order and position', () => { + it('numbers a finding by its line in the file, fences included', async() => { + write(DOC, [ '```', 'x', '```', 'See `src/api/gone.ts`.' ].join('\n')); + + expect(await checkFile(repo, DOC)).toEqual([ + { file: DOC, line: 4, message: 'path reference does not exist: src/api/gone.ts' }, + ]); + }); + + it('reports the backtick paths of a line before its links', async() => { + expect(await messagesFor('`src/api/gone.ts` and [docs](./rules/gone.md)')).toEqual([ + 'path reference does not exist: src/api/gone.ts', + 'link target does not exist: ./rules/gone.md', + ]); + }); + + it('resolves relative references from the realpath of a symlinked entry point', async() => { + write('.agents/rules/docs.md'); + fs.symlinkSync(path.join(root, DOC), path.join(root, 'CLAUDE.md')); + write(DOC, 'See `./rules/docs.md`.'); + + expect(await checkFile(repo, 'CLAUDE.md')).toEqual([]); + }); +}); diff --git a/tools/doc-links/check.ts b/tools/doc-links/check.ts new file mode 100644 index 00000000000..65133b35a03 --- /dev/null +++ b/tools/doc-links/check.ts @@ -0,0 +1,85 @@ +import { readFile, realpath } from 'node:fs/promises'; +import path from 'node:path'; + +import type { RepoIndex } from './resolve'; +import { headingSlugs, isPlaceholder, nearby, resolves, shorthandFor } from './resolve'; +import { withoutFences, withoutIllustrations } from './strip'; + +const PATH_EXTENSIONS = /\.(?:md|mdc|mjs|json|jsonc|ya?ml|sh|tsx?)$/; + +export interface Finding { + readonly file: string; + readonly line: number; + readonly message: string; +} + +interface LineContext { + readonly repo: RepoIndex; + readonly realDir: string; +} + +// A trailing slash marks a directory, a known extension marks a file. Anything else in backticks — a config +// key, a dotted token, a fragment of prose — is not a path. +const looksLikePath = (target: string): boolean => target.endsWith('/') || PATH_EXTENSIONS.test(target); + +function checkBacktickPath(ctx: LineContext, target: string): string | undefined { + if (/\s/.test(target) || isPlaceholder(target) || !target.includes('/')) return undefined; + if (!looksLikePath(target)) return undefined; + if (resolves(ctx.repo, ctx.realDir, target)) return undefined; + + const full = shorthandFor(ctx.repo, target); + if (full) return `${ target } is shorthand; write it in full: ${ full }`; + + const isReference = target.startsWith('./') || + ctx.repo.topLevel.has(target.split('/')[0]) || + nearby(ctx.realDir, target); + + return isReference ? `path reference does not exist: ${ target }` : undefined; +} + +async function checkLink(ctx: LineContext, target: string): Promise<string | undefined> { + if (/^(?:https?:|mailto:|#)/.test(target) || isPlaceholder(target)) return undefined; + + const [ filePart, anchor ] = target.split('#'); + // A link with neither a slash nor a file extension is prose in brackets, not a path. + if (!filePart.includes('/') && !PATH_EXTENSIONS.test(filePart)) return undefined; + + const resolved = resolves(ctx.repo, ctx.realDir, filePart); + if (!resolved) return `link target does not exist: ${ target }`; + if (!anchor || !resolved.endsWith('.md')) return undefined; + + const slugs = await headingSlugs(resolved); + return slugs.has(anchor.toLowerCase()) ? undefined : `heading anchor not found in target: ${ target }`; +} + +async function checkLine(ctx: LineContext, rawLine: string): Promise<Array<string>> { + const checkable = withoutIllustrations(rawLine); + + // Backtick paths are collected first and then stripped, so an inline code span holding a markdown-link + // example — `[Link Text](URL)` — is not read as a link. + const spans = [ ...checkable.matchAll(/`([^`]+)`/g) ].map((match) => match[1]); + const outsideSpans = checkable.replace(/`[^`]+`/g, ''); + + const messages: Array<string | undefined> = spans.map((target) => checkBacktickPath(ctx, target)); + + for (const [ , target ] of outsideSpans.matchAll(/\[[^\]]*\]\(([^)\s]+)\)/g)) { + messages.push(await checkLink(ctx, target)); + } + + return messages.filter((message): message is string => message !== undefined); +} + +export async function checkFile(repo: RepoIndex, fileRel: string): Promise<Array<Finding>> { + const absPath = path.join(repo.root, fileRel); + const ctx: LineContext = { repo, realDir: path.dirname(await realpath(absPath)) }; + const lines = withoutFences(await readFile(absPath, 'utf8')); + + const findings: Array<Finding> = []; + for (const [ index, rawLine ] of lines.entries()) { + for (const message of await checkLine(ctx, rawLine)) { + findings.push({ file: fileRel, line: index + 1, message }); + } + } + + return findings; +} diff --git a/tools/doc-links/index.ts b/tools/doc-links/index.ts new file mode 100644 index 00000000000..1593e6b5b98 --- /dev/null +++ b/tools/doc-links/index.ts @@ -0,0 +1,44 @@ +/* eslint-disable no-console -- CLI tool, console output is the interface */ +import { execFileSync } from 'node:child_process'; + +import { checkFile } from './check'; +import { renderReport } from './report'; +import { buildRepoIndex } from './resolve'; +import { collectSurface } from './surface'; + +// These files instruct agents rather than humans, so a reference that no longer resolves does not merely read +// badly — it sends an agent to a file that is not there, and nothing else in the toolchain notices. Kept +// mechanical on purpose: a review agent should spend its judgement on what a rule says, not on whether the +// rule's target still exists. +// +// CLI entry only; everything worth a test lives in the modules beside it. See ./CONTEXT.md for the file map. + +// The root comes from git rather than from hops counted off this file: the entry runs compiled from ./dist, +// so its depth below the repo root is not the source's. +function repoRoot(): string { + return execFileSync('git', [ 'rev-parse', '--show-toplevel' ], { cwd: __dirname, encoding: 'utf8' }).trim(); +} + +function trackedFiles(root: string): Array<string> { + return execFileSync('git', [ 'ls-files' ], { cwd: root, encoding: 'utf8' }).split('\n').filter(Boolean); +} + +async function main(): Promise<void> { + const root = repoRoot(); + const repo = buildRepoIndex(root, trackedFiles(root)); + const files = await collectSurface(root, repo.tracked); + + const findings = []; + for (const file of files) { + findings.push(...await checkFile(repo, file)); + } + + const report = renderReport(findings, files.length); + for (const line of report.output) { + (line.stream === 'err' ? console.error : console.log)(line.text); + } + + process.exitCode = report.exitCode; +} + +void main(); diff --git a/tools/doc-links/report.spec.ts b/tools/doc-links/report.spec.ts new file mode 100644 index 00000000000..f42ae513492 --- /dev/null +++ b/tools/doc-links/report.spec.ts @@ -0,0 +1,41 @@ +import { describe, it, expect } from 'vitest'; + +import type { Finding } from './check'; +import { renderReport } from './report'; +import { ILLUSTRATION_FORMS } from './strip'; + +const FILE_COUNT = 67; + +const FINDINGS: ReadonlyArray<Finding> = [ + { file: '.agents/AGENTS.md', line: 12, message: 'path reference does not exist: src/api/gone.ts' }, + { file: 'src/api/CONTEXT.md', line: 3, message: 'link target does not exist: ./gone.md' }, +]; + +describe('renderReport', () => { + it('prints one summary line on stdout and exits 0 when nothing is broken', () => { + expect(renderReport([], FILE_COUNT)).toEqual({ + output: [ { stream: 'out', text: `Doc links: ${ FILE_COUNT } files checked, every reference resolves.` } ], + exitCode: 0, + }); + }); + + it('prints file:line — message per finding on stderr, in the order found', () => { + const { output } = renderReport(FINDINGS, FILE_COUNT); + + expect(output.slice(0, 2)).toEqual([ + { stream: 'err', text: '.agents/AGENTS.md:12 — path reference does not exist: src/api/gone.ts' }, + { stream: 'err', text: 'src/api/CONTEXT.md:3 — link target does not exist: ./gone.md' }, + ]); + }); + + it('closes with a count footer that restates the illustration convention, and exits 1', () => { + const { output, exitCode } = renderReport(FINDINGS, FILE_COUNT); + + expect(exitCode).toBe(1); + expect(output[output.length - 1]).toEqual({ + stream: 'err', + text: `\n2 unresolved reference(s) across ${ FILE_COUNT } file(s).\n` + + `A path naming a shape rather than a file has to be marked as one, or it is read as a reference: ${ ILLUSTRATION_FORMS }.`, + }); + }); +}); diff --git a/tools/doc-links/report.ts b/tools/doc-links/report.ts new file mode 100644 index 00000000000..fd2ed424cc6 --- /dev/null +++ b/tools/doc-links/report.ts @@ -0,0 +1,35 @@ +// Formats the findings. Kept free of `console` so a spec can assert the exact lines and exit code. + +import type { Finding } from './check'; +import { ILLUSTRATION_FORMS } from './strip'; + +export interface OutputLine { + readonly stream: 'out' | 'err'; + readonly text: string; +} + +export interface Report { + readonly output: ReadonlyArray<OutputLine>; + readonly exitCode: number; +} + +export function renderReport(findings: ReadonlyArray<Finding>, fileCount: number): Report { + if (findings.length === 0) { + return { + output: [ { stream: 'out', text: `Doc links: ${ fileCount } files checked, every reference resolves.` } ], + exitCode: 0, + }; + } + + const output: Array<OutputLine> = findings.map(({ file, line, message }) => ( + { stream: 'err', text: `${ file }:${ line } — ${ message }` } + )); + + output.push({ + stream: 'err', + text: `\n${ findings.length } unresolved reference(s) across ${ fileCount } file(s).\n` + + `A path naming a shape rather than a file has to be marked as one, or it is read as a reference: ${ ILLUSTRATION_FORMS }.`, + }); + + return { output, exitCode: 1 }; +} diff --git a/tools/doc-links/resolve.spec.ts b/tools/doc-links/resolve.spec.ts new file mode 100644 index 00000000000..38ad78ae40a --- /dev/null +++ b/tools/doc-links/resolve.spec.ts @@ -0,0 +1,151 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; + +import type { RepoIndex } from './resolve'; +import { buildRepoIndex, headingSlugs, isPlaceholder, nearby, resolves, shorthandFor, slugify } from './resolve'; + +const TRACKED = [ + 'package.json', + 'src/api/types.ts', + 'src/toolkit/theme/theme.ts', + 'src/slices/token/types/api.ts', + 'src/slices/block/types/api.ts', + '.agents/AGENTS.md', +]; + +let root: string; +let repo: RepoIndex; + +function write(rel: string, body = ''): string { + const absPath = path.join(root, rel); + fs.mkdirSync(path.dirname(absPath), { recursive: true }); + fs.writeFileSync(absPath, body); + return absPath; +} + +beforeEach(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'doc-links-'))); + repo = buildRepoIndex(root, TRACKED); +}); + +afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); +}); + +describe('buildRepoIndex', () => { + it('derives the top-level directories from the tracked paths', () => { + expect([ ...repo.topLevel ].sort()).toEqual([ '.agents', 'src' ]); + }); + + it('leaves out root-level files, which have no directory segment', () => { + expect(repo.topLevel.has('package.json')).toBe(false); + }); +}); + +describe('isPlaceholder', () => { + it.each([ + 'src/<entity>/index.ts', + 'src/{slice}/index.ts', + 'src/*/index.ts', + 'src/__name__/index.ts', + ])('exempts the marked segment in %s', (target) => { + expect(isPlaceholder(target)).toBe(true); + }); + + it('does not exempt an ordinary path', () => { + expect(isPlaceholder('src/api/types.ts')).toBe(false); + }); +}); + +describe('resolves', () => { + it('finds a path written relative to the referring file', () => { + write('.agents/rules/docs.md'); + + expect(resolves(repo, path.join(root, '.agents'), 'rules/docs.md')).toBe(path.join(root, '.agents/rules/docs.md')); + }); + + it('finds a path written from the repo root', () => { + write('src/api/types.ts'); + + expect(resolves(repo, path.join(root, '.agents'), 'src/api/types.ts')).toBe(path.join(root, 'src/api/types.ts')); + }); + + it('strips a leading ./ before resolving', () => { + write('.agents/rules/docs.md'); + + expect(resolves(repo, path.join(root, '.agents'), './rules/docs.md')).toBeDefined(); + }); + + it('prefers the file beside the referrer when both candidates exist', () => { + write('rules/docs.md'); + write('.agents/rules/docs.md'); + + expect(resolves(repo, path.join(root, '.agents'), 'rules/docs.md')).toBe(path.join(root, '.agents/rules/docs.md')); + }); + + it('returns undefined when neither candidate exists', () => { + expect(resolves(repo, path.join(root, '.agents'), 'rules/gone.md')).toBeUndefined(); + }); +}); + +describe('shorthandFor', () => { + it('names the full path when exactly one tracked file ends with the target', () => { + expect(shorthandFor(repo, 'toolkit/theme/theme.ts')).toBe('src/toolkit/theme/theme.ts'); + }); + + it('stays silent when several tracked files end with the target — no single location to point at', () => { + expect(shorthandFor(repo, 'types/api.ts')).toBeUndefined(); + }); + + it('stays silent when nothing matches', () => { + expect(shorthandFor(repo, 'nowhere/at/all.ts')).toBeUndefined(); + }); +}); + +describe('nearby', () => { + it('is true when the parent directory of the target sits beside the referring file', () => { + write('.agents/rules/docs.md'); + + expect(nearby(path.join(root, '.agents'), 'rules/gone.md')).toBe(true); + }); + + it('is false for a bare filename, even though the referring directory itself exists', () => { + write('.agents/AGENTS.md'); + + expect(nearby(path.join(root, '.agents'), 'gone.md')).toBe(false); + }); + + it('is false for a directory target — a trailing slash names a convention, not one location', () => { + write('.agents/rules/docs.md'); + + expect(nearby(path.join(root, '.agents'), 'rules/')).toBe(false); + }); +}); + +describe('slugify', () => { + it.each([ + [ 'What earns a line', 'what-earns-a-line' ], + [ 'Running `pnpm dev`', 'running-pnpm-dev' ], + [ 'Gotchas (these bit us)', 'gotchas-these-bit-us' ], + [ 'Data & API', 'data-api' ], + ])('matches the GitHub slug for %s', (heading, slug) => { + expect(slugify(heading)).toBe(slug); + }); +}); + +describe('headingSlugs', () => { + it('collects every heading level and ignores non-heading lines', async() => { + const absPath = write('doc.md', [ '# Top', 'body', '###### Deep One', 'not # a heading', '####### too deep' ].join('\n')); + + expect(await headingSlugs(absPath)).toEqual(new Set([ 'top', 'deep-one' ])); + }); + + it('ignores a hash with no space after it', async() => { + const absPath = write('doc.md', '#NotAHeading'); + + expect(await headingSlugs(absPath)).toEqual(new Set()); + }); +}); diff --git a/tools/doc-links/resolve.ts b/tools/doc-links/resolve.ts new file mode 100644 index 00000000000..9421b82db35 --- /dev/null +++ b/tools/doc-links/resolve.ts @@ -0,0 +1,65 @@ +import { existsSync } from 'node:fs'; +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; + +export interface RepoIndex { + readonly root: string; + readonly tracked: ReadonlyArray<string>; + // Derived rather than listed, so a new top-level directory needs no edit here. A path is only expected to + // resolve when its first segment is one of these: `types/api.ts` names a kind of file, `src/api/types.ts` + // a location. + readonly topLevel: ReadonlySet<string>; +} + +export function buildRepoIndex(root: string, tracked: ReadonlyArray<string>): RepoIndex { + return { + root, + tracked, + topLevel: new Set(tracked.filter((file) => file.includes('/')).map((file) => file.split('/')[0])), + }; +} + +export const isPlaceholder = (target: string): boolean => /[<>{}*]|__/.test(target); + +// Resolved against the file's realpath, so a symlinked entry point (`.claude/CLAUDE.md` → `.agents/AGENTS.md`) +// resolves its relative links from where the file really lives. +export function resolves(repo: RepoIndex, realDir: string, target: string): string | undefined { + const clean = target.replace(/^\.\//, ''); + return [ path.resolve(realDir, clean), path.resolve(repo.root, clean) ].find((candidate) => existsSync(candidate)); +} + +// A path that resolves nowhere may still name a real file written short — `toolkit/theme/theme.ts` for +// `src/toolkit/theme/theme.ts`. Reported only when exactly one tracked file ends with it, which makes the +// intended file certain; `types/api.ts` matches thirty of them and so asserts no single location to check. +// Files only: a bare directory such as `hooks/` names a convention every slice follows, not one location, +// and nothing distinguishes that from shorthand. +export function shorthandFor(repo: RepoIndex, target: string): string | undefined { + const matches = repo.tracked.filter((file) => file.endsWith(`/${ target }`)); + return matches.length === 1 ? matches[0] : undefined; +} + +// A path whose parent directory sits beside the file was written relative to it — `components/Provider.tsx` +// in a CONTEXT.md is a reference to a neighbour, and its absence is a break. Without this the whole relative +// class goes unprotected: once broken, such a path is indistinguishable from `types/api.ts` naming a kind of +// file, so a renamed neighbour would fail silently. +export function nearby(realDir: string, target: string): boolean { + const parent = path.dirname(target); + return parent !== '.' && !target.endsWith('/') && existsSync(path.resolve(realDir, parent)); +} + +// GitHub's heading slug. +export const slugify = (heading: string): string => heading + .toLowerCase() + .replace(/`/g, '') + .replace(/[^\w\s-]/g, '') + .trim() + .replace(/\s+/g, '-'); + +export async function headingSlugs(absPath: string): Promise<Set<string>> { + const body = await readFile(absPath, 'utf8'); + return new Set( + body.split('\n') + .filter((line) => /^#{1,6}\s/.test(line)) + .map((line) => slugify(line.replace(/^#{1,6}\s+/, ''))), + ); +} diff --git a/tools/doc-links/run.sh b/tools/doc-links/run.sh new file mode 100755 index 00000000000..13a985ea005 --- /dev/null +++ b/tools/doc-links/run.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# Compile-on-run wrapper for the doc-link checker. +# Resolves its own location, so it can be called from any working directory. +# +# Usage: tools/doc-links/run.sh + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" + +# Use the repo-local TypeScript so the wrapper is self-contained (no global tsc needed). +"$ROOT/node_modules/.bin/tsc" -p "$DIR/tsconfig.json" +node "$DIR/dist/index.js" "$@" diff --git a/tools/doc-links/strip.spec.ts b/tools/doc-links/strip.spec.ts new file mode 100644 index 00000000000..7c67a9ec720 --- /dev/null +++ b/tools/doc-links/strip.spec.ts @@ -0,0 +1,63 @@ +import { describe, it, expect } from 'vitest'; + +import { ILLUSTRATION_FORMS, withoutFences, withoutIllustrations } from './strip'; + +describe('withoutFences', () => { + it('blanks the fence markers and everything between them', () => { + const body = [ 'before', '```bash', 'pnpm run gone.sh', '```', 'after' ].join('\n'); + + expect(withoutFences(body)).toEqual([ 'before', '', '', '', 'after' ]); + }); + + it('keeps the line numbering, so a finding after a fence points at the right line', () => { + const body = [ '```', 'x', '```', '', '`src/kept.ts`' ].join('\n'); + + expect(withoutFences(body)).toHaveLength(5); + expect(withoutFences(body)[4]).toBe('`src/kept.ts`'); + }); + + it('blanks an indented fence, as found inside a list item', () => { + const body = [ ' ```', ' `src/gone.ts`', ' ```' ].join('\n'); + + expect(withoutFences(body)).toEqual([ '', '', '' ]); + }); + + it('treats an unclosed fence as running to the end of the file', () => { + const body = [ 'before', '```', 'still fenced' ].join('\n'); + + expect(withoutFences(body)).toEqual([ 'before', '', '' ]); + }); +}); + +describe('withoutIllustrations', () => { + it('blanks the arrow and its output cell in a table row', () => { + const row = '| `src/<entity>/index.ts` | → `src/token/index.ts` |'; + + expect(withoutIllustrations(row)).toBe('| `src/<entity>/index.ts` | |'); + }); + + it('leaves the pattern cell before the arrow checkable', () => { + const row = '| `src/real.ts` | → `src/made-up.ts` |'; + + expect(withoutIllustrations(row)).toContain('`src/real.ts`'); + }); + + it('blanks each arrow cell independently in a multi-column row', () => { + const row = '| a | → `x/one.ts` | b | → `x/two.ts` |'; + + expect(withoutIllustrations(row)).toBe('| a | | b | |'); + }); + + it('leaves an arrow in prose alone — there it is punctuation, not an illustration mark', () => { + const line = 'The symlink `.claude/CLAUDE.md` → `.agents/AGENTS.md` is checked once.'; + + expect(withoutIllustrations(line)).toBe(line); + }); +}); + +describe('ILLUSTRATION_FORMS', () => { + it('names both marks, since it is the only statement of them and is printed on failure', () => { + expect(ILLUSTRATION_FORMS).toContain('<placeholder>'); + expect(ILLUSTRATION_FORMS).toContain('→'); + }); +}); diff --git a/tools/doc-links/strip.ts b/tools/doc-links/strip.ts new file mode 100644 index 00000000000..806b5ffb68d --- /dev/null +++ b/tools/doc-links/strip.ts @@ -0,0 +1,35 @@ +// Blanks the regions of a line that are not references, leaving the rest checkable. +// +// The instruction documents carry paths that are *illustrations* rather than references — a template's +// output column, a kind of file that lives in many slices. Checking those would produce noise that trains +// everyone to ignore the checker, so an illustration is exempt where it carries a mark that cannot be read +// as a reference; `ILLUSTRATION_FORMS` below is the only statement of what those marks are. Each exemption +// is scoped to the path itself rather than to its whole line, so a real reference standing beside an +// illustration is still checked, and anything unmarked is read as a reference and has to resolve. +// +// An `e.g.` is deliberately *not* a mark. Prose that introduces a real file as an example is the common +// case by far, and exempting it would leave those references unprotected against a later rename — the drift +// this script exists to catch. An example that names no real file gets a `<placeholder>` segment instead, +// which is the per-path form of the exemption (`isPlaceholder` in ./resolve.ts). + +// Fenced blocks hold example commands and JSON payloads; neither is a reference. +export function withoutFences(body: string): Array<string> { + let inFence = false; + return body.split('\n').map((line) => { + if (/^\s*```/.test(line)) { + inFence = !inFence; + return ''; + } + return inFence ? '' : line; + }); +} + +// Stated once, and printed on failure so the convention reaches an author at the moment they trip it rather +// than in a document they would have to know to read. +export const ILLUSTRATION_FORMS = 'give it a <placeholder> segment, or place it after a → in a table row as the ' + + 'output of the pattern before it'; + +// The arrow form is confined to table rows, where a cell pairs a pattern with its filled-in output; in prose +// an arrow is ordinary punctuation and the path after it is a reference like any other. +export const withoutIllustrations = (line: string): string => + (/^\s*\|/.test(line) ? line.replace(/→[^|]*/g, '') : line); diff --git a/tools/doc-links/surface.spec.ts b/tools/doc-links/surface.spec.ts new file mode 100644 index 00000000000..1a98ff96639 --- /dev/null +++ b/tools/doc-links/surface.spec.ts @@ -0,0 +1,183 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; + +import { collectMarkdown, collectSurface, contextDirs, contextSurface, dedupeByRealPath } from './surface'; + +let root: string; + +function write(rel: string, body = ''): void { + const absPath = path.join(root, rel); + fs.mkdirSync(path.dirname(absPath), { recursive: true }); + fs.writeFileSync(absPath, body); +} + +beforeEach(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'doc-links-'))); +}); + +afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); +}); + +describe('collectMarkdown', () => { + it('walks nested directories and takes .md and .mdc files only', async() => { + write('.agents/AGENTS.md'); + write('.agents/rules/docs.md'); + write('.agents/rules/docs.mdc'); + write('.agents/skills/run.sh'); + + expect((await collectMarkdown(root, '.agents')).sort()).toEqual([ + '.agents/AGENTS.md', + '.agents/rules/docs.md', + '.agents/rules/docs.mdc', + ]); + }); + + it('skips the excluded subtrees', async() => { + write('.agents/AGENTS.md'); + write('.agents/tasks/1234-thing/spec.md'); + + expect(await collectMarkdown(root, '.agents')).toEqual([ '.agents/AGENTS.md' ]); + }); + + it('keeps a directory whose name merely starts with an excluded one', async() => { + write('.agents/tasks/1234-thing/spec.md'); + write('.agents/tasks-archive/notes.md'); + + expect(await collectMarkdown(root, '.agents')).toEqual([ '.agents/tasks-archive/notes.md' ]); + }); + + it('skips node_modules and other generated directories', async() => { + write('.agents/node_modules/pkg/README.md'); + write('.agents/.next/build.md'); + write('.agents/AGENTS.md'); + + expect(await collectMarkdown(root, '.agents')).toEqual([ '.agents/AGENTS.md' ]); + }); + + it('returns the accumulator unchanged when the root is absent from this checkout', async() => { + expect(await collectMarkdown(root, '.cursor')).toEqual([]); + }); + + it('does not descend into a symlinked directory — the walk reaches those files by their real path', async() => { + write('.agents/skills/deploy/SKILL.md'); + write('.claude/CLAUDE.md'); + fs.symlinkSync(path.join(root, '.agents/skills'), path.join(root, '.claude/skills')); + + expect(await collectMarkdown(root, '.claude')).toEqual([ '.claude/CLAUDE.md' ]); + }); +}); + +describe('contextDirs', () => { + it('takes the directory of every file named exactly CONTEXT.md, wherever it lives', () => { + const tracked = [ 'src/api/CONTEXT.md', 'tools/profiling/CONTEXT.md', 'docs/README.md', 'src/api/index.ts' ]; + + expect([ ...contextDirs(tracked) ]).toEqual([ 'src/api', 'tools/profiling' ]); + }); + + it('does not take a directory off a file whose name merely contains CONTEXT.md', () => { + expect([ ...contextDirs([ 'docs/OLD-CONTEXT.md' ]) ]).toEqual([]); + }); +}); + +describe('contextSurface', () => { + it('takes every markdown file beside a CONTEXT.md, not only the CONTEXT.md itself', () => { + const tracked = [ 'tools/thing/CONTEXT.md', 'tools/thing/NOTES.md', 'tools/thing/index.ts' ]; + + expect(contextSurface(tracked)).toEqual([ 'tools/thing/CONTEXT.md', 'tools/thing/NOTES.md' ]); + }); + + it('recurses: a markdown file in a nested subdirectory of a CONTEXT.md directory is in the surface', () => { + const tracked = [ + 'tools/thing/CONTEXT.md', + 'tools/thing/docs/RUNNING.md', + 'tools/thing/adr/0001-why.md', + 'tools/thing/adr/deeper/0002-why.md', + ]; + + expect(contextSurface(tracked)).toEqual(tracked); + }); + + it('takes nothing from a directory with no CONTEXT.md, however much markdown it holds', () => { + expect(contextSurface([ 'tools/other/CONTEXT.md', 'docs/guide.md' ])).toEqual([ 'tools/other/CONTEXT.md' ]); + }); + + it('leaves a CONTEXT.md directory holding no other markdown with exactly its one file', () => { + expect(contextSurface([ 'src/api/CONTEXT.md', 'src/api/index.ts' ])).toEqual([ 'src/api/CONTEXT.md' ]); + }); + + it('exempts src/toolkit/package/ — the published wrapper readme addresses npm consumers, not agents', () => { + const tracked = [ 'src/toolkit/CONTEXT.md', 'src/toolkit/package/README.md' ]; + + expect(contextSurface(tracked)).toEqual([ 'src/toolkit/CONTEXT.md' ]); + }); + + it('keeps the exemption a path, so a module README.md elsewhere stays checked', () => { + const tracked = [ 'tools/thing/CONTEXT.md', 'tools/thing/README.md' ]; + + expect(contextSurface(tracked)).toEqual([ 'tools/thing/CONTEXT.md', 'tools/thing/README.md' ]); + }); + + it('still excludes the task specs, which describe files that do not exist yet by design', () => { + const tracked = [ '.agents/CONTEXT.md', '.agents/tasks/1234-thing/spec.md' ]; + + expect(contextSurface(tracked)).toEqual([ '.agents/CONTEXT.md' ]); + }); + + it('skips a generated directory below a CONTEXT.md directory', () => { + const tracked = [ 'tools/thing/CONTEXT.md', 'tools/thing/node_modules/pkg/README.md' ]; + + expect(contextSurface(tracked)).toEqual([ 'tools/thing/CONTEXT.md' ]); + }); +}); + +describe('dedupeByRealPath', () => { + it('keeps the first path that reached a real file, so a symlink does not double-report it', async() => { + write('.agents/AGENTS.md'); + fs.symlinkSync(path.join(root, '.agents/AGENTS.md'), path.join(root, 'CLAUDE.md')); + + expect(await dedupeByRealPath(root, [ '.agents/AGENTS.md', 'CLAUDE.md' ])).toEqual([ '.agents/AGENTS.md' ]); + }); + + it('preserves the order the paths were walked in', async() => { + write('.agents/b.md'); + write('.agents/a.md'); + + expect(await dedupeByRealPath(root, [ '.agents/b.md', '.agents/a.md' ])).toEqual([ '.agents/b.md', '.agents/a.md' ]); + }); +}); + +describe('collectSurface', () => { + it('walks the config roots in order, then appends the markdown around the tracked CONTEXT.md files', async() => { + write('.agents/AGENTS.md'); + write('.claude/CLAUDE.md'); + write('src/api/CONTEXT.md'); + write('src/api/docs/RESOURCES.md'); + + expect(await collectSurface(root, [ 'src/api/CONTEXT.md', 'src/api/docs/RESOURCES.md' ])).toEqual([ + '.agents/AGENTS.md', + '.claude/CLAUDE.md', + 'src/api/CONTEXT.md', + 'src/api/docs/RESOURCES.md', + ]); + }); + + it('reports a CONTEXT.md inside a config root once, under the path the walk found it at', async() => { + write('.agents/skills/CONTEXT.md'); + + expect(await collectSurface(root, [ '.agents/skills/CONTEXT.md' ])).toEqual([ '.agents/skills/CONTEXT.md' ]); + }); + + it('reports a file the config walk already reached once, even when a CONTEXT.md sits beside it', async() => { + write('.agents/skills/CONTEXT.md'); + write('.agents/skills/SKILL.md'); + + expect(await collectSurface(root, [ '.agents/skills/CONTEXT.md', '.agents/skills/SKILL.md' ])).toEqual([ + '.agents/skills/CONTEXT.md', + '.agents/skills/SKILL.md', + ]); + }); +}); diff --git a/tools/doc-links/surface.ts b/tools/doc-links/surface.ts new file mode 100644 index 00000000000..01b38b64b81 --- /dev/null +++ b/tools/doc-links/surface.ts @@ -0,0 +1,81 @@ +// The instruction surface: which files the checker reads. The agent config directories are walked whole; +// a directory that carries a `CONTEXT.md` contributes every markdown file in and below it, so a directory +// documenting itself across several files is covered whole rather than through that one entry point. +// Task specs are excluded — they describe files that do not exist yet by design. + +import type { Dirent } from 'node:fs'; +import { readdir, realpath } from 'node:fs/promises'; +import path from 'node:path'; + +const ROOTS: ReadonlyArray<string> = [ '.agents', '.claude', '.cursor' ]; + +const EXCLUDED: ReadonlyArray<string> = [ '.agents/tasks', '.claude/worktrees', 'src/toolkit/package' ]; + +const SKIPPED_DIRS = new Set([ 'node_modules', '.git', '.next' ]); + +const MARKDOWN = /\.mdc?$/; + +// The trailing slashes match an excluded path and everything below it, but not a sibling whose name +// merely starts the same way — `.agents/tasks-archive`. +const isExcluded = (rel: string): boolean => EXCLUDED.some((ex) => `${ rel }/`.startsWith(`${ ex }/`)); + +export async function collectMarkdown(root: string, dir: string, acc: Array<string> = []): Promise<Array<string>> { + let entries: Array<Dirent>; + try { + entries = await readdir(path.join(root, dir), { withFileTypes: true }); + } catch { + return acc; // a root absent from this checkout is not an error + } + + for (const entry of entries) { + const rel = path.join(dir, entry.name); + if (isExcluded(rel)) continue; + + // A symlinked directory (`.claude/skills` → `../.agents/skills`) is not a directory to `readdir`, so the + // walk skips it — correctly, since the walk over `.agents` reaches those files by their real path. + if (entry.isDirectory()) { + if (!SKIPPED_DIRS.has(entry.name)) await collectMarkdown(root, rel, acc); + } else if (MARKDOWN.test(entry.name)) { + acc.push(rel); + } + } + + return acc; +} + +export const contextDirs = (tracked: ReadonlyArray<string>): Set<string> => + new Set(tracked.filter((file) => path.basename(file) === 'CONTEXT.md').map((file) => path.dirname(file))); + +// Walking the ancestors rather than matching one level down is what makes a nested `adr/` or `docs/` count. +const isBelowContextDir = (file: string, dirs: ReadonlySet<string>): boolean => { + for (let dir = path.dirname(file); dir !== '.'; dir = path.dirname(dir)) { + if (SKIPPED_DIRS.has(path.basename(dir))) return false; + if (dirs.has(dir)) return true; + } + return false; +}; + +// Every markdown file in and below a `CONTEXT.md` directory, taken from the tracked-file list the caller +// already has — an untracked or generated file is not part of the instruction surface. +export const contextSurface = (tracked: ReadonlyArray<string>): Array<string> => { + const dirs = contextDirs(tracked); + return tracked.filter((file) => + MARKDOWN.test(file) && !isExcluded(file) && isBelowContextDir(file, dirs)); +}; + +// One entry per real file. `.cursor/rules/*.mdc` and `.claude/CLAUDE.md` are symlinks onto files the walk +// already reached under `.agents`, and checking a file twice reports each of its findings twice. First seen +// wins, so the path reported is the one the walk arrived at. +export async function dedupeByRealPath(root: string, relativePaths: ReadonlyArray<string>): Promise<Array<string>> { + const seen = new Map<string, string>(); + for (const rel of relativePaths) { + const real = await realpath(path.join(root, rel)); + if (!seen.has(real)) seen.set(real, rel); + } + return [ ...seen.values() ]; +} + +export async function collectSurface(root: string, tracked: ReadonlyArray<string>): Promise<Array<string>> { + const walked = (await Promise.all(ROOTS.map((dir) => collectMarkdown(root, dir)))).flat(); + return dedupeByRealPath(root, [ ...walked, ...contextSurface(tracked) ]); +} diff --git a/tools/doc-links/tsconfig.json b/tools/doc-links/tsconfig.json new file mode 100644 index 00000000000..63b509307f8 --- /dev/null +++ b/tools/doc-links/tsconfig.json @@ -0,0 +1,22 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "node16", + "target": "es2022", + "moduleResolution": "node16", + "resolveJsonModule": false, + "isolatedModules": false, + "noEmit": false, + // Disable incremental (inherited from the root config): dist/ is git-ignored and compiled on + // demand, so a stale .tsbuildinfo must never short-circuit the emit. + "incremental": false, + "rootDir": ".", + "outDir": "./dist" + }, + "include": [ + "./index.ts" + ], + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/tools/eslint/run.sh b/tools/eslint/run.sh new file mode 100755 index 00000000000..122ec45ea25 --- /dev/null +++ b/tools/eslint/run.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +# Usage: tools/eslint/run.sh [--changed[=<ref>]] [<eslint args>...] [<path>...] +# (no path) the whole repo +# <path>... only those files or directories +# --changed[=<ref>] files this branch changed vs <ref> (default origin/main), including +# uncommitted and untracked ones; exits 0 when nothing lintable changed + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" +BIN="$ROOT/node_modules/.bin/eslint" + +cd "$ROOT" + +BASE_REF=origin/main +CHANGED=0 +ARGS=() +for arg in "$@"; do + case "$arg" in + --changed) CHANGED=1 ;; + --changed=*) CHANGED=1; BASE_REF="${arg#--changed=}" ;; + *) ARGS+=("$arg") ;; + esac +done + +if [ "$CHANGED" = 0 ]; then + exec "$BIN" "${ARGS[@]}" +fi + +# Diff against the merge-base so files that only moved on the base branch stay out, then add +# untracked files: a new file is the most lint-worthy thing in a change and `git diff` alone misses it. +BASE_COMMIT="$(git merge-base "$BASE_REF" HEAD)" +FILES=() +while IFS= read -r -d '' file; do + case "$file" in + *.js|*.jsx|*.mjs|*.cjs|*.ts|*.mts|*.tsx) [ -f "$file" ] && FILES+=("$file") ;; + esac +done < <({ git diff --name-only -z "$BASE_COMMIT" --; git ls-files --others --exclude-standard -z; } | sort -zu) + +if [ "${#FILES[@]}" = 0 ]; then + echo "eslint: no changed files to lint (vs $BASE_REF)" + exit 0 +fi + +# A changed file the config ignores is a warning when named explicitly; it is not a finding. +exec "$BIN" --no-warn-ignored "${ARGS[@]}" "${FILES[@]}" diff --git a/tools/mutation-testing/CONTEXT.md b/tools/mutation-testing/CONTEXT.md new file mode 100644 index 00000000000..7eeb11d21ed --- /dev/null +++ b/tools/mutation-testing/CONTEXT.md @@ -0,0 +1,91 @@ +# Mutation testing — context + +A gate on **assertion strength**. It changes a line of code, reruns the specs, and checks whether any test notices. Coverage shows that a line executed; a surviving mutant shows that no test asserted its behavior. + +## Where to look + +| Question | Answer | +| --- | --- | +| The gate failed. What do I change? | the next section | +| How do I run it? What do the flags do? | `pnpm test:mutation-testing --help` | +| Why was my file or line never mutated? | `./docs/SCOPE.md` | +| Why only five mutator classes? Why no score threshold? | `./docs/SCOPE.md` | +| May I suppress a mutant? | `./docs/SUPPRESSING.md` | +| Why is a run slow or truncated? | `./docs/RUNNING.md` | +| Why did my run refuse to start? | `./docs/RUNNING.md` | +| Where does CI run it, and why in its own job? | `./docs/RUNNING.md` | +| Why does Stryker need repository-level setup? | `./docs/RUNNING.md` | +| Which file implements each part? | the file map below | + +## The gate failed — what now + +Reproduce the failure for your file: + +```bash +pnpm test:mutation-testing path/to/your/file.ts +``` + +This mutates the entire file, while CI mutates only changed lines. A focused run may therefore find survivors that do not affect the gate. Only mutants on your diff are gating. + +**`SURVIVED` — the failure.** The mutator name describes the change, such as forcing a condition to a constant, changing `<` to `<=`, `&&` to `||`, or `+` to `-`. Ask what behavior the change affects and assert on it. + +Valid outcomes: + +- the test checks the wrong thing — **add the missing assertion**; +- the branch is dead and deleting it costs nothing — **delete the redundant branch, guard, or operand**; +- the branch has a job besides the one the mutant changed — **suppress the mutant** according to `./docs/SUPPRESSING.md`. + +The last two both mean "no observable difference", so ask what else the code is doing. Narrowing a type, +satisfying a lint rule, and holding an invariant the runtime already guarantees all count as a job. Code +with one stays and gets a suppression. Only code with none gets deleted. + +A test that only executes the line does not kill the mutant. Mutation testing checks assertions, not just coverage. + +**A survivor is not a reason to restructure working code.** If satisfying the gate means moving a hook, +splitting a component, or reshaping a signature, the wrong outcome was chosen. Go back and pick again. +Watch for the fix that drops the file to zero mutants: `behavior` code moved into a `jsx` render body +stops being mutated at all (`./docs/SCOPE.md`), so the survivor disappears without anything being tested. + +**`NO COVERAGE` — not this gate's finding.** No test reached the line. The CRAP gate (`../code-complexity/CONTEXT.md`) already reports this as insufficient coverage. It appears here as a count and never fails the run. + +**`Run TRUNCATED`** — the wall-clock budget expired, so the results cover only part of the selection. A green result is not a pass, and a run that tested nothing at all fails. See `./docs/RUNNING.md`. + +## File map + +The process has four stages: **select** files and lines → **run** Stryker → **read** the results → **render** the output. + +### Root + +- `./index.ts` — CLI flags, stage order, and exit code; the flag mechanics live in `../cli/flags.ts` +- `./config.ts` — default budget, base ref, and shared paths +- `./stryker.config.json` — fixed Stryker settings, mutator classes, and determinism requirements +- `./vitest.config.ts` — the Vitest configuration Stryker uses +- `./run.sh` — compile-and-run wrapper +- `./tsconfig.json` — covers this folder, `../code-complexity`, and `../cli` + +### `select/` + +- `./select/files.ts` — selection modes, eligibility, and empty-run exits +- `./select/ranges.ts` — eligible lines and exclusions + +These reuse Git plumbing, scope rules, and function classification from `../code-complexity`. + +### `stryker/` + +- `./stryker/invoke.ts` — runs, limits, and stops Stryker without orphaned processes +- `./stryker/lock.ts` — one run per checkout +- `./stryker/streaming-reporter.mts` — preserves results from interrupted runs +- `./stryker/stream.ts` — reads streamed results +- `./stryker/results.ts` — selects complete or truncated results +- `./stryker/report.ts` — report structure, scores, findings, and failure conditions + +### `render/` + +- `./render/table.ts` — per-file score table +- `./render/findings.ts` — survivors and no-coverage findings +- `./render/truncation.ts` — partial-run warning +- `./render/github.ts` — PR diff annotations + +### `eslint/` + +- `./eslint/well-formed-disable.mjs` — enforces the suppression policy defined in `./docs/SUPPRESSING.md` \ No newline at end of file diff --git a/tools/mutation-testing/config.ts b/tools/mutation-testing/config.ts new file mode 100644 index 00000000000..ae1e4c491db --- /dev/null +++ b/tools/mutation-testing/config.ts @@ -0,0 +1,38 @@ +import path from 'path'; + +import strykerConfig from './stryker.config.json'; + +export const DEFAULT_BASE_REF = 'origin/main'; + +const TOOL_DIR = path.join('tools', 'mutation-testing'); + +export const STRYKER_BIN = path.join('node_modules', '.bin', 'stryker'); +export const STRYKER_CONFIG_FILE = path.join(TOOL_DIR, 'stryker.config.json'); + +// Read off the committed config rather than restated here: the reporter writes where that file says, +// and a second copy of the path would silently start reading a report nobody writes. +export const JSON_REPORT_FILE = strykerConfig.jsonReporter.fileName; +export const HTML_REPORT_FILE = strykerConfig.htmlReporter.fileName; +export const SANDBOX_DIR = strykerConfig.tempDirName; + +// Held for the whole of a run. The path is restated in .gitignore and in stryker.config.json's +// ignorePatterns, neither of which can read it from here. +export const LOCK_FILE = path.join(TOOL_DIR, '.lock'); + +// Stryker's own json report is written only once a whole run finishes, so a run stopped at its +// budget would leave nothing behind. ./stryker/streaming-reporter.mts appends a record here as each +// mutant is tested, and ./stryker/stream.ts reads it back when the run did not finish. +export const STREAM_REPORT_FILE = path.join(TOOL_DIR, 'reports', 'mutation.ndjson'); + +// src/toolkit/utils/consts, which owns the shared unit constants, sits outside this tool's tsconfig +// rootDir and cannot be imported here. +export const MINUTE_MS = 60 * 1_000; + +// A run is bounded by wall-clock time rather than mutant count because cost follows import-graph +// centrality: one 28-mutant file imported across the app costs more than five leaf utilities with +// 140 between them, since Stryker's dry run executes everything related to what it mutates. +// Overridable per invocation with --budget. +export const DEFAULT_BUDGET_MS = 15 * MINUTE_MS; + +// How long the stopped process group gets to exit on its own before it is killed outright. +export const STOP_GRACE_MS = 5 * 1_000; diff --git a/tools/mutation-testing/docs/RUNNING.md b/tools/mutation-testing/docs/RUNNING.md new file mode 100644 index 00000000000..70c899a304e --- /dev/null +++ b/tools/mutation-testing/docs/RUNNING.md @@ -0,0 +1,65 @@ +# Mutation testing — running it + +`pnpm test:mutation-testing --help` lists the flags. This page covers what they do not: run cost, limits, CI behavior, and repo quirks required for Stryker to boot. + +## What a run costs + +Runtime follows **import-graph centrality, not mutant count**. Stryker's dry run executes everything related to mutated code: five leaf utilities with 140 mutants finished in 10 seconds, while one 28-mutant file imported across the app took 70. Diff size predicts nothing. + +Runs are therefore bounded by wall clock (`--budget`, default in `../config.ts`), not mutant count. A count limit would need to track Stryker's generator and still would not predict runtime. + +Central changes are the cases worth expecting. If a run truncates: + +- narrow it — a focused run on one file answers the same question for that file; +- or raise `--budget` and let it finish. + +**A truncated run is not a pass.** Its table covers only reached mutants and reports the selection completed. CI also adds a warning annotation because a green job is easy to overlook. Its findings are real; unreached mutants remain unknown. + +## Determinism + +Runs over an unchanged tree must produce identical counts; otherwise survivors become debatable instead of actionable. Three settings in `../stryker.config.json` ensure this: +- static mutants are ignored because whether they are killed depends on module load order across the suite; +- the per-mutant timeout exceeds Vitest's to prevent slow machines scoring timeouts as kills and fast machines as survivals; +- drift specs are excluded (`./SCOPE.md`). + +`--changed` invokes git without setting a working directory, so it scores the diff from the directory where you run it. `../run.sh` locates itself to compile, so it runs from anywhere. Compilation is cwd-independent; the diff is not. + +## Output on disk + +Reports and Stryker's per-run sandbox live in this gitignored folder. A complete local run prints the HTML report location; use it to see a mutant's actual diff, which the terminal report omits. A CI run does not print it: the runner's workspace is gone by the time anyone reads the log. + +The key failure mode is mistaking a stale report for a fresh one. That is why each run clears previous output before starting, not after finishing. + +## One run per checkout + +The report files and the sandbox are shared, so a second run started in the same checkout would wipe the first's output mid-write and leave both reading each other's results. A run therefore holds a lock file in this folder for its whole duration, and a second run refuses to start — exit 1, naming the holder's pid, start time and selection. It does not wait. Parallel runs belong in separate worktrees, each with its own checkout. + +A run killed outright leaves its lock behind; the next run finds the pid dead, says so, and takes over. CI never meets the lock: one job is one checkout. + +## In CI + +`.github/workflows/checks.yml` → the `mutation_tests` job, diff-scoped against `origin/main`, runs only on pull requests. Two details: + +- **Its own job, not a unit-test step.** It cannot reuse that job's artifacts because Stryker drives Vitest once per mutant. +- **Chained after the unit-test job.** If the suite is red, Stryker aborts during its dry run, making the error look like a tooling failure rather than the failing test. Job ordering ensures the honest message appears first. + +The job timeout is separate from the run's wall-clock budget, so an expired run can still print its truncation report instead of being killed mid-write. + +### Where a CI run's output lands + +A job log is a poor place to read a result from — it opens below checkout and install output, and Stryker narrates its own run on top of that. So the report reaches a reviewer three ways, none of which requires reading the log: + +- the **job summary** on the run page carries the whole report, score table included; +- each survivor is an **`::error` annotation on the diff line** it was found on; +- a truncated run adds a **`::warning`**, because a green run is easy to overlook. + +For the summary to be readable, `../vitest.config.ts` has to name a reporter: Vitest otherwise adds its own github-actions reporter under CI, which writes a job-summary block per test run — and Stryker ends one test run per mutant. + +## Why Stryker needed repo-level plumbing + +Two integration issues are solved outside this folder and are easy to misdiagnose: + +- **`pnpm-workspace.yaml` has a scoped `minimatch@10>brace-expansion` override.** The repo globally pins `brace-expansion` to a 1.x security override, but Stryker's `minimatch` dependency needs the 5.x ESM build. Without the scoped override, Stryker does not boot. The global pin remains unchanged. +- **`../stryker.config.json` explicitly lists the Vitest runner in `plugins`.** Otherwise Stryker discovers plugins by globbing its own `node_modules` scope, which pnpm's isolated layout prevents. The resulting “no TestRunner plugins were loaded” error looks like a missing dependency rather than a resolution-layout issue. + +The config's `ignorePatterns` address the same problem: Stryker copies the project into a per-run sandbox, and without them the copy fails on symlinks under agent worktree directories. The allowlist is also what a test can read from inside the sandbox: `.agents/` is on it because `tools/review-screen/rubric.spec.ts` checks that every rule's cited file exists, and a path missing from the list fails only under Stryker, never under plain vitest. \ No newline at end of file diff --git a/tools/mutation-testing/docs/SCOPE.md b/tools/mutation-testing/docs/SCOPE.md new file mode 100644 index 00000000000..488868f0a9c --- /dev/null +++ b/tools/mutation-testing/docs/SCOPE.md @@ -0,0 +1,37 @@ +# Mutation testing — what it measures, and deliberately does not + +Every boundary below is intentional, so nobody has to rediscover it by trial and error. The rules live in code — `../select/` for files and lines, `../stryker.config.json` for mutators—while this page explains the reasoning. + +## Only files with a co-located Vitest spec + +A file is mutated only when `X.spec.ts` or `X.spec.tsx` sits beside `X.ts` or `X.tsx`. + +The question is: “Would a bug here be caught?” A file untouched by unit tests would produce only mutants nothing could kill, drowning meaningful findings in duplicates. The CRAP gate already reports that condition: an untested `behavior` function has 0% coverage and fails the PR. + +A new file without a spec is therefore the CRAP gate’s responsibility, not this one. + +## Only lines outside a `jsx` render body + +Markup is not behaviour. A render-body mutant changes what the component draws, which no Vitest assertion in this repo is designed to detect. The Playwright screenshot suite covers that, but Stryker cannot run it (below). Such mutants would be unkillable in principle. + +`behavior` code is mutated wherever it lives. The classifier is the complexity gate’s (`../../code-complexity/measure/complexity.ts`), so `KIND` in complexity reports always agrees with mutability here. + +## Only the five logic mutator classes + +Conditional expressions, equality operators, logical operators, arithmetic operators, and boolean literals. Everything else is disabled at *generation* time, not filtered from the report afterward. + +This is based on sampling, not preference. Of 22 survivors sampled across the full mutator set, roughly one-third were unkillable by any Vitest test worth writing: React dependency arrays, theme-variable objects, and colour-token string literals—visual or idiomatic rather than behavioural. + +If an excluded class hides a real bug, that is the ratchet — and why the set lives in committed configuration rather than being assembled at runtime. + +## Not Playwright, not visuals + +Stryker’s Vitest runner cannot execute Playwright tests, and its browser mode is explicitly unsupported. The screenshot suite is not measured, and a green run here says nothing about rendering. + +## Not a mutation score threshold + +The gate is exactly “no survivor on a changed line.” There is no percentage threshold. + +## Not the whole repo, in CI + +CI runs only diff-scoped mutation testing. Before the mutator restriction above, the full eligible set took 17 min 29 s locally, which is unsuitable per PR, and no scheduled workflow runs it. It remains reproducible on demand with `pnpm test:mutation-testing`. \ No newline at end of file diff --git a/tools/mutation-testing/docs/SUPPRESSING.md b/tools/mutation-testing/docs/SUPPRESSING.md new file mode 100644 index 00000000000..f9fce161790 --- /dev/null +++ b/tools/mutation-testing/docs/SUPPRESSING.md @@ -0,0 +1,27 @@ +# Mutation testing — suppressing a mutant + +A suppression is a **claim** to the reviewer: *this edit cannot change observable behaviour, so no test could have caught it.* It is not a way to turn a red job green. Written as below, a reviewer can verify the claim in the diff; otherwise, ESLint rejects it. + +## The only accepted form + +```ts +// Stryker disable next-line ConditionalExpression: <reason> +``` + +This is enforced by `stryker/well-formed-disable`, defined in `../eslint/well-formed-disable.mjs` and included in `pnpm lint:eslint`. Three things are required: + +- **`next-line`.** Stryker permits a bare `disable`, which applies to the rest of the file—a blanket mute that continues silencing mutants added months later. A suppression must identify the single exempted line. +- **The mutator name(s), comma-separated** (`ConditionalExpression,EqualityOperator`). `all` is rejected: a survivor is specific, so its exemption must be too. +- **A reason after the colon.** Stryker treats it as optional, but here it is the claim itself. Without it, there is nothing for a reviewer to evaluate. + +## What makes the claim legitimate + +A suppression is honest when the mutation produces a program **equivalent by construction** — when no assertion could distinguish the versions and adding a test would test the language rather than the code. In practice, this means a defensive guard for a condition the type system already rules out, or an unreachable fallback cheaper to keep than to prove impossible. + +It is *not* legitimate when: + +- the behaviour differs only in a way that is difficult to reach from a spec—that is a testability problem, and the fix belongs in the code's seams; +- the difference is visual — nothing in a render body is mutated in the first place (`./SCOPE.md`), so a survivor here is behavioural by definition; +- the mutation reveals a dead branch. Delete the branch. Deleted lines generate no mutants and need no comment defending them. + +If your reason would be "no test covers this", the finding is `NO COVERAGE`, not a survivor, and it does not fail this gate. \ No newline at end of file diff --git a/tools/mutation-testing/eslint/well-formed-disable.mjs b/tools/mutation-testing/eslint/well-formed-disable.mjs new file mode 100644 index 00000000000..c6e71fdb040 --- /dev/null +++ b/tools/mutation-testing/eslint/well-formed-disable.mjs @@ -0,0 +1,59 @@ +// The ESLint side of the mutation gate: suppressing a mutant has to stay a claim a reviewer can +// check, so this rule allows only the fully specified disable comment. Registered from the root +// eslint.config.mjs, which is where the repo's rule set lives. +// +// Stryker's directive grammar (@stryker-mutator/instrumenter, directive-bookkeeper.js) is +// Stryker (disable|restore) [next-line] <MutatorName>[,<MutatorName>…][: <reason>] +// and everything after `disable` is optional to it. Without `next-line` a disable runs to the end of +// the file, and `all` covers every mutator — both mute code nobody chose to exempt. + +const STRYKER_DISABLE = /^\s*Stryker\s+disable\b/; +const STRYKER_WILDCARD = 'all'; +const STRYKER_MUTATOR_NAME = /^[a-z]+$/i; +const STRYKER_WELL_FORMED = '// Stryker disable next-line <MutatorName>: <reason>'; + +// The comma-separated mutator list Stryker parses, and whether the directive was scoped to one line. +function parseStrykerDisable(directive) { + const words = directive.trim().split(/\s+/).slice(2); + const scoped = words[0] === 'next-line'; + const listed = scoped ? words.slice(1) : words; + + return { scoped, mutators: listed.join(' ').split(',').map((mutator) => mutator.trim()).filter(Boolean) }; +} + +export function strykerDisableProblem(comment) { + const [ directive, ...reason ] = comment.split(':'); + const { scoped, mutators } = parseStrykerDisable(directive); + + if (mutators.length === 0) return 'noMutator'; + if (!scoped) return 'fileScoped'; + if (mutators.includes(STRYKER_WILDCARD)) return 'wildcard'; + if (!mutators.every((mutator) => STRYKER_MUTATOR_NAME.test(mutator))) return 'noMutator'; + if (reason.join(':').trim() === '') return 'noReason'; + return undefined; +} + +export const strykerDisableRule = { + meta: { + type: 'problem', + messages: { + noMutator: `A Stryker disable must name the mutators it silences, comma-separated: ${ STRYKER_WELL_FORMED }`, + fileScoped: `A Stryker disable must be scoped to the line it exempts: ${ STRYKER_WELL_FORMED }`, + wildcard: `"all" silences every mutator. Name the ones being silenced: ${ STRYKER_WELL_FORMED }`, + noReason: `A Stryker disable must give its reason after a colon: ${ STRYKER_WELL_FORMED }`, + }, + schema: [], + }, + create(context) { + return { + Program() { + for (const comment of context.sourceCode.getAllComments()) { + if (!STRYKER_DISABLE.test(comment.value)) continue; + + const messageId = strykerDisableProblem(comment.value); + if (messageId) context.report({ loc: comment.loc, messageId }); + } + }, + }; + }, +}; diff --git a/tools/mutation-testing/eslint/well-formed-disable.spec.ts b/tools/mutation-testing/eslint/well-formed-disable.spec.ts new file mode 100644 index 00000000000..be5c5c88e11 --- /dev/null +++ b/tools/mutation-testing/eslint/well-formed-disable.spec.ts @@ -0,0 +1,92 @@ +import type { Linter as LinterTypes, Rule } from 'eslint'; +import { Linter } from 'eslint'; + +import { describe, expect, it } from 'vitest'; + +import { strykerDisableRule } from './well-formed-disable.mjs'; + +// The rule exercised in both directions, through ESLint itself rather than against the parse helper: +// a suppression Stryker would honour has to name its mutators, scope itself to one line, and give a +// reason, and everything short of that has to be an error rather than a quiet mute. + +const linter = new Linter(); + +const CONFIG: LinterTypes.Config = { + plugins: { stryker: { rules: { 'well-formed-disable': strykerDisableRule as Rule.RuleModule } } }, + rules: { 'stryker/well-formed-disable': 'error' }, +}; + +function messageIdsOf(code: string): Array<string | undefined> { + return linter.verify(code, CONFIG).map((message) => message.messageId); +} + +function lint(comment: string): Array<string | undefined> { + return messageIdsOf([ comment, 'const isReady = a && b;' ].join('\n')); +} + +describe('stryker/well-formed-disable', () => { + it('accepts a disable that names one mutator and gives a reason', () => { + expect(lint('// Stryker disable next-line ConditionalExpression: the false branch is unreachable')).toEqual([]); + }); + + it('accepts a disable that names several mutators', () => { + expect(lint('// Stryker disable next-line ConditionalExpression,LogicalOperator: both are guards on a type, not on a value')).toEqual([]); + }); + + it('accepts a mutator list written with spaces after the commas', () => { + expect(lint('// Stryker disable next-line ConditionalExpression, LogicalOperator: guards on a type')).toEqual([]); + }); + + it('rejects a blanket file-level disable', () => { + expect(lint('// Stryker disable all')).toEqual([ 'fileScoped' ]); + }); + + it('rejects a disable that is not scoped to a line, however narrow its mutator list', () => { + expect(lint('// Stryker disable ConditionalExpression: the false branch is unreachable')).toEqual([ 'fileScoped' ]); + }); + + it('rejects "all" even when the disable is scoped and reasoned', () => { + expect(lint('// Stryker disable next-line all: every mutant here is noise')).toEqual([ 'wildcard' ]); + }); + + it('rejects a disable that names no mutator', () => { + expect(lint('// Stryker disable next-line: the false branch is unreachable')).toEqual([ 'noMutator' ]); + }); + + it('rejects a mutator list Stryker cannot parse as names', () => { + expect(lint('// Stryker disable next-line Conditional Expression: two words are one unknown name')).toEqual([ 'noMutator' ]); + }); + + it('rejects a disable with no reason', () => { + expect(lint('// Stryker disable next-line ConditionalExpression')).toEqual([ 'noReason' ]); + }); + + it('rejects a disable whose reason is empty', () => { + expect(lint('// Stryker disable next-line ConditionalExpression: ')).toEqual([ 'noReason' ]); + }); + + it('keeps a reason that contains a colon', () => { + expect(lint('// Stryker disable next-line EqualityOperator: see #3665: the bound is exclusive by contract')).toEqual([]); + }); + + it('checks a block comment the same way, since Stryker reads those as directives too', () => { + expect(lint('/* Stryker disable all */')).toEqual([ 'fileScoped' ]); + }); + + it('leaves a restore directive alone — it un-mutes rather than mutes', () => { + expect(lint('// Stryker restore all')).toEqual([]); + }); + + it('leaves prose that merely mentions Stryker alone', () => { + expect(lint('// Stryker reports this line as a survivor')).toEqual([]); + }); + + it('reports every malformed disable in a file', () => { + expect(messageIdsOf([ + '// Stryker disable all', + 'const a = 1;', + '// Stryker disable next-line ConditionalExpression', + 'const b = a > 0;', + ].join('\n'))).toEqual([ 'fileScoped', 'noReason' ]); + }); +}); diff --git a/tools/mutation-testing/index.spec.ts b/tools/mutation-testing/index.spec.ts new file mode 100644 index 00000000000..72932d82eb3 --- /dev/null +++ b/tools/mutation-testing/index.spec.ts @@ -0,0 +1,102 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { DEFAULT_BASE_REF, DEFAULT_BUDGET_MS, MINUTE_MS } from './config'; +import { parseArgs } from './index'; + +describe('parseArgs', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('defaults to full mode against the configured base ref, under the configured budget', () => { + expect(parseArgs([])).toEqual({ + baseRef: DEFAULT_BASE_REF, + diffSelected: false, + focusPaths: [], + budgetMs: DEFAULT_BUDGET_MS, + }); + }); + + it('collects non-flag arguments as focus paths', () => { + expect(parseArgs([ 'src/a.ts', 'src/b.tsx' ]).focusPaths).toEqual([ 'src/a.ts', 'src/b.tsx' ]); + }); + + it('selects diff mode from --changed, with an optional inline ref', () => { + expect(parseArgs([ '--changed' ])).toMatchObject({ diffSelected: true, baseRef: DEFAULT_BASE_REF }); + expect(parseArgs([ '--changed=upstream/main' ])).toMatchObject({ diffSelected: true, baseRef: 'upstream/main' }); + }); + + // The CI invocation: --changed must not consume the following token as its ref. + it('leaves the token after a bare --changed alone', () => { + expect(parseArgs([ '--changed', 'src/a.ts' ])).toMatchObject({ + diffSelected: true, + baseRef: DEFAULT_BASE_REF, + focusPaths: [ 'src/a.ts' ], + }); + }); + + it('selects diff mode from --base and takes its ref', () => { + expect(parseArgs([ '--base', 'upstream/main' ])).toMatchObject({ diffSelected: true, baseRef: 'upstream/main' }); + expect(parseArgs([ '--base=upstream/main' ])).toMatchObject({ diffSelected: true, baseRef: 'upstream/main' }); + }); + + // A value flag takes the following token only when it carries no inline value: swallowing the + // token after --base=<ref> would drop a focus path, and not swallowing it after a bare --base + // would turn the ref itself into one. + it('consumes the token after a value flag only when the value is not inline', () => { + expect(parseArgs([ '--base', 'upstream/main', 'src/a.ts' ])).toMatchObject({ + baseRef: 'upstream/main', + focusPaths: [ 'src/a.ts' ], + }); + expect(parseArgs([ '--base=upstream/main', 'src/a.ts' ])).toMatchObject({ + baseRef: 'upstream/main', + focusPaths: [ 'src/a.ts' ], + }); + }); + + it('combines flags and focus paths in any order', () => { + expect(parseArgs([ 'src/a.ts', '--changed=upstream/main', 'src/b.ts' ])).toMatchObject({ + diffSelected: true, + baseRef: 'upstream/main', + focusPaths: [ 'src/a.ts', 'src/b.ts' ], + }); + }); + + it('takes the budget in minutes, overriding the default', () => { + expect(parseArgs([ '--budget', '3' ]).budgetMs).toBe(3 * MINUTE_MS); + expect(parseArgs([ '--budget=0.5' ]).budgetMs).toBe(MINUTE_MS / 2); + }); + + // Falling back to the default on a bad value would make the flag lie about what bounds the run. + it('rejects a budget that is not a positive number of minutes', () => { + expect(() => parseArgs([ '--budget', 'soon' ])).toThrow('--budget takes a positive number of minutes, got: soon'); + expect(() => parseArgs([ '--budget', '0' ])).toThrow('--budget takes a positive number of minutes, got: 0'); + expect(() => parseArgs([ '--budget', '-5' ])).toThrow('--budget takes a positive number of minutes, got: -5'); + }); + + it('rejects an unknown flag', () => { + expect(() => parseArgs([ '--nope' ])).toThrow('Unknown flag: --nope'); + // A near-miss of a real flag is unknown too, not a loose prefix match. + expect(() => parseArgs([ '--change=main' ])).toThrow('Unknown flag: --change'); + }); + + it('rejects a value flag with no value', () => { + expect(() => parseArgs([ '--base' ])).toThrow('Missing value for --base'); + }); + + it('rejects a value passed to a switch flag', () => { + expect(() => parseArgs([ '--help=yes' ])).toThrow('--help takes no value'); + }); + + // The same flag bare is the whole point of a switch: it has to be accepted rather than rejected + // for missing its value. + it('prints the usage text and exits on a bare switch flag', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(process, 'exit').mockImplementation((code) => { + throw new Error(`exited with ${ code }`); + }); + + expect(() => parseArgs([ '--help' ])).toThrow('exited with 0'); + expect(log).toHaveBeenCalledWith(expect.stringContaining('Usage:')); + }); +}); diff --git a/tools/mutation-testing/index.ts b/tools/mutation-testing/index.ts new file mode 100644 index 00000000000..3f250b1b9fb --- /dev/null +++ b/tools/mutation-testing/index.ts @@ -0,0 +1,217 @@ +/* eslint-disable no-console -- this is a CLI whose entire job is to print a report to stdout */ +import fs from 'fs'; +import { pathToFileURL } from 'url'; + +import type { FlagSpec } from '../cli/flags'; +import { parseArgs as parseFlags } from '../cli/flags'; +import { DEFAULT_BASE_REF, DEFAULT_BUDGET_MS, HTML_REPORT_FILE, MINUTE_MS } from './config'; +import { formatFindings } from './render/findings'; +import { githubAnnotations, stepSummary, truncationAnnotation } from './render/github'; +import { formatTable } from './render/table'; +import { formatTruncationNotice } from './render/truncation'; +import type { MutateTarget, Selection } from './select/files'; +import { selectFiles } from './select/files'; +import type { RunOutcome } from './stryker/invoke'; +import { runStryker } from './stryker/invoke'; +import { acquireLock, formatHeldMessage, formatStaleMessage, releaseLock } from './stryker/lock'; +import type { Findings } from './stryker/report'; +import { buildFileScores, collectFindings, isFailingRun } from './stryker/report'; +import type { RunResults } from './stryker/results'; +import { readResults, testedNothing } from './stryker/results'; + +// Mutation testing: change the code, and see whether any test notices. Coverage answers "was this +// line executed?"; a surviving mutant answers "would a bug here be caught?", which is the question +// this tool exists to ask. +// +// Selection has three modes, mirroring the complexity gate's flags; ./select/files.ts owns them. +// USAGE below is the flag reference. + +interface CliOptions { + baseRef: string; + diffSelected: boolean; + focusPaths: Array<string>; + budgetMs: number; +} + +const USAGE = `Usage: + test:mutation-testing + Full mode (default): mutate every in-scope file that has a co-located vitest spec. + + test:mutation-testing <path...> + Focused mode: mutate the given files. A file with no spec beside it is skipped. + + test:mutation-testing --changed[=<ref>] [--base <ref>] + Diff mode: mutate only the lines this branch changed vs the base ref + (default ${ DEFAULT_BASE_REF }, resolved through the merge-base, so uncommitted edits count and + base-branch churn does not). + + --budget <minutes> + Wall-clock bound on the run (default ${ DEFAULT_BUDGET_MS / MINUTE_MS }). At expiry the run is + stopped and everything tested so far is reported, marked as truncated. + + A file is mutated only when a vitest spec sits beside it (X.spec.ts / X.spec.tsx next to X.ts / + X.tsx) — an untested file would otherwise produce a run of unkillable mutants. In every mode, the + lines inside a jsx render body are left alone. When the selection comes out empty the run says why + and exits 0 without starting Stryker.`; + +// Two readers, two places. A local run is read in the terminal it was started from; a CI run is read +// on the run page, where the log sits behind a click and shares the job with checkout and install +// output. $GITHUB_STEP_SUMMARY is absent in Actions runtimes that provide no summary file. +/* eslint-disable no-restricted-properties -- a Node CLI reading its own CI runtime, not app env vars */ +const IN_GITHUB_ACTIONS = Boolean(process.env.GITHUB_ACTIONS); +const STEP_SUMMARY_FILE = process.env.GITHUB_STEP_SUMMARY; +/* eslint-enable no-restricted-properties */ + +// A budget of zero or less would stop the run before it started, and a misspelt value must not +// silently fall back to the default — either way the flag would lie about what bounds the run. +function parseBudgetMinutes(value: string): number { + const minutes = Number(value); + if (!Number.isFinite(minutes) || minutes <= 0) throw new Error(`--budget takes a positive number of minutes, got: ${ value }`); + return minutes; +} + +const FLAGS: ReadonlyMap<string, FlagSpec<CliOptions>> = new Map<string, FlagSpec<CliOptions>>([ + [ '--help', { kind: 'switch', apply: () => { + console.log(USAGE); + process.exit(0); + } } ], + [ '-h', { kind: 'switch', apply: () => { + console.log(USAGE); + process.exit(0); + } } ], + [ '--changed', { kind: 'optional', apply: (options, value) => { + options.diffSelected = true; + if (value !== undefined) options.baseRef = value; + } } ], + [ '--base', { kind: 'value', apply: (options, value) => { + options.diffSelected = true; + options.baseRef = value; + } } ], + [ '--budget', { kind: 'value', apply: (options, value) => { + options.budgetMs = parseBudgetMinutes(value) * MINUTE_MS; + } } ], +]); + +export function parseArgs(argv: ReadonlyArray<string>): CliOptions { + const { options, rest } = parseFlags<CliOptions>(argv, FLAGS, { + baseRef: DEFAULT_BASE_REF, + diffSelected: false, + focusPaths: [], + budgetMs: DEFAULT_BUDGET_MS, + }, { kind: 'reject', usage: USAGE }); + + options.focusPaths = rest; + return options; +} + +function describeSelection(options: CliOptions): string { + if (options.focusPaths.length > 0) return options.focusPaths.join(', '); + if (options.diffSelected) return `--changed vs ${ options.baseRef }`; + return 'every eligible file'; +} + +// Taken only once there is something to run: an empty selection never touches the shared output, so +// it has nothing to protect and must not refuse because of a run that does. +function lockCheckout(options: CliOptions): void { + const attempt = acquireLock(describeSelection(options)); + if (attempt.outcome === 'held') throw new Error(formatHeldMessage(attempt.holder)); + if (attempt.staleLockRemoved !== undefined) console.error(formatStaleMessage(attempt.staleLockRemoved)); +} + +function reportSelection(selection: Extract<Selection, { outcome: 'selected' }>): void { + for (const file of selection.ineligible) { + console.error(`› skipped ${ file }: no co-located vitest spec`); + } + console.error(`› Mutating ${ selection.targets.length } file(s)…`); +} + +// Stryker writes the html report only when a whole run finishes, and ./stryker/invoke.ts deletes the +// previous one before starting — so the file existing is what makes the path this run's rather than +// a stale one being advertised as fresh. Only a local reader can open the path: on a runner it names +// a workspace that is gone by the time anyone reads the log. +function reportHtmlLocation(): void { + if (!fs.existsSync(HTML_REPORT_FILE)) return; + console.log(`\nFull report: ${ pathToFileURL(HTML_REPORT_FILE).href }`); +} + +function formatReport(results: RunResults, findings: Findings, budgetMs: number): string { + const sections = [ formatTable(buildFileScores(results.report)) ]; + if (results.truncated) sections.push(formatTruncationNotice(results, budgetMs)); + sections.push(formatFindings(findings)); + return sections.join('\n\n'); +} + +// Stryker narrates its own run — instrumentation counts, worker setup, report paths — through this +// process's inherited stdio, so in CI that lands between the selection line and the report. A log +// group folds it away instead of silencing it: when Stryker fails, its output is the diagnosis. +async function runGrouped(targets: ReadonlyArray<MutateTarget>, budgetMs: number): Promise<RunOutcome> { + if (!IN_GITHUB_ACTIONS) return runStryker(targets, budgetMs); + + console.log('::group::Stryker output'); + try { + return await runStryker(targets, budgetMs); + } finally { + console.log('::endgroup::'); + } +} + +// Under $GITHUB_ACTIONS, repeat the findings as annotation directives so they land on the PR diff. +// The plain-stdout report has already been printed, and is what a local run reads. +function emitGithubActionsOutput(findings: Findings, results: RunResults, budgetMs: number): void { + for (const annotation of githubAnnotations(findings)) console.log(annotation); + if (results.truncated) console.log(truncationAnnotation(formatTruncationNotice(results, budgetMs))); +} + +function writeStepSummary(report: string): void { + if (STEP_SUMMARY_FILE === undefined) return; + fs.appendFileSync(STEP_SUMMARY_FILE, stepSummary(report)); +} + +async function main(): Promise<void> { + const options = parseArgs(process.argv.slice(2)); + const selection = selectFiles(options, process.cwd()); + + if (selection.outcome === 'empty') { + console.log(selection.reason); + return; + } + + lockCheckout(options); + reportSelection(selection); + let results: RunResults; + try { + results = readResults(await runGrouped(selection.targets, options.budgetMs)); + } finally { + releaseLock(); + } + const findings = collectFindings(results.report); + + const report = formatReport(results, findings, options.budgetMs); + console.log(report); + + if (IN_GITHUB_ACTIONS) { + emitGithubActionsOutput(findings, results, options.budgetMs); + writeStepSummary(report); + } else { + reportHtmlLocation(); + } + + if (isFailingRun(findings) || testedNothing(results)) process.exitCode = 1; +} + +// run.sh always executes the compiled entry point, so that path is what marks this module as the +// process entry. The guard exists so index.spec.ts can import parseArgs without kicking off a whole +// mutation run — under vitest the entry is vitest's own binary. +const CLI_ENTRY_PATH = 'mutation-testing/index.js'; + +function isProcessEntryPoint(): boolean { + const entry = process.argv[1]?.replace(/\\/g, '/'); + return entry !== undefined && entry.endsWith(CLI_ENTRY_PATH); +} + +if (isProcessEntryPoint()) { + main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + }); +} diff --git a/tools/mutation-testing/render/findings.spec.ts b/tools/mutation-testing/render/findings.spec.ts new file mode 100644 index 00000000000..648fb6ace59 --- /dev/null +++ b/tools/mutation-testing/render/findings.spec.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest'; + +import type { Findings } from '../stryker/report'; +import { formatFindings } from './findings'; + +const EMPTY: Findings = { survivors: [], noCoverage: [] }; + +describe('formatFindings', () => { + it('names every mutator that survived on one line as a single finding under its file', () => { + const findings: Findings = { + survivors: [ { + file: 'src/a.ts', + lines: [ + { line: 12, mutators: [ { name: 'ConditionalExpression', count: 1 }, { name: 'LogicalOperator', count: 1 } ] }, + { line: 130, mutators: [ { name: 'EqualityOperator', count: 1 } ] }, + ], + } ], + noCoverage: [], + }; + + expect(formatFindings(findings)).toBe([ + 'SURVIVED — these changes were made and no test failed:', + '', + 'src/a.ts', + ' L 12 ConditionalExpression, LogicalOperator', + ' L130 EqualityOperator', + ].join('\n')); + }); + + it('counts repeats of a mutator on one line instead of listing it twice', () => { + const findings: Findings = { + survivors: [ { file: 'src/a.ts', lines: [ { line: 4, mutators: [ { name: 'BooleanLiteral', count: 3 } ] } ] } ], + noCoverage: [], + }; + + expect(formatFindings(findings)).toContain('L4 BooleanLiteral ×3'); + }); + + it('separates the files it groups under', () => { + const findings: Findings = { + survivors: [ + { file: 'src/a.ts', lines: [ { line: 1, mutators: [ { name: 'LogicalOperator', count: 1 } ] } ] }, + { file: 'src/b.ts', lines: [ { line: 2, mutators: [ { name: 'LogicalOperator', count: 1 } ] } ] }, + ], + noCoverage: [], + }; + + expect(formatFindings(findings)).toBe([ + 'SURVIVED — these changes were made and no test failed:', + '', + 'src/a.ts', + ' L1 LogicalOperator', + '', + 'src/b.ts', + ' L2 LogicalOperator', + ].join('\n')); + }); + + it('summarises the uncovered mutants on one line, whatever they span', () => { + const findings: Findings = { + survivors: [], + noCoverage: [ { file: 'src/a.ts', mutants: 5 }, { file: 'src/b.ts', mutants: 2 } ], + }; + + expect(formatFindings(findings)).toBe( + 'NO COVERAGE — 7 mutant(s) on 2 file(s) ran no test at all, which the CRAP gate covers: src/a.ts (5), src/b.ts (2).', + ); + }); + + it('prints both findings as separate sections when a run has both', () => { + const findings: Findings = { + survivors: [ { file: 'src/a.ts', lines: [ { line: 9, mutators: [ { name: 'EqualityOperator', count: 1 } ] } ] } ], + noCoverage: [ { file: 'src/a.ts', mutants: 1 } ], + }; + + expect(formatFindings(findings)).toBe([ + 'SURVIVED — these changes were made and no test failed:', + '', + 'src/a.ts', + ' L9 EqualityOperator', + '', + 'NO COVERAGE — 1 mutant(s) on 1 file(s) ran no test at all, which the CRAP gate covers: src/a.ts (1).', + ].join('\n')); + }); + + it('says a clean run is clean in one line rather than printing empty sections', () => { + expect(formatFindings(EMPTY)).toBe('No survivors and no uncovered mutants — nothing to act on.'); + }); +}); diff --git a/tools/mutation-testing/render/findings.ts b/tools/mutation-testing/render/findings.ts new file mode 100644 index 00000000000..9fd3c88cddb --- /dev/null +++ b/tools/mutation-testing/render/findings.ts @@ -0,0 +1,50 @@ +// Renders what a run found: the survivors, grouped by the source line they sit on, and a one-line +// count of the mutants no test covered. The two are rendered differently on purpose — a survivor is +// an assertion to strengthen and needs its line, while a no-coverage mutant is a missing test, which +// is the CRAP gate's finding and needs only its size. + +import type { Findings, LineFinding } from '../stryker/report'; + +const NOTHING_FOUND = 'No survivors and no uncovered mutants — nothing to act on.'; + +const SURVIVORS_HEADING = 'SURVIVED — these changes were made and no test failed:'; + +// Shared with ./github.ts, so a survivor reads the same on the terminal and in the annotation +// GitHub puts on the diff line. +export function formatMutators(finding: LineFinding): string { + return finding.mutators.map(({ name, count }) => count === 1 ? name : `${ name } ×${ count }`).join(', '); +} + +function survivorLines(findings: Findings): Array<string> { + const lines = [ SURVIVORS_HEADING ]; + + for (const { file, lines: found } of findings.survivors) { + lines.push('', file); + // The line number is padded to the file's widest, so the mutator names line up in one column. + const width = Math.max(...found.map((finding) => String(finding.line).length)); + for (const finding of found) lines.push(` L${ String(finding.line).padStart(width) } ${ formatMutators(finding) }`); + } + + return lines; +} + +function sum(findings: Findings): number { + return findings.noCoverage.reduce((total, entry) => total + entry.mutants, 0); +} + +// Deliberately one line, however many files it spans: an uncovered line is a coverage gap the CRAP +// gate already reports per function, and listing it again here would bury the survivors. +function noCoverageLine(findings: Findings): string { + const perFile = findings.noCoverage.map(({ file, mutants }) => `${ file } (${ mutants })`).join(', '); + + return `NO COVERAGE — ${ sum(findings) } mutant(s) on ${ findings.noCoverage.length } file(s) ran no test at all, ` + + `which the CRAP gate covers: ${ perFile }.`; +} + +export function formatFindings(findings: Findings): string { + const sections: Array<string> = []; + if (findings.survivors.length > 0) sections.push(survivorLines(findings).join('\n')); + if (findings.noCoverage.length > 0) sections.push(noCoverageLine(findings)); + + return sections.length === 0 ? NOTHING_FOUND : sections.join('\n\n'); +} diff --git a/tools/mutation-testing/render/github.spec.ts b/tools/mutation-testing/render/github.spec.ts new file mode 100644 index 00000000000..1419adac52f --- /dev/null +++ b/tools/mutation-testing/render/github.spec.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from 'vitest'; + +import type { Findings } from '../stryker/report'; +import { githubAnnotations, stepSummary, truncationAnnotation } from './github'; + +const NO_FINDINGS: Findings = { survivors: [], noCoverage: [] }; + +describe('githubAnnotations', () => { + it('anchors one error to each surviving line, naming the mutators that survived on it', () => { + const findings: Findings = { + survivors: [ { + file: 'src/a.ts', + lines: [ + { line: 12, mutators: [ { name: 'ConditionalExpression', count: 1 }, { name: 'LogicalOperator', count: 1 } ] }, + { line: 130, mutators: [ { name: 'EqualityOperator', count: 1 } ] }, + ], + } ], + noCoverage: [], + }; + + expect(githubAnnotations(findings)).toEqual([ + '::error file=src/a.ts,line=12::Mutant survived: ConditionalExpression, LogicalOperator — this change was made here and no test failed.', + '::error file=src/a.ts,line=130::Mutant survived: EqualityOperator — this change was made here and no test failed.', + ]); + }); + + it('carries the repeat count of a mutator into the annotation', () => { + const findings: Findings = { + survivors: [ { file: 'src/a.ts', lines: [ { line: 4, mutators: [ { name: 'BooleanLiteral', count: 3 } ] } ] } ], + noCoverage: [], + }; + + expect(githubAnnotations(findings)[0]).toContain('BooleanLiteral ×3'); + }); + + it('annotates every file a run found survivors in', () => { + const findings: Findings = { + survivors: [ + { file: 'src/a.ts', lines: [ { line: 1, mutators: [ { name: 'LogicalOperator', count: 1 } ] } ] }, + { file: 'tools/b.ts', lines: [ { line: 2, mutators: [ { name: 'LogicalOperator', count: 1 } ] } ] }, + ], + noCoverage: [], + }; + + expect(githubAnnotations(findings).map((annotation) => annotation.split('::')[1])).toEqual([ + 'error file=src/a.ts,line=1', + 'error file=tools/b.ts,line=2', + ]); + }); + + it('annotates nothing when a run only found mutants no test covered', () => { + expect(githubAnnotations({ survivors: [], noCoverage: [ { file: 'src/a.ts', mutants: 5 } ] })).toEqual([]); + }); + + it('annotates nothing when a run found nothing', () => { + expect(githubAnnotations(NO_FINDINGS)).toEqual([]); + }); + + it('keeps a message on one line, since a newline would truncate the directive', () => { + const findings: Findings = { + survivors: [ { file: 'src/a.ts', lines: [ { line: 1, mutators: [ { name: 'Logical\nOperator', count: 1 } ] } ] } ], + noCoverage: [], + }; + + expect(githubAnnotations(findings)[0]).toBe( + '::error file=src/a.ts,line=1::Mutant survived: Logical Operator — this change was made here and no test failed.', + ); + }); +}); + +describe('truncationAnnotation', () => { + it('reports a truncated run as a warning, so it is visible without failing the gate', () => { + expect(truncationAnnotation('Run TRUNCATED: the 15 min budget expired')).toBe( + '::warning::Run TRUNCATED: the 15 min budget expired', + ); + }); + + it('flattens a multi-line notice onto the single line a directive allows', () => { + expect(truncationAnnotation('Run TRUNCATED\nRaise the budget')).toBe('::warning::Run TRUNCATED Raise the budget'); + }); +}); + +describe('stepSummary', () => { + it('fences the report so the score table keeps its column alignment once rendered as markdown', () => { + expect(stepSummary('FILE SCORE\nsrc/a.ts 80%')).toBe( + '## Mutation testing\n\n```\nFILE SCORE\nsrc/a.ts 80%\n```\n', + ); + }); + + it('carries the report through verbatim, so the summary and the log say the same thing', () => { + const report = 'FILE\n\nSURVIVED — 1 mutant(s) on 1 file(s):\n src/a.ts:12 ConditionalExpression'; + + expect(stepSummary(report)).toContain(report); + }); +}); diff --git a/tools/mutation-testing/render/github.ts b/tools/mutation-testing/render/github.ts new file mode 100644 index 00000000000..5805c71ba04 --- /dev/null +++ b/tools/mutation-testing/render/github.ts @@ -0,0 +1,41 @@ +// GitHub Actions output path, which puts the report where a reviewer already is: an inline `::error` +// annotation per surviving line, so a weak assertion shows up on the diff rather than at the bottom +// of a job log, and the whole report as a step summary on the run page. Pure formatters here; the +// writes live in index.ts, guarded by $GITHUB_ACTIONS. + +import type { Findings, LineFinding } from '../stryker/report'; +import { formatMutators } from './findings'; + +// Annotation directives are single-line; a newline would truncate the message and leave the rest +// of it on stdout as stray output. +function sanitize(message: string): string { + return message.replace(/[\r\n]+/g, ' '); +} + +function survivorMessage(finding: LineFinding): string { + return `Mutant survived: ${ formatMutators(finding) } — this change was made here and no test failed.`; +} + +// One `::error file=<f>,line=<n>::<msg>` per surviving line, matching the terminal report's grouping: +// several mutators surviving together is one weak assertion, so it gets one annotation. +export function githubAnnotations(findings: Findings): Array<string> { + return findings.survivors.flatMap(({ file, lines }) => lines.map((finding) => + `::error file=${ file },line=${ finding.line }::${ sanitize(survivorMessage(finding)) }`)); +} + +// A truncated run reports fewer survivors than the selection holds, so it could pass the gate on +// mutants it never tested. The notice is on stdout either way; as a `::warning` it also reaches the +// job's annotation list, where a green run gets looked at. +export function truncationAnnotation(notice: string): string { + return `::warning::${ sanitize(notice) }`; +} + +// A fence because markdown renders its contents verbatim, which the score table's column alignment +// needs; as prose the table would collapse into one run of words. +const CODE_FENCE = '```'; + +// The step summary renders on the run page itself, which is where a passing run gets read — its +// table would otherwise only exist inside a job log, below checkout and install output. +export function stepSummary(report: string): string { + return `## Mutation testing\n\n${ CODE_FENCE }\n${ report }\n${ CODE_FENCE }\n`; +} diff --git a/tools/mutation-testing/render/table.spec.ts b/tools/mutation-testing/render/table.spec.ts new file mode 100644 index 00000000000..1834ebaf837 --- /dev/null +++ b/tools/mutation-testing/render/table.spec.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest'; + +import type { FileScore } from '../stryker/report'; +import { formatTable } from './table'; + +function score(file: string, killed: number, survived: number, noCoverage = 0): FileScore { + const mutants = killed + survived + noCoverage; + return { file, mutants, killed, survived, noCoverage, score: mutants === 0 ? null : (killed / mutants) * 100 }; +} + +describe('formatTable', () => { + it('renders a column per metric, right-aligned under its header', () => { + expect(formatTable([ score('src/a.ts', 3, 1) ])).toBe([ + 'FILE SCORE MUTANTS KILLED SURVIVED NO-COV', + 'src/a.ts 75% 4 3 1 0', + '', + '1 file(s), 4 mutant(s): 3 killed, 1 survived, 0 without coverage — score 75%.', + ].join('\n')); + }); + + it('leads with the worst-scoring file', () => { + const table = formatTable([ score('src/good.ts', 4, 0), score('src/bad.ts', 1, 3) ]); + expect(table.indexOf('src/bad.ts')).toBeLessThan(table.indexOf('src/good.ts')); + }); + + it('sinks a file with no scored mutants below every scored one', () => { + const table = formatTable([ score('src/none.ts', 0, 0), score('src/perfect.ts', 4, 0) ]); + expect(table.indexOf('src/perfect.ts')).toBeLessThan(table.indexOf('src/none.ts')); + expect(table).toContain('src/none.ts — 0 0 0 0'); + }); + + it('weighs the overall score by mutant count rather than averaging the per-file scores', () => { + // Averaging the rows would read 50%; the mutant-weighted score is 10 killed out of 11. + expect(formatTable([ score('src/big.ts', 10, 0), score('src/small.ts', 0, 1) ])) + .toContain('2 file(s), 11 mutant(s): 10 killed, 1 survived, 0 without coverage — score 91%.'); + }); + + it('summarises a run where nothing was scored without dividing by zero', () => { + expect(formatTable([ score('src/none.ts', 0, 0) ])) + .toContain('1 file(s), 0 mutant(s): 0 killed, 0 survived, 0 without coverage — score —.'); + }); + + it('counts mutants nothing covered separately from survivors', () => { + expect(formatTable([ score('src/a.ts', 1, 1, 2) ])) + .toContain('1 file(s), 4 mutant(s): 1 killed, 1 survived, 2 without coverage — score 25%.'); + }); +}); diff --git a/tools/mutation-testing/render/table.ts b/tools/mutation-testing/render/table.ts new file mode 100644 index 00000000000..7ac20bf823d --- /dev/null +++ b/tools/mutation-testing/render/table.ts @@ -0,0 +1,61 @@ +// Renders the per-file score table: how many mutants each file got, how many any test noticed, and +// the resulting mutation score, worst file first. + +import type { FileScore } from '../stryker/report'; + +const NA = '—'; + +function scoreText(score: number | null): string { + return score === null ? NA : `${ Math.round(score) }%`; +} + +// Worst score first, so the weakest assertions lead. Files with nothing scored (null) fall to the +// bottom rather than reading as a perfect zero. +function byScoreAscending(a: FileScore, b: FileScore): number { + return (a.score ?? Number.POSITIVE_INFINITY) - (b.score ?? Number.POSITIVE_INFINITY) || b.mutants - a.mutants; +} + +interface Column { + readonly header: string; + readonly cell: (row: FileScore) => string; + readonly alignRight: boolean; +} + +const COLUMNS: ReadonlyArray<Column> = [ + { header: 'FILE', cell: (row) => row.file, alignRight: false }, + { header: 'SCORE', cell: (row) => scoreText(row.score), alignRight: true }, + { header: 'MUTANTS', cell: (row) => String(row.mutants), alignRight: true }, + { header: 'KILLED', cell: (row) => String(row.killed), alignRight: true }, + { header: 'SURVIVED', cell: (row) => String(row.survived), alignRight: true }, + { header: 'NO-COV', cell: (row) => String(row.noCoverage), alignRight: true }, +]; + +function sum(rows: ReadonlyArray<FileScore>, of: (row: FileScore) => number): number { + return rows.reduce((total, row) => total + of(row), 0); +} + +// The overall score is recomputed from the totals rather than averaged over the per-file scores: a +// one-mutant file would otherwise weigh as much as a fifty-mutant one. +function summaryLine(rows: ReadonlyArray<FileScore>): string { + const mutants = sum(rows, (row) => row.mutants); + const killed = sum(rows, (row) => row.killed); + const survived = sum(rows, (row) => row.survived); + const noCoverage = sum(rows, (row) => row.noCoverage); + const score = scoreText(mutants === 0 ? null : (killed / mutants) * 100); + + return `${ rows.length } file(s), ${ mutants } mutant(s): ${ killed } killed, ${ survived } survived, ${ noCoverage } without coverage — score ${ score }.`; +} + +export function formatTable(rows: ReadonlyArray<FileScore>): string { + const sorted = [ ...rows ].sort(byScoreAscending); + const widths = COLUMNS.map((column) => Math.max(column.header.length, ...sorted.map((row) => column.cell(row).length))); + const renderRow = (cells: ReadonlyArray<string>): string => + cells.map((cell, index) => COLUMNS[index].alignRight ? cell.padStart(widths[index]) : cell.padEnd(widths[index])).join(' '); + + const lines = [ renderRow(COLUMNS.map((column) => column.header)) ]; + for (const row of sorted) lines.push(renderRow(COLUMNS.map((column) => column.cell(row)))); + lines.push(''); + lines.push(summaryLine(sorted)); + + return lines.join('\n'); +} diff --git a/tools/mutation-testing/render/truncation.spec.ts b/tools/mutation-testing/render/truncation.spec.ts new file mode 100644 index 00000000000..692a5b8d4f3 --- /dev/null +++ b/tools/mutation-testing/render/truncation.spec.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; + +import { MINUTE_MS } from '../config'; +import { formatTruncationNotice } from './truncation'; + +const BUDGET_MS = 15 * MINUTE_MS; + +function notice(tested: number, planned: number | null, budgetMs = BUDGET_MS): string { + return formatTruncationNotice({ truncated: true, report: { files: {} }, tested, planned }, budgetMs); +} + +describe('formatTruncationNotice', () => { + it('says the run was truncated, at what budget, and what share it covered', () => { + expect(notice(42, 137)).toBe( + 'Run TRUNCATED: the 15 min budget expired after 42 of 137 mutant(s) — 31% of the selection was covered. ' + + 'Raise the budget with --budget <minutes>.', + ); + }); + + it('reports a sub-minute budget without rounding it away to zero', () => { + expect(notice(1, 2, MINUTE_MS / 2)).toContain('the 0.5 min budget'); + }); + + it('states plainly that nothing was covered when no mutant was tested', () => { + expect(notice(0, 137)).toContain('after 0 of 137 mutant(s) — none of the selection was covered'); + }); + + it('does not invent a share when the planned total never arrived', () => { + expect(notice(3, null)).toContain('after 3 mutant(s) — an unknown share of the selection was covered'); + }); +}); diff --git a/tools/mutation-testing/render/truncation.ts b/tools/mutation-testing/render/truncation.ts new file mode 100644 index 00000000000..5ccb82861fe --- /dev/null +++ b/tools/mutation-testing/render/truncation.ts @@ -0,0 +1,32 @@ +import { MINUTE_MS } from '../config'; +import type { RunResults } from '../stryker/results'; + +// The line a truncated run prints alongside its totals. A run stopped at its budget covers part of +// the selection, and the numbers beside it are only that part's — so the notice says both, and the +// report is never presented as a complete one. + +const PERCENT = 100; + +// Two decimals so a budget set in seconds during a bisect is still reported as what was asked for, +// while the whole minutes a real run uses print bare. +const BUDGET_DECIMALS = 2; + +function budgetText(budgetMs: number): string { + return `${ Number((budgetMs / MINUTE_MS).toFixed(BUDGET_DECIMALS)) } min`; +} + +// Stryker plans a run before testing anything, so a stream with no plan record was cut off during +// the dry run — the denominator is genuinely unknown rather than zero. +function shareText(tested: number, planned: number | null): string { + if (tested === 0) return 'none of the selection'; + if (planned === null) return 'an unknown share of the selection'; + return `${ Math.round((tested / planned) * PERCENT) }% of the selection`; +} + +export function formatTruncationNotice(results: Extract<RunResults, { truncated: true }>, budgetMs: number): string { + const { tested, planned } = results; + const total = planned === null ? '' : ` of ${ planned }`; + + return `Run TRUNCATED: the ${ budgetText(budgetMs) } budget expired after ${ tested }${ total } mutant(s) — ` + + `${ shareText(tested, planned) } was covered. Raise the budget with --budget <minutes>.`; +} diff --git a/tools/mutation-testing/run.sh b/tools/mutation-testing/run.sh new file mode 100755 index 00000000000..5ba62bf05f0 --- /dev/null +++ b/tools/mutation-testing/run.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +# Usage: tools/mutation-testing/run.sh [--changed[=<ref>]] [--base <ref>] [<path>...] + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" + +# Compiled into a directory of this run's own: a shared one would be rewritten by a second run while +# Stryker is still loading the reporter plugin out of it for the first. It has to sit inside the repo, +# where the compiled code resolves node_modules; .gitignore and stryker.config.json both name it. +OUT="$(mktemp -d "$DIR/.build.XXXXXX")" +trap 'rm -rf "$OUT"' EXIT + +# The tool imports the complexity gate's selection modules, so tsc's rootDir spans both tool +# folders and the entry point lands one level deeper than the outDir. +"$ROOT/node_modules/.bin/tsc" -p "$DIR/tsconfig.json" --outDir "$OUT" +node "$OUT/mutation-testing/index.js" "$@" diff --git a/tools/mutation-testing/select/files.spec.ts b/tools/mutation-testing/select/files.spec.ts new file mode 100644 index 00000000000..c28189c0453 --- /dev/null +++ b/tools/mutation-testing/select/files.spec.ts @@ -0,0 +1,248 @@ +import { execFileSync } from 'child_process'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import type { Selection, SelectionRequest } from './files'; +import { selectFiles } from './files'; + +// Real repo files, so eligibility is exercised against the naming convention on disk rather than a +// stubbed fs: crap.spec.ts sits beside the first, nothing sits beside the second. +const ELIGIBLE_FILE = 'tools/code-complexity/measure/crap.ts'; +const INELIGIBLE_FILE = 'tools/code-complexity/config.ts'; + +const BASE_REF = 'main'; + +const NOTHING_OUTSIDE_RENDER_BODIES = 'Every eligible file has all of its logic inside a jsx render body — nothing to mutate.'; + +// A component with no logic of its own outside the render body it returns. +const CARD_COMPONENT = `const Card = ({ show }: { show: boolean }) => ( + <div>{ show ? 'yes' : 'no' }</div> +); + +export default Card; +`; + +// The same component with nothing left at module scope, so every line of the file is render body +// and the file has no mutable line at all. +const RENDER_BODY_ONLY_COMPONENT = `export default ({ show }: { show: boolean }) => ( + <div>{ show ? 'yes' : 'no' }</div> +); +`; + +function request(overrides: Partial<SelectionRequest>, cwd: string = process.cwd()): Selection { + return selectFiles({ focusPaths: [], diffSelected: false, baseRef: BASE_REF, ...overrides }, cwd); +} + +// The files a selection resolved to, dropping the ranges each was narrowed to — ./ranges.spec.ts +// covers those. +function selectedFiles(selection: Selection): Array<string> { + if (selection.outcome === 'empty') throw new Error(`Expected a selection, got: ${ selection.reason }`); + return selection.targets.map((target) => target.file); +} + +describe('focused mode', () => { + it('selects the given files and separates the ones with no spec beside them', () => { + const selection = request({ focusPaths: [ ELIGIBLE_FILE, INELIGIBLE_FILE ] }); + expect(selectedFiles(selection)).toEqual([ ELIGIBLE_FILE ]); + expect(selection).toMatchObject({ ineligible: [ INELIGIBLE_FILE ] }); + }); + + it('strips a leading ./ so a shell-completed path matches the diff paths', () => { + expect(selectedFiles(request({ focusPaths: [ `./${ ELIGIBLE_FILE }` ] }))).toEqual([ ELIGIBLE_FILE ]); + }); + + it('is empty when no given file has a spec beside it', () => { + expect(request({ focusPaths: [ INELIGIBLE_FILE ] })).toEqual({ + outcome: 'empty', + reason: 'No given file has a co-located vitest spec — nothing to mutate.', + }); + }); + + it('rejects a path that does not exist', () => { + expect(() => request({ focusPaths: [ 'src/nope.ts' ] })).toThrow('No such file: src/nope.ts'); + }); + + it('takes the given paths even when --changed is also set', () => { + expect(selectedFiles(request({ focusPaths: [ ELIGIBLE_FILE ], diffSelected: true }))).toEqual([ ELIGIBLE_FILE ]); + }); +}); + +// The git-backed modes run against a throwaway repository, so the assertions do not depend on what +// this branch happens to have changed. +describe('git-backed modes', () => { + let repo = ''; + + afterEach(() => { + if (repo) fs.rmSync(repo, { recursive: true, force: true }); + repo = ''; + }); + + // The repo is addressed by path rather than by making it the process's directory: process.chdir() + // throws in the worker threads Stryker runs vitest in, and these specs have to survive that. + function git(...args: Array<string>): void { + execFileSync('git', [ '-c', 'user.email=t@t.t', '-c', 'user.name=t', ...args ], { cwd: repo, stdio: 'ignore' }); + } + + function write(filePath: string, body: string): void { + const target = path.join(repo, filePath); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, body); + } + + function selectIn(overrides: Partial<SelectionRequest>): Selection { + return request(overrides, repo); + } + + // A repo forked from `main`, with one commit on each side of the fork point: + // main: src/base.ts (+spec), then src/landed-later.ts (+spec) after the fork + // feature: src/touched.ts (+spec), src/untested.ts (no spec), src/notes.md (out of scope) + function createForkedRepo(): void { + repo = fs.mkdtempSync(path.join(os.tmpdir(), 'mutation-select-')); + git('init', '-b', BASE_REF); + + write('src/base.ts', 'export const base = 1;\n'); + write('src/base.spec.ts', 'export const spec = 1;\n'); + git('add', '.'); + git('commit', '-m', 'base'); + + git('checkout', '-b', 'feature'); + write('src/touched.ts', 'export const touched = 1;\n'); + write('src/touched.spec.ts', 'export const spec = 1;\n'); + write('src/untested.ts', 'export const untested = 1;\n'); + write('src/notes.md', 'notes\n'); + git('add', '.'); + git('commit', '-m', 'feature'); + + git('checkout', BASE_REF); + write('src/landed-later.ts', 'export const landedLater = 1;\n'); + write('src/landed-later.spec.ts', 'export const spec = 1;\n'); + git('add', '.'); + git('commit', '-m', 'landed later'); + + git('checkout', 'feature'); + } + + it('selects only the eligible files the branch itself touched', () => { + createForkedRepo(); + expect(selectIn({ diffSelected: true })).toEqual({ + outcome: 'selected', + targets: [ { file: 'src/touched.ts', ranges: [ [ 1, 1 ] ] } ], + ineligible: [], + }); + }); + + it('honours an explicit base ref', () => { + createForkedRepo(); + git('branch', 'other-base', BASE_REF); + expect(selectedFiles(selectIn({ diffSelected: true, baseRef: 'other-base' }))).toEqual([ 'src/touched.ts' ]); + }); + + it('picks up an uncommitted edit to an eligible file', () => { + createForkedRepo(); + write('src/base.ts', 'export const base = 2;\n'); + expect(selectedFiles(selectIn({ diffSelected: true }))).toEqual([ 'src/base.ts', 'src/touched.ts' ]); + }); + + // src/base.ts predates the fork point, so only the two lines appended to it are in the diff. + it('narrows a changed file to the lines the diff touched', () => { + createForkedRepo(); + write('src/base.ts', 'export const base = 1;\nexport const extra = 2;\nexport const more = 3;\n'); + expect(selectIn({ diffSelected: true })).toMatchObject({ + targets: [ + { file: 'src/base.ts', ranges: [ [ 2, 3 ] ] }, + { file: 'src/touched.ts', ranges: [ [ 1, 1 ] ] }, + ], + }); + }); + + it('is empty on the base branch itself, naming the ref', () => { + createForkedRepo(); + git('checkout', BASE_REF); + expect(selectIn({ diffSelected: true })).toEqual({ + outcome: 'empty', + reason: `No source file in scope changed vs ${ BASE_REF } — nothing to mutate.`, + }); + }); + + it('is empty when the changed files have no specs beside them', () => { + createForkedRepo(); + git('checkout', '-b', 'untested-only', BASE_REF); + write('src/lonely.ts', 'export const lonely = 1;\n'); + git('add', '.'); + git('commit', '-m', 'untested'); + expect(selectIn({ diffSelected: true })).toEqual({ + outcome: 'empty', + reason: `No file changed vs ${ BASE_REF } has a co-located vitest spec — nothing to mutate.`, + }); + }); + + it('drops a file the branch deleted', () => { + createForkedRepo(); + git('rm', 'src/base.ts', 'src/base.spec.ts'); + git('commit', '-m', 'delete base'); + expect(selectedFiles(selectIn({ diffSelected: true }))).toEqual([ 'src/touched.ts' ]); + }); + + // A repo holding nothing but the given files, committed on the base branch. Full mode's empty + // cases need one: the real repo always has both an eligible file and a mutable line in it. + function createRepo(files: Readonly<Record<string, string>>): void { + repo = fs.mkdtempSync(path.join(os.tmpdir(), 'mutation-select-')); + git('init', '-b', BASE_REF); + for (const [ filePath, body ] of Object.entries(files)) write(filePath, body); + git('add', '.'); + git('commit', '-m', 'initial'); + } + + it('selects every eligible in-scope file when invoked bare', () => { + createForkedRepo(); + expect(selectIn({})).toEqual({ + outcome: 'selected', + targets: [ + { file: 'src/base.ts', ranges: [ [ 1, 1 ] ] }, + { file: 'src/touched.ts', ranges: [ [ 1, 1 ] ] }, + ], + ineligible: [], + }); + }); + + it('is empty when no file in the repo has a spec beside it', () => { + createRepo({ 'src/untested.ts': 'export const untested = 1;\n' }); + expect(selectIn({})).toEqual({ + outcome: 'empty', + reason: 'No source file in scope has a co-located vitest spec — nothing to mutate.', + }); + }); + + // Eligible and still nothing to mutate — the two empty reasons are different findings, so the one + // that comes back has to be the one that applies. + it('is empty when every eligible file is nothing but a render body', () => { + createRepo({ 'src/Card.tsx': RENDER_BODY_ONLY_COMPONENT, 'src/Card.spec.tsx': 'export const spec = 1;\n' }); + expect(selectIn({})).toEqual({ outcome: 'empty', reason: NOTHING_OUTSIDE_RENDER_BODIES }); + }); + + it('is empty when every given file is nothing but a render body', () => { + createRepo({ 'src/Card.tsx': RENDER_BODY_ONLY_COMPONENT, 'src/Card.spec.tsx': 'export const spec = 1;\n' }); + expect(selectIn({ focusPaths: [ 'src/Card.tsx' ] })).toEqual({ outcome: 'empty', reason: NOTHING_OUTSIDE_RENDER_BODIES }); + }); + + // The change is real, but every line it touched is inside the render body, so the file is dropped + // and the run has nothing left to do. + it('is empty when the diff only touched a jsx render body', () => { + createForkedRepo(); + git('checkout', BASE_REF); + write('src/Card.tsx', CARD_COMPONENT); + write('src/Card.spec.tsx', 'export const spec = 1;\n'); + git('add', '.'); + git('commit', '-m', 'card'); + git('checkout', '-b', 'card-tweak'); + write('src/Card.tsx', CARD_COMPONENT.replace('yes', 'nope')); + + expect(selectIn({ diffSelected: true })).toEqual({ + outcome: 'empty', + reason: `No line changed vs ${ BASE_REF } falls outside a jsx render body — nothing to mutate.`, + }); + }); +}); diff --git a/tools/mutation-testing/select/files.ts b/tools/mutation-testing/select/files.ts new file mode 100644 index 00000000000..144b3349c4f --- /dev/null +++ b/tools/mutation-testing/select/files.ts @@ -0,0 +1,113 @@ +import fs from 'fs'; +import path from 'path'; + +import type { LineRange } from '../../code-complexity/select/diff'; +import { getAllSourceFiles, getChangedFiles, getChangedLineRanges, resolveBaseCommit } from '../../code-complexity/select/diff'; +import { hasCoLocatedSpec } from '../../code-complexity/select/eligibility'; +import { isInScope } from '../../code-complexity/select/scope'; +import { computeMutationRanges } from './ranges'; + +// Which files a run mutates, and which of their lines. Three modes mirror the complexity gate's: the +// full eligible set when invoked bare, the given paths when invoked with some, and the diff against a +// base ref under --changed. Eligibility is the same rule in all three — a file is mutated only when a +// vitest spec sits beside it, so an untested file yields no findings instead of a run of unkillable +// mutants. ./ranges.ts then narrows each file to the lines worth mutating. + +export interface SelectionRequest { + readonly focusPaths: ReadonlyArray<string>; + readonly diffSelected: boolean; + readonly baseRef: string; +} + +export interface MutateTarget { + readonly file: string; + readonly ranges: ReadonlyArray<LineRange>; +} + +export type Selection = + // `ineligible` carries only files the user named explicitly: in the other two modes the untested + // files are the bulk of the repo, and listing them would bury the report. + { readonly outcome: 'selected'; readonly targets: ReadonlyArray<MutateTarget>; readonly ineligible: ReadonlyArray<string> } | + // Nothing to mutate. `reason` is the one line the CLI prints before exiting 0 without ever + // starting Stryker. + { readonly outcome: 'empty'; readonly reason: string }; + +const NOTHING_OUTSIDE_RENDER_BODIES = 'Every eligible file has all of its logic inside a jsx render body — nothing to mutate.'; + +function normalizePath(filePath: string): string { + return filePath.replace(/\\/g, '/').replace(/^\.\//, ''); +} + +// Every path a selection reports stays relative to the repo, because that is the form Stryker's +// --mutate patterns take; only the filesystem lookups are resolved against `cwd`. +function isEligible(cwd: string, file: string): boolean { + return hasCoLocatedSpec(path.resolve(cwd, file)); +} + +// A file with no mutable line left is dropped from the selection rather than carried into it with an +// empty range list, so the file count the run reports is the count Stryker was actually given. +function toTarget(cwd: string, file: string, changedRanges: ReadonlyArray<LineRange> | undefined): MutateTarget | undefined { + const ranges = computeMutationRanges(fs.readFileSync(path.resolve(cwd, file), 'utf8'), file, changedRanges); + return ranges.length === 0 ? undefined : { file, ranges }; +} + +function isTarget(target: MutateTarget | undefined): target is MutateTarget { + return target !== undefined; +} + +function toWholeFileTargets(cwd: string, files: ReadonlyArray<string>): Array<MutateTarget> { + return files.map((file) => toTarget(cwd, file, undefined)).filter(isTarget); +} + +// Full mode: every in-scope file in the repo that has a spec beside it. +function selectAll(cwd: string): Selection { + const eligible = getAllSourceFiles(cwd).filter((file) => isEligible(cwd, file)); + if (eligible.length === 0) return { outcome: 'empty', reason: 'No source file in scope has a co-located vitest spec — nothing to mutate.' }; + + const targets = toWholeFileTargets(cwd, eligible); + if (targets.length === 0) return { outcome: 'empty', reason: NOTHING_OUTSIDE_RENDER_BODIES }; + return { outcome: 'selected', targets, ineligible: [] }; +} + +// Focused mode: the given paths, no diff-scoping. A path that does not exist is a typo worth failing +// on; one that exists but has no spec is reported as ineligible rather than silently dropped, so +// "no findings" never has to mean "your file was never mutated". +function selectFocused(cwd: string, focusPaths: ReadonlyArray<string>): Selection { + const paths = focusPaths.map(normalizePath); + const missing = paths.filter((filePath) => !fs.existsSync(path.resolve(cwd, filePath))); + if (missing.length > 0) throw new Error(`No such file: ${ missing.join(', ') }`); + + const eligible = paths.filter((filePath) => isEligible(cwd, filePath)); + const ineligible = paths.filter((filePath) => !isEligible(cwd, filePath)); + if (eligible.length === 0) return { outcome: 'empty', reason: 'No given file has a co-located vitest spec — nothing to mutate.' }; + + const targets = toWholeFileTargets(cwd, eligible); + if (targets.length === 0) return { outcome: 'empty', reason: NOTHING_OUTSIDE_RENDER_BODIES }; + return { outcome: 'selected', targets, ineligible }; +} + +// Diff mode: the in-scope files the branch touched, resolved through the merge-base so the selection +// carries the branch's own commits plus uncommitted edits and never base-branch churn. Deleted files +// are dropped — they are in the diff, but there is nothing left to mutate. Each file is narrowed to +// the lines the diff added or modified, so a one-line fix does not pay for the whole file. +function selectChanged(cwd: string, baseRef: string): Selection { + const baseCommit = resolveBaseCommit(baseRef, cwd); + const changed = getChangedFiles(baseCommit, cwd).filter(isInScope).filter((file) => fs.existsSync(path.resolve(cwd, file))); + if (changed.length === 0) return { outcome: 'empty', reason: `No source file in scope changed vs ${ baseRef } — nothing to mutate.` }; + + const eligible = changed.filter((file) => isEligible(cwd, file)); + if (eligible.length === 0) return { outcome: 'empty', reason: `No file changed vs ${ baseRef } has a co-located vitest spec — nothing to mutate.` }; + + const targets = eligible.map((file) => toTarget(cwd, file, getChangedLineRanges(baseCommit, file, cwd))).filter(isTarget); + if (targets.length === 0) return { outcome: 'empty', reason: `No line changed vs ${ baseRef } falls outside a jsx render body — nothing to mutate.` }; + return { outcome: 'selected', targets, ineligible: [] }; +} + +// `cwd` is the repository to resolve the selection in, passed rather than read off the process: +// ./files.spec.ts points it at a throwaway repo, and process.chdir() throws in the worker threads +// Stryker runs vitest in — which this tool's own specs have to survive. +export function selectFiles(request: SelectionRequest, cwd: string): Selection { + if (request.focusPaths.length > 0) return selectFocused(cwd, request.focusPaths); + if (request.diffSelected) return selectChanged(cwd, request.baseRef); + return selectAll(cwd); +} diff --git a/tools/mutation-testing/select/ranges.spec.ts b/tools/mutation-testing/select/ranges.spec.ts new file mode 100644 index 00000000000..018bd097f76 --- /dev/null +++ b/tools/mutation-testing/select/ranges.spec.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from 'vitest'; + +import { computeMutationRanges, intersectRanges, mutableLineRanges } from './ranges'; + +// A component whose render body sits at lines 5, 9-11, with a `behavior` handler nested inside it at +// lines 6-8 and module scope either side of it. +const COMPONENT_WITH_HANDLER = `import React from 'react'; + +const LIMIT = 10; + +const Row = ({ count }: { count: number }) => { + const handleClick = React.useCallback(() => { + if (count > LIMIT) report(count); + }, [ count ]); + + return <div onClick={ handleClick }>{ count }</div>; +}; + +export default Row; +`; + +// A hook — `behavior` throughout — whose only JSX is inside a nested `.map()` callback at lines 6-8. +const HOOK_RENDERING_ROWS = `import { useMemo } from 'react'; + +export function useRows(items: Array<number>) { + const positive = items.filter((item) => item > 0); + return useMemo(() => { + return positive.map((item) => ( + <span key={ item }>{ item }</span> + )); + }, [ positive ]); +} +`; + +const PLAIN_MODULE = `export const LIMIT = 10; +export const isBig = (value: number): boolean => value > LIMIT; +`; + +const RENDER_BODY_ONLY = `const Empty = ({ show }: { show: boolean }) => ( + <div>{ show ? 'yes' : 'no' }</div> +); +`; + +// Two functions opening and closing on line 3, so neither encloses the other by span. The outer one +// is the render body; the callback nested in it is behavior. +const JSX_TIED_WITH_NESTED_BEHAVIOR = `const CELLS = [ 1, 2 ]; + +const Cells = () => <div>{ CELLS.map(function (value) { return value * 2; }) }</div>; +`; + +// The same tie the other way round: the outer function renders nothing itself, and the callback +// nested in it on line 3 is the render body. +const BEHAVIOR_TIED_WITH_NESTED_JSX = `const CELLS = [ 1, 2 ]; + +const renderCells = () => CELLS.map((value) => <b>{ value }</b>); +`; + +// Two near misses, where a callback shares one of its bounding lines with the render body around it +// but not the other. Sharing one is not a tie: the callback is nested, so its own line stays +// behavior and `sum + item` keeps its mutants. +const CALLBACK_CLOSING_WITH_A_RENDER_BODY = `const Total = ({ items }: { items: Array<number> }) => ( + <output>{ items.reduce((sum, item) => sum + item, 0) }</output>); +`; + +const CALLBACK_OPENING_WITH_A_RENDER_BODY = `const Total = ({ items }: { items: Array<number> }) => <output>{ items.reduce((sum, item) => sum + item, 0) + }</output>; +`; + +describe('mutableLineRanges', () => { + it('covers the whole file when nothing in it renders', () => { + expect(mutableLineRanges(PLAIN_MODULE, 'src/util.ts')).toEqual([ [ 1, 2 ] ]); + }); + + it('drops a render body but keeps a behavior function nested inside it', () => { + expect(mutableLineRanges(COMPONENT_WITH_HANDLER, 'src/Row.tsx')).toEqual([ [ 1, 4 ], [ 6, 8 ], [ 12, 13 ] ]); + }); + + it('drops a render callback nested inside a behavior function', () => { + expect(mutableLineRanges(HOOK_RENDERING_ROWS, 'src/useRows.tsx')).toEqual([ [ 1, 5 ], [ 9, 10 ] ]); + }); + + it('comes out empty when every line is part of a render body', () => { + expect(mutableLineRanges(RENDER_BODY_ONLY, 'src/Empty.tsx')).toEqual([]); + }); + + // Both tie cases drop line 3: whichever function is the render body, a mutant inside it is + // unkillable, so the tie goes to jsx rather than to the nesting. + it('drops a line a render body shares with a behavior function nested in it', () => { + expect(mutableLineRanges(JSX_TIED_WITH_NESTED_BEHAVIOR, 'src/Cells.tsx')).toEqual([ [ 1, 2 ] ]); + }); + + it('drops a line a behavior function shares with a render callback nested in it', () => { + expect(mutableLineRanges(BEHAVIOR_TIED_WITH_NESTED_JSX, 'src/renderCells.tsx')).toEqual([ [ 1, 2 ] ]); + }); + + it('keeps a line a nested callback shares with the last line of the render body', () => { + expect(mutableLineRanges(CALLBACK_CLOSING_WITH_A_RENDER_BODY, 'src/Total.tsx')).toEqual([ [ 2, 2 ] ]); + }); + + it('keeps a line a nested callback shares with the first line of the render body', () => { + expect(mutableLineRanges(CALLBACK_OPENING_WITH_A_RENDER_BODY, 'src/Total.tsx')).toEqual([ [ 1, 1 ] ]); + }); +}); + +describe('intersectRanges', () => { + it('keeps only the overlap of each pair', () => { + expect(intersectRanges([ [ 1, 10 ], [ 20, 30 ] ], [ [ 5, 25 ] ])).toEqual([ [ 5, 10 ], [ 20, 25 ] ]); + }); + + it('is empty when nothing overlaps', () => { + expect(intersectRanges([ [ 1, 4 ] ], [ [ 5, 9 ] ])).toEqual([]); + }); +}); + +describe('computeMutationRanges', () => { + it('mutates the whole file, minus render bodies, when no diff scopes it', () => { + expect(computeMutationRanges(COMPONENT_WITH_HANDLER, 'src/Row.tsx', undefined)) + .toEqual([ [ 1, 4 ], [ 6, 8 ], [ 12, 13 ] ]); + }); + + it('keeps a changed line in the handler and drops one inside the render body', () => { + expect(computeMutationRanges(COMPONENT_WITH_HANDLER, 'src/Row.tsx', [ [ 7, 7 ], [ 10, 10 ] ])) + .toEqual([ [ 7, 7 ] ]); + }); + + it('comes out empty when the diff only touched a render body', () => { + expect(computeMutationRanges(COMPONENT_WITH_HANDLER, 'src/Row.tsx', [ [ 9, 11 ] ])).toEqual([]); + }); +}); diff --git a/tools/mutation-testing/select/ranges.ts b/tools/mutation-testing/select/ranges.ts new file mode 100644 index 00000000000..0e0e459a8d9 --- /dev/null +++ b/tools/mutation-testing/select/ranges.ts @@ -0,0 +1,93 @@ +import type { FunctionComplexity } from '../../code-complexity/measure/complexity'; +import { computeFunctionComplexities } from '../../code-complexity/measure/complexity'; +import type { LineRange } from '../../code-complexity/select/diff'; + +// Which lines of a file Stryker may create mutants on. Two restrictions compose: a `jsx` function +// body is never mutated, and under --changed only the lines the diff touched are. +// +// Stryker's `mutate` option takes ranges but has no exclude form, so an exclusion is expressed as +// the complement — the spans of the file no `jsx` body covers. + +function countLines(source: string): number { + // A trailing newline ends the last line rather than starting another one, so a whole-file range + // never reaches past the end of the file. + return source.replace(/\n+$/, '').split('\n').length; +} + +function coversTheSameLines(fn: FunctionComplexity, other: FunctionComplexity): boolean { + return fn.startLine === other.startLine && fn.endLine === other.endLine; +} + +// A line belongs to the innermost function containing it: a `useCallback` body inside a component is +// `behavior` even though the component around it renders JSX, and a `.map(() => <Row/>)` callback is +// `jsx` even though the `useMemo` around it is `behavior`. +// +// computeFunctionComplexities reports a nested function before the one enclosing it, so the first +// function containing the line is the innermost one and no nesting test is needed. The one case the +// order does not settle is a tie — two functions covering exactly the same lines — where `jsx` +// wins, because an unkillable survivor costs more than a mutant that was never generated. +function innermostFunctionAt(functions: ReadonlyArray<FunctionComplexity>, line: number): FunctionComplexity | undefined { + let innermost: FunctionComplexity | undefined; + + for (const fn of functions) { + if (fn.startLine > line || fn.endLine < line) continue; + if (innermost === undefined || (coversTheSameLines(fn, innermost) && fn.containsJsx)) innermost = fn; + } + + return innermost; +} + +// Consecutive lines collapse, so a file with no JSX in it comes out as one span rather than one +// range per line. +function toRanges(lines: ReadonlyArray<number>): Array<LineRange> { + const ranges: Array<LineRange> = []; + + for (const line of lines) { + const last = ranges[ranges.length - 1]; + if (last !== undefined && last[1] === line - 1) last[1] = line; + else ranges.push([ line, line ]); + } + + return ranges; +} + +// Every line whose innermost enclosing function is not a `jsx` body — module scope included, since a +// line belonging to no function belongs to no render body either. +export function mutableLineRanges(source: string, fileName: string): Array<LineRange> { + const functions = computeFunctionComplexities(source, fileName); + const lastLine = countLines(source); + const lines: Array<number> = []; + + for (let line = 1; line <= lastLine; line++) { + const innermost = innermostFunctionAt(functions, line); + if (innermost === undefined || !innermost.containsJsx) lines.push(line); + } + + return toRanges(lines); +} + +export function intersectRanges(first: ReadonlyArray<LineRange>, second: ReadonlyArray<LineRange>): Array<LineRange> { + const ranges: Array<LineRange> = []; + + for (const [ firstStart, firstEnd ] of first) { + for (const [ secondStart, secondEnd ] of second) { + const start = Math.max(firstStart, secondStart); + const end = Math.min(firstEnd, secondEnd); + if (start <= end) ranges.push([ start, end ]); + } + } + + return ranges; +} + +// The ranges one file contributes to a run. `changedRanges` is undefined outside --changed, where the +// whole file (minus its `jsx` bodies) is mutated. An empty result means the file has nothing left to +// mutate and is dropped from the selection. +export function computeMutationRanges( + source: string, + fileName: string, + changedRanges: ReadonlyArray<LineRange> | undefined, +): Array<LineRange> { + const mutable = mutableLineRanges(source, fileName); + return changedRanges === undefined ? mutable : intersectRanges(mutable, changedRanges); +} diff --git a/tools/mutation-testing/stryker.config.json b/tools/mutation-testing/stryker.config.json new file mode 100644 index 00000000000..3275ac8b835 --- /dev/null +++ b/tools/mutation-testing/stryker.config.json @@ -0,0 +1,69 @@ +{ + "$schema": "../../node_modules/@stryker-mutator/core/schema/stryker-schema.json", + "packageManager": "pnpm", + "testRunner": "vitest", + "vitest": { + "configFile": "tools/mutation-testing/vitest.config.ts" + }, + "plugins": [ + "@stryker-mutator/vitest-runner" + ], + "reporters": [ "json", "html", "stream" ], + "jsonReporter": { + "fileName": "tools/mutation-testing/reports/mutation.json" + }, + "htmlReporter": { + "fileName": "tools/mutation-testing/reports/mutation.html" + }, + "tempDirName": "tools/mutation-testing/.stryker-tmp", + "ignoreStatic": true, + "timeoutMS": 60000, + "dryRunTimeoutMinutes": 15, + "mutator": { + "excludedMutations": [ + "ArrayDeclaration", + "ArrowFunction", + "AssignmentOperator", + "BlockStatement", + "CallExpression", + "MethodExpression", + "ObjectLiteral", + "OptionalChaining", + "Regex", + "StringLiteral", + "UnaryOperator", + "UpdateOperator" + ] + }, + "ignorePatterns": [ + "**", + "!/src/**", + "!/tools/**", + "!/deploy/scripts/make_envs_script.sh", + "!/deploy/tools/assets-downloader/**", + "!/deploy/tools/envs-validator/**", + "!/.agents/**", + "!/docs/BUILD-TIME_ENVS.md", + "!/docs/DEPRECATED_ENVS.md", + "!/docs/ENVS.md", + "!/docs/PULL_REQUEST_TEMPLATE.md", + "!/docs/RELEASING.md", + "!/vitest/**", + "!/decs.d.ts", + "!/global.d.ts", + "!/next-types.d.ts", + "!/package.json", + "!/pnpm-workspace.yaml", + "!/reset.d.ts", + "!/tsconfig.json", + "!/vitest.config.ts", + "**/node_modules", + "**/node_modules_linux", + "**/dist", + "tools/mutation-testing/.build.*", + "tools/mutation-testing/.stryker-tmp", + "tools/mutation-testing/reports", + "tools/mutation-testing/.lock", + "**/*.pw.tsx" + ] +} diff --git a/tools/mutation-testing/stryker/invoke.spec.ts b/tools/mutation-testing/stryker/invoke.spec.ts new file mode 100644 index 00000000000..0afe23417d3 --- /dev/null +++ b/tools/mutation-testing/stryker/invoke.spec.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest'; + +import { formatMutateTargets } from './invoke'; + +describe('formatMutateTargets', () => { + it('emits one entry per range, so Stryker unions them per file', () => { + expect(formatMutateTargets([ { file: 'src/util.ts', ranges: [ [ 1, 4 ], [ 9, 9 ] ] } ])) + .toEqual([ 'src/util.ts:1-4', 'src/util.ts:9-9' ]); + }); + + // Stryker refuses a mutation range on a pattern it reads as a glob, which a Next.js route file is. + it('escapes glob metacharacters in the path', () => { + expect(formatMutateTargets([ { file: 'src/pages/tx/[hash].tsx', ranges: [ [ 2, 3 ] ] } ])) + .toEqual([ 'src/pages/tx/\\[hash\\].tsx:2-3' ]); + }); + + // A backslash left as-is would be read as escaping the next character instead of as itself. + it('escapes a backslash in the path', () => { + expect(formatMutateTargets([ { file: 'src/a\\b.ts', ranges: [ [ 1, 1 ] ] } ])) + .toEqual([ 'src/a\\\\b.ts:1-1' ]); + }); +}); diff --git a/tools/mutation-testing/stryker/invoke.ts b/tools/mutation-testing/stryker/invoke.ts new file mode 100644 index 00000000000..91476be760a --- /dev/null +++ b/tools/mutation-testing/stryker/invoke.ts @@ -0,0 +1,134 @@ +import { spawn } from 'child_process'; +import fs from 'fs'; +import path from 'path'; + +import { HTML_REPORT_FILE, JSON_REPORT_FILE, SANDBOX_DIR, STOP_GRACE_MS, STREAM_REPORT_FILE, STRYKER_BIN, STRYKER_CONFIG_FILE } from '../config'; +import type { MutateTarget } from '../select/files'; + +// Runs Stryker over a selection, under a wall-clock budget. Everything that does not vary per run +// lives in the committed stryker.config.json, so the command line carries only what to mutate. + +// Stryker rejects a mutation range on a pattern minimatch reads as a glob, and Next.js route files +// (`src/pages/tx/[hash].tsx`) are exactly that. Escaping the metacharacters makes the pattern +// literal — which is also the only form that matches such a path at all. The backslash is itself +// minimatch's escape character, so a path containing one has to be escaped first, not left to be +// read as escaping whatever follows it. +const GLOB_METACHARACTERS = /([\\[\]{}()*?!+@])/g; + +const STREAMING_REPORTER_PLUGIN = path.join(__dirname, 'streaming-reporter.mjs'); + +// A run stopped at its budget has no complete json report, only the stream the reporter plugin +// appended to. `truncated` is what tells the report which of the two to read, and says so in print. +export interface RunOutcome { + readonly truncated: boolean; +} + +// One `mutate` entry per range: Stryker unions the ranges it is given for the same file, and a file +// named with no range at all would be mutated in full. +export function formatMutateTargets(targets: ReadonlyArray<MutateTarget>): Array<string> { + return targets.flatMap(({ file, ranges }) => { + const pattern = file.replace(GLOB_METACHARACTERS, '\\$1'); + return ranges.map(([ start, end ]) => `${ pattern }:${ start }-${ end }`); + }); +} + +// A run that dies leaves the previous run's output behind, and reading that would present stale +// results as fresh ones. Clearing it first makes a failed run visibly result-less instead. The +// sandbox goes too: Stryker removes it only on an exit it controls, so a stopped run leaves a full +// copy of the repo on disk. +function clearPreviousRun(): void { + fs.mkdirSync(path.dirname(JSON_REPORT_FILE), { recursive: true }); + fs.rmSync(JSON_REPORT_FILE, { force: true }); + fs.rmSync(HTML_REPORT_FILE, { force: true }); + fs.rmSync(STREAM_REPORT_FILE, { force: true }); + fs.rmSync(SANDBOX_DIR, { recursive: true, force: true }); +} + +type StopSignal = 'SIGTERM' | 'SIGKILL'; + +// Stryker forks a worker per concurrent test run and, on a signal, exits without killing them — so +// signalling the process alone orphans the vitest workers. The run is spawned detached, which makes +// it a process-group leader, and a negative pid signals the whole group. +function signalGroup(pid: number, signal: StopSignal): void { + try { + process.kill(-pid, signal); + } catch { /* ESRCH: nothing left in the group, which is the outcome being asked for. */ } +} + +const FORWARDED_SIGNALS = [ 'SIGINT', 'SIGTERM' ] as const; + +export function runStryker(targets: ReadonlyArray<MutateTarget>, budgetMs: number): Promise<RunOutcome> { + clearPreviousRun(); + + // The config file is a positional argument to `stryker run`, not a flag. --mutate takes one + // comma-separated list; repeating the flag overwrites it rather than appending. The reporter plugin + // sits beside this module in the per-run compile directory, which only this process knows. + const args = [ + 'run', STRYKER_CONFIG_FILE, + '--mutate', formatMutateTargets(targets).join(','), + '--appendPlugins', STREAMING_REPORTER_PLUGIN, + ]; + const child = spawn(STRYKER_BIN, args, { stdio: 'inherit', detached: true }); + + return new Promise<RunOutcome>((resolve, reject) => { + const pid = child.pid; + let budgetExpired = false; + let interrupted = false; + let hardStop: ReturnType<typeof setTimeout> | undefined; + + function stop(): void { + if (pid === undefined) return; + signalGroup(pid, 'SIGTERM'); + hardStop = setTimeout(() => signalGroup(pid, 'SIGKILL'), STOP_GRACE_MS); + } + + const budget = setTimeout(() => { + budgetExpired = true; + stop(); + }, budgetMs); + + // Detaching puts the run outside the terminal's foreground group, so a Ctrl-C reaches this + // process only. Without forwarding it, quitting the CLI would leave the whole run behind. + function interrupt(): void { + interrupted = true; + stop(); + } + for (const signal of FORWARDED_SIGNALS) process.on(signal, interrupt); + + function cleanUp(): void { + clearTimeout(budget); + if (hardStop !== undefined) clearTimeout(hardStop); + for (const signal of FORWARDED_SIGNALS) process.off(signal, interrupt); + // The group's leader has exited; anything still in the group is a worker that outlived it. + // This process is not in that group, so the sweep cannot reach it. + if (pid !== undefined) signalGroup(pid, 'SIGKILL'); + // Stryker removes the sandbox itself, but only on an exit it controls. + fs.rmSync(SANDBOX_DIR, { recursive: true, force: true }); + } + + child.on('error', (error) => { + cleanUp(); + reject(error); + }); + + child.on('exit', (code) => { + cleanUp(); + if (interrupted) { + reject(new Error('Run interrupted.')); + return; + } + // Stryker keeps working for a moment after writing its reports — disposing workers, clearing + // the sandbox — so a budget expiring in that window did not cost any results. The json report + // is the honest test: Stryker writes it only once a whole run has finished. + if (budgetExpired) { + resolve({ truncated: !fs.existsSync(JSON_REPORT_FILE) }); + return; + } + if (code === 0) { + resolve({ truncated: false }); + return; + } + reject(new Error('Stryker did not finish — see its output above for why.')); + }); + }); +} diff --git a/tools/mutation-testing/stryker/lock.spec.ts b/tools/mutation-testing/stryker/lock.spec.ts new file mode 100644 index 00000000000..8b736fbf728 --- /dev/null +++ b/tools/mutation-testing/stryker/lock.spec.ts @@ -0,0 +1,168 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { LockDeps, RunLock } from './lock'; +import { acquireLock, formatHeldMessage, formatStaleMessage, parseLock, releaseLock } from './lock'; + +const NOW = new Date('2026-10-15T10:00:00.000Z'); +const OTHER_PID = 424242; +const OTHER_RUN: RunLock = { pid: OTHER_PID, startedAt: '2026-10-15T09:00:00.000Z', selection: 'src/b.ts' }; + +let tempDir: string; +let lockFile: string; +let marker: string; + +function deps(alivePids: ReadonlyArray<number>): LockDeps { + return { lockFile, isProcessAlive: (pid) => alivePids.includes(pid), now: () => NOW }; +} + +function writeLock(lock: RunLock): void { + fs.writeFileSync(lockFile, JSON.stringify(lock)); +} + +function readLockFile(): RunLock { + return JSON.parse(fs.readFileSync(lockFile, 'utf8')) as RunLock; +} + +beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mutation-lock-')); + lockFile = path.join(tempDir, '.lock'); + marker = `${ lockFile }.acquiring`; +}); + +afterEach(() => { + vi.restoreAllMocks(); + fs.rmSync(tempDir, { recursive: true, force: true }); +}); + +describe('acquireLock', () => { + it('creates the lock naming this process and the selection, and nothing else', () => { + expect(acquireLock('src/a.ts', deps([]))).toEqual({ outcome: 'acquired', staleLockRemoved: undefined }); + expect(readLockFile()).toEqual({ pid: process.pid, startedAt: NOW.toISOString(), selection: 'src/a.ts' }); + expect(fs.readdirSync(tempDir)).toEqual([ '.lock' ]); + }); + + // A reader must never see the record half-written, so it is moved into place complete. + it('writes the record in one step', () => { + const rename = vi.spyOn(fs, 'renameSync'); + acquireLock('src/a.ts', deps([])); + expect(rename).toHaveBeenCalledWith(expect.stringContaining(process.pid.toString()), lockFile); + }); + + // Two runs reclaiming the same dead lock must not interleave: the one that gets there second would + // otherwise replace the record the first has just put in its place. + it('refuses while another run is between reading the lock and writing its own', () => { + writeLock(OTHER_RUN); + fs.mkdirSync(marker); + + expect(() => acquireLock('src/a.ts', deps([]))).toThrow(/is taking .* this instant/); + expect(readLockFile()).toEqual(OTHER_RUN); + expect(fs.readdirSync(tempDir).sort()).toEqual([ '.lock', '.lock.acquiring' ]); + }); + + it('holds other runs off from the read until the record is written', () => { + writeLock(OTHER_RUN); + const isProcessAlive = vi.fn((): boolean => { + expect(fs.existsSync(marker)).toBe(true); + return false; + }); + + expect(acquireLock('src/a.ts', { ...deps([]), isProcessAlive })).toEqual({ outcome: 'acquired', staleLockRemoved: OTHER_RUN }); + expect(isProcessAlive).toHaveBeenCalledWith(OTHER_PID); + expect(fs.existsSync(marker)).toBe(false); + }); + + it('lets other runs in again after refusing', () => { + writeLock(OTHER_RUN); + acquireLock('src/a.ts', deps([ OTHER_PID ])); + expect(fs.readdirSync(tempDir)).toEqual([ '.lock' ]); + }); + + it('refuses while a live run holds the lock, and leaves its record intact', () => { + writeLock(OTHER_RUN); + + expect(acquireLock('src/a.ts', deps([ OTHER_PID ]))).toEqual({ outcome: 'held', holder: OTHER_RUN }); + expect(readLockFile()).toEqual(OTHER_RUN); + }); + + it('replaces a lock whose pid is dead, and reports what it removed', () => { + writeLock(OTHER_RUN); + + expect(acquireLock('src/a.ts', deps([]))).toEqual({ outcome: 'acquired', staleLockRemoved: OTHER_RUN }); + expect(readLockFile().pid).toBe(process.pid); + }); + + it('replaces a lock that does not parse', () => { + fs.writeFileSync(lockFile, '{"pid":'); + + expect(acquireLock('src/a.ts', deps([ OTHER_PID ]))).toEqual({ outcome: 'acquired', staleLockRemoved: undefined }); + expect(readLockFile().pid).toBe(process.pid); + }); + + it('propagates a failure to write the record', () => { + const missingDir = { ...deps([]), lockFile: path.join(tempDir, 'missing', '.lock') }; + expect(() => acquireLock('src/a.ts', missingDir)).toThrow(/ENOENT/); + }); + + it('leaves nothing behind when moving the record into place fails', () => { + vi.spyOn(fs, 'renameSync').mockImplementation(() => { + throw Object.assign(new Error('EACCES'), { code: 'EACCES' }); + }); + + expect(() => acquireLock('src/a.ts', deps([]))).toThrow(/EACCES/); + expect(fs.readdirSync(tempDir)).toEqual([]); + }); +}); + +describe('releaseLock', () => { + it('removes the lock this process holds', () => { + acquireLock('src/a.ts', deps([])); + releaseLock(deps([])); + expect(fs.existsSync(lockFile)).toBe(false); + }); + + it('leaves a lock held by another process alone', () => { + writeLock(OTHER_RUN); + releaseLock(deps([ OTHER_PID ])); + expect(readLockFile()).toEqual(OTHER_RUN); + }); + + it('is a no-op without a lock', () => { + expect(() => releaseLock(deps([]))).not.toThrow(); + }); +}); + +describe('parseLock', () => { + it('accepts a complete record', () => { + expect(parseLock('{"pid":1,"startedAt":"x","selection":"y"}')).toEqual({ pid: 1, startedAt: 'x', selection: 'y' }); + }); + + it('rejects anything that is not an object with the three typed fields', () => { + expect(parseLock('null')).toBeUndefined(); + expect(parseLock('42')).toBeUndefined(); + expect(parseLock('{"startedAt":"x","selection":"y"}')).toBeUndefined(); + expect(parseLock('{"pid":1,"selection":"y"}')).toBeUndefined(); + expect(parseLock('{"pid":1,"startedAt":"x"}')).toBeUndefined(); + expect(parseLock('{"pid":"1","startedAt":"x","selection":"y"}')).toBeUndefined(); + expect(parseLock('{"pid":1,"startedAt":2,"selection":"y"}')).toBeUndefined(); + expect(parseLock('{"pid":1,"startedAt":"x","selection":3}')).toBeUndefined(); + }); +}); + +describe('messages', () => { + const lock: RunLock = { pid: 7, startedAt: '2026-10-15T09:00:00.000Z', selection: '--changed vs origin/main' }; + + it('names the holder, its start time and selection', () => { + expect(formatHeldMessage(lock)).toBe( + 'Another test:mutation-testing run holds this checkout: pid 7, started 2026-10-15T09:00:00.000Z, ' + + 'mutating --changed vs origin/main. Wait for it to finish, or run from a separate worktree.', + ); + }); + + it('names what a stale lock belonged to', () => { + expect(formatStaleMessage(lock)).toBe('› removed a stale lock left by pid 7 (started 2026-10-15T09:00:00.000Z, mutating --changed vs origin/main)'); + }); +}); diff --git a/tools/mutation-testing/stryker/lock.ts b/tools/mutation-testing/stryker/lock.ts new file mode 100644 index 00000000000..7fbf0dc68e5 --- /dev/null +++ b/tools/mutation-testing/stryker/lock.ts @@ -0,0 +1,129 @@ +import fs from 'fs'; + +import { LOCK_FILE } from '../config'; + +// One run per checkout. Every run writes to the same report files and the same Stryker sandbox, so a +// second run started while the first is still going wipes the first's output and leaves either run +// reading the other's results. The lock names the holder so the message can say what to wait for. + +export interface RunLock { + readonly pid: number; + readonly startedAt: string; + readonly selection: string; +} + +export interface LockDeps { + readonly lockFile: string; + readonly isProcessAlive: (pid: number) => boolean; + readonly now: () => Date; +} + +export type LockAttempt = + { readonly outcome: 'acquired'; readonly staleLockRemoved: RunLock | undefined } | + { readonly outcome: 'held'; readonly holder: RunLock }; + +function isRunLock(value: unknown): value is RunLock { + const record = value as Partial<RunLock> | null | undefined; + return typeof record?.pid === 'number' && typeof record?.startedAt === 'string' && typeof record?.selection === 'string'; +} + +// A lock that does not parse is treated as stale: it was either half-written by a run that died in +// that instant or edited by hand, and in neither case does a live run depend on it. +export function parseLock(contents: string): RunLock | undefined { + try { + const parsed: unknown = JSON.parse(contents); + return isRunLock(parsed) ? parsed : undefined; + } catch { + return undefined; + } +} + +export function formatHeldMessage(holder: RunLock): string { + return `Another test:mutation-testing run holds this checkout: pid ${ holder.pid }, started ${ holder.startedAt }, ` + + `mutating ${ holder.selection }. Wait for it to finish, or run from a separate worktree.`; +} + +export function formatStaleMessage(stale: RunLock): string { + return `› removed a stale lock left by pid ${ stale.pid } (started ${ stale.startedAt }, mutating ${ stale.selection })`; +} + +function readLock(lockFile: string): RunLock | undefined { + try { + return parseLock(fs.readFileSync(lockFile, 'utf8')); + } catch { + return undefined; + } +} + +function errorCode(error: unknown): unknown { + return (error as { readonly code?: unknown } | null | undefined)?.code; +} + +function removeFile(file: string): void { + try { + fs.unlinkSync(file); + } catch { /* Already gone, which is the state being asked for. */ } +} + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + // EPERM means the pid exists but belongs to another user — alive, just not ours to signal. + return errorCode(error) === 'EPERM'; + } +} + +// The record is written in full to a private file and renamed over the lock, so no reader can ever +// see the lock half-written — an open-then-write would expose an empty file in between. +function writeLock(lockFile: string, lock: RunLock): void { + const draft = `${ lockFile }.${ lock.pid }.draft`; + try { + fs.writeFileSync(draft, JSON.stringify(lock)); + fs.renameSync(draft, lockFile); + } finally { + removeFile(draft); + } +} + +// Reading the lock, judging its holder dead and replacing it are three steps, and a second run doing +// the same three in between would end with two runs each believing it holds the lock. A directory is +// the one thing every platform creates atomically and exclusively, so it serialises the sequence. +function acquireExclusively<T>(lockFile: string, attempt: () => T): T { + const marker = `${ lockFile }.acquiring`; + try { + fs.mkdirSync(marker); + } catch (error) { + if (errorCode(error) !== 'EEXIST') throw error; + throw new Error(`Another test:mutation-testing run is taking ${ lockFile } this instant — start the run again. ` + + `If that keeps failing, remove ${ marker }: it was left by a run killed mid-step.`); + } + try { + return attempt(); + } finally { + fs.rmdirSync(marker); + } +} + +const DEFAULT_DEPS: LockDeps = { lockFile: LOCK_FILE, isProcessAlive: isAlive, now: () => new Date() }; + +// A record whose pid is dead is left over from a run that was killed outright and never reached +// releaseLock; it is replaced rather than refused. +export function acquireLock(selection: string, deps: LockDeps = DEFAULT_DEPS): LockAttempt { + const lock: RunLock = { pid: process.pid, startedAt: deps.now().toISOString(), selection }; + + return acquireExclusively(deps.lockFile, () => { + const holder = readLock(deps.lockFile); + if (holder !== undefined && deps.isProcessAlive(holder.pid)) return { outcome: 'held', holder }; + + writeLock(deps.lockFile, lock); + return { outcome: 'acquired', staleLockRemoved: holder }; + }); +} + +// Only the holder removes its own record: a run that lost the race must not release the winner's. +export function releaseLock(deps: LockDeps = DEFAULT_DEPS): void { + if (readLock(deps.lockFile)?.pid !== process.pid) return; + removeFile(deps.lockFile); +} diff --git a/tools/mutation-testing/stryker/report.spec.ts b/tools/mutation-testing/stryker/report.spec.ts new file mode 100644 index 00000000000..be28e63301b --- /dev/null +++ b/tools/mutation-testing/stryker/report.spec.ts @@ -0,0 +1,207 @@ +import { describe, expect, it } from 'vitest'; + +import type { Mutant, MutantStatus, MutationReport } from './report'; +import { buildFileScores, collectFindings, isFailingRun, parseReport } from './report'; + +const LINE = 10; + +function mutant(status: MutantStatus, mutatorName = 'EqualityOperator', line = LINE): Mutant { + return { + id: `${ status }-${ mutatorName }-${ line }`, + mutatorName, + status, + location: { start: { line, column: 1 }, end: { line, column: 20 } }, + }; +} + +function reportOf(statuses: ReadonlyArray<MutantStatus>): MutationReport { + return { files: { 'src/a.ts': { mutants: statuses.map((status) => mutant(status)) } } }; +} + +describe('buildFileScores', () => { + it('scores a file off the killed share of its scored mutants', () => { + expect(buildFileScores(reportOf([ 'Killed', 'Killed', 'Survived', 'NoCoverage' ]))).toEqual([ { + file: 'src/a.ts', + mutants: 4, + killed: 2, + survived: 1, + noCoverage: 1, + score: 50, + } ]); + }); + + it('counts a timeout as killed, the way Stryker scores it', () => { + expect(buildFileScores(reportOf([ 'Timeout', 'Survived' ]))[0]).toMatchObject({ mutants: 2, killed: 1, survived: 1, score: 50 }); + }); + + it('leaves the excluded mutators and the error statuses out of the score entirely', () => { + expect(buildFileScores(reportOf([ 'Killed', 'Ignored', 'CompileError', 'RuntimeError', 'Pending' ]))[0]) + .toMatchObject({ mutants: 1, killed: 1, survived: 0, noCoverage: 0, score: 100 }); + }); + + it('scores a file with nothing but excluded mutants as null rather than zero', () => { + expect(buildFileScores(reportOf([ 'Ignored' ]))[0]).toMatchObject({ mutants: 0, killed: 0, score: null }); + }); + + it('returns one row per file in the report', () => { + const report = { + files: { + 'src/a.ts': { mutants: [ mutant('Killed') ] }, + 'src/b.ts': { mutants: [ mutant('Survived') ] }, + }, + }; + expect(buildFileScores(report).map((row) => row.file)).toEqual([ 'src/a.ts', 'src/b.ts' ]); + }); + + it('produces no rows when Stryker mutated nothing', () => { + expect(buildFileScores({ files: {} })).toEqual([]); + }); +}); + +describe('collectFindings', () => { + const FIRST_LINE = 12; + const SECOND_LINE = 30; + + it('groups the survivors on one line into a single finding naming every mutator', () => { + const report = { + files: { + 'src/a.ts': { + mutants: [ + mutant('Survived', 'ConditionalExpression', FIRST_LINE), + mutant('Survived', 'LogicalOperator', FIRST_LINE), + mutant('Survived', 'EqualityOperator', SECOND_LINE), + ], + }, + }, + }; + + expect(collectFindings(report).survivors).toEqual([ { + file: 'src/a.ts', + lines: [ + { line: FIRST_LINE, mutators: [ { name: 'ConditionalExpression', count: 1 }, { name: 'LogicalOperator', count: 1 } ] }, + { line: SECOND_LINE, mutators: [ { name: 'EqualityOperator', count: 1 } ] }, + ], + } ]); + }); + + it('counts repeats of one mutator on a line rather than repeating its name', () => { + const report = { + files: { + 'src/a.ts': { + mutants: [ + mutant('Survived', 'EqualityOperator', FIRST_LINE), + mutant('Survived', 'EqualityOperator', FIRST_LINE), + ], + }, + }, + }; + + expect(collectFindings(report).survivors[0].lines).toEqual([ + { line: FIRST_LINE, mutators: [ { name: 'EqualityOperator', count: 2 } ] }, + ]); + }); + + it('keeps mutants nothing covered out of the survivor listing, counting them separately', () => { + const findings = collectFindings(reportOf([ 'Survived', 'NoCoverage', 'NoCoverage' ])); + + expect(findings.survivors[0].lines).toEqual([ { line: LINE, mutators: [ { name: 'EqualityOperator', count: 1 } ] } ]); + expect(findings.noCoverage).toEqual([ { file: 'src/a.ts', mutants: 2 } ]); + }); + + it('splits off the status field, so nothing killed or excluded is reported as a finding', () => { + expect(collectFindings(reportOf([ 'Killed', 'Timeout', 'Ignored', 'CompileError', 'RuntimeError', 'Pending' ]))) + .toEqual({ survivors: [], noCoverage: [] }); + }); + + // Stryker reports the mutants of a file in whatever order it happened to test them, and two runs + // over an unchanged tree must read identically. + it('orders the lines of a file ascending, whatever order Stryker emitted them in', () => { + const report = { + files: { + 'src/a.ts': { + mutants: [ + mutant('Survived', 'EqualityOperator', SECOND_LINE), + mutant('Survived', 'EqualityOperator', FIRST_LINE), + ], + }, + }, + }; + + expect(collectFindings(report).survivors[0].lines.map(({ line }) => line)).toEqual([ FIRST_LINE, SECOND_LINE ]); + }); + + it('orders the mutators of a line by name, whatever order Stryker emitted them in', () => { + const report = { + files: { + 'src/a.ts': { + mutants: [ + mutant('Survived', 'LogicalOperator', FIRST_LINE), + mutant('Survived', 'ConditionalExpression', FIRST_LINE), + ], + }, + }, + }; + + expect(collectFindings(report).survivors[0].lines[0].mutators) + .toEqual([ { name: 'ConditionalExpression', count: 1 }, { name: 'LogicalOperator', count: 1 } ]); + }); + + it('orders files alphabetically, whatever order Stryker emitted them in', () => { + const report = { + files: { + 'src/z.ts': { mutants: [ mutant('Survived'), mutant('NoCoverage') ] }, + 'src/a.ts': { mutants: [ mutant('Survived'), mutant('NoCoverage') ] }, + }, + }; + + expect(collectFindings(report).survivors.map((entry) => entry.file)).toEqual([ 'src/a.ts', 'src/z.ts' ]); + expect(collectFindings(report).noCoverage.map((entry) => entry.file)).toEqual([ 'src/a.ts', 'src/z.ts' ]); + }); + + it('lists a file only under the finding it actually has', () => { + const report = { + files: { + 'src/survivor.ts': { mutants: [ mutant('Survived') ] }, + 'src/uncovered.ts': { mutants: [ mutant('NoCoverage') ] }, + }, + }; + + expect(collectFindings(report).survivors.map((entry) => entry.file)).toEqual([ 'src/survivor.ts' ]); + expect(collectFindings(report).noCoverage.map((entry) => entry.file)).toEqual([ 'src/uncovered.ts' ]); + }); +}); + +describe('isFailingRun', () => { + it('fails a run that left a survivor', () => { + expect(isFailingRun(collectFindings(reportOf([ 'Killed', 'Survived' ])))).toBe(true); + }); + + it('passes a run whose only finding is a mutant no test covered, which the CRAP gate owns', () => { + expect(isFailingRun(collectFindings(reportOf([ 'Killed', 'NoCoverage' ])))).toBe(false); + }); + + it('passes a run that killed everything', () => { + expect(isFailingRun(collectFindings(reportOf([ 'Killed', 'Timeout' ])))).toBe(false); + }); + + it('passes a run that mutated nothing', () => { + expect(isFailingRun(collectFindings({ files: {} }))).toBe(false); + }); +}); + +describe('parseReport', () => { + it('reads the mutants out of the reporter JSON', () => { + const json = [ + '{"files":{"src/a.ts":{"mutants":[{"id":"1","mutatorName":"LogicalOperator",', + '"status":"Survived","location":{"start":{"line":3,"column":1},"end":{"line":3,"column":9}}}]}}}', + ].join(''); + expect(buildFileScores(parseReport(json))).toEqual([ { + file: 'src/a.ts', + mutants: 1, + killed: 0, + survived: 1, + noCoverage: 0, + score: 0, + } ]); + }); +}); diff --git a/tools/mutation-testing/stryker/report.ts b/tools/mutation-testing/stryker/report.ts new file mode 100644 index 00000000000..a177e4d9934 --- /dev/null +++ b/tools/mutation-testing/stryker/report.ts @@ -0,0 +1,157 @@ +import fs from 'fs'; + +import { JSON_REPORT_FILE } from '../config'; + +// Reads Stryker's JSON report — the mutation-testing-elements schema its json reporter writes — and +// reduces it to one row per file. The clear-text reporter is not used: it prints every mutant with +// its full diff, which is unusable at this scale. + +// Stryker's per-mutant verdicts. Only the four that bear on assertion strength are scored; see +// SCORED_STATUSES. +export type MutantStatus = + 'Killed' | 'Survived' | 'NoCoverage' | 'Timeout' | + 'CompileError' | 'RuntimeError' | 'Ignored' | 'Pending'; + +export interface MutantPosition { + readonly line: number; + readonly column: number; +} + +export interface Mutant { + readonly id: string; + readonly mutatorName: string; + readonly status: MutantStatus; + readonly location: { readonly start: MutantPosition; readonly end: MutantPosition }; +} + +export interface MutationReport { + readonly files: Readonly<Record<string, { readonly mutants: ReadonlyArray<Mutant> }>>; +} + +export interface FileScore { + readonly file: string; + readonly mutants: number; // the scored ones only, i.e. killed + survived + noCoverage + readonly killed: number; + readonly survived: number; + readonly noCoverage: number; + readonly score: number | null; // percentage; null when the file has no scored mutants at all +} + +// A timeout means the mutant broke the code badly enough to hang a test, which is a detection — +// Stryker's own score counts it as killed, and so does the KILLED column. +const KILLED_STATUSES: ReadonlyArray<MutantStatus> = [ 'Killed', 'Timeout' ]; + +// Everything else is excluded from the denominator: Ignored is the whole non-logic mutator set the +// config turns off, and the error statuses say the mutant never ran rather than that nothing caught it. +const SCORED_STATUSES: ReadonlyArray<MutantStatus> = [ ...KILLED_STATUSES, 'Survived', 'NoCoverage' ]; + +export function parseReport(json: string): MutationReport { + return JSON.parse(json) as MutationReport; +} + +export function readReport(): MutationReport { + if (!fs.existsSync(JSON_REPORT_FILE)) { + throw new Error(`Stryker wrote no report to ${ JSON_REPORT_FILE } — see its output above for why the run did not finish.`); + } + return parseReport(fs.readFileSync(JSON_REPORT_FILE, 'utf8')); +} + +function countBy(mutants: ReadonlyArray<Mutant>, statuses: ReadonlyArray<MutantStatus>): number { + return mutants.filter((mutant) => statuses.includes(mutant.status)).length; +} + +function scoreFile(file: string, mutants: ReadonlyArray<Mutant>): FileScore { + const killed = countBy(mutants, KILLED_STATUSES); + const scored = countBy(mutants, SCORED_STATUSES); + + return { + file, + mutants: scored, + killed, + survived: countBy(mutants, [ 'Survived' ]), + noCoverage: countBy(mutants, [ 'NoCoverage' ]), + score: scored === 0 ? null : (killed / scored) * 100, + }; +} + +export function buildFileScores(report: MutationReport): Array<FileScore> { + return Object.entries(report.files).map(([ file, { mutants } ]) => scoreFile(file, mutants)); +} + +// The two findings a run produces, kept apart because they are different problems. A survivor is a +// weak assertion: a test ran the line and noticed nothing. A no-coverage mutant is an untested line, +// which is the CRAP gate's question, not this one's — so it is counted, not listed. + +// Survivors are grouped by the line they sit on: several mutators surviving together is one weak +// assertion, not several findings. +export interface LineFinding { + readonly line: number; + // Mutator names, each carrying how many mutants of that kind survived on the line. + readonly mutators: ReadonlyArray<{ readonly name: string; readonly count: number }>; +} + +export interface FileSurvivors { + readonly file: string; + readonly lines: ReadonlyArray<LineFinding>; +} + +export interface FileNoCoverage { + readonly file: string; + readonly mutants: number; +} + +export interface Findings { + readonly survivors: ReadonlyArray<FileSurvivors>; + readonly noCoverage: ReadonlyArray<FileNoCoverage>; +} + +// Sorted by name, through the default sort rather than the shared collator: this tool sits outside +// the src/ tsconfig that owns the collator, and the default sort's code-unit order is +// locale-independent, which is what keeps two runs over an unchanged tree byte-identical. Tallying +// the names in that order leaves the map's insertion order sorted too. +function tally(names: ReadonlyArray<string>): Array<{ name: string; count: number }> { + const counts = new Map<string, number>(); + for (const name of [ ...names ].sort()) counts.set(name, (counts.get(name) ?? 0) + 1); + + return [ ...counts ].map(([ name, count ]) => ({ name, count })); +} + +function groupByLine(mutants: ReadonlyArray<Mutant>): Array<LineFinding> { + const byLine = new Map<number, Array<string>>(); + for (const mutant of mutants) { + const line = mutant.location.start.line; + byLine.set(line, [ ...byLine.get(line) ?? [], mutant.mutatorName ]); + } + + return [ ...byLine ] + .sort(([ a ], [ b ]) => a - b) + .map(([ line, names ]) => ({ line, mutators: tally(names) })); +} + +function withStatus(mutants: ReadonlyArray<Mutant>, status: MutantStatus): Array<Mutant> { + return mutants.filter((mutant) => mutant.status === status); +} + +// What makes a run's findings a failure, and the only finding that does: a mutant nothing caught. A +// no-coverage mutant is an untested line, which the CRAP gate already fails a PR for — failing here +// too would report one gap twice and make this gate's verdict unreadable. A run that tested nothing +// has no findings at all and fails on `testedNothing` in ./results.ts instead. +export function isFailingRun(findings: Findings): boolean { + return findings.survivors.length > 0; +} + +export function collectFindings(report: MutationReport): Findings { + // Alphabetical by file, ascending by line: two runs over an unchanged tree must read identically, + // and the report's own file order is whatever Stryker happened to emit. Sorting the file names up + // front carries that order into both listings; see tally() on why it is the default sort. + const files = Object.keys(report.files).sort().map((file) => ({ file, mutants: report.files[file].mutants })); + + return { + survivors: files + .map(({ file, mutants }) => ({ file, lines: groupByLine(withStatus(mutants, 'Survived')) })) + .filter((entry) => entry.lines.length > 0), + noCoverage: files + .map(({ file, mutants }) => ({ file, mutants: withStatus(mutants, 'NoCoverage').length })) + .filter((entry) => entry.mutants > 0), + }; +} diff --git a/tools/mutation-testing/stryker/results.spec.ts b/tools/mutation-testing/stryker/results.spec.ts new file mode 100644 index 00000000000..481e78fd4d3 --- /dev/null +++ b/tools/mutation-testing/stryker/results.spec.ts @@ -0,0 +1,57 @@ +import { describe, expect, it, vi } from 'vitest'; + +import type { MutationReport } from './report'; +import type { ResultSources } from './results'; +import { chooseResults, testedNothing } from './results'; +import type { StreamedRun } from './stream'; + +const COMPLETE_REPORT: MutationReport = { files: { 'src/complete.ts': { mutants: [] } } }; +const STREAMED_RUN: StreamedRun = { + report: { files: { 'src/streamed.ts': { mutants: [] } } }, + tested: 4, + planned: 10, +}; + +function sources(): ResultSources { + return { + complete: vi.fn(() => COMPLETE_REPORT), + streamed: vi.fn(() => STREAMED_RUN), + }; +} + +describe('chooseResults', () => { + it('reads Stryker\'s own report on a run that finished', () => { + const readers = sources(); + + expect(chooseResults({ truncated: false }, readers)).toEqual({ truncated: false, report: COMPLETE_REPORT }); + // The streaming path must change nothing on the normal path — including not being read. + expect(readers.streamed).not.toHaveBeenCalled(); + }); + + it('falls back to the streamed results on a truncated run, carrying how far it got', () => { + const readers = sources(); + + expect(chooseResults({ truncated: true }, readers)).toEqual({ + truncated: true, + report: STREAMED_RUN.report, + tested: 4, + planned: 10, + }); + // A truncated run wrote no json report at all, so reading one would throw. + expect(readers.complete).not.toHaveBeenCalled(); + }); +}); + +describe('testedNothing', () => { + it('fails a truncated run that got through no mutant, which has no survivor to fail on', () => { + expect(testedNothing({ truncated: true, report: { files: {} }, tested: 0, planned: null })).toBe(true); + }); + + it('passes a truncated run that got partway, whose findings are real and reported as partial', () => { + expect(testedNothing({ truncated: true, report: STREAMED_RUN.report, tested: 4, planned: 10 })).toBe(false); + }); + + it('passes a complete run, which tested everything it selected', () => { + expect(testedNothing({ truncated: false, report: COMPLETE_REPORT })).toBe(false); + }); +}); diff --git a/tools/mutation-testing/stryker/results.ts b/tools/mutation-testing/stryker/results.ts new file mode 100644 index 00000000000..3b077cd14d5 --- /dev/null +++ b/tools/mutation-testing/stryker/results.ts @@ -0,0 +1,38 @@ +import type { RunOutcome } from './invoke'; +import type { MutationReport } from './report'; +import { readReport } from './report'; +import type { StreamedRun } from './stream'; +import { readStream } from './stream'; + +// Where a run's results come from. A complete run reads Stryker's own json report untouched; only a +// run stopped at its budget falls back to the stream the reporter plugin appended to, and then +// carries how much of the selection it got through so the report cannot pass as a complete one. + +export type RunResults = + { readonly truncated: false; readonly report: MutationReport } | + { readonly truncated: true; readonly report: MutationReport; readonly tested: number; readonly planned: number | null }; + +export interface ResultSources { + readonly complete: () => MutationReport; + readonly streamed: () => StreamedRun; +} + +// Kept pure — the sources are thunks, so the choice is unit-testable and it is visible that a +// complete run never reads the stream, nor a truncated one a json report that was never written. +export function chooseResults(outcome: RunOutcome, sources: ResultSources): RunResults { + if (!outcome.truncated) return { truncated: false, report: sources.complete() }; + + const { report, tested, planned } = sources.streamed(); + return { truncated: true, report, tested, planned }; +} + +export function readResults(outcome: RunOutcome): RunResults { + return chooseResults(outcome, { complete: readReport, streamed: readStream }); +} + +// A run stopped before a single mutant was tested is the one truncated outcome that has to fail +// rather than warn: it has no survivor to fail on, so the exit code would otherwise report a pass +// over a selection nothing was ever asked about. `formatTruncationNotice` already prints why. +export function testedNothing(results: RunResults): boolean { + return results.truncated && results.tested === 0; +} diff --git a/tools/mutation-testing/stryker/stream.spec.ts b/tools/mutation-testing/stryker/stream.spec.ts new file mode 100644 index 00000000000..b05b6fc6445 --- /dev/null +++ b/tools/mutation-testing/stryker/stream.spec.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from 'vitest'; + +import type { Mutant } from './report'; +import type { StreamRecord } from './stream'; +import { formatStreamRecord, parseStream } from './stream'; + +function mutant(id: string, status: Mutant['status'], line: number): Mutant { + return { + id, + mutatorName: 'ConditionalExpression', + status, + location: { start: { line, column: 1 }, end: { line, column: 20 } }, + }; +} + +function stream(...records: ReadonlyArray<StreamRecord>): string { + return records.map(formatStreamRecord).join(''); +} + +describe('parseStream', () => { + it('reads back what the reporter wrote, keyed the way the json report keys files', () => { + const contents = stream( + { kind: 'plan', mutants: 2 }, + { kind: 'mutant', file: 'src/a.ts', mutant: mutant('1', 'Killed', 4) }, + { kind: 'mutant', file: 'src/a.ts', mutant: mutant('2', 'Survived', 9) }, + ); + + expect(parseStream(contents)).toEqual({ + report: { files: { 'src/a.ts': { mutants: [ mutant('1', 'Killed', 4), mutant('2', 'Survived', 9) ] } } }, + tested: 2, + planned: 2, + }); + }); + + it('groups the mutants of each file under their own entry', () => { + const contents = stream( + { kind: 'mutant', file: 'src/a.ts', mutant: mutant('1', 'Killed', 4) }, + { kind: 'mutant', file: 'src/b.ts', mutant: mutant('2', 'Survived', 4) }, + { kind: 'mutant', file: 'src/a.ts', mutant: mutant('3', 'NoCoverage', 7) }, + ); + + const { report } = parseStream(contents); + expect(Object.keys(report.files)).toEqual([ 'src/a.ts', 'src/b.ts' ]); + expect(report.files['src/a.ts'].mutants.map(({ id }) => id)).toEqual([ '1', '3' ]); + }); + + // The point of the whole format: a process killed mid-write leaves a half-written last line, and + // every complete line before it must still be readable. + it('keeps every complete record when the last line was cut off mid-write', () => { + const complete = stream( + { kind: 'plan', mutants: 3 }, + { kind: 'mutant', file: 'src/a.ts', mutant: mutant('1', 'Killed', 4) }, + ); + const cutOff = `${ complete }{"kind":"mutant","file":"src/a.ts","mut`; + + expect(parseStream(cutOff)).toEqual(parseStream(complete)); + }); + + it('reads an empty stream as a run that tested nothing rather than an error', () => { + expect(parseStream('')).toEqual({ report: { files: {} }, tested: 0, planned: null }); + }); + + // Stryker plans the whole run before testing anything, so a stream with no plan record was cut + // off during the dry run: the total is unknown, and reporting it as 0 would invert the fraction. + it('leaves the planned total unknown when no plan record arrived', () => { + const contents = stream({ kind: 'mutant', file: 'src/a.ts', mutant: mutant('1', 'Killed', 4) }); + + expect(parseStream(contents)).toMatchObject({ tested: 1, planned: null }); + }); + + it('counts only mutant records as tested', () => { + const contents = stream( + { kind: 'plan', mutants: 9 }, + { kind: 'mutant', file: 'src/a.ts', mutant: mutant('1', 'Killed', 4) }, + ); + + expect(parseStream(contents)).toMatchObject({ tested: 1, planned: 9 }); + }); +}); diff --git a/tools/mutation-testing/stryker/stream.ts b/tools/mutation-testing/stryker/stream.ts new file mode 100644 index 00000000000..b0711200a1b --- /dev/null +++ b/tools/mutation-testing/stryker/stream.ts @@ -0,0 +1,69 @@ +import fs from 'fs'; + +import { STREAM_REPORT_FILE } from '../config'; +import type { Mutant, MutationReport } from './report'; + +// The line-delimited result stream the reporter plugin writes and a truncated run reads back. +// Stryker's own json report lands only when a whole run finishes, so a run stopped at its +// wall-clock budget has nothing else to report from. One JSON object per line is what makes a file +// cut off mid-write usable: every complete line before the cut is still a whole record. + +export type StreamRecord = + // Emitted once, when Stryker has planned the run: the denominator for how much of the selection a + // truncated run got through. + { readonly kind: 'plan'; readonly mutants: number } | + { readonly kind: 'mutant'; readonly file: string; readonly mutant: Mutant }; + +export interface StreamedRun { + readonly report: MutationReport; + readonly tested: number; + // null when the run was stopped before Stryker finished planning, which leaves the total unknown + // rather than zero. + readonly planned: number | null; +} + +export function formatStreamRecord(record: StreamRecord): string { + return `${ JSON.stringify(record) }\n`; +} + +// Every line that is not a whole record is dropped, blank ones included — the trailing newline of +// the last complete record leaves one, and the last line of a stopped run can be half-written. Any +// other line that does not parse is equally unusable, and dropping it beats failing the whole read. +function parseLine(line: string): StreamRecord | undefined { + try { + return JSON.parse(line) as StreamRecord; + } catch { + return undefined; + } +} + +function isRecord(record: StreamRecord | undefined): record is StreamRecord { + return record !== undefined; +} + +export function parseStream(contents: string): StreamedRun { + const records = contents.split('\n').map(parseLine).filter(isRecord); + + const files: Record<string, { mutants: Array<Mutant> }> = {}; + let planned: number | null = null; + let tested = 0; + + for (const record of records) { + if (record.kind === 'plan') { + planned = record.mutants; + continue; + } + files[record.file] ??= { mutants: [] }; + files[record.file].mutants.push(record.mutant); + tested += 1; + } + + return { report: { files }, tested, planned }; +} + +// A run stopped before the plugin wrote anything leaves no file at all, which is a stream with +// nothing in it rather than an error: the report then says plainly that no mutant was tested. +export function readStream(): StreamedRun { + const contents = fs.existsSync(STREAM_REPORT_FILE) ? fs.readFileSync(STREAM_REPORT_FILE, 'utf8') : ''; + return parseStream(contents); +} diff --git a/tools/mutation-testing/stryker/streaming-reporter.mts b/tools/mutation-testing/stryker/streaming-reporter.mts new file mode 100644 index 00000000000..ef845b1e4a4 --- /dev/null +++ b/tools/mutation-testing/stryker/streaming-reporter.mts @@ -0,0 +1,55 @@ +import type { MutantResult } from '@stryker-mutator/api/core'; +import { declareValuePlugin, PluginKind } from '@stryker-mutator/api/plugin'; +import type { MutationTestingPlanReadyEvent, Reporter } from '@stryker-mutator/api/report'; +import fs from 'fs'; +import path from 'path'; + +import { STREAM_REPORT_FILE } from '../config.js'; +import { formatStreamRecord } from './stream.js'; + +// A Stryker reporter that appends each mutant's verdict to STREAM_REPORT_FILE the moment it is +// tested, so a run stopped at its wall-clock budget still leaves its completed work behind — +// Stryker's own json reporter writes once, at the very end, and a stopped run never gets there. +// +// This file is .mts, and so emitted as ESM, because Stryker loads a plugin through import() and +// reads a `strykerPlugins` binding off the module namespace. + +// The name stryker.config.json's `reporters` list enables this plugin under. +const REPORTER_NAME = 'stream'; + +// Stryker hands reporters absolute paths; its json reporter keys files by a cwd-relative, forward- +// slashed name. Matching that here is what lets a truncated stream be read as if it were the report. +function toReportFileName(fileName: string): string { + return path.relative(process.cwd(), fileName).replace(/\\/g, '/'); +} + +class StreamingReporter implements Reporter { + private directoryReady = false; + + // Appended synchronously, one open-write-close per record. A buffered stream would be the obvious + // choice, but Stryker answers a signal with process.exit, which drops whatever has not been + // flushed — and the records that matter most are the last ones before the run was stopped. + private write(line: string): void { + if (!this.directoryReady) { + fs.mkdirSync(path.dirname(STREAM_REPORT_FILE), { recursive: true }); + this.directoryReady = true; + } + fs.appendFileSync(STREAM_REPORT_FILE, line); + } + + public onMutationTestingPlanReady({ mutantPlans }: MutationTestingPlanReadyEvent): void { + this.write(formatStreamRecord({ kind: 'plan', mutants: mutantPlans.length })); + } + + public onMutantTested({ fileName, id, mutatorName, status, location }: Readonly<MutantResult>): void { + this.write(formatStreamRecord({ + kind: 'mutant', + file: toReportFileName(fileName), + mutant: { id, mutatorName, status, location }, + })); + } +} + +export const strykerPlugins = [ + declareValuePlugin(PluginKind.Reporter, REPORTER_NAME, new StreamingReporter()), +]; diff --git a/tools/mutation-testing/tsconfig.json b/tools/mutation-testing/tsconfig.json new file mode 100644 index 00000000000..6f4d38311da --- /dev/null +++ b/tools/mutation-testing/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "node16", + "target": "es2022", + "moduleResolution": "node16", + "resolveJsonModule": true, + "isolatedModules": false, + "noEmit": false, + "incremental": false, + "rootDir": ".." + }, + "include": [ + "./index.ts", + "./stryker/streaming-reporter.mts" + ], + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/tools/mutation-testing/vitest.config.ts b/tools/mutation-testing/vitest.config.ts new file mode 100644 index 00000000000..dcdfd7b3136 --- /dev/null +++ b/tools/mutation-testing/vitest.config.ts @@ -0,0 +1,18 @@ +import { defineConfig, mergeConfig } from 'vitest/config'; + +import baseConfig from '../../vitest.config'; + +// Primed-request drift tests (src/server/primedRequests/CONTEXT.md) mount whole pages without +// exercising behaviour, so every mutant they kill is killed incidentally — and they dominate the +// runtime of a Stryker run. They are excluded from execution rather than from Stryker's sandbox, +// because the drift check in src/server/primedRequests/index.spec.ts globs them off disk. +// Naming a reporter is what keeps Vitest's own github-actions reporter off: Vitest appends that one +// to the defaults whenever $GITHUB_ACTIONS is set. It writes a "Vitest Test Report" block to the job +// summary per test run, and Stryker ends one of those per mutant — so the summary would fill with +// hundreds of them, each killed mutant reported as a test failure, above the report that matters. +export default mergeConfig(baseConfig, defineConfig({ + test: { + exclude: [ '**/*.primed.spec.tsx' ], + reporters: [ 'default' ], + }, +})); diff --git a/tools/playwright/CONTEXT.md b/tools/playwright/CONTEXT.md new file mode 100644 index 00000000000..0b163574094 --- /dev/null +++ b/tools/playwright/CONTEXT.md @@ -0,0 +1,34 @@ +# Playwright runner — context + +The `pnpm test:pw` entry point runs Playwright component tests (`*.pw.tsx`) locally, in Docker, and in CI. To learn how to use it, run `pnpm test:pw --help`. + +## Where to look + +| Question | Answer | +| --- | --- | +| Which tests ran, with what outcome, and where is each screenshot diff? | `playwright-results/report.json` after the run — the agent-readable surface, no console parsing needed | +| Where are the html / blob reports? | `playwright-report/` (local html), `blob-report/` (CI) | +| `--changed` ran the full suite. Why? | a changed file is on the force-full list in `./config.ts`; the tool prints which one | +| `--changed` ran zero tests. Why? | the bundler's module graph reaches no registered component from the diff — a type-only file, a server-only module, a doc. If the edit does reach the browser some other way, it belongs on the force-full list | +| Why is selection Playwright's job and not a dependency walk? | `./adr/0001-affected-tests-delegated-to-playwright.md` | +| Why no dry-run of what `--changed` would select? | `--only-changed --list` lists zero tests in CT mode; see the constraint below and the ADR's consequences | +| A test failed with "Unmocked localhost requests". What now? | the component requested a URL no mock handles; the rule and how to read the failure are the "Mock flow" section of `../../.agents/rules/tests-visual.md`. The check lives in `../../playwright/lib.ts` | + +## Constraints + +- **The force-full list in `./config.ts` and the `pw_changes` gate step in `.github/workflows/checks.yml` move together.** The gate's paths are the force-full paths plus `src/`. A path added to only one either wastes a matrix run or skips a needed one. +- **`--only-changed` cannot see icons.** The sprite is built at run time from `src/sprite/icons/`, outside the bundler's module graph, so an icon edit selects zero tests. The force-full list exists for this; anything else that reaches the browser outside the module graph belongs on it too. +- **`--only-changed --list` reports zero tests in CT mode** (list mode never sets up the CT plugin), so there is no dry-run of what `--changed` would select. Run it and read `playwright-results/report.json`. +- **Running `playwright test` directly skips the pre-run steps**, so the harness loads whatever `playwright/envs.js` and sprite the last `pnpm test:pw` run left behind. +- **The json report lives under `outputDir`, not next to the html report.** The html reporter deletes `playwright-report/` when the run ends, so a second reporter writing there loses its file. +- **The Docker image name and OS suffix in `./config.ts` are paired with `container.image` in `.github/workflows/checks.yml`**, so a Mac `--docker` run renders with the same browsers as CI. The tag follows the installed `@playwright/test` version on its own. + +## File map + +- `./index.ts` — CLI flags, the pre-run steps, the spawn of `playwright test`, and the exit code +- `./select.ts` — the full-vs-`--only-changed` rule `--changed` applies to the changed files +- `./docker.ts` — the `docker run` argv for `--docker` and `--docker-deps`, and the image / pnpm version derivation +- `./config.ts` — paths, the base ref, the force-full list, the Node heap size Playwright runs with, and the Docker image name and mounts +- `./run.sh` — compile-and-run wrapper + +The Playwright configuration itself is `../../playwright-ct.config.ts`; the test harness, fixtures and mocks are under `../../playwright/`. diff --git a/tools/playwright/adr/0001-affected-tests-delegated-to-playwright.md b/tools/playwright/adr/0001-affected-tests-delegated-to-playwright.md new file mode 100644 index 00000000000..7e74666f794 --- /dev/null +++ b/tools/playwright/adr/0001-affected-tests-delegated-to-playwright.md @@ -0,0 +1,56 @@ +# 0001 — affected-test selection is delegated to Playwright's `--only-changed` + +| | | +| --- | --- | +| Status | accepted | +| Date | 2026-09-15 | +| Deciders | @tom2drum | +| Supersedes | — | + +## Decision + +**Under `--changed`, the tool passes the merge-base sha to `playwright test --only-changed` and lets the +component-testing plugin decide which `*.pw.tsx` files are affected.** The tool keeps one rule of its +own, the force-full list in `../config.ts`: a change under it runs the whole suite instead. There is no +custom dependency walk. + +## Why + +**The bundler already holds the real module graph.** With `@playwright/experimental-ct-react` the CT +plugin builds the Vite bundle, records every registered component's module graph, and maps the changed +files onto test files through it. Measured in this repo, before this decision: + +| Change | Tests selected | +| --- | --- | +| a type-only module | 0 — the bundler erases type imports, so they never form an edge | +| a leaf component | only its dependents (31 files) | +| a theme recipe, a toolkit component, or `playwright/TestApp.tsx` | the full project — `TestApp` is registered as a component through the render fixture, so anything it reaches, reaches every test | + +**The rejected alternative was patching the walker.** The previous tool walked imports with +`dependency-tree`. Its gaps were that type-only imports counted as edges, the diff ran against the base +tip rather than the merge-base, and nothing forced a full run when the harness or the lockfile changed. +The first could be cut with `detective: { ts, tsx: { skipTypeImports: true } }` (about 20% fewer +edges), the others were small fixes — but the result stays a second, hand-maintained model of what the +bundler already knows, and drifts with every Vite or path-alias change. + +**Icons are the blind spot the force-full list exists for.** SVG icons reach the browser as a sprite +built at run time, not through the module graph, so an icon edit selects nothing under `--only-changed`. +The other entries cover the harness template files (`playwright/**`), the config, and the lockfile — +build-shape and dependency changes with no module edge either. `package.json` is deliberately absent: +under `--frozen-lockfile` any dependency change also changes `pnpm-lock.yaml`, and script or metadata +edits do not affect the tests. + +## Consequences + +- Selection quality is Playwright's: an upgrade can change which tests a diff selects, and the fix for a + mis-selection is an upstream report, not a local patch. `--only-changed --list` reporting zero tests + in CT mode was reproduced but not reported: Playwright 1.63 froze the `@playwright/experimental-ct-*` + packages, and in the replacement stories model no import edge links a test to its component, so + `--only-changed` cannot select by component there at all (maintainers' position: + microsoft/playwright#40691). This decision is revisited when the suite migrates off the experimental + packages. +- The force-full list must stay a mirror of the `pw_changes` gate step in + `.github/workflows/checks.yml`; a path added to one without the other either wastes a matrix run or + skips a needed one. +- A file that reaches the browser outside the module graph and is not on the list is invisible to + `--changed`. Adding to the list is the answer; a dependency walk is not. diff --git a/tools/playwright/config.ts b/tools/playwright/config.ts new file mode 100644 index 00000000000..4a6a56270fb --- /dev/null +++ b/tools/playwright/config.ts @@ -0,0 +1,53 @@ +import path from 'path'; + +export const DEFAULT_BASE_REF = 'origin/main'; + +export const PLAYWRIGHT_BIN = path.join('node_modules', '.bin', 'playwright'); +export const PLAYWRIGHT_CONFIG_FILE = 'playwright-ct.config.ts'; + +// The browser-side envs for component tests. The pre-run steps turn this file into the +// window.__envs script the test harness (playwright/index.ts) loads. +export const ENV_FILE = path.join('playwright', '.env.pw'); +export const ENVS_SCRIPT_FILE = path.join('playwright', 'envs.js'); +export const MAKE_ENVS_SCRIPT = path.join('deploy', 'scripts', 'make_envs_script.sh'); + +// The sprite build skips content hashing under this app env, so the harness can load a fixed +// sprite.svg path. +export const SPRITE_APP_ENV = 'pw'; + +// The CT bundle of the whole app does not fit Node's default heap. +export const PLAYWRIGHT_NODE_OPTIONS = '--max-old-space-size=8192'; + +// Playwright's build cache for the component bundle; see the commented-out step in ./index.ts. +export const PLAYWRIGHT_CACHE_DIR = path.join('playwright', '.cache'); + +// Changes that reach the browser outside the bundler's module graph, so `--only-changed` cannot see +// them: the sprite (built at run time from src/sprite/icons), the harness template files, the config, the +// lockfile. Any hit under --changed runs the whole suite. A trailing slash means "everything under"; +// the other entries match one exact path. Paired with the `pw_changes` gate step in +// .github/workflows/checks.yml, which lists the same paths so an empty diff there skips the matrix — +// keep the two in sync. +export const FORCE_FULL_PATHS: ReadonlyArray<string> = [ + 'src/sprite/icons/', + 'playwright/', + PLAYWRIGHT_CONFIG_FILE, + 'pnpm-lock.yaml', +]; + +// Where --docker runs. The tag is derived at run time from the installed @playwright/test version, +// because the browsers baked into the image must match the runner. The name and the OS suffix are +// paired with `container.image` in .github/workflows/checks.yml — keep the two in sync, so a Mac +// --docker run renders with the same browsers as CI. +export const DOCKER_IMAGE_NAME = 'mcr.microsoft.com/playwright'; +export const DOCKER_IMAGE_OS_SUFFIX = '-noble'; +export const PLAYWRIGHT_PACKAGE_FILE = path.join('node_modules', '@playwright', 'test', 'package.json'); +export const PACKAGE_FILE = 'package.json'; + +// The Linux dependency tree --docker mounts over node_modules, so Node inside the container resolves +// the Linux-native optional packages instead of the Mac ones. --docker-deps installs it, keeping the +// pnpm store in a named volume across installs. +export const LINUX_MODULES_DIR = 'node_modules_linux'; +export const LINUX_MODULES_MARKER = path.join(LINUX_MODULES_DIR, '.modules.yaml'); +export const PNPM_STORE_VOLUME = 'blockscout-pnpm-linux'; +export const CONTAINER_WORKDIR = '/work/'; +export const CONTAINER_PNPM_STORE = '/pnpm-store'; diff --git a/tools/playwright/docker.spec.ts b/tools/playwright/docker.spec.ts new file mode 100644 index 00000000000..330e5ea78b8 --- /dev/null +++ b/tools/playwright/docker.spec.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from 'vitest'; + +import { + CONTAINER_PNPM_STORE, + CONTAINER_WORKDIR, + DOCKER_IMAGE_NAME, + DOCKER_IMAGE_OS_SUFFIX, + LINUX_MODULES_DIR, + PACKAGE_FILE, + PLAYWRIGHT_PACKAGE_FILE, + PNPM_STORE_VOLUME, +} from './config'; +import type { DockerOptions } from './docker'; +import { buildDockerCommand, buildDockerDepsCommand, resolveDockerOptions } from './docker'; + +const CWD = '/Users/dev/frontend'; +const IMAGE = 'example.test/playwright:v0.0.0-test'; +const PNPM_VERSION = '11.0.0'; +const OPTIONS: DockerOptions = { tty: false, image: IMAGE, pnpm: PNPM_VERSION }; + +function scriptOf(args: ReadonlyArray<string>): string { + const bashIndex = args.indexOf('bash'); + expect(args[bashIndex + 1]).toBe('-c'); + return args[bashIndex + 2]; +} + +describe('buildDockerCommand', () => { + it('mounts the repo and the Linux modules, then runs the inner test:pw with the args as "$@"', () => { + const { command, args } = buildDockerCommand([ 'src/a.pw.tsx', '-g', 'renders the empty state', '--update-snapshots' ], OPTIONS, CWD); + + expect(command).toBe('docker'); + expect(args).toEqual([ + 'run', '--rm', '--ipc=host', + '-v', `${ CWD }:${ CONTAINER_WORKDIR }`, + '-v', `${ CWD }/${ LINUX_MODULES_DIR }:${ CONTAINER_WORKDIR }node_modules`, + '-w', CONTAINER_WORKDIR, + IMAGE, + 'bash', '-c', expect.stringContaining('pnpm test:pw "$@"'), + 'bash', 'src/a.pw.tsx', '-g', 'renders the empty state', '--update-snapshots', + ]); + }); + + it('activates the pinned pnpm and disables the pre-run dependency check inside the container', () => { + const script = scriptOf(buildDockerCommand([], OPTIONS, CWD).args); + + expect(script).toBe( + 'npm i -g corepack@latest && ' + + `corepack enable && corepack prepare pnpm@${ PNPM_VERSION } --activate && ` + + 'PNPM_CONFIG_VERIFY_DEPS_BEFORE_RUN=false pnpm test:pw "$@"', + ); + }); + + // An agent or CI caller has no terminal; docker with -it would then abort with "the input device is + // not a TTY". + it('asks docker for a terminal only when the caller has one', () => { + expect(buildDockerCommand([], { ...OPTIONS, tty: true }, CWD).args).toContain('-it'); + expect(buildDockerCommand([], { ...OPTIONS, tty: false }, CWD).args).not.toContain('-it'); + }); +}); + +describe('buildDockerDepsCommand', () => { + // The Linux tree sits at node_modules inside the container, so the repo's postinstall resolves the + // Linux binaries it just installed rather than the Mac ones. + it('mounts the repo, the Linux modules over node_modules and the pnpm store volume, then installs', () => { + const { command, args } = buildDockerDepsCommand({ ...OPTIONS, tty: true }, CWD); + + expect(command).toBe('docker'); + expect(args).toEqual([ + 'run', '--rm', '--ipc=host', '-it', + '-v', `${ CWD }:${ CONTAINER_WORKDIR }`, + '-v', `${ CWD }/${ LINUX_MODULES_DIR }:${ CONTAINER_WORKDIR }node_modules`, + '-v', `${ PNPM_STORE_VOLUME }:${ CONTAINER_PNPM_STORE }`, + '-w', CONTAINER_WORKDIR, + IMAGE, + 'bash', '-c', expect.any(String), + ]); + + const script = scriptOf(args); + expect(script).toContain('apt-get install -y build-essential'); + expect(script).toContain(`corepack prepare pnpm@${ PNPM_VERSION } --activate`); + expect(script).toContain(`pnpm install --store-dir ${ CONTAINER_PNPM_STORE }`); + expect(script).not.toContain('--modules-dir'); + expect(script).toContain('CI=true'); + }); +}); + +describe('resolveDockerOptions', () => { + const files: Record<string, string> = { + [PLAYWRIGHT_PACKAGE_FILE]: JSON.stringify({ name: '@playwright/test', version: '1.99.0' }), + [PACKAGE_FILE]: JSON.stringify({ packageManager: 'pnpm@12.3.4' }), + }; + const readFile = (file: string): string => files[file]; + + it('derives the image tag from the installed playwright and the pnpm version from packageManager', () => { + expect(resolveDockerOptions(readFile, true)).toEqual({ + tty: true, + image: `${ DOCKER_IMAGE_NAME }:v1.99.0${ DOCKER_IMAGE_OS_SUFFIX }`, + pnpm: '12.3.4', + }); + }); + + it('rejects a packageManager that is not pnpm', () => { + const readYarn = (file: string): string => file === PACKAGE_FILE ? JSON.stringify({ packageManager: 'yarn@4.0.0' }) : files[file]; + + expect(() => resolveDockerOptions(readYarn, false)).toThrow('must be pnpm@<version>'); + }); + + it('rejects a playwright package without a version', () => { + const readBroken = (file: string): string => file === PLAYWRIGHT_PACKAGE_FILE ? JSON.stringify({ name: '@playwright/test' }) : files[file]; + + expect(() => resolveDockerOptions(readBroken, false)).toThrow(`No "version" string in ${ PLAYWRIGHT_PACKAGE_FILE }`); + }); + + it('rejects a package file whose JSON is not an object', () => { + const readNull = (file: string): string => file === PLAYWRIGHT_PACKAGE_FILE ? JSON.stringify(null) : files[file]; + + expect(() => resolveDockerOptions(readNull, false)).toThrow(`No "version" string in ${ PLAYWRIGHT_PACKAGE_FILE }`); + }); +}); diff --git a/tools/playwright/docker.ts b/tools/playwright/docker.ts new file mode 100644 index 00000000000..4f0bad53e85 --- /dev/null +++ b/tools/playwright/docker.ts @@ -0,0 +1,110 @@ +import path from 'path'; + +import { + CONTAINER_PNPM_STORE, + CONTAINER_WORKDIR, + DOCKER_IMAGE_NAME, + DOCKER_IMAGE_OS_SUFFIX, + LINUX_MODULES_DIR, + PACKAGE_FILE, + PLAYWRIGHT_PACKAGE_FILE, + PNPM_STORE_VOLUME, +} from './config'; + +export interface DockerOptions { + readonly tty: boolean; + readonly image: string; + readonly pnpm: string; +} + +export interface DockerCommand { + readonly command: 'docker'; + readonly args: Array<string>; +} + +// The Playwright image ships Node but not pnpm; corepack activates the version package.json pins. +// The corepack bundled with the image's Node predates pnpm 12's native-binary layout and resolves the +// bin/pnpm.cjs that no longer ships, so it is upgraded before the prepare. +function pnpmSetup(pnpm: string): string { + return `npm i -g corepack@latest && corepack enable && corepack prepare pnpm@${ pnpm } --activate`; +} + +// The Linux tree was installed from a bind mount, so its recorded paths differ from what pnpm's +// pre-run check expects and it would refuse to start a script. +const INNER_TEST_ENV = 'PNPM_CONFIG_VERIFY_DEPS_BEFORE_RUN=false'; + +// Build tools for the native dependencies the Linux tree compiles on install. +const BUILD_TOOLS_INSTALL = [ + 'apt-get update', + 'apt-get install -y build-essential python3 cmake pkg-config libssl-dev', + 'rm -rf /var/lib/apt/lists/*', +].join(' && '); + +// CI=true keeps pnpm 11 from prompting to purge the modules dir. +const LINUX_DEPS_INSTALL = [ + 'export npm_config_build_from_source=false npm_config_prefer_offline=true CI=true', + `pnpm install --store-dir ${ CONTAINER_PNPM_STORE } --config.confirm-modules-purge=true`, +].join(' && '); + +function dockerRunArgs(options: DockerOptions, cwd: string, mounts: ReadonlyArray<string>): Array<string> { + return [ + 'run', '--rm', '--ipc=host', + ...(options.tty ? [ '-it' ] : []), + '-v', `${ cwd }:${ CONTAINER_WORKDIR }`, + ...mounts.flatMap((mount) => [ '-v', mount ]), + '-w', CONTAINER_WORKDIR, + options.image, + ]; +} + +function linuxModulesMount(cwd: string): string { + return `${ path.join(cwd, LINUX_MODULES_DIR) }:${ path.posix.join(CONTAINER_WORKDIR, 'node_modules') }`; +} + +// The inner command is `bash -c '<script>' bash <args...>`: the args reach the script as "$@", so a +// test title with spaces or a shell metacharacter never goes through a second round of quoting. +export function buildDockerCommand(args: ReadonlyArray<string>, options: DockerOptions, cwd: string = process.cwd()): DockerCommand { + const script = `${ pnpmSetup(options.pnpm) } && ${ INNER_TEST_ENV } pnpm test:pw "$@"`; + return { + command: 'docker', + args: [ ...dockerRunArgs(options, cwd, [ linuxModulesMount(cwd) ]), 'bash', '-c', script, 'bash', ...args ], + }; +} + +// The Linux tree is mounted over node_modules for the install as well, rather than installed with +// --modules-dir: the repo's postinstall (chakra typegen) resolves esbuild from ./node_modules, and with +// the Mac tree there it loads the darwin binary and fails. +export function buildDockerDepsCommand(options: DockerOptions, cwd: string = process.cwd()): DockerCommand { + const storeMount = `${ PNPM_STORE_VOLUME }:${ CONTAINER_PNPM_STORE }`; + const script = `${ BUILD_TOOLS_INSTALL } && ${ pnpmSetup(options.pnpm) } && ${ LINUX_DEPS_INSTALL }`; + return { + command: 'docker', + args: [ ...dockerRunArgs(options, cwd, [ linuxModulesMount(cwd), storeMount ]), 'bash', '-c', script ], + }; +} + +function fieldOf(json: string, field: string, file: string): string { + const parsed: unknown = JSON.parse(json); + // JSON.parse never yields undefined, and indexing a primitive yields undefined, so null is the only + // value that needs guarding before the property access. + const value = parsed === null ? undefined : (parsed as Record<string, unknown>)[field]; + if (typeof value !== 'string') throw new Error(`No "${ field }" string in ${ file }`); + return value; +} + +function pnpmVersionOf(packageManager: string): string { + const match = /^pnpm@(\S+)$/.exec(packageManager); + if (match === null) throw new Error(`"packageManager" in ${ PACKAGE_FILE } must be pnpm@<version>, got ${ packageManager }`); + return match[1]; +} + +// Neither version is written into the tool: a Playwright upgrade moves the image with it, a pnpm +// bump moves what corepack activates. +export function resolveDockerOptions(readFile: (file: string) => string, tty: boolean): DockerOptions { + const playwrightVersion = fieldOf(readFile(PLAYWRIGHT_PACKAGE_FILE), 'version', PLAYWRIGHT_PACKAGE_FILE); + return { + tty, + image: `${ DOCKER_IMAGE_NAME }:v${ playwrightVersion }${ DOCKER_IMAGE_OS_SUFFIX }`, + pnpm: pnpmVersionOf(fieldOf(readFile(PACKAGE_FILE), 'packageManager', PACKAGE_FILE)), + }; +} diff --git a/tools/playwright/index.spec.ts b/tools/playwright/index.spec.ts new file mode 100644 index 00000000000..cbf93633076 --- /dev/null +++ b/tools/playwright/index.spec.ts @@ -0,0 +1,320 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { + DEFAULT_BASE_REF, + DOCKER_IMAGE_NAME, + DOCKER_IMAGE_OS_SUFFIX, + ENV_FILE, + ENVS_SCRIPT_FILE, + LINUX_MODULES_MARKER, + MAKE_ENVS_SCRIPT, + PACKAGE_FILE, + PLAYWRIGHT_BIN, + PLAYWRIGHT_CONFIG_FILE, + PLAYWRIGHT_NODE_OPTIONS, + PLAYWRIGHT_PACKAGE_FILE, + SPRITE_APP_ENV, +} from './config'; +import type { Runtime, Step } from './index'; +import { parseArgs, run } from './index'; + +const ENV_FILE_CONTENT = 'NEXT_PUBLIC_FROM_FILE=file\nNEXT_PUBLIC_APP_ENV=testing\n'; +const MERGE_BASE = 'a1b2c3d4'; +const PLAYWRIGHT_VERSION = '1.99.0'; +const PNPM_VERSION = '12.3.4'; +const FILES: Record<string, string> = { + [ENV_FILE]: ENV_FILE_CONTENT, + [PLAYWRIGHT_PACKAGE_FILE]: JSON.stringify({ version: PLAYWRIGHT_VERSION }), + [PACKAGE_FILE]: JSON.stringify({ packageManager: `pnpm@${ PNPM_VERSION }` }), +}; + +interface RecordingRuntime extends Runtime { + readonly steps: Array<Step>; + readonly reads: Array<string>; + readonly baseRefs: Array<string>; +} + +interface RecordingOptions { + readonly statuses?: ReadonlyArray<number>; + readonly changedFiles?: ReadonlyArray<string>; + readonly existingFiles?: ReadonlyArray<string>; + readonly isTTY?: boolean; +} + +// A runtime that records every step and answers each with the next status from the list, 0 once +// the list runs out; the diff lookup answers with a fixed merge-base and the given changed files. +function recordingRuntime({ statuses = [], changedFiles = [], existingFiles = [], isTTY = false }: RecordingOptions = {}): RecordingRuntime { + const steps: Array<Step> = []; + const reads: Array<string> = []; + const baseRefs: Array<string> = []; + const pending = [ ...statuses ]; + return { + steps, + reads, + baseRefs, + isTTY, + spawn: (step) => { + steps.push(step); + return pending.shift() ?? 0; + }, + readFile: (file) => { + reads.push(file); + return FILES[file]; + }, + fileExists: (file) => existingFiles.includes(file), + changes: (baseRef) => { + baseRefs.push(baseRef); + return { baseCommit: MERGE_BASE, changedFiles }; + }, + }; +} + +function playwrightArgsOf(runtime: RecordingRuntime): ReadonlyArray<string> { + return runtime.steps[runtime.steps.length - 1].args; +} + +describe('parseArgs', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('defaults to a plain run with nothing to pass through', () => { + expect(parseArgs([])).toEqual({ + baseRef: DEFAULT_BASE_REF, + diffSelected: false, + docker: false, + dockerDeps: false, + playwrightArgs: [], + }); + }); + + // The whole point of the tool: whatever it does not own reaches playwright in the order given, + // with a multi-word value staying one token. + it('passes unknown flags and positionals through in argv order', () => { + const argv = [ 'src/a.pw.tsx', '--project=default', '-g', 'renders the empty state', '--update-snapshots', 'src/b.pw.tsx' ]; + expect(parseArgs(argv).playwrightArgs).toEqual(argv); + }); + + it('splits its own flags off from the pass-through list', () => { + expect(parseArgs([ '--changed', '--project=default', '--base', 'upstream/main', 'src/a.pw.tsx' ])).toEqual({ + baseRef: 'upstream/main', + diffSelected: true, + docker: false, + dockerDeps: false, + playwrightArgs: [ '--project=default', 'src/a.pw.tsx' ], + }); + }); + + it('selects diff mode from --changed, with an optional inline ref', () => { + expect(parseArgs([ '--changed' ])).toMatchObject({ diffSelected: true, baseRef: DEFAULT_BASE_REF }); + expect(parseArgs([ '--changed=upstream/main' ])).toMatchObject({ diffSelected: true, baseRef: 'upstream/main' }); + }); + + // The CI invocation: --changed must not consume the following token as its ref. + it('leaves the token after a bare --changed alone', () => { + expect(parseArgs([ '--changed', '--project=mobile' ])).toMatchObject({ + baseRef: DEFAULT_BASE_REF, + playwrightArgs: [ '--project=mobile' ], + }); + }); + + it('takes the docker switches', () => { + expect(parseArgs([ '--docker' ])).toMatchObject({ docker: true, dockerDeps: false }); + expect(parseArgs([ '--docker-deps' ])).toMatchObject({ docker: false, dockerDeps: true }); + }); + + it('prints the usage text and exits on --help', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(process, 'exit').mockImplementation((code) => { + throw new Error(`exited with ${ code }`); + }); + + expect(() => parseArgs([ '--help' ])).toThrow('exited with 0'); + expect(log).toHaveBeenCalledWith(expect.stringContaining('Usage:')); + expect(log).toHaveBeenCalledWith(expect.stringContaining('--changed[=<ref>]')); + expect(log).toHaveBeenCalledWith(expect.stringContaining('--docker-deps')); + }); +}); + +describe('run', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('runs the envs script, the sprite build, then playwright with the pass-through args', () => { + const runtime = recordingRuntime(); + + run([ 'src/a.pw.tsx', '-g', 'renders the empty state' ], runtime); + + expect(runtime.reads).toEqual([ ENV_FILE ]); + expect(runtime.steps.map((step) => [ step.command, ...step.args ])).toEqual([ + [ MAKE_ENVS_SCRIPT, ENVS_SCRIPT_FILE ], + [ 'pnpm', 'svg:build-sprite' ], + [ PLAYWRIGHT_BIN, 'test', '-c', PLAYWRIGHT_CONFIG_FILE, 'src/a.pw.tsx', '-g', 'renders the empty state' ], + ]); + }); + + // The sprite and playwright need the pw app env; the envs script must not see it, or envs.js + // would carry a different app env than the file declares. + it('gives every child the env file, and only the sprite and playwright the pw app env', () => { + const runtime = recordingRuntime(); + + run([], runtime); + + const [ envsStep, spriteStep, playwrightStep ] = runtime.steps; + expect(envsStep.env).toMatchObject({ NEXT_PUBLIC_FROM_FILE: 'file', NEXT_PUBLIC_APP_ENV: 'testing' }); + expect(spriteStep.env).toMatchObject({ NEXT_PUBLIC_FROM_FILE: 'file', NEXT_PUBLIC_APP_ENV: SPRITE_APP_ENV }); + expect(playwrightStep.env).toMatchObject({ + NEXT_PUBLIC_FROM_FILE: 'file', + NEXT_PUBLIC_APP_ENV: SPRITE_APP_ENV, + NODE_OPTIONS: PLAYWRIGHT_NODE_OPTIONS, + }); + expect(envsStep.env.NODE_OPTIONS).toBeUndefined(); + expect(spriteStep.env.NODE_OPTIONS).toBeUndefined(); + }); + + it('lets a variable already in the shell win over the env file', () => { + vi.stubEnv('NEXT_PUBLIC_FROM_FILE', 'shell'); + const runtime = recordingRuntime(); + + run([], runtime); + + expect(runtime.steps[0].env.NEXT_PUBLIC_FROM_FILE).toBe('shell'); + }); + + it('returns playwright\'s exit code', () => { + expect(run([], recordingRuntime({ statuses: [ 0, 0, 0 ] }))).toBe(0); + expect(run([], recordingRuntime({ statuses: [ 0, 0, 1 ] }))).toBe(1); + }); + + it('stops at the first failing pre-run step and returns its status', () => { + const runtime = recordingRuntime({ statuses: [ 0, 2 ] }); + + expect(run([], runtime)).toBe(2); + expect(runtime.steps).toHaveLength(2); + }); +}); + +describe('run --docker', () => { + const IMAGE = `${ DOCKER_IMAGE_NAME }:v${ PLAYWRIGHT_VERSION }${ DOCKER_IMAGE_OS_SUFFIX }`; + + afterEach(() => { + vi.restoreAllMocks(); + }); + + // The whole command line minus --docker goes to the container, so the inner run sees --changed + // and the pass-through args exactly as the caller wrote them. + it('runs one docker step with the image derived from the installed playwright and the rest of the argv inside', () => { + const runtime = recordingRuntime({ existingFiles: [ LINUX_MODULES_MARKER ] }); + + const status = run([ '--changed', '--docker', 'src/a.pw.tsx', '--update-snapshots' ], runtime); + + expect(status).toBe(0); + expect(runtime.steps).toHaveLength(1); + const [ step ] = runtime.steps; + expect(step.command).toBe('docker'); + expect(step.args).toContain(IMAGE); + expect(step.args.slice(-4)).toEqual([ 'bash', '--changed', 'src/a.pw.tsx', '--update-snapshots' ]); + expect(step.args.join(' ')).toContain(`corepack prepare pnpm@${ PNPM_VERSION }`); + expect(runtime.baseRefs).toEqual([]); + }); + + it('gives docker a terminal only when stdin is one', () => { + const withTTY = recordingRuntime({ existingFiles: [ LINUX_MODULES_MARKER ], isTTY: true }); + run([ '--docker' ], withTTY); + expect(withTTY.steps[0].args).toContain('-it'); + + const withoutTTY = recordingRuntime({ existingFiles: [ LINUX_MODULES_MARKER ], isTTY: false }); + run([ '--docker' ], withoutTTY); + expect(withoutTTY.steps[0].args).not.toContain('-it'); + }); + + it('returns docker\'s exit code', () => { + expect(run([ '--docker' ], recordingRuntime({ existingFiles: [ LINUX_MODULES_MARKER ], statuses: [ 3 ] }))).toBe(3); + }); + + it('refuses to start without the Linux dependencies and names the command that installs them', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const runtime = recordingRuntime(); + + expect(run([ '--docker' ], runtime)).toBe(1); + expect(runtime.steps).toHaveLength(0); + expect(error).toHaveBeenCalledWith(expect.stringContaining('pnpm test:pw --docker-deps')); + }); + + it('installs the Linux dependencies with --docker-deps, without needing them first', () => { + const runtime = recordingRuntime(); + + expect(run([ '--docker-deps' ], runtime)).toBe(0); + expect(runtime.steps).toHaveLength(1); + expect(runtime.steps[0].command).toBe('docker'); + expect(runtime.steps[0].args).toContain(IMAGE); + expect(runtime.steps[0].args.join(' ')).toContain('pnpm install --store-dir'); + }); + + it('rejects --docker-deps combined with any other flag or argument', () => { + for (const argv of [ [ '--docker-deps', '--docker' ], [ '--docker-deps', '--changed' ], [ '--docker-deps', 'src/a.pw.tsx' ] ]) { + const runtime = recordingRuntime(); + expect(() => run(argv, runtime)).toThrow('--docker-deps takes no other flag or argument'); + expect(runtime.steps).toHaveLength(0); + } + }); +}); + +describe('run --changed', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('does not look at the diff in a plain run', () => { + const runtime = recordingRuntime(); + + run([ 'src/a.pw.tsx' ], runtime); + + expect(runtime.baseRefs).toEqual([]); + expect(playwrightArgsOf(runtime)).not.toContainEqual(expect.stringContaining('--only-changed')); + }); + + it('hands the merge-base to playwright after the pass-through args', () => { + const runtime = recordingRuntime({ changedFiles: [ 'src/ui/Foo.tsx' ] }); + + run([ '--changed', '--project=default', '--pass-with-no-tests' ], runtime); + + expect(runtime.baseRefs).toEqual([ DEFAULT_BASE_REF ]); + expect(playwrightArgsOf(runtime)).toEqual([ + 'test', '-c', PLAYWRIGHT_CONFIG_FILE, '--project=default', '--pass-with-no-tests', `--only-changed=${ MERGE_BASE }`, + ]); + }); + + it('resolves the merge-base against the ref from --changed=<ref> or --base', () => { + const inline = recordingRuntime(); + run([ '--changed=upstream/main' ], inline); + expect(inline.baseRefs).toEqual([ 'upstream/main' ]); + + const separate = recordingRuntime(); + run([ '--base', 'release/1.0' ], separate); + expect(separate.baseRefs).toEqual([ 'release/1.0' ]); + expect(playwrightArgsOf(separate)).toContain(`--only-changed=${ MERGE_BASE }`); + }); + + it('runs the whole suite and names the file that forced it', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined); + const runtime = recordingRuntime({ changedFiles: [ 'src/ui/Foo.tsx', 'src/sprite/icons/arrows/east.svg' ] }); + + run([ '--changed', '--project=mobile' ], runtime); + + expect(playwrightArgsOf(runtime)).toEqual([ 'test', '-c', PLAYWRIGHT_CONFIG_FILE, '--project=mobile' ]); + expect(log).toHaveBeenCalledWith(expect.stringContaining('src/sprite/icons/arrows/east.svg')); + }); + + // The tool must not short-circuit on an empty diff: Playwright selects nothing and the caller's + // --pass-with-no-tests decides the exit code, locally and in CI alike. + it('still invokes playwright with --only-changed on an empty diff', () => { + const runtime = recordingRuntime({ changedFiles: [] }); + + run([ '--changed' ], runtime); + + expect(runtime.steps).toHaveLength(3); + expect(playwrightArgsOf(runtime)).toContain(`--only-changed=${ MERGE_BASE }`); + }); +}); diff --git a/tools/playwright/index.ts b/tools/playwright/index.ts new file mode 100644 index 00000000000..1e793f0c4e3 --- /dev/null +++ b/tools/playwright/index.ts @@ -0,0 +1,231 @@ +/* eslint-disable no-console -- this is a CLI whose entire job is to drive playwright and print to stdout */ +import { spawnSync } from 'child_process'; +import dotenv from 'dotenv'; +import fs from 'fs'; + +import type { FlagSpec } from '../cli/flags'; +import { parseArgs as parseFlags } from '../cli/flags'; +import { getChangedFiles, resolveBaseCommit } from '../code-complexity/select/diff'; +import { + DEFAULT_BASE_REF, + ENV_FILE, + ENVS_SCRIPT_FILE, + LINUX_MODULES_MARKER, + MAKE_ENVS_SCRIPT, + PLAYWRIGHT_BIN, + PLAYWRIGHT_CONFIG_FILE, + PLAYWRIGHT_NODE_OPTIONS, + SPRITE_APP_ENV, +} from './config'; +import { buildDockerCommand, buildDockerDepsCommand, resolveDockerOptions } from './docker'; +import { selectMode } from './select'; + +export interface CliOptions { + baseRef: string; + diffSelected: boolean; + docker: boolean; + dockerDeps: boolean; + playwrightArgs: Array<string>; +} + +const USAGE = `Usage: + test:pw [<playwright args>...] + Run the Playwright component tests (*.pw.tsx). Every argument the tool does not own is passed + to \`playwright test -c ${ PLAYWRIGHT_CONFIG_FILE }\` untouched — --project, --shard, -g, file + paths, --update-snapshots, --pass-with-no-tests, ... + + test:pw --changed[=<ref>] [--base <ref>] [...] + Affected mode: run only the tests reachable from the diff vs the base ref (default + ${ DEFAULT_BASE_REF }, resolved through the merge-base, so uncommitted edits count and + base-branch churn does not), via Playwright's --only-changed. A change under src/sprite/icons/**, + playwright/**, ${ PLAYWRIGHT_CONFIG_FILE } or pnpm-lock.yaml runs the whole suite instead. + + test:pw --docker [...] + Run the same command inside the Playwright image matching the installed @playwright/test, with + the Linux node_modules_linux mounted over node_modules — how CI-matching screenshots are made + on a Mac. Docker gets a terminal only when stdin is one. + + test:pw --docker-deps + Install the Linux dependencies into node_modules_linux (once, before the first --docker run). + Takes no other flag or argument. + + Before every run the tool regenerates ${ ENVS_SCRIPT_FILE } from ${ ENV_FILE } and builds the SVG + sprite for the ${ SPRITE_APP_ENV } app env. Every run writes playwright-results/report.json next + to the html (local) or blob (CI) report. The exit code is Playwright's.`; + +const FLAGS: ReadonlyMap<string, FlagSpec<CliOptions>> = new Map<string, FlagSpec<CliOptions>>([ + [ '--help', { kind: 'switch', apply: () => { + console.log(USAGE); + process.exit(0); + } } ], + [ '-h', { kind: 'switch', apply: () => { + console.log(USAGE); + process.exit(0); + } } ], + [ '--changed', { kind: 'optional', apply: (options, value) => { + options.diffSelected = true; + if (value !== undefined) options.baseRef = value; + } } ], + [ '--base', { kind: 'value', apply: (options, value) => { + options.diffSelected = true; + options.baseRef = value; + } } ], + [ '--docker', { kind: 'switch', apply: (options) => { + options.docker = true; + } } ], + [ '--docker-deps', { kind: 'switch', apply: (options) => { + options.dockerDeps = true; + } } ], +]); + +export function parseArgs(argv: ReadonlyArray<string>): CliOptions { + const { options, rest } = parseFlags<CliOptions>(argv, FLAGS, { + baseRef: DEFAULT_BASE_REF, + diffSelected: false, + docker: false, + dockerDeps: false, + playwrightArgs: [], + }, { kind: 'passthrough' }); + + options.playwrightArgs = rest; + return options; +} + +type ProcessEnv = typeof process.env; + +export interface Step { + readonly command: string; + readonly args: ReadonlyArray<string>; + readonly env: ProcessEnv; +} + +export interface BranchChanges { + readonly baseCommit: string; + readonly changedFiles: ReadonlyArray<string>; +} + +// The process boundary, injected so index.spec.ts can record the steps instead of running them. +export interface Runtime { + readonly spawn: (step: Step) => number; + readonly readFile: (file: string) => string; + readonly fileExists: (file: string) => boolean; + readonly changes: (baseRef: string) => BranchChanges; + readonly isTTY: boolean; +} + +const DEFAULT_RUNTIME: Runtime = { + spawn: (step) => { + const result = spawnSync(step.command, step.args, { stdio: 'inherit', env: step.env }); + if (result.error) throw result.error; + return result.status ?? 1; + }, + readFile: (file) => fs.readFileSync(file, 'utf8'), + fileExists: (file) => fs.existsSync(file), + changes: (baseRef) => { + const baseCommit = resolveBaseCommit(baseRef, process.cwd()); + return { baseCommit, changedFiles: getChangedFiles(baseCommit, process.cwd()) }; + }, + isTTY: process.stdin.isTTY === true, +}; + +const DOCKER_FLAG = '--docker'; + +// --docker-deps is an install, not a run: anything else on the command line has nowhere to go. +function rejectDepsCompanions(options: CliOptions): void { + const hasCompanion = options.docker || options.diffSelected || options.playwrightArgs.length > 0; + if (hasCompanion) throw new Error('--docker-deps takes no other flag or argument'); +} + +// The container runs the same command line minus --docker, so --changed and every pass-through arg +// reach the inner `pnpm test:pw` untouched. +function runInDocker(argv: ReadonlyArray<string>, options: CliOptions, runtime: Runtime): number { + /* eslint-disable-next-line no-restricted-properties -- the docker child inherits the shell env like every other child */ + const env = process.env; + const dockerOptions = resolveDockerOptions(runtime.readFile, runtime.isTTY); + + if (options.dockerDeps) { + rejectDepsCompanions(options); + return runtime.spawn({ ...buildDockerDepsCommand(dockerOptions), env }); + } + + if (!runtime.fileExists(LINUX_MODULES_MARKER)) { + console.error('Linux dependencies are missing. Install them with: pnpm test:pw --docker-deps'); + return 1; + } + return runtime.spawn({ ...buildDockerCommand(argv.filter((arg) => arg !== DOCKER_FLAG), dockerOptions), env }); +} + +// A variable already in the shell wins over the file's value, as it did under dotenv-cli. +function loadEnvFile(runtime: Runtime, shellEnv: ProcessEnv): ProcessEnv { + return { ...dotenv.parse(runtime.readFile(ENV_FILE)), ...shellEnv }; +} + +// The Playwright args --changed adds after the user's own. An empty diff still goes through +// --only-changed — Playwright then selects nothing and the caller's --pass-with-no-tests decides the +// exit code — so a local run and a CI run of the same branch behave the same. +export function selectionArgs(options: CliOptions, runtime: Runtime): Array<string> { + if (!options.diffSelected) return []; + + const { baseCommit, changedFiles } = runtime.changes(options.baseRef); + const mode = selectMode(changedFiles); + if (mode.kind === 'full') { + console.log(`Running the full suite: ${ mode.forcedBy } changed`); + return []; + } + return [ `--only-changed=${ baseCommit }` ]; +} + +// The three children in order: the envs script, the sprite, then Playwright itself. The sprite and +// Playwright run under the pw app env; the envs script does not, so envs.js keeps the app env the +// file declares. +export function buildSteps(options: CliOptions, env: ProcessEnv, extraPlaywrightArgs: ReadonlyArray<string>): Array<Step> { + const spriteEnv = { ...env, NEXT_PUBLIC_APP_ENV: SPRITE_APP_ENV }; + return [ + { command: MAKE_ENVS_SCRIPT, args: [ ENVS_SCRIPT_FILE ], env }, + { command: 'pnpm', args: [ 'svg:build-sprite' ], env: spriteEnv }, + { + command: PLAYWRIGHT_BIN, + args: [ 'test', '-c', PLAYWRIGHT_CONFIG_FILE, ...options.playwrightArgs, ...extraPlaywrightArgs ], + env: { ...spriteEnv, NODE_OPTIONS: PLAYWRIGHT_NODE_OPTIONS }, + }, + ]; +} + +export function run(argv: ReadonlyArray<string>, runtime: Runtime = DEFAULT_RUNTIME): number { + const options = parseArgs(argv); + if (options.docker || options.dockerDeps) return runInDocker(argv, options, runtime); + + const extraPlaywrightArgs = selectionArgs(options, runtime); + + /* eslint-disable-next-line no-restricted-properties -- a Node CLI forwarding its own shell env to the children it spawns */ + const env = loadEnvFile(runtime, process.env); + + // Playwright's own CT build cache invalidation has been reliable, so the unconditional delete is + // off; re-enable it if a stale CT build is ever observed. + // fs.rmSync(PLAYWRIGHT_CACHE_DIR, { recursive: true, force: true }); + + for (const step of buildSteps(options, env, extraPlaywrightArgs)) { + const status = runtime.spawn(step); + if (status !== 0) return status; + } + return 0; +} + +// run.sh always executes the compiled entry point, so that path is what marks this module as the +// process entry. The guard exists so index.spec.ts can import the module without starting a run — +// under vitest the entry is vitest's own binary. +const CLI_ENTRY_PATH = 'playwright/dist/playwright/index.js'; + +function isProcessEntryPoint(): boolean { + const entry = process.argv[1]?.replace(/\\/g, '/'); + return entry !== undefined && entry.endsWith(CLI_ENTRY_PATH); +} + +if (isProcessEntryPoint()) { + try { + process.exitCode = run(process.argv.slice(2)); + } catch (error: unknown) { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + } +} diff --git a/tools/playwright/run.sh b/tools/playwright/run.sh new file mode 100755 index 00000000000..3427391e4e0 --- /dev/null +++ b/tools/playwright/run.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +# Usage: tools/playwright/run.sh [--changed[=<ref>]] [--base <ref>] [--docker] [--docker-deps] [<playwright args>...] + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" + +# The tool imports the shared flag parser from ../cli, so tsc's rootDir spans the tools folder and +# the entry point lands one level deeper than the outDir. +"$ROOT/node_modules/.bin/tsc" -p "$DIR/tsconfig.json" +node "$DIR/dist/playwright/index.js" "$@" diff --git a/tools/playwright/select.spec.ts b/tools/playwright/select.spec.ts new file mode 100644 index 00000000000..e64bfe21a68 --- /dev/null +++ b/tools/playwright/select.spec.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest'; + +import { selectMode } from './select'; + +describe('selectMode', () => { + it('delegates to --only-changed when nothing on the force-full list changed', () => { + expect(selectMode([ 'src/ui/Foo.tsx', 'src/ui/Foo.pw.tsx' ])).toEqual({ kind: 'only-changed' }); + }); + + it('delegates to --only-changed on an empty diff', () => { + expect(selectMode([])).toEqual({ kind: 'only-changed' }); + }); + + it.each([ + [ 'an icon', 'src/sprite/icons/arrows/east.svg' ], + [ 'a harness file', 'playwright/index.html' ], + [ 'the playwright config', 'playwright-ct.config.ts' ], + [ 'the lockfile', 'pnpm-lock.yaml' ], + ])('forces a full run when %s changed', (_, file) => { + expect(selectMode([ 'src/ui/Foo.tsx', file ])).toEqual({ kind: 'full', forcedBy: file }); + }); + + // An exact-path entry must not act as a prefix, and a directory entry must not match a sibling + // that merely starts with the same characters. + it('matches exact-path entries exactly and directory entries by prefix', () => { + expect(selectMode([ 'playwright-ct.config.ts.bak', 'pnpm-lock.yaml.orig' ])).toEqual({ kind: 'only-changed' }); + expect(selectMode([ 'playwright-results/report.json' ])).toEqual({ kind: 'only-changed' }); + expect(selectMode([ 'src/sprite/iconsList.ts' ])).toEqual({ kind: 'only-changed' }); + }); + + it('names the first forcing file when several changed', () => { + expect(selectMode([ 'pnpm-lock.yaml', 'src/sprite/icons/a.svg' ])).toEqual({ kind: 'full', forcedBy: 'pnpm-lock.yaml' }); + }); +}); diff --git a/tools/playwright/select.ts b/tools/playwright/select.ts new file mode 100644 index 00000000000..11fa0b5ff5a --- /dev/null +++ b/tools/playwright/select.ts @@ -0,0 +1,17 @@ +import { FORCE_FULL_PATHS } from './config'; + +// Under --changed the tool either hands the merge-base to Playwright's --only-changed or, when a +// changed file sits outside the module graph, drops selection altogether. Paths are repo-relative, +// as `git diff --name-only` reports them. +export type SelectionMode = + { readonly kind: 'full'; readonly forcedBy: string } | + { readonly kind: 'only-changed' }; + +function isForceFull(file: string): boolean { + return FORCE_FULL_PATHS.some((entry) => entry.endsWith('/') ? file.startsWith(entry) : file === entry); +} + +export function selectMode(changedFiles: ReadonlyArray<string>): SelectionMode { + const forcedBy = changedFiles.find(isForceFull); + return forcedBy === undefined ? { kind: 'only-changed' } : { kind: 'full', forcedBy }; +} diff --git a/tools/playwright/tsconfig.json b/tools/playwright/tsconfig.json new file mode 100644 index 00000000000..20973a56264 --- /dev/null +++ b/tools/playwright/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "node16", + "target": "es2022", + "moduleResolution": "node16", + "isolatedModules": false, + "noEmit": false, + "incremental": false, + "rootDir": "..", + "outDir": "./dist" + }, + "include": [ + "./index.ts" + ], + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/tools/profiling/CONTEXT.md b/tools/profiling/CONTEXT.md index 4c6793f1643..f99c1c42912 100644 --- a/tools/profiling/CONTEXT.md +++ b/tools/profiling/CONTEXT.md @@ -7,7 +7,8 @@ long lists). | File | Role | |---|---| -| `aggregate-react-profile.mjs` | `pnpm profile:analyze <profile.json> [profileB.json]` — turns a React DevTools Profiler export into a per-component cost table (total self ms / instances / avg). With two files, also prints a delta table. | +| `aggregate.ts` | Turns a React DevTools Profiler export into a per-component cost table (total self ms / instances / avg), plus the delta between two of them. Importable — the CLI is not in here. | +| `index.ts` | CLI entry for `pnpm profile:analyze <profile.json> [profileB.json]`: argument parsing and the print calls. | ## Running a profileable build diff --git a/tools/profiling/aggregate-react-profile.mjs b/tools/profiling/aggregate-react-profile.mjs deleted file mode 100755 index 974d5bd0ecb..00000000000 --- a/tools/profiling/aggregate-react-profile.mjs +++ /dev/null @@ -1,244 +0,0 @@ -#!/usr/bin/env node -// SPDX-License-Identifier: LicenseRef-Blockscout - -/* eslint-disable no-console -- CLI tool, console output is the interface */ - -// Aggregates a React DevTools Profiler export ("Save profile..." JSON) into a per-component -// cost table: total self-render time, instance count, and average per instance. -// -// Usage: -// node tools/profiling/aggregate-react-profile.mjs <profile.json> [options] -// node tools/profiling/aggregate-react-profile.mjs <a.json> <b.json> [options] # compare mode -// -// Options: -// --commit=N commit index to analyze in the first file (default: the longest commit) -// --commit-b=N commit index in the second file (default: the longest commit) -// --top=N number of rows to print (default: 40) -// --min-ms=N only list commits >= N ms in the overview (default: 15) -// -// Compare mode prints each file's table plus a delta table (matched by component name). -// Only compare traces from the same build flavor: minified names differ across builds. -// -// See tools/profiling/CONTEXT.md for the full workflow. - -import fs from 'node:fs'; - -const TYPE_NAMES = { - '1': 'Class', '2': 'Context', '3': 'Function', '4': 'ForwardRef', '5': 'Function', - '6': 'ForwardRef', '7': 'HostComponent', '8': 'Memo', '9': 'OtherOrUnknown', - '10': 'Profiler', '11': 'Root', '12': 'Suspense', '13': 'SuspenseList', '14': 'TracingMarker', -}; -const ELEMENT_TYPE_ROOT = 11; - -function utfDecode(arr, start, length) { - let s = ''; - for (let k = 0; k < length; k++) { - s += String.fromCodePoint(arr[start + k]); - } - return s; -} - -// Replays one entry of the DevTools "operations" wire format -// (react-devtools-shared store operations; ADD records carry a trailing -// compiledWithForget flag in recent DevTools versions). -function replayOperations(operations, names) { - let i = 2; // [0]=rendererID, [1]=rootID - const stringTable = [ null ]; - const stringTableSize = operations[i++]; - const stringTableEnd = i + stringTableSize; - while (i < stringTableEnd) { - const len = operations[i++]; - stringTable.push(utfDecode(operations, i, len)); - i += len; - } - - while (i < operations.length) { - const op = operations[i]; - switch (op) { - case 1: { // ADD - const id = operations[i + 1]; - const type = operations[i + 2]; - i += 3; - if (type === ELEMENT_TYPE_ROOT) { - i += 4; // isStrictModeCompliant, profilingFlags, supportsStrictMode, hasOwnerMetadata - names.set(id, { name: '(root)', type }); - } else { - // parentID, ownerID, displayNameStringID, keyStringID, compiledWithForget - const displayNameStringID = operations[i + 2]; - i += 5; - if (displayNameStringID >= stringTable.length) { - throw new Error(`string id out of range: ${ displayNameStringID }`); - } - names.set(id, { name: stringTable[displayNameStringID] ?? 'Anonymous', type }); - } - break; - } - case 2: // REMOVE: count, ...ids - i += 2 + operations[i + 1]; - break; - case 3: // REORDER_CHILDREN: id, numChildren, ...children - i += 3 + operations[i + 2]; - break; - case 4: // UPDATE_TREE_BASE_DURATION: id, duration - i += 3; - break; - case 5: // UPDATE_ERRORS_OR_WARNINGS: id, errors, warnings - i += 4; - break; - case 6: // REMOVE_ROOT - i += 1; - break; - case 7: // SET_SUBTREE_MODE: rootID, mode - i += 3; - break; - default: - throw new Error(`unknown op ${ op } at index ${ i }`); - } - } -} - -function loadProfile(file) { - const data = JSON.parse(fs.readFileSync(file, 'utf8')); - const root = data.dataForRoots[0]; - - // fiberID -> { name, type }; operations cover everything mounted while profiling, - // snapshots fill in fibers that existed before profiling started (and still exist at the end) - const names = new Map(); - for (const [ index, ops ] of root.operations.entries()) { - try { - replayOperations(ops, names); - } catch (error) { - console.warn(`(warning: failed to parse operations[${ index }] of ${ file }: ${ error.message } — attribution may be partial)`); - } - } - for (const [ id, node ] of root.snapshots) { - if (!names.has(id)) { - const hocPrefix = node.hocDisplayNames?.length ? `${ node.hocDisplayNames.join('(') }(` : ''; - const name = hocPrefix ? `${ hocPrefix }${ node.displayName })` : (node.displayName ?? 'Anonymous'); - names.set(id, { name, type: node.type }); - } - } - - return { root, names }; -} - -function biggestCommitIndex(root) { - return root.commitData.reduce((best, c, i) => (c.duration > root.commitData[best].duration ? i : best), 0); -} - -function aggregate({ root, names }, commitIndex) { - const commit = root.commitData[commitIndex]; - const byName = new Map(); - let unknownCount = 0; - let unknownTime = 0; - let totalSelf = 0; - - for (const [ fiberId, selfMs ] of commit.fiberSelfDurations) { - totalSelf += selfMs; - const info = names.get(fiberId); - if (!info) { - unknownCount++; - unknownTime += selfMs; - continue; - } - const label = `${ info.name } (${ TYPE_NAMES[info.type] ?? info.type })`; - const entry = byName.get(label) || { total: 0, count: 0 }; - entry.total += selfMs; - entry.count += 1; - byName.set(label, entry); - } - - const rows = [ ...byName.entries() ] - .map(([ name, e ]) => ({ name, ...e, avg: e.total / e.count })) - .sort((a, b) => b.total - a.total); - - return { commit, commitIndex, rows, totalSelf, unknownCount, unknownTime }; -} - -function printCommitList(root, minMs) { - root.commitData.forEach((c, i) => { - if (c.duration >= minMs) { - console.log(` commit ${ i }: ${ c.duration.toFixed(1) }ms, ${ c.fiberSelfDurations.length } fibers, at ${ (c.timestamp / 1000).toFixed(1) }s`); - } - }); -} - -function printTable(file, result, top) { - const { commit, commitIndex, rows, totalSelf, unknownCount, unknownTime } = result; - console.log(`\n=== ${ file } — commit #${ commitIndex }: duration=${ commit.duration.toFixed(1) }ms, ` + - `fibers=${ commit.fiberSelfDurations.length }, sum(self)=${ totalSelf.toFixed(1) }ms, ` + - `effects=${ commit.effectDuration?.toFixed(1) }ms, passive=${ commit.passiveEffectDuration?.toFixed(1) }ms ===`); - if (unknownCount) { - console.log(`(unattributed: ${ unknownCount } fibers, ${ unknownTime.toFixed(1) }ms)`); - } - console.log('rank | component | total ms | % of self | instances | avg ms'); - rows.slice(0, top).forEach((r, i) => { - console.log( - String(i + 1).padStart(4) + ' | ' + - r.name.padEnd(44) + ' | ' + - r.total.toFixed(1).padStart(8) + ' | ' + - ((r.total / totalSelf) * 100).toFixed(1).padStart(6) + '% | ' + - String(r.count).padStart(6) + ' | ' + - r.avg.toFixed(3).padStart(7), - ); - }); - const shown = rows.slice(0, top).reduce((s, r) => s + r.total, 0); - console.log(`top-${ top } account for ${ shown.toFixed(1) }ms of ${ totalSelf.toFixed(1) }ms self time; ${ rows.length } component types`); -} - -function printDelta(resultA, resultB, top) { - const allNames = new Set([ ...resultA.rows.map((r) => r.name), ...resultB.rows.map((r) => r.name) ]); - const mapA = new Map(resultA.rows.map((r) => [ r.name, r ])); - const mapB = new Map(resultB.rows.map((r) => [ r.name, r ])); - - const deltas = [ ...allNames ] - .map((name) => { - const a = mapA.get(name) ?? { total: 0, count: 0 }; - const b = mapB.get(name) ?? { total: 0, count: 0 }; - return { name, a, b, delta: b.total - a.total }; - }) - .sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta)); - - console.log(`\n=== Delta (B − A): ${ (resultB.totalSelf - resultA.totalSelf).toFixed(1) }ms total self time ===`); - console.log('component | A ms (inst) | B ms (inst) | delta ms'); - deltas.slice(0, top).forEach((d) => { - console.log( - d.name.padEnd(44) + ' | ' + - `${ d.a.total.toFixed(1) } (${ d.a.count })`.padStart(14) + ' | ' + - `${ d.b.total.toFixed(1) } (${ d.b.count })`.padStart(14) + ' | ' + - (d.delta >= 0 ? '+' : '') + d.delta.toFixed(1), - ); - }); -} - -// --- CLI --- - -const args = process.argv.slice(2); -const files = args.filter((a) => !a.startsWith('--')); -const getOption = (name, fallback) => { - const raw = args.find((a) => a.startsWith(`--${ name }=`)); - return raw ? Number(raw.split('=')[1]) : fallback; -}; - -if (files.length < 1 || files.length > 2) { - console.error('Usage: node tools/profiling/aggregate-react-profile.mjs <profile.json> [profileB.json] [--commit=N] [--commit-b=N] [--top=N] [--min-ms=N]'); - process.exit(1); -} - -const top = getOption('top', 40); -const minMs = getOption('min-ms', 15); - -const profileA = loadProfile(files[0]); -console.log(`Commits >= ${ minMs }ms in ${ files[0] }:`); -printCommitList(profileA.root, minMs); -const resultA = aggregate(profileA, getOption('commit', biggestCommitIndex(profileA.root))); -printTable(files[0], resultA, top); - -if (files[1]) { - const profileB = loadProfile(files[1]); - console.log(`\nCommits >= ${ minMs }ms in ${ files[1] }:`); - printCommitList(profileB.root, minMs); - const resultB = aggregate(profileB, getOption('commit-b', biggestCommitIndex(profileB.root))); - printTable(files[1], resultB, top); - printDelta(resultA, resultB, top); -} diff --git a/tools/profiling/aggregate.spec.ts b/tools/profiling/aggregate.spec.ts new file mode 100644 index 00000000000..67cdc446eda --- /dev/null +++ b/tools/profiling/aggregate.spec.ts @@ -0,0 +1,387 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { describe, it, expect, vi, afterEach } from 'vitest'; + +import type { AggregateResult, CommitData, FiberNames, ProfileExport, RootData, SnapshotNode } from './aggregate'; +import { + replayOperations, + loadProfile, + biggestCommitIndex, + aggregate, + printCommitList, + printTable, + printDelta, +} from './aggregate'; + +// --- Hand-built wire-format fixtures ------------------------------------------------------------ +// +// Deliberately not a real DevTools export: an export pins the fixture to one DevTools version, and +// the wire format is exactly what is under test. The record layouts below mirror +// react-devtools-shared's store operations — keep them in step with the parser's op codes and operand notes. + +const RENDERER_ID = 1; +const ROOT_ID = 1; +const ELEMENT_TYPE_ROOT = 11; +const ELEMENT_TYPE_FUNCTION = 5; +const ELEMENT_TYPE_MEMO = 8; + +function encodeString(value: string): Array<number> { + const points = [ ...value ].map((char) => char.codePointAt(0) ?? 0); + return [ points.length, ...points ]; +} + +// The string table is length-prefixed with the number of ints it occupies, not the number of strings. +function stringTable(strings: ReadonlyArray<string>): Array<number> { + const encoded = strings.flatMap(encodeString); + return [ encoded.length, ...encoded ]; +} + +function addRoot(id: number): Array<number> { + return [ 1, id, ELEMENT_TYPE_ROOT, 1, 0, 1, 0 ]; +} + +function addElement(id: number, type: number, displayNameStringID: number): Array<number> { + return [ 1, id, type, ROOT_ID, 0, displayNameStringID, 0, 0 ]; +} + +const removeRecord = (...ids: Array<number>): Array<number> => [ 2, ids.length, ...ids ]; +const reorderChildren = (id: number, ...children: Array<number>): Array<number> => [ 3, id, children.length, ...children ]; +const updateTreeBaseDuration = (id: number, duration: number): Array<number> => [ 4, id, duration ]; +const updateErrorsOrWarnings = (id: number, errors: number, warnings: number): Array<number> => [ 5, id, errors, warnings ]; +const removeRootRecord = (): Array<number> => [ 6 ]; +const setSubtreeMode = (mode: number): Array<number> => [ 7, ROOT_ID, mode ]; + +function operations(strings: ReadonlyArray<string>, ...records: Array<Array<number>>): Array<number> { + return [ RENDERER_ID, ROOT_ID, ...stringTable(strings), ...records.flat() ]; +} + +function snapshot(id: number, node: Partial<SnapshotNode>): readonly [ number, SnapshotNode ] { + return [ id, { displayName: null, type: ELEMENT_TYPE_FUNCTION, ...node } ]; +} + +function commitOf( + duration: number, + fiberSelfDurations: ReadonlyArray<readonly [ number, number ]>, + extra: Partial<CommitData> = {}, +): CommitData { + return { duration, timestamp: 0, effectDuration: 0, passiveEffectDuration: 0, fiberSelfDurations, ...extra }; +} + +function rootOf(root: Partial<RootData>): RootData { + return { operations: [], snapshots: [], commitData: [], ...root }; +} + +function withProfileFile(profile: ProfileExport, run: (file: string) => void): void { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'profile-analyze-spec-')); + const file = path.join(directory, 'profile.json'); + try { + fs.writeFileSync(file, JSON.stringify(profile)); + run(file); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +function capturedLines(spy: { mock: { calls: Array<Array<unknown>> } }): Array<string> { + return spy.mock.calls.map((call) => String(call[0])); +} + +// Splits a padded table row into its trimmed cells, so an assertion states the column contents +// without restating every pad width. +function cells(line: string): Array<string> { + return line.split('|').map((cell) => cell.trim()); +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('replayOperations', () => { + it('decodes the string table and names an element by its display-name string id', () => { + const names: FiberNames = new Map(); + replayOperations(operations([ 'AddressTable', 'Row' ], addElement(4, ELEMENT_TYPE_FUNCTION, 2)), names); + expect(names.get(4)).toEqual({ name: 'Row', type: ELEMENT_TYPE_FUNCTION }); + }); + + it('decodes multi-byte code points in the string table', () => { + const names: FiberNames = new Map(); + replayOperations(operations([ 'Σum' ], addElement(4, ELEMENT_TYPE_FUNCTION, 1)), names); + expect(names.get(4)?.name).toBe('Σum'); + }); + + it('names a root record "(root)" and consumes its four extra fields', () => { + const names: FiberNames = new Map(); + replayOperations(operations([ 'Row' ], addRoot(ROOT_ID), addElement(4, ELEMENT_TYPE_MEMO, 1)), names); + expect(names.get(ROOT_ID)).toEqual({ name: '(root)', type: ELEMENT_TYPE_ROOT }); + expect(names.get(4)).toEqual({ name: 'Row', type: ELEMENT_TYPE_MEMO }); + }); + + // String id 0 is the table's reserved null slot — an element DevTools could not name. + it('falls back to "Anonymous" for string id 0', () => { + const names: FiberNames = new Map(); + replayOperations(operations([ 'Row' ], addElement(4, ELEMENT_TYPE_FUNCTION, 0)), names); + expect(names.get(4)?.name).toBe('Anonymous'); + }); + + // Id 2 is the first past the end of a one-string table (index 0 is the null placeholder). + it('throws on the first string id past the end of the table', () => { + expect(() => replayOperations(operations([ 'Row' ], addElement(4, ELEMENT_TYPE_FUNCTION, 2)), new Map())) + .toThrow('string id out of range: 2'); + }); + + it('throws on an unknown op code, naming the index it stalled at', () => { + expect(() => replayOperations(operations([ 'Row' ], [ 42, 0, 0 ]), new Map())) + .toThrow(/unknown op 42 at index \d+/); + }); + + // Each of these records is skipped by width alone; getting the arithmetic wrong desynchronises the + // walk, so the check is that the ADD that follows still lands. Operand values are kept above the op-code + // range, so a walk that lands mid-record cannot read one of them as a valid op and resynchronise. + const SKIPPED: ReadonlyArray<readonly [ string, Array<number> ]> = [ + [ 'REMOVE', removeRecord(7, 8, 9) ], + [ 'REORDER_CHILDREN', reorderChildren(2, 30, 31, 32) ], + [ 'UPDATE_TREE_BASE_DURATION', updateTreeBaseDuration(2, 12) ], + [ 'UPDATE_ERRORS_OR_WARNINGS', updateErrorsOrWarnings(2, 30, 31) ], + [ 'REMOVE_ROOT', removeRootRecord() ], + [ 'SET_SUBTREE_MODE', setSubtreeMode(1) ], + ]; + + it.each(SKIPPED)('advances past a %s record to the next ADD', (_label, record) => { + const names: FiberNames = new Map(); + replayOperations(operations([ 'Row' ], record, addElement(20, ELEMENT_TYPE_FUNCTION, 1)), names); + expect(names.get(20)).toEqual({ name: 'Row', type: ELEMENT_TYPE_FUNCTION }); + }); + + it('accumulates names across entries into the same map', () => { + const names: FiberNames = new Map(); + replayOperations(operations([ 'Row' ], addElement(4, ELEMENT_TYPE_FUNCTION, 1)), names); + replayOperations(operations([ 'Cell' ], addElement(5, ELEMENT_TYPE_FUNCTION, 1)), names); + expect([ ...names.keys() ]).toEqual([ 4, 5 ]); + }); +}); + +describe('loadProfile', () => { + it('names fibers from the operations replay', () => { + withProfileFile({ dataForRoots: [ rootOf({ + operations: [ operations([ 'Row' ], addRoot(ROOT_ID), addElement(4, ELEMENT_TYPE_FUNCTION, 1)) ], + }) ] }, (file) => { + expect(loadProfile(file).names.get(4)).toEqual({ name: 'Row', type: ELEMENT_TYPE_FUNCTION }); + }); + }); + + // Fibers unmounted mid-session are only nameable through the replay, so the replay wins and + // snapshots only fill the gaps. + it('takes snapshots only for fibers the replay did not name', () => { + withProfileFile({ dataForRoots: [ rootOf({ + operations: [ operations([ 'Row' ], addElement(4, ELEMENT_TYPE_FUNCTION, 1)) ], + snapshots: [ snapshot(4, { displayName: 'Stale' }), snapshot(9, { displayName: 'Preexisting', type: ELEMENT_TYPE_MEMO }) ], + }) ] }, (file) => { + const { names } = loadProfile(file); + expect(names.get(4)?.name).toBe('Row'); + expect(names.get(9)).toEqual({ name: 'Preexisting', type: ELEMENT_TYPE_MEMO }); + }); + }); + + it('wraps a snapshot display name in its HOC display names', () => { + withProfileFile({ dataForRoots: [ rootOf({ + snapshots: [ snapshot(9, { displayName: 'Table', hocDisplayNames: [ 'Memo', 'ForwardRef' ] }) ], + }) ] }, (file) => { + expect(loadProfile(file).names.get(9)?.name).toBe('Memo(ForwardRef(Table)'); + }); + }); + + it('falls back to "Anonymous" for a snapshot with no display name and no HOCs', () => { + withProfileFile({ dataForRoots: [ rootOf({ + snapshots: [ snapshot(9, { displayName: null, hocDisplayNames: [] }) ], + }) ] }, (file) => { + expect(loadProfile(file).names.get(9)?.name).toBe('Anonymous'); + }); + }); + + // Format drift must degrade to partial attribution, never fail the run. + it('warns naming the entry index and the file, and keeps the entries that parsed', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + withProfileFile({ dataForRoots: [ rootOf({ + operations: [ + operations([ 'Row' ], [ 42, 0, 0 ]), + operations([ 'Cell' ], addElement(5, ELEMENT_TYPE_FUNCTION, 1)), + ], + }) ] }, (file) => { + const { names } = loadProfile(file); + expect(names.get(5)?.name).toBe('Cell'); + expect(warn).toHaveBeenCalledTimes(1); + const message = String(warn.mock.calls[0][0]); + expect(message).toContain('operations[0]'); + expect(message).toContain(file); + expect(message).toContain('unknown op 42'); + expect(message).toContain('attribution may be partial'); + }); + }); +}); + +describe('biggestCommitIndex', () => { + it('picks the longest commit', () => { + expect(biggestCommitIndex(rootOf({ commitData: [ commitOf(5, []), commitOf(31, []), commitOf(12, []) ] }))).toBe(1); + }); + + it('keeps the earlier commit when durations tie', () => { + expect(biggestCommitIndex(rootOf({ commitData: [ commitOf(9, []), commitOf(9, []) ] }))).toBe(0); + }); +}); + +describe('aggregate', () => { + const names: FiberNames = new Map([ + [ 1, { name: 'Table', type: ELEMENT_TYPE_FUNCTION } ], + [ 2, { name: 'Row', type: ELEMENT_TYPE_MEMO } ], + [ 3, { name: 'Row', type: ELEMENT_TYPE_MEMO } ], + [ 4, { name: 'Odd', type: 99 } ], + ]); + + const root = rootOf({ commitData: [ + commitOf(4, [ [ 1, 4 ] ]), + commitOf(20, [ [ 1, 2 ], [ 2, 5 ], [ 3, 3 ], [ 4, 1 ], [ 77, 0.5 ] ]), + ] }); + + it('groups instances of one component into a single row with a total, count and average', () => { + const { rows } = aggregate({ root, names }, 1); + expect(rows[0]).toEqual({ name: 'Row (Memo)', total: 8, count: 2, avg: 4 }); + }); + + it('sorts rows by total self time, descending', () => { + expect(aggregate({ root, names }, 1).rows.map((r) => r.name)) + .toEqual([ 'Row (Memo)', 'Table (Function)', 'Odd (99)' ]); + }); + + it('labels an element type it has no name for with the raw type number', () => { + expect(aggregate({ root, names }, 1).rows.map((r) => r.name)).toContain('Odd (99)'); + }); + + it('accounts fibers with no name as unattributed rather than dropping their time', () => { + const result = aggregate({ root, names }, 1); + expect(result.unknownCount).toBe(1); + expect(result.unknownTime).toBe(0.5); + expect(result.totalSelf).toBe(11.5); + }); + + it('reports the commit it was pointed at', () => { + const result = aggregate({ root, names }, 0); + expect(result.commitIndex).toBe(0); + expect(result.commit).toBe(root.commitData[0]); + expect(result.rows).toEqual([ { name: 'Table (Function)', total: 4, count: 1, avg: 4 } ]); + }); +}); + +describe('printCommitList', () => { + it('lists only commits at or above the minimum, with their fiber count and second offset', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + printCommitList(rootOf({ commitData: [ + commitOf(4.44, [ [ 1, 1 ] ], { timestamp: 1000 }), + commitOf(15, [ [ 1, 1 ], [ 2, 1 ] ], { timestamp: 2500 }), + commitOf(31.25, [ [ 1, 1 ] ], { timestamp: 9000 }), + ] }), 15); + expect(capturedLines(log)).toEqual([ + ' commit 1: 15.0ms, 2 fibers, at 2.5s', + ' commit 2: 31.3ms, 1 fibers, at 9.0s', + ]); + }); +}); + +const PRINT_RESULT: AggregateResult = { + commit: commitOf(12.34, [ [ 1, 8 ], [ 2, 2 ], [ 3, 0.5 ] ], { effectDuration: 1.5, passiveEffectDuration: 2.5 }), + commitIndex: 3, + rows: [ + { name: 'Table (Function)', total: 8, count: 2, avg: 4 }, + { name: 'Row (Memo)', total: 2, count: 4, avg: 0.5 }, + ], + totalSelf: 10, + unknownCount: 1, + unknownTime: 0.5, +}; + +describe('printTable', () => { + it('heads the table with the commit index, duration, fiber count and effect totals', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + printTable('a.json', PRINT_RESULT, 40); + expect(capturedLines(log)[0]).toBe( + '\n=== a.json — commit #3: duration=12.3ms, fibers=3, sum(self)=10.0ms, effects=1.5ms, passive=2.5ms ===', + ); + }); + + it('reports the unattributed fibers under the header', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + printTable('a.json', PRINT_RESULT, 40); + expect(capturedLines(log)[1]).toBe('(unattributed: 1 fibers, 0.5ms)'); + }); + + it('omits the unattributed line when everything was attributed', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + printTable('a.json', { ...PRINT_RESULT, unknownCount: 0, unknownTime: 0 }, 40); + expect(capturedLines(log)[1]).toBe('rank | component | total ms | % of self | instances | avg ms'); + }); + + it('ranks each row with its share of self time, instance count and average', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + printTable('a.json', PRINT_RESULT, 40); + const lines = capturedLines(log); + expect(cells(lines[3])).toEqual([ '1', 'Table (Function)', '8.0', '80.0%', '2', '4.000' ]); + expect(cells(lines[4])).toEqual([ '2', 'Row (Memo)', '2.0', '20.0%', '4', '0.500' ]); + }); + + it('prints at most `top` rows and totals only those in the summary', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + printTable('a.json', PRINT_RESULT, 1); + const lines = capturedLines(log); + expect(cells(lines[3])[1]).toBe('Table (Function)'); + expect(lines[4]).toBe('top-1 account for 8.0ms of 10.0ms self time; 2 component types'); + }); +}); + +describe('printDelta', () => { + const resultB: AggregateResult = { + ...PRINT_RESULT, + rows: [ + { name: 'Row (Memo)', total: 9, count: 4, avg: 2.25 }, + { name: 'Table (Function)', total: 7, count: 2, avg: 3.5 }, + ], + totalSelf: 16, + }; + + it('heads the delta with the change in total self time', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + printDelta(PRINT_RESULT, resultB, 40); + expect(capturedLines(log)[0]).toBe('\n=== Delta (B − A): 6.0ms total self time ==='); + }); + + it('ranks components by the size of the change, signing each delta', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + printDelta(PRINT_RESULT, resultB, 40); + const lines = capturedLines(log); + expect(cells(lines[2])).toEqual([ 'Row (Memo)', '2.0 (4)', '9.0 (4)', '+7.0' ]); + expect(cells(lines[3])).toEqual([ 'Table (Function)', '8.0 (2)', '7.0 (2)', '-1.0' ]); + }); + + it('scores a component present on only one side against zero', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + printDelta( + { ...PRINT_RESULT, rows: [] }, + { ...resultB, rows: [ { name: 'Row (Memo)', total: 9, count: 4, avg: 2.25 } ] }, + 40, + ); + expect(cells(capturedLines(log)[2])).toEqual([ 'Row (Memo)', '0.0 (0)', '9.0 (4)', '+9.0' ]); + }); + + it('signs an unchanged component with a plus', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + const unchanged = [ { name: 'Row (Memo)', total: 2, count: 4, avg: 0.5 } ]; + printDelta({ ...PRINT_RESULT, rows: unchanged }, { ...resultB, rows: unchanged }, 40); + expect(cells(capturedLines(log)[2])).toEqual([ 'Row (Memo)', '2.0 (4)', '2.0 (4)', '+0.0' ]); + }); + + it('prints at most `top` rows', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + printDelta(PRINT_RESULT, resultB, 1); + expect(capturedLines(log)).toHaveLength(3); + }); +}); diff --git a/tools/profiling/aggregate.ts b/tools/profiling/aggregate.ts new file mode 100644 index 00000000000..86b705724d3 --- /dev/null +++ b/tools/profiling/aggregate.ts @@ -0,0 +1,278 @@ +/* eslint-disable no-console -- CLI tool, console output is the interface */ +import fs from 'fs'; + +// Aggregates a React DevTools Profiler export ("Save profile..." JSON) into a per-component cost +// table: total self-render time, instance count, and average per instance. With two profiles the +// caller also gets a delta table matched by component name. +// +// Argument parsing and the print calls live in ./index.ts, so everything here can be imported by the +// specs without executing a run. +// +// See tools/profiling/CONTEXT.md for the full workflow and the wire-format gotchas. + +const TYPE_NAMES: Record<number, string | undefined> = { + '1': 'Class', '2': 'Context', '3': 'Function', '4': 'ForwardRef', '5': 'Function', + '6': 'ForwardRef', '7': 'HostComponent', '8': 'Memo', '9': 'OtherOrUnknown', + '10': 'Profiler', '11': 'Root', '12': 'Suspense', '13': 'SuspenseList', '14': 'TracingMarker', +}; +const ELEMENT_TYPE_ROOT = 11; + +const OP_ADD = 1; +const OP_REMOVE = 2; +const OP_REORDER_CHILDREN = 3; +const OP_UPDATE_TREE_BASE_DURATION = 4; +const OP_UPDATE_ERRORS_OR_WARNINGS = 5; +const OP_REMOVE_ROOT = 6; +const OP_SET_SUBTREE_MODE = 7; + +export interface SnapshotNode { + readonly displayName: string | null; + readonly type: number; + readonly hocDisplayNames?: ReadonlyArray<string> | null; +} + +export interface CommitData { + readonly duration: number; + readonly timestamp: number; + readonly effectDuration?: number | null; + readonly passiveEffectDuration?: number | null; + // [ fiberID, self render duration in ms ] + readonly fiberSelfDurations: ReadonlyArray<readonly [ number, number ]>; +} + +export interface RootData { + // one flat op-code array per commit — see replayOperations + readonly operations: ReadonlyArray<ReadonlyArray<number>>; + // the final tree, serialized from a Map + readonly snapshots: ReadonlyArray<readonly [ number, SnapshotNode ]>; + readonly commitData: ReadonlyArray<CommitData>; +} + +export interface ProfileExport { + readonly dataForRoots: ReadonlyArray<RootData>; +} + +export interface FiberInfo { + readonly name: string; + readonly type: number; +} + +export type FiberNames = Map<number, FiberInfo>; + +export interface Profile { + readonly root: RootData; + readonly names: FiberNames; +} + +export interface ComponentRow { + readonly name: string; + readonly total: number; + readonly count: number; + readonly avg: number; +} + +export interface AggregateResult { + readonly commit: CommitData; + readonly commitIndex: number; + readonly rows: ReadonlyArray<ComponentRow>; + readonly totalSelf: number; + readonly unknownCount: number; + readonly unknownTime: number; +} + +function utfDecode(arr: ReadonlyArray<number>, start: number, length: number): string { + let s = ''; + for (let k = 0; k < length; k++) { + s += String.fromCodePoint(arr[start + k]); + } + return s; +} + +// ADD: id, type, then either the four root-only fields (isStrictModeCompliant, profilingFlags, +// supportsStrictMode, hasOwnerMetadata) or parentID, ownerID, displayNameStringID, keyStringID and +// the trailing compiledWithForget flag recent DevTools versions carry. Returns the next index. +function replayAdd( + operations: ReadonlyArray<number>, + i: number, + stringTable: ReadonlyArray<string | null>, + names: FiberNames, +): number { + const id = operations[i + 1]; + const type = operations[i + 2]; + + if (type === ELEMENT_TYPE_ROOT) { + names.set(id, { name: '(root)', type }); + return i + 7; + } + + const displayNameStringID = operations[i + 5]; + if (displayNameStringID >= stringTable.length) { + throw new Error(`string id out of range: ${ displayNameStringID }`); + } + names.set(id, { name: stringTable[displayNameStringID] ?? 'Anonymous', type }); + return i + 8; +} + +// Replays one entry of the DevTools "operations" wire format +// (react-devtools-shared store operations). +export function replayOperations(operations: ReadonlyArray<number>, names: FiberNames): void { + let i = 2; // [0]=rendererID, [1]=rootID + const stringTable: Array<string | null> = [ null ]; + const stringTableSize = operations[i++]; + const stringTableEnd = i + stringTableSize; + while (i < stringTableEnd) { + const len = operations[i++]; + stringTable.push(utfDecode(operations, i, len)); + i += len; + } + + while (i < operations.length) { + const op = operations[i]; + switch (op) { + case OP_ADD: + i = replayAdd(operations, i, stringTable, names); + break; + case OP_REMOVE: // operands: count, ...ids + i += 2 + operations[i + 1]; + break; + case OP_REORDER_CHILDREN: // operands: id, numChildren, ...children + i += 3 + operations[i + 2]; + break; + case OP_UPDATE_TREE_BASE_DURATION: // operands: id, duration + i += 3; + break; + case OP_UPDATE_ERRORS_OR_WARNINGS: // operands: id, errors, warnings + i += 4; + break; + case OP_REMOVE_ROOT: + i += 1; + break; + case OP_SET_SUBTREE_MODE: // operands: rootID, mode + i += 3; + break; + default: + throw new Error(`unknown op ${ op } at index ${ i }`); + } + } +} + +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function snapshotName(node: SnapshotNode): string { + const hocPrefix = node.hocDisplayNames?.length ? `${ node.hocDisplayNames.join('(') }(` : ''; + return hocPrefix ? `${ hocPrefix }${ node.displayName })` : (node.displayName ?? 'Anonymous'); +} + +export function loadProfile(file: string): Profile { + const data = JSON.parse(fs.readFileSync(file, 'utf8')) as ProfileExport; + const root = data.dataForRoots[0]; + + // fiberID -> { name, type }; operations cover everything mounted while profiling, + // snapshots fill in fibers that existed before profiling started (and still exist at the end) + const names: FiberNames = new Map(); + for (const [ index, ops ] of root.operations.entries()) { + try { + replayOperations(ops, names); + } catch (error) { + console.warn(`(warning: failed to parse operations[${ index }] of ${ file }: ${ messageOf(error) } — attribution may be partial)`); + } + } + for (const [ id, node ] of root.snapshots) { + if (!names.has(id)) { + names.set(id, { name: snapshotName(node), type: node.type }); + } + } + + return { root, names }; +} + +export function biggestCommitIndex(root: RootData): number { + return root.commitData.reduce((best, c, i) => (c.duration > root.commitData[best].duration ? i : best), 0); +} + +export function aggregate({ root, names }: Profile, commitIndex: number): AggregateResult { + const commit = root.commitData[commitIndex]; + const byName = new Map<string, { total: number; count: number }>(); + let unknownCount = 0; + let unknownTime = 0; + let totalSelf = 0; + + for (const [ fiberId, selfMs ] of commit.fiberSelfDurations) { + totalSelf += selfMs; + const info = names.get(fiberId); + if (!info) { + unknownCount++; + unknownTime += selfMs; + continue; + } + const label = `${ info.name } (${ TYPE_NAMES[info.type] ?? info.type })`; + const entry = byName.get(label) || { total: 0, count: 0 }; + entry.total += selfMs; + entry.count += 1; + byName.set(label, entry); + } + + const rows = [ ...byName.entries() ] + .map(([ name, e ]) => ({ name, ...e, avg: e.total / e.count })) + .sort((a, b) => b.total - a.total); + + return { commit, commitIndex, rows, totalSelf, unknownCount, unknownTime }; +} + +export function printCommitList(root: RootData, minMs: number): void { + root.commitData.forEach((c, i) => { + if (c.duration >= minMs) { + console.log(` commit ${ i }: ${ c.duration.toFixed(1) }ms, ${ c.fiberSelfDurations.length } fibers, at ${ (c.timestamp / 1000).toFixed(1) }s`); + } + }); +} + +export function printTable(file: string, result: AggregateResult, top: number): void { + const { commit, commitIndex, rows, totalSelf, unknownCount, unknownTime } = result; + console.log(`\n=== ${ file } — commit #${ commitIndex }: duration=${ commit.duration.toFixed(1) }ms, ` + + `fibers=${ commit.fiberSelfDurations.length }, sum(self)=${ totalSelf.toFixed(1) }ms, ` + + `effects=${ commit.effectDuration?.toFixed(1) }ms, passive=${ commit.passiveEffectDuration?.toFixed(1) }ms ===`); + if (unknownCount) { + console.log(`(unattributed: ${ unknownCount } fibers, ${ unknownTime.toFixed(1) }ms)`); + } + console.log('rank | component | total ms | % of self | instances | avg ms'); + rows.slice(0, top).forEach((r, i) => { + console.log( + String(i + 1).padStart(4) + ' | ' + + r.name.padEnd(44) + ' | ' + + r.total.toFixed(1).padStart(8) + ' | ' + + ((r.total / totalSelf) * 100).toFixed(1).padStart(6) + '% | ' + + String(r.count).padStart(6) + ' | ' + + r.avg.toFixed(3).padStart(7), + ); + }); + const shown = rows.slice(0, top).reduce((s, r) => s + r.total, 0); + console.log(`top-${ top } account for ${ shown.toFixed(1) }ms of ${ totalSelf.toFixed(1) }ms self time; ${ rows.length } component types`); +} + +export function printDelta(resultA: AggregateResult, resultB: AggregateResult, top: number): void { + const allNames = new Set([ ...resultA.rows.map((r) => r.name), ...resultB.rows.map((r) => r.name) ]); + const mapA = new Map(resultA.rows.map((r) => [ r.name, r ])); + const mapB = new Map(resultB.rows.map((r) => [ r.name, r ])); + + const deltas = [ ...allNames ] + .map((name) => { + const a = mapA.get(name) ?? { total: 0, count: 0 }; + const b = mapB.get(name) ?? { total: 0, count: 0 }; + return { name, a, b, delta: b.total - a.total }; + }) + .sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta)); + + console.log(`\n=== Delta (B − A): ${ (resultB.totalSelf - resultA.totalSelf).toFixed(1) }ms total self time ===`); + console.log('component | A ms (inst) | B ms (inst) | delta ms'); + deltas.slice(0, top).forEach((d) => { + console.log( + d.name.padEnd(44) + ' | ' + + `${ d.a.total.toFixed(1) } (${ d.a.count })`.padStart(14) + ' | ' + + `${ d.b.total.toFixed(1) } (${ d.b.count })`.padStart(14) + ' | ' + + (d.delta >= 0 ? '+' : '') + d.delta.toFixed(1), + ); + }); +} diff --git a/tools/profiling/index.ts b/tools/profiling/index.ts new file mode 100644 index 00000000000..16b66ec9ea8 --- /dev/null +++ b/tools/profiling/index.ts @@ -0,0 +1,46 @@ +/* eslint-disable no-console -- CLI tool, console output is the interface */ +import type { AggregateResult } from './aggregate'; +import { aggregate, biggestCommitIndex, loadProfile, printCommitList, printDelta, printTable } from './aggregate'; + +// CLI entry for the React DevTools profile aggregator. Everything worth a test lives in +// ./aggregate.ts; this file only parses arguments and calls the printers. +// +// See tools/profiling/CONTEXT.md for the full workflow. + +const USAGE = 'Usage: pnpm profile:analyze <profile.json> [profileB.json] [--commit=N] [--commit-b=N] [--top=N] [--min-ms=N]'; +const DEFAULT_TOP = 40; +const DEFAULT_MIN_MS = 15; + +const args = process.argv.slice(2); +const files = args.filter((a) => !a.startsWith('--')); + +function getOption(name: string, fallback: number): number { + const raw = args.find((a) => a.startsWith(`--${ name }=`)); + return raw ? Number(raw.split('=')[1]) : fallback; +} + +if (files.length < 1 || files.length > 2) { + console.error(USAGE); + process.exit(1); +} + +const top = getOption('top', DEFAULT_TOP); +const minMs = getOption('min-ms', DEFAULT_MIN_MS); + +// Loading comes first so any wire-format warning lands ahead of the file's commit list, the way it +// reads as a preamble to that file's numbers. +function analyze(file: string, commitOption: string, heading: string): AggregateResult { + const profile = loadProfile(file); + console.log(heading); + printCommitList(profile.root, minMs); + const result = aggregate(profile, getOption(commitOption, biggestCommitIndex(profile.root))); + printTable(file, result, top); + return result; +} + +const resultA = analyze(files[0], 'commit', `Commits >= ${ minMs }ms in ${ files[0] }:`); + +if (files[1]) { + const resultB = analyze(files[1], 'commit-b', `\nCommits >= ${ minMs }ms in ${ files[1] }:`); + printDelta(resultA, resultB, top); +} diff --git a/tools/profiling/run.sh b/tools/profiling/run.sh new file mode 100755 index 00000000000..4f224464d57 --- /dev/null +++ b/tools/profiling/run.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# Compile-on-run wrapper for the React profile aggregator. +# Resolves its own location, so it can be called from any working directory. +# +# Usage: tools/profiling/run.sh <profile.json> [profileB.json] [--commit=N] [--commit-b=N] [--top=N] [--min-ms=N] + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" + +# Use the repo-local TypeScript so the wrapper is self-contained (no global tsc needed). +"$ROOT/node_modules/.bin/tsc" -p "$DIR/tsconfig.json" +node "$DIR/dist/index.js" "$@" diff --git a/tools/profiling/tsconfig.json b/tools/profiling/tsconfig.json new file mode 100644 index 00000000000..63b509307f8 --- /dev/null +++ b/tools/profiling/tsconfig.json @@ -0,0 +1,22 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "node16", + "target": "es2022", + "moduleResolution": "node16", + "resolveJsonModule": false, + "isolatedModules": false, + "noEmit": false, + // Disable incremental (inherited from the root config): dist/ is git-ignored and compiled on + // demand, so a stale .tsbuildinfo must never short-circuit the emit. + "incremental": false, + "rootDir": ".", + "outDir": "./dist" + }, + "include": [ + "./index.ts" + ], + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/tools/react-doctor/CONTEXT.md b/tools/react-doctor/CONTEXT.md new file mode 100644 index 00000000000..1c802659a65 --- /dev/null +++ b/tools/react-doctor/CONTEXT.md @@ -0,0 +1,35 @@ +# React Doctor gate + +[React Doctor](https://www.react.doctor/docs) catches React bugs ESLint does not. The rule set is `doctor.config.json` at the repo root. + +The gate runs on pull requests only and reports only what the branch introduces. The existing +backlog is not gated; a full scan (`pnpm lint:react-doctor`) lists it. + +| Question | Answer | +|---|---| +| What would CI say about my branch? | `pnpm lint:react-doctor --scope changed --base origin/main` | +| Why did this rule fire here? | `pnpm lint:react-doctor why path/to/file.tsx:42` | +| What does a rule mean? | `https://www.react.doctor/docs/rules/react-doctor/<rule-name>` | +| Was this rule already tried? | `docs/REJECTED_RULES.md` | +| The finding is wrong. | `// react-doctor-disable-next-line react-doctor/<rule-name>` plus the reason on the same comment | + +## Constraints + +- **The config is an allowlist.** Every category is off and each rule is enabled by name at `error`, + with warnings hidden. The tool is pre-1.0 and adds or retunes rules in most releases; with an + allowlist a version bump cannot fail a PR through a rule nobody reviewed. Do not turn a category on. +- **A rule joins the allowlist only after reading its hits from a full scan.** With every category + off, a candidate shows nothing until it is named: add it at `error` in `doctor.config.json`, run + `pnpm lint:react-doctor`, read the hits, then keep it or remove it and add a row to + `docs/REJECTED_RULES.md`, so the same rule is not re-tried blind. +- **This directory is its own pnpm project, outside the root workspace.** Inside the workspace, + react-doctor's `jiti` and `lightningcss` become optional peers of eslint, vite and webpack and + re-key about 1,500 lines of the root lockfile. `run.sh` installs from the local lockfile on + each run, so the root `pnpm install` never pulls it. +- **Keep the version exact and bump it by hand**: edit `package.json`, run `pnpm install` in this + directory, then run a full scan and compare the findings before committing. +- **The root `react-doctor` package script is the mute switch for the agent install hint.** Without a + script by that name, a scan run from an agent session ends with "React Doctor is not installed in + this project", and the agent reports the gate as not run. Keep the alias beside `lint:react-doctor`. +- **Nothing leaves the machine.** The config and `run.sh` switch off the score API, telemetry, share + links and the Socket.dev supply-chain scan. Keep them off. diff --git a/tools/react-doctor/docs/REJECTED_RULES.md b/tools/react-doctor/docs/REJECTED_RULES.md new file mode 100644 index 00000000000..d4412925658 --- /dev/null +++ b/tools/react-doctor/docs/REJECTED_RULES.md @@ -0,0 +1,27 @@ +# Rejected rules + +Rules that were tried against a full scan and kept out of the allowlist in `doctor.config.json`. +Check here before proposing a rule; add a row when a trial ends in a rejection. To revisit one, +re-run the trial on the current version — a rule rejected for false positives may have been fixed. + +Hits are from the full scan at the version named. + +| Rule | Version | Hits | Why rejected | +|---|---|---|---| +| `effect-needs-cleanup` | 0.9.14 | 8 | False positives: fires on a state setter named `setInterval`, and on the socket `.on` subscription whose cleanup it does not recognise. | +| `public-env-secret-name` | 0.9.14 | 12 | False positives: reads "TOKEN" in `NEXT_PUBLIC_*` names as a credential; here it means a crypto token. | +| `rendering-conditional-render` | 0.9.13 | 4 | Matches on variable names (`*Count`, `*Total`, `length`…) with no type information: 3 of 4 hits were objects or strings, and numbers under other names were missed. Replaced by the type-aware ESLint rule `@eslint-react/no-leaked-conditional-rendering`. | +| `no-unguarded-browser-global-in-render-or-hook-init` | 0.9.13 | 9 | Cannot see which components sit behind `ssr: false` or render only after an interaction; all hits were safe. A real one fails loudly with `window is not defined` on first load. | +| `no-hydration-branch-on-browser-global` | 0.9.14 | 5 | False positives: all hits are `multichainConfig()`, which reads the same startup-generated config on server and client, so the branch cannot differ at hydration. The rule cannot tell such an isomorphic accessor from a real branch. | +| `no-ref-current-in-render` | 0.9.14 | 11 | Clashes with an established pattern: the latest-ref hooks assign `ref.current` during render on purpose. | +| `no-inline-hoc-on-component` | 0.9.13 | 4 | Clashes with an established pattern: `chakra(() => …)`. | +| `no-derived-useState` | 0.9.13 | 3 | `useState(prop)` as a deliberate initial value is common here; the rule cannot tell intent. | +| `nextjs-no-client-side-redirect` | 0.9.14 | 32 | `router.replace()` in an effect is how the pages router cleans up query params. | +| `only-export-components` | 0.9.14 | 31 | Mostly context files exporting a provider next to its hook; Fast Refresh cost only. | +| `server-sequential-independent-await` | 0.9.14 | 43 | 40 of the hits are sequential `await`s in Playwright tests, where order is the point. | +| `no-array-index-as-key` | 0.9.14 | 78 | The sampled hits are static lists that never reorder; too noisy to block on. | +| `js-set-map-lookups` | 0.9.14 | 33 | `.includes()` on arrays of a handful of items; no measurable cost. | +| `rerender-lazy-state-init` | 0.9.13 | 16 | True but trivial: a cheap `map`/`concat` in a `useState` initialiser. | +| `query-destructure-result` | 0.9.13 | 3 | Spreading a query result is how the paginated-query wrappers are built. | +| `no-high-complexity-react-function`, `no-giant-component` | 0.9.14 | 74 | Duplicate the gate in `tools/code-complexity/`. | +| `require-pnpm-hardening` | 0.9.14 | 1 | Not a React concern; dependency policy lives in `pnpm-workspace.yaml`. | diff --git a/tools/react-doctor/package.json b/tools/react-doctor/package.json new file mode 100644 index 00000000000..4dcc13ccc1d --- /dev/null +++ b/tools/react-doctor/package.json @@ -0,0 +1,8 @@ +{ + "name": "react-doctor-runner", + "version": "1.0.0", + "private": true, + "devDependencies": { + "react-doctor": "0.9.13" + } +} diff --git a/tools/react-doctor/pnpm-lock.yaml b/tools/react-doctor/pnpm-lock.yaml new file mode 100644 index 00000000000..9c810ba5fb7 --- /dev/null +++ b/tools/react-doctor/pnpm-lock.yaml @@ -0,0 +1,2310 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + react-doctor: + specifier: 0.9.13 + version: 0.9.13(@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1))(eslint@10.10.0(jiti@2.7.0))(react@19.3.0) + +packages: + + '@astrojs/compiler@4.0.0': + resolution: {integrity: sha512-eouss7G8ygdZqHuke033VMcVw5HTZUu+PXd/h06DGDUg/jt5btPYPqh66ENWw/mU78rBrf/oeC4oqoBwMtDMNA==} + + '@babel/code-frame@7.29.7': + resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} + engines: {node: '>=6.9.0'} + + '@babel/compat-data@7.29.7': + resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==} + engines: {node: '>=6.9.0'} + + '@babel/core@7.29.7': + resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==} + engines: {node: '>=6.9.0'} + + '@babel/generator@7.29.8': + resolution: {integrity: sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==} + engines: {node: '>=6.9.0'} + + '@babel/helper-compilation-targets@7.29.7': + resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-globals@7.29.7': + resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-imports@7.29.7': + resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-transforms@7.29.7': + resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 + + '@babel/helper-string-parser@7.29.7': + resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-option@7.29.7': + resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==} + engines: {node: '>=6.9.0'} + + '@babel/helpers@7.29.7': + resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==} + engines: {node: '>=6.9.0'} + + '@babel/parser@7.29.8': + resolution: {integrity: sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/template@7.29.7': + resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==} + engines: {node: '>=6.9.0'} + + '@babel/traverse@7.29.8': + resolution: {integrity: sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==} + engines: {node: '>=6.9.0'} + + '@babel/types@7.29.8': + resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==} + engines: {node: '>=6.9.0'} + + '@cacheable/memory@2.2.0': + resolution: {integrity: sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==} + + '@cacheable/utils@2.5.0': + resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==} + + '@emnapi/core@1.11.2': + resolution: {integrity: sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==} + + '@emnapi/runtime@1.11.2': + resolution: {integrity: sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==} + + '@emnapi/wasi-threads@1.2.2': + resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} + + '@eslint-community/eslint-utils@4.10.1': + resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.2': + resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/config-array@0.23.5': + resolution: {integrity: sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/config-helpers@0.7.0': + resolution: {integrity: sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/core@1.2.1': + resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/object-schema@3.0.5': + resolution: {integrity: sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/plugin-kit@0.7.3': + resolution: {integrity: sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@humanfs/core@0.19.2': + resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} + engines: {node: '>=18.18.0'} + + '@humanfs/node@0.16.8': + resolution: {integrity: sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==} + engines: {node: '>=18.18.0'} + + '@humanfs/types@0.15.0': + resolution: {integrity: sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==} + engines: {node: '>=18.18.0'} + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/retry@0.4.3': + resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} + engines: {node: '>=18.18'} + + '@iarna/toml@2.2.5': + resolution: {integrity: sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@keyv/bigmap@1.3.1': + resolution: {integrity: sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==} + engines: {node: '>= 18'} + peerDependencies: + keyv: ^5.6.0 + + '@keyv/serialize@1.1.1': + resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==} + + '@napi-rs/wasm-runtime@1.2.4': + resolution: {integrity: sha512-AJxoUD2/15ESHbvpcyjU274nsAPLuOtPHCk0vKJM5pj//Fg/B1FXNWjPnXTT9PymCYYiHo4zPj0ZomXBKhoy7g==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + peerDependencies: + '@emnapi/core': ^1.7.1 || ^2.0.0-alpha.4 + '@emnapi/runtime': ^1.7.1 || ^2.0.0-alpha.4 + + '@opentelemetry/api-logs@0.220.0': + resolution: {integrity: sha512-CmVa4ImJ+ynfrPMNaAXHET6Bhb44SwzmfyVJFq9ni2jgXJR/l7C6gfVFddNmHP+ZOkP9cf4f9DBe68qVLTHc9w==} + engines: {node: '>=8.0.0'} + + '@opentelemetry/api@1.9.1': + resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==} + engines: {node: '>=8.0.0'} + + '@opentelemetry/core@2.11.0': + resolution: {integrity: sha512-7YP44XH0tV6+Mb54x2YGf84i7yi+31MBZlE8JwvozkxyTvXbSp10X7cI7YE49ChJ3shMJoBmCJF3+1QFBJctGA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': '>=1.0.0 <1.10.0' + + '@opentelemetry/instrumentation@0.220.0': + resolution: {integrity: sha512-xQx3E2WxP1mDvKzxLxX+CTCtNLa560YJZ3087qYHerl2YmiKpv7AH+dAy7vmx+eVrZ5BwhfWUAVoKOoxCNHcpw==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/resources@2.11.0': + resolution: {integrity: sha512-Ie7+8q8MDF4FAEQCKVMTx3ReUvxiIAgIiiW3c9JdmP8+HMcDy20puT+AHjexnExgnbvBxjQ9fjkFDWrikJ2jQA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': '>=1.3.0 <1.10.0' + + '@opentelemetry/sdk-trace-base@2.11.0': + resolution: {integrity: sha512-H19x/TX/LZdqiYOjM7fqtSxwlplC5pgelavqbQdHbhdq0q/AI/TGkM2dfGuuynTXmJPeF2HoZVoPDu+TGoW78A==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': '>=1.3.0 <1.10.0' + + '@opentelemetry/sdk-trace@2.11.0': + resolution: {integrity: sha512-fFnTqGm8/G73GQVnxYi7LXa1ZVYEUvgL6XI1LpvV0bPC7WQ/ZGgKxCSl8FnlZBKto9JHHEFTO6s6CUpvvtwFrA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': '>=1.3.0 <1.10.0' + + '@opentelemetry/semantic-conventions@1.43.0': + resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==} + engines: {node: '>=14'} + + '@oxc-parser/binding-android-arm-eabi@0.146.0': + resolution: {integrity: sha512-jBCZIsff/9J/zdK1KSKZREScXOtRE4wYO+MUjrE+5NHGdsslrP4biJA9QJyKwErwS8lkwxH6Z537HaL4CQr0ow==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxc-parser/binding-android-arm64@0.146.0': + resolution: {integrity: sha512-BVwj6sVmgD9j5F+R5B+13pYQKOCmew+3myS19wcG5e+AeZu5ybBLEfcaKueC8MhvjtwL2Suh2tQE/Ywop2Z8rA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxc-parser/binding-darwin-arm64@0.146.0': + resolution: {integrity: sha512-jQGIM4zEEvvuypbBcoeoWuigRfP6R8Ow/9gfDzVoYkv5mFyVPbIePNQnV752jUynfty0nDxarIpML+7Q/MyMPg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxc-parser/binding-darwin-x64@0.146.0': + resolution: {integrity: sha512-quDy3cvW1712l6W+qe1/xWRym6STOuGJmFzRIg5StXVJglsbqrCpHfw9PyqPs0hQeOAjAEO1USrjPaIvHiRKQw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxc-parser/binding-freebsd-x64@0.146.0': + resolution: {integrity: sha512-wx/p/9phlX4VbYk671G4WewST3pysXNQfZRx4gx69QIz0/uW2O3MCnnEQh4il6l2lYr0EDAq3kFYovIw68CXHw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxc-parser/binding-linux-arm-gnueabihf@0.146.0': + resolution: {integrity: sha512-W9nzfbWH8Z6cIaBj6Rh/eVgymFkZ2MaOV0rQruKTLYKLAZADo9JlOmBml6Dq2QbChtmuc3DKDL42KDHaQFX8yQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxc-parser/binding-linux-arm-musleabihf@0.146.0': + resolution: {integrity: sha512-S5X1mEvTLBTl+xt7bRlr1n6qI+OTy1EaRkYyd4EQgEZqV7i53fQa1I72OqR0IwSQKVwh6TZPkzDcsN7fS9MynQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxc-parser/binding-linux-arm64-gnu@0.146.0': + resolution: {integrity: sha512-Br9UB4nnecVfj/Vp+JiJnJo2wIJtwaOm+uN7MwWKF5cx10P816urucmksG/iG2OeL7hfZ4h5fCmePrLU6TocfQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-arm64-musl@0.146.0': + resolution: {integrity: sha512-5AP+od9VGhRyCwswTfuD0jSDfIcWptEBC+K0LWmXsUJ9BPVF3KbhsjeoV+9tijX6g5is0w4H8DUV7NkOJoOVVA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxc-parser/binding-linux-ppc64-gnu@0.146.0': + resolution: {integrity: sha512-Qz3jc1qgvU9B9vQu3jAJcxKlGX7zYRtKs8LPYtQi8cmirhtYcX6XvXseESaDFbi1L+SorXhjRQ/2npEX85kKBw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-riscv64-gnu@0.146.0': + resolution: {integrity: sha512-Mfmg18lOZ1IWJJJuHi1ZsMLunqNVeLEh3Byuw+Aa8dYo7qOrZOMZQz1gFgAeNga5/Z5jjRuIKuIdo9aO7HYMdg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-riscv64-musl@0.146.0': + resolution: {integrity: sha512-6OdXwYnzbwYcnUH8f0LYauLNitjIcgDR/CDA/wcZ2whwJwVflGtCLF3+3HOXgs/SESnpQCWXr7Q/z9muLJ5bmQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxc-parser/binding-linux-s390x-gnu@0.146.0': + resolution: {integrity: sha512-BilV4Ei84A0m6r1v+LmgVrfUMbAz33IXRooVw/BQNDExUvGGNLrk6NWeot+ve99bRidTZdwWuzBHgxWCnSSa9Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-x64-gnu@0.146.0': + resolution: {integrity: sha512-RaMfGIpWOa87u3aD87drbPgisy7Nv6gIdjRFw6msIDKO+3FmcOTw+vpp4hVANhUIzpQta2EAsmYQRrqeprZTmQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-x64-musl@0.146.0': + resolution: {integrity: sha512-0bzF60jfQRsJ9TJOIHK+wSUirenJAyWCdP9z3P6LMS0znD4Gf7WYOiv7niONVOpRnlGjzMPd4kqgOJfCDLQAQg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxc-parser/binding-openharmony-arm64@0.146.0': + resolution: {integrity: sha512-O1gxUFt5FUgyFVUQK2BhZNwv7jLsqLR8uBANOhpYE5D5q+eCvcry7RvQT3DgKpWP1XRYB5UsbQGHHcwchEKb+w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxc-parser/binding-win32-arm64-msvc@0.146.0': + resolution: {integrity: sha512-i46zYS0TTCt+oaXaDx4mKxuXo+h8OBWI12XFatRm5I9/l2WKhp4TQ6VAjw0r1NMRiQQZ9dwQlRyQNhyTkOaINg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxc-parser/binding-win32-ia32-msvc@0.146.0': + resolution: {integrity: sha512-v1bb+ma2oKXwh4NHAg2NQwe9ORXFBDSCEkuO1qC4Rzm8EXcQdNhiJHpTNfulZ2P+1QpYUB6QYupW4mgMVom/tA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxc-parser/binding-win32-x64-msvc@0.146.0': + resolution: {integrity: sha512-uT8N1/qdNSGonvW1O2kZYNczqb/VYfnj5dpUy1FmedOPodj3MNFNWhAJkMZlI5u8xuTRtrpTccnr0U5HAMVRjQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@oxc-project/types@0.146.0': + resolution: {integrity: sha512-XC0QsnnhVe7sLIWmYmdPw7x5P0h4W8vUU3Nv1ySgWXtvCz8NizoAEpGXA0sOYoJQV2Rl13LgURAHQ5cI5ILCSA==} + + '@oxc-resolver/binding-android-arm-eabi@11.24.2': + resolution: {integrity: sha512-y09e0L0SRI2OA2tUIrjBgoV3eH5hvUKXNkJqXmNo5V2WxIjyC7I7aJfRLMEVpA8yi95f90gFDvO0VMgrDw+vwA==} + cpu: [arm] + os: [android] + + '@oxc-resolver/binding-android-arm64@11.24.2': + resolution: {integrity: sha512-cl4icWaZFnLdg8m6qtnh5rBMuGbxc/ptStFHLeCNwr+2cZjkjNwQu/jYRS0CHlnPecOJMpuS5M6/BH+0J/YkEg==} + cpu: [arm64] + os: [android] + + '@oxc-resolver/binding-darwin-arm64@11.24.2': + resolution: {integrity: sha512-At29QEMF6HajbQvgY8K6OXnHD1x9rad74xBEfmCB6ZqCGsdq75aK7tOYcTbOanMy8qdIBrfL3SMr3p/lfSlb9w==} + cpu: [arm64] + os: [darwin] + + '@oxc-resolver/binding-darwin-x64@11.24.2': + resolution: {integrity: sha512-A5Kqr1EUj4oIL5CF4WRssq/o5P0Y11cwoFouMRmQ7YnC/A8V93nv1nb7aSU8HwcgmXropjLNkVTl4MN87cu28Q==} + cpu: [x64] + os: [darwin] + + '@oxc-resolver/binding-freebsd-x64@11.24.2': + resolution: {integrity: sha512-R5xkRBRRz7ceH/P5Jrc6G7FmdUdgpLYyESFAUDVTNQ9K0sGPxcp4ljiwEwEqsvNcQ4sYbMRrWcHHBCu7ksAJVw==} + cpu: [x64] + os: [freebsd] + + '@oxc-resolver/binding-linux-arm-gnueabihf@11.24.2': + resolution: {integrity: sha512-k/RuYL4L/R58IBn3wT5ma3Wh4k62bp1eYCFRWCmMsasUOqL+H6sW0VGFadEzKWXFFlz+2uIMoeMk9ySSZJHgbg==} + cpu: [arm] + os: [linux] + + '@oxc-resolver/binding-linux-arm-musleabihf@11.24.2': + resolution: {integrity: sha512-bnHAak3ujYfH5pKk4NieFNbvYvernfoQDgwLddbZ3OtMYrem87/qjlA+u+aKG0oZcqSLGCful/6/CEA+aeAgaA==} + cpu: [arm] + os: [linux] + + '@oxc-resolver/binding-linux-arm64-gnu@11.24.2': + resolution: {integrity: sha512-vDT3KHgzYp47gmtNOqL2VNhCyl5Zv643eyxm//A68J8DeUGXrvD1pZFiaT4jSfe+RInfnn1R2yVHye4enx6RnA==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxc-resolver/binding-linux-arm64-musl@11.24.2': + resolution: {integrity: sha512-+kMlQvbzfyEYtu5FcjE4p+ttBLpKW4d/AsAsuE69BxV6V4twZJeIQZFfD8gh/wqglY0MkPSezWXQH0jBV13MUw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxc-resolver/binding-linux-ppc64-gnu@11.24.2': + resolution: {integrity: sha512-shjfMhmZ3gq9fv/w7bi3PnZlgOPG+2QAOFf0BJF0EgBSIGZ6PMLN2zbGEblTUYB/NKVDRyYhE2ff3dJ1QqNPkA==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxc-resolver/binding-linux-riscv64-gnu@11.24.2': + resolution: {integrity: sha512-zGelwFR5oRo+b69k8Lrzun86DyUHzfKN6cnjbR9l7Z7NIRznOE/2ZvPa1IUKqAL2PzAXOdwkfVqNvO1H2RlpAw==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxc-resolver/binding-linux-riscv64-musl@11.24.2': + resolution: {integrity: sha512-qxZ1SWCXJY0eyhAlP6Lmo9F2Nrtx7EkYj9oCgL8apDPCwXwCEDA2U697bbT81JIc2IrVjxO4KX6WU2N+oN9Z4w==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxc-resolver/binding-linux-s390x-gnu@11.24.2': + resolution: {integrity: sha512-sGCecF3cx2DFlH4t/z7ApnOnXqN48p5p5mlHDEnHTAukQa2P+qMVE4CwyWE9W+q/m3QJ7kKfGrIjax31f44oFQ==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxc-resolver/binding-linux-x64-gnu@11.24.2': + resolution: {integrity: sha512-k/VlMMcSzMlahb3/fENM4rTlsJ0s3fFROA0KXPBmKggqmTSaE383sl8F3KCOXPLmVsYfW6hCitMhXCEtNeZxxg==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxc-resolver/binding-linux-x64-musl@11.24.2': + resolution: {integrity: sha512-8hbnZyNi97b/8wapYaIF9+t9GmZKBW2vunaOc3h9HGJptH7b7XpvZqOTBSm/MpTjr7H497BlgOaSfLUdhmy2bw==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxc-resolver/binding-openharmony-arm64@11.24.2': + resolution: {integrity: sha512-MvyGik3a6pVgZ0t/kWlbmFxFLmXQJwgLsY2eYFHLpy0wGwRbfzeIGgDwQ3kXqE30z+kSXennRkCrT7TUvkptNg==} + cpu: [arm64] + os: [openharmony] + + '@oxc-resolver/binding-wasm32-wasi@11.24.2': + resolution: {integrity: sha512-vHcssMPwO08RTvj/c0iOBz90attxyG3wQJ0dTcyEQK43LRpcdLWZlV5feBhv6Isn6ahbQIzHbCgfa81+RiML0Q==} + engines: {node: '>=14.0.0'} + cpu: [wasm32] + + '@oxc-resolver/binding-win32-arm64-msvc@11.24.2': + resolution: {integrity: sha512-uokJqro2iBqkFvJdKQLP7d8/BUmFwESQFVmIJUQKj1Xn1a/LysJoe1vmeECLF5b3jsV8CAL5sEMJXX6SdK9Nhg==} + cpu: [arm64] + os: [win32] + + '@oxc-resolver/binding-win32-x64-msvc@11.24.2': + resolution: {integrity: sha512-UqGPmo56KDfLlfXFAFIrNflHT8tFxWGEivWg3Zeyp4Uy2NlKN1FGPr6/BxcLGG3+kZ6Wp14g5Uj+n71boqZfiw==} + cpu: [x64] + os: [win32] + + '@oxlint/binding-android-arm-eabi@1.79.0': + resolution: {integrity: sha512-TebFaaMklO/RXzTv7PucaCq9l3X6D1gA+C8H6K4njtjFOV+zWE9MKLpulcJZN9bzytbUbQIY0mZuz12nQ5Kv4Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxlint/binding-android-arm64@1.79.0': + resolution: {integrity: sha512-KqqnOtAVgNsPPF0YSodkFZA1O80jcKoCZCTu3bgsszxA+MrMP9TLzfXitKjEj1FmrPprKDMdRDMmY3weESO9sg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxlint/binding-darwin-arm64@1.79.0': + resolution: {integrity: sha512-BVC2nsMzqQzRDPc5RhixkZ+m1p7iH4bxRRvqkbwDXX0PlQKm1BPy8J8cRjnAFafOq2QzI+BfO3vE8w2GZ3CBag==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxlint/binding-darwin-x64@1.79.0': + resolution: {integrity: sha512-p6Lm+snmhGuLKL1+CpCV8L6ijkE/qJzK2H2jG9+eKJT0n31RbY4FLsdhexekgP3bLpw4Kgde+9DZuDZQ4yIInA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxlint/binding-freebsd-x64@1.79.0': + resolution: {integrity: sha512-qDMm0dXZnoHyRqSL4N4xUq82T4sqK5cbKSjvd/dF/YbMUXc2R1wEPf+vmA5S0qUmi0nwXfNbjXBtZaIqzQLIMg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxlint/binding-linux-arm-gnueabihf@1.79.0': + resolution: {integrity: sha512-2od7s0nuKPzqyUZAWk9KkCyGg7eI9dwFPZg+20lB15fKFkVZ0c9ZFxqPfiBAyDTlTkh9stPI0t+JlPCqMbItVA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxlint/binding-linux-arm-musleabihf@1.79.0': + resolution: {integrity: sha512-ZOQUjkzDnvlhSE3+tWC3YXx94MMl+sYMlwH+u1+YGApGHOJP/YAc8ZBRFOXZ6eOBmxtXAWuS/fBcdZr8qqNO1A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxlint/binding-linux-arm64-gnu@1.79.0': + resolution: {integrity: sha512-lu158FR4nGqGeRS3BQvtG85wRgU/Fy4MD5Cxp1hzJXizGiLo6u2742wJSCDKh8cFcZntvX7fcxlq4mMmfryH1g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-arm64-musl@1.79.0': + resolution: {integrity: sha512-mbpKQeE2aflTjddaHK7MP8KP/OFbUM++lt5M635ENM8IyIdK0jm2t9pb+2v9mVVIvhF6TqA4l7F79Pll1mi+uw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxlint/binding-linux-ppc64-gnu@1.79.0': + resolution: {integrity: sha512-WpGNua7gaxaHnpSDeog2ji8IDHn/QLPl9LPzwkR/FvVv58vT5BcXjRXnU+wbu3N75cpeha8CdC7ho/U2OIsB4g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-riscv64-gnu@1.79.0': + resolution: {integrity: sha512-tK1E93A5LVzISg4ngpKJnfTs7EqtIUceGI7MQ4GyDjJiLi8wPCkEyKlj2xkyKWZ1yzkDJyLHTBJ5/iFWRdnJvg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-riscv64-musl@1.79.0': + resolution: {integrity: sha512-qhQvUIrngXivA2A9pQ+xPCychztn/5qUv7yS3gDwXv3w7Rag+eTeeXWmRyx+t7XsW5x6LuY/8AsTq36UgFIblg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxlint/binding-linux-s390x-gnu@1.79.0': + resolution: {integrity: sha512-sv6AaVgU/eE6u+6WFiQVDcPPwTxP6IJMSB9k701W2r/r6Tx465e8vPvVyRxquNH4Vy6KwRNu90mVbxXJN8+5gg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-x64-gnu@1.79.0': + resolution: {integrity: sha512-iFZL02deziHslb3jEX9KdqlAkYoo4fGyotchKDzdfK1f5mxlIBeiQeHhvK3iFpuEJSB4ma/qeFn9oxPiwnhUPQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-x64-musl@1.79.0': + resolution: {integrity: sha512-3DtZR2raqObnh7wXZoFYFd0Fw7skBvcb3f7A+/lkEiDuh8hrE6vv9b/62Qxao1a9/OeHLw/FcXlXzgsW9wTRFg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxlint/binding-openharmony-arm64@1.79.0': + resolution: {integrity: sha512-Oatt4GuA1WJkqzk2ozx4HrWROOi7opV3AKDw/U8qDIqeTqzsjn5K2x3REJMNjU3/KU/Bkq96Zi3CknaiDTaC/Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxlint/binding-win32-arm64-msvc@1.79.0': + resolution: {integrity: sha512-NAgZr9Qp8nIA9rpo0JEvwiabTF/2UVqBNnupBG9X4kxXcQoScJUTi+qHhvabb9s/thgj5wQ4XcIaJvb+ZMgoKw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxlint/binding-win32-ia32-msvc@1.79.0': + resolution: {integrity: sha512-+KyXjIvcpaXmWW/j9NNY5yWjrIVxaX18VyIheQy3jwc2GSYgpCr7MGI/HxIGQ/shAL5IWEKbhsqoMpAO5Stiog==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxlint/binding-win32-x64-msvc@1.79.0': + resolution: {integrity: sha512-mEelcCMMBS57sIXh2veGMNy+pQwuGtcMxHxGIZWQ5Ba9pJ5jCCUFOZB9E2JhBaxGsURe+WGe0zJp4RVre52gpQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@sentry/conventions@0.16.0': + resolution: {integrity: sha512-fO9PLmHdVURcSPUpWCItWAtgKiMwGdJHbovoSEyLplX5sxs2ugvI4CBPTrkkgqhObnZOD0CnWBKDzSVQYBKEyQ==} + engines: {node: '>=14'} + + '@sentry/core@10.74.0': + resolution: {integrity: sha512-u9rY8vcZfktccwm6LznfCZlqP5C9A+p76r4/pFS1grqpuTO0m21Cl8rosnlESrDGP/Xd9tfr91rWYk0jPH8jeQ==} + engines: {node: '>=18'} + + '@sentry/node-core@10.74.0': + resolution: {integrity: sha512-btgZXcGmkOGgojbxHo/gfGiyqYpzC9E8zVR78Q3MtM6Xnemk9gwJiQlhNmEX/FM+C36WBRPZrdcZcnMaJhbfJw==} + engines: {node: '>=18'} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + '@opentelemetry/core': ^1.30.1 || ^2.1.0 + '@opentelemetry/exporter-trace-otlp-http': '>=0.57.0 <1' + '@opentelemetry/instrumentation': '>=0.57.1 <1' + '@opentelemetry/sdk-trace-base': ^1.30.1 || ^2.1.0 + peerDependenciesMeta: + '@opentelemetry/api': + optional: true + '@opentelemetry/core': + optional: true + '@opentelemetry/exporter-trace-otlp-http': + optional: true + '@opentelemetry/instrumentation': + optional: true + '@opentelemetry/sdk-trace-base': + optional: true + + '@sentry/node@10.74.0': + resolution: {integrity: sha512-u1wsarTOWHn9CCev81Da5T4IQHZgdcosXRfX2+4DMII/lVJMBYesKixTQuMwXexjVG2+pkf16zTmgjZDa+75jA==} + engines: {node: '>=18'} + + '@sentry/opentelemetry@10.74.0': + resolution: {integrity: sha512-ua5mt0NDBfye+/ACKjAw9Ad2i+y42lOLvhxXZepZXjszblMz80MEsIZflMB7uLZUCTNH7MbZN8tlzCy8KsJKmQ==} + engines: {node: '>=18'} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + '@opentelemetry/core': ^1.30.1 || ^2.1.0 + '@opentelemetry/sdk-trace-base': ^1.30.1 || ^2.1.0 + + '@sentry/server-utils@10.74.0': + resolution: {integrity: sha512-AHmPIGE8yVRyywpZRhAkm/H0cHTgsQSPhFZFbaeQLcYHFE/eOP9bAMh8Nj/Apr7WMagFXYHd04tR/63BxtLgKw==} + engines: {node: '>=18'} + + '@shaderfrog/glsl-parser@7.0.1': + resolution: {integrity: sha512-8mpfsoPeRhesY3pOrzNZBL8uG6N5GVX1EHLBYbd4gzKs+c7vaEIqpTNK5VrffU33qQN4cwpP2v3u4aPPBU32sw==} + engines: {node: '>=16'} + + '@tybys/wasm-util@0.10.3': + resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==} + + '@types/esrecurse@4.3.1': + resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + + '@typescript-eslint/types@8.70.0': + resolution: {integrity: sha512-asTOIYhDg4zdzOScCyaytrsV3cR6B4ecPQlXw/dJIm7J/MZTtCtfVII9JD8Geh4jTCrK/Xe6cg5UevoleMcoJQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn@8.18.0: + resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==} + engines: {node: '>=0.4.0'} + hasBin: true + + agent-install@0.0.5: + resolution: {integrity: sha512-nHlms9BkP8ZiY79HrwCGiA2DcNaXrAaJrCM/BEqQ7MEsSKyCk+2A76xPGylIfASZSZE0SaU3T0bNSg4rBPIJAQ==} + hasBin: true + + ajv-formats@3.0.1: + resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + + ajv@6.15.0: + resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + + atomically@2.1.1: + resolution: {integrity: sha512-P4w9o2dqARji6P7MHprklbfiArZAWvo07yW7qs3pdljb3BWr12FIB7W+p0zJiuiVsUpRO0iZn1kFFcpPegg0tQ==} + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + + baseline-browser-mapping@2.11.21: + resolution: {integrity: sha512-uh8vpY/1/YyFkunIDFH/12p7/7VdPKA1hejMVEbdkEaWnUz0Hesvx5EbiU6XxjyHZIOju+ZMbQJkRh+es3/spQ==} + engines: {node: '>=6.0.0'} + hasBin: true + + bippy@0.6.1: + resolution: {integrity: sha512-ky4m94Y/KfsddjGkKTsV4uFjZqkJjpOjQ2t5gKPdX6XH1MNxMNX5FrVefsxV4lpjemEmEdwe0e0YbzAMNs3oUQ==} + peerDependencies: + react: '>=17.0.1' + + brace-expansion@5.0.9: + resolution: {integrity: sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==} + engines: {node: 20 || >=22} + + browserslist@4.28.9: + resolution: {integrity: sha512-EWazOblFYUvlGZcfGhPUPmYh3nikUxBVb+y9MJun5f3hBi812X+8MSQTujLBtgK3cf51fJWbWfOjyeO954d+Eg==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + cacheable@2.5.0: + resolution: {integrity: sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==} + + caniuse-lite@1.0.30001810: + resolution: {integrity: sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==} + + cjs-module-lexer@2.2.1: + resolution: {integrity: sha512-Ca8swihM+/4yKecYHY52kgJd300hi2lADU/a1RxNTRe+RJ9jvqQlESpbz9DnG9mowez8qwXHB8qYdIUw9e+F5Q==} + + commander@14.0.3: + resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} + engines: {node: '>=20'} + + conf@15.1.0: + resolution: {integrity: sha512-Uy5YN9KEu0WWDaZAVJ5FAmZoaJt9rdK6kH+utItPyGsCqCgaTKkrmZx3zoE0/3q6S3bcp3Ihkk+ZqPxWxFK5og==} + engines: {node: '>=20'} + + confbox@0.2.4: + resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + debounce-fn@6.0.0: + resolution: {integrity: sha512-rBMW+F2TXryBwB54Q0d8drNEI+TfoS9JpNTAoVpukbWEhjXQq4rySFYLaqXMFXwdv61Zb2OHtj5bviSoimqxRQ==} + engines: {node: '>=18'} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + dot-prop@10.2.0: + resolution: {integrity: sha512-BTJ9aZYL3vCfZlZOBLy9v8TUqWGQ0pzFnygKwFZt5udj6viBoFIBviKPUoZLDCPn1FoXffv6McQFDenrm5Krfw==} + engines: {node: '>=20'} + + electron-to-chromium@1.5.426: + resolution: {integrity: sha512-2Gcq6inCQs/AqfHP3f5ftCzk+pqeW2VlA1LgmPqEj2hfBO8HiZRspNYkD4HzFBe4u6lGqca4BspFr6Ix4Q400g==} + + env-paths@3.0.0: + resolution: {integrity: sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + es-module-lexer@3.0.2: + resolution: {integrity: sha512-BuIB67FngDSyQ/dpQNOZybwdEBDUGJQvOqwWr4ha/ufYiqzuEwPkKO2zLhRAgay28tStRIHUeWmszZAJo3GCOg==} + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + eslint-plugin-react-hooks@7.1.1: + resolution: {integrity: sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==} + engines: {node: '>=18'} + peerDependencies: + eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0 + + eslint-scope@9.1.2: + resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@5.0.1: + resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint@10.10.0: + resolution: {integrity: sha512-NPXn6r5zl4uET1DAVPaOwzX3rut4c0wcmw3dWJAfOsTM5+TogXo0DDjz8pwm/hL8cyVNpHqeK4JpN0NjnyFFNw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + hasBin: true + peerDependencies: + jiti: '*' + peerDependenciesMeta: + jiti: + optional: true + + espree@11.2.0: + resolution: {integrity: sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + esquery@1.7.0: + resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + + fast-uri@3.1.7: + resolution: {integrity: sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==} + + file-entry-cache@11.1.5: + resolution: {integrity: sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@6.1.23: + resolution: {integrity: sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==} + + flatted@3.4.4: + resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + + gensync@1.0.0-beta.2: + resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} + engines: {node: '>=6.9.0'} + + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + hashery@1.5.1: + resolution: {integrity: sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==} + engines: {node: '>=20'} + + hermes-estree@0.25.1: + resolution: {integrity: sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==} + + hermes-parser@0.25.1: + resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==} + + hookified@1.15.1: + resolution: {integrity: sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==} + + hookified@2.2.0: + resolution: {integrity: sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==} + + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + import-in-the-middle@3.5.0: + resolution: {integrity: sha512-O6wo8l0lhBuytKz3x8S65TvacFtoopji+gCVeEBbjCaRy75gkk4bCBQoVmY7OEZ63cbFK+yf77pDCTWaadV7hQ==} + engines: {node: '>=18'} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-unicode-supported@2.1.0: + resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==} + engines: {node: '>=18'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + jsesc@3.1.0: + resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} + engines: {node: '>=6'} + hasBin: true + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + + json-schema-typed@8.0.2: + resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + + json5@2.2.3: + resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} + engines: {node: '>=6'} + hasBin: true + + jsonc-parser@3.3.1: + resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==} + + keyv@5.6.0: + resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==} + + kleur@3.0.3: + resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} + engines: {node: '>=6'} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + + lru-cache@5.1.1: + resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + + magicast@0.5.4: + resolution: {integrity: sha512-llBEhWm1SacoRwgHUoQJYtwp4PBLF4faQi5TCpIGyGs9n4y5+juI0tDgyKIfpqxckRHaHzouUEph3THklWh03w==} + + mimic-function@5.0.1: + resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==} + engines: {node: '>=18'} + + minimatch@10.2.6: + resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} + engines: {node: 18 || 20 || >=22} + + module-details-from-path@1.0.4: + resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + + node-releases@2.0.55: + resolution: {integrity: sha512-mIrE/Cw9y+9Au6dS5vDKDhQza9YvG6w+ZrS6X+ZzA7yFW/soAeaups4Qzn1bL6g5FVy8WtP79+0j82oPIbqRjQ==} + engines: {node: '>=18'} + + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + + oxc-parser@0.146.0: + resolution: {integrity: sha512-hrt0Ou2mCL8dLuvfvKWFjRlWaJKt0Xs7CfacAgb9mha0gKW1lSisUzNRyALgItMPIfThxkl8jH2ONP6ZbQXpaA==} + engines: {node: ^20.19.0 || >=22.12.0} + + oxc-resolver@11.24.2: + resolution: {integrity: sha512-FY91FiDBj7ls5MsFS9jN3tjz2o0/zsdSsymlakySaBwVJZorHhkWyICLZMKxlu1R9vYo+sd3z1jwb4J8x7bNDw==} + + oxlint-plugin-react-doctor@0.9.13: + resolution: {integrity: sha512-JuGpGSZ2mmzRaZlhSDdDu3+TZZ+d1q9HPyptU3XW3yL7YMDsJqq9QCPZqTwphPohOByvk+sypBI1+kKgovsPcg==} + engines: {node: ^20.19.0 || >=22.13.0} + + oxlint@1.79.0: + resolution: {integrity: sha512-hVJ9hq9m2unPS+Of4eJJgCPdIeCC+3DHEUX3tkmrPJr3OK2hz7PhXwgC+ZP71ZcYu8cCDEtQrqLxWNvxBppBVg==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + oxlint-tsgolint: '>=7.0.2001' + vite-plus: '*' + peerDependenciesMeta: + oxlint-tsgolint: + optional: true + vite-plus: + optional: true + + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + playwright-core@1.63.0: + resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==} + engines: {node: '>=20'} + hasBin: true + + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + prompts@2.4.2: + resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==} + engines: {node: '>= 6'} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + qified@0.10.1: + resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==} + engines: {node: '>=20'} + + react-doctor@0.9.13: + resolution: {integrity: sha512-OGzhgLmH+eFlYa3gOv8Y/yOaR6yswRxiLJ37wWc9/fm57bP8/3n5/TZQLMctv/8izKvqtmblIpW+0SqMYKP7Xg==} + engines: {node: ^20.19.0 || >=22.13.0} + hasBin: true + + react@19.3.0: + resolution: {integrity: sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==} + engines: {node: '>=0.10.0'} + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + require-in-the-middle@8.0.1: + resolution: {integrity: sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ==} + engines: {node: '>=9.3.0 || >=8.10.0 <9.0.0'} + + semver@6.3.1: + resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} + hasBin: true + + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + sisteransi@1.0.5: + resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + stubborn-fs@2.0.0: + resolution: {integrity: sha512-Y0AvSwDw8y+nlSNFXMm2g6L51rBGdAQT20J3YSOqxC53Lo3bjWRtr2BKcfYoAf352WYpsZSTURrA0tqhfgudPA==} + + stubborn-utils@1.0.2: + resolution: {integrity: sha512-zOh9jPYI+xrNOyisSelgym4tolKTJCQd5GBhK0+0xJvcYDcwlOoxF/rnFKQ2KRZknXSG9jWAp66fwP6AxN9STg==} + + tagged-tag@1.0.0: + resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==} + engines: {node: '>=20'} + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + + type-fest@5.9.0: + resolution: {integrity: sha512-yANm3Jr3GiJ1qgJlxGAVxTOIcEOk1rhQHamlXtnrCK7EHP4HeM9OGxtMg/W7HFdrVzw/ZWJKGVIJusVH85sLtw==} + engines: {node: '>=20'} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + uint8array-extras@1.5.0: + resolution: {integrity: sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==} + engines: {node: '>=18'} + + update-browserslist-db@1.3.2: + resolution: {integrity: sha512-UQ+MSxlhRm1bzjhU+DcuXfjFO1FzNtqhK5+9Yvlp90ItDLk5vT932A0rFu619nf7RVS+Y/VeaUW1jaRDqZ8VJw==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + + when-exit@2.1.5: + resolution: {integrity: sha512-VGkKJ564kzt6Ms1dbgPP/yuIoQCrsFAnRbptpC5wOEsDaNsbCB2bnfnaA8i/vRs5tjUSEOtIuvl9/MyVsvQZCg==} + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + + yallist@3.1.1: + resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + + yaml@2.9.0: + resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} + engines: {node: '>= 14.6'} + hasBin: true + + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + + yoga-layout@3.2.1: + resolution: {integrity: sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==} + + zod-validation-error@4.0.2: + resolution: {integrity: sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==} + engines: {node: '>=18.0.0'} + peerDependencies: + zod: ^3.25.0 || ^4.0.0 + + zod@4.6.1: + resolution: {integrity: sha512-341aRWQsve0rvronKNTqZpjmzdbUDlFuzHaI/XLg/Ej82qffDJRRfBTCuv7+9q/rMjB6LSLyEBnW4InJeMtt/Q==} + +snapshots: + + '@astrojs/compiler@4.0.0': {} + + '@babel/code-frame@7.29.7': + dependencies: + '@babel/helper-validator-identifier': 7.29.7 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/compat-data@7.29.7': {} + + '@babel/core@7.29.7': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/helper-compilation-targets': 7.29.7 + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helpers': 7.29.7 + '@babel/parser': 7.29.8 + '@babel/template': 7.29.7 + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + '@jridgewell/remapping': 2.3.5 + convert-source-map: 2.0.0 + debug: 4.4.3 + gensync: 1.0.0-beta.2 + json5: 2.2.3 + semver: 6.3.1 + transitivePeerDependencies: + - supports-color + + '@babel/generator@7.29.8': + dependencies: + '@babel/parser': 7.29.8 + '@babel/types': 7.29.8 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + jsesc: 3.1.0 + + '@babel/helper-compilation-targets@7.29.7': + dependencies: + '@babel/compat-data': 7.29.7 + '@babel/helper-validator-option': 7.29.7 + browserslist: 4.28.9 + lru-cache: 5.1.1 + semver: 6.3.1 + + '@babel/helper-globals@7.29.7': {} + + '@babel/helper-module-imports@7.29.7': + dependencies: + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + transitivePeerDependencies: + - supports-color + + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-module-imports': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + '@babel/traverse': 7.29.8 + transitivePeerDependencies: + - supports-color + + '@babel/helper-string-parser@7.29.7': {} + + '@babel/helper-validator-identifier@7.29.7': {} + + '@babel/helper-validator-option@7.29.7': {} + + '@babel/helpers@7.29.7': + dependencies: + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 + + '@babel/parser@7.29.8': + dependencies: + '@babel/types': 7.29.8 + + '@babel/template@7.29.7': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/parser': 7.29.8 + '@babel/types': 7.29.8 + + '@babel/traverse@7.29.8': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/helper-globals': 7.29.7 + '@babel/parser': 7.29.8 + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + '@babel/types@7.29.8': + dependencies: + '@babel/helper-string-parser': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + + '@cacheable/memory@2.2.0': + dependencies: + '@cacheable/utils': 2.5.0 + '@keyv/bigmap': 1.3.1(keyv@5.6.0) + hookified: 1.15.1 + keyv: 5.6.0 + + '@cacheable/utils@2.5.0': + dependencies: + hashery: 1.5.1 + keyv: 5.6.0 + + '@emnapi/core@1.11.2': + dependencies: + '@emnapi/wasi-threads': 1.2.2 + tslib: 2.8.1 + optional: true + + '@emnapi/runtime@1.11.2': + dependencies: + tslib: 2.8.1 + optional: true + + '@emnapi/wasi-threads@1.2.2': + dependencies: + tslib: 2.8.1 + optional: true + + '@eslint-community/eslint-utils@4.10.1(eslint@10.10.0(jiti@2.7.0))': + dependencies: + eslint: 10.10.0(jiti@2.7.0) + eslint-visitor-keys: 3.4.3 + + '@eslint-community/regexpp@4.12.2': {} + + '@eslint/config-array@0.23.5': + dependencies: + '@eslint/object-schema': 3.0.5 + debug: 4.4.3 + minimatch: 10.2.6 + transitivePeerDependencies: + - supports-color + + '@eslint/config-helpers@0.7.0': + dependencies: + '@eslint/core': 1.2.1 + + '@eslint/core@1.2.1': + dependencies: + '@types/json-schema': 7.0.15 + + '@eslint/object-schema@3.0.5': {} + + '@eslint/plugin-kit@0.7.3': + dependencies: + '@eslint/core': 1.2.1 + levn: 0.4.1 + + '@humanfs/core@0.19.2': + dependencies: + '@humanfs/types': 0.15.0 + + '@humanfs/node@0.16.8': + dependencies: + '@humanfs/core': 0.19.2 + '@humanfs/types': 0.15.0 + '@humanwhocodes/retry': 0.4.3 + + '@humanfs/types@0.15.0': {} + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/retry@0.4.3': {} + + '@iarna/toml@2.2.5': {} + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@keyv/bigmap@1.3.1(keyv@5.6.0)': + dependencies: + hashery: 1.5.1 + hookified: 1.15.1 + keyv: 5.6.0 + + '@keyv/serialize@1.1.1': {} + + '@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)': + dependencies: + '@emnapi/core': 1.11.2 + '@emnapi/runtime': 1.11.2 + '@tybys/wasm-util': 0.10.3 + optional: true + + '@opentelemetry/api-logs@0.220.0': + dependencies: + '@opentelemetry/api': 1.9.1 + + '@opentelemetry/api@1.9.1': {} + + '@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/semantic-conventions': 1.43.0 + + '@opentelemetry/instrumentation@0.220.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/api-logs': 0.220.0 + import-in-the-middle: 3.5.0 + require-in-the-middle: 8.0.1 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/resources@2.11.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.43.0 + + '@opentelemetry/sdk-trace-base@2.11.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-trace': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.43.0 + + '@opentelemetry/sdk-trace@2.11.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.43.0 + + '@opentelemetry/semantic-conventions@1.43.0': {} + + '@oxc-parser/binding-android-arm-eabi@0.146.0': + optional: true + + '@oxc-parser/binding-android-arm64@0.146.0': + optional: true + + '@oxc-parser/binding-darwin-arm64@0.146.0': + optional: true + + '@oxc-parser/binding-darwin-x64@0.146.0': + optional: true + + '@oxc-parser/binding-freebsd-x64@0.146.0': + optional: true + + '@oxc-parser/binding-linux-arm-gnueabihf@0.146.0': + optional: true + + '@oxc-parser/binding-linux-arm-musleabihf@0.146.0': + optional: true + + '@oxc-parser/binding-linux-arm64-gnu@0.146.0': + optional: true + + '@oxc-parser/binding-linux-arm64-musl@0.146.0': + optional: true + + '@oxc-parser/binding-linux-ppc64-gnu@0.146.0': + optional: true + + '@oxc-parser/binding-linux-riscv64-gnu@0.146.0': + optional: true + + '@oxc-parser/binding-linux-riscv64-musl@0.146.0': + optional: true + + '@oxc-parser/binding-linux-s390x-gnu@0.146.0': + optional: true + + '@oxc-parser/binding-linux-x64-gnu@0.146.0': + optional: true + + '@oxc-parser/binding-linux-x64-musl@0.146.0': + optional: true + + '@oxc-parser/binding-openharmony-arm64@0.146.0': + optional: true + + '@oxc-parser/binding-win32-arm64-msvc@0.146.0': + optional: true + + '@oxc-parser/binding-win32-ia32-msvc@0.146.0': + optional: true + + '@oxc-parser/binding-win32-x64-msvc@0.146.0': + optional: true + + '@oxc-project/types@0.146.0': {} + + '@oxc-resolver/binding-android-arm-eabi@11.24.2': + optional: true + + '@oxc-resolver/binding-android-arm64@11.24.2': + optional: true + + '@oxc-resolver/binding-darwin-arm64@11.24.2': + optional: true + + '@oxc-resolver/binding-darwin-x64@11.24.2': + optional: true + + '@oxc-resolver/binding-freebsd-x64@11.24.2': + optional: true + + '@oxc-resolver/binding-linux-arm-gnueabihf@11.24.2': + optional: true + + '@oxc-resolver/binding-linux-arm-musleabihf@11.24.2': + optional: true + + '@oxc-resolver/binding-linux-arm64-gnu@11.24.2': + optional: true + + '@oxc-resolver/binding-linux-arm64-musl@11.24.2': + optional: true + + '@oxc-resolver/binding-linux-ppc64-gnu@11.24.2': + optional: true + + '@oxc-resolver/binding-linux-riscv64-gnu@11.24.2': + optional: true + + '@oxc-resolver/binding-linux-riscv64-musl@11.24.2': + optional: true + + '@oxc-resolver/binding-linux-s390x-gnu@11.24.2': + optional: true + + '@oxc-resolver/binding-linux-x64-gnu@11.24.2': + optional: true + + '@oxc-resolver/binding-linux-x64-musl@11.24.2': + optional: true + + '@oxc-resolver/binding-openharmony-arm64@11.24.2': + optional: true + + '@oxc-resolver/binding-wasm32-wasi@11.24.2': + dependencies: + '@emnapi/core': 1.11.2 + '@emnapi/runtime': 1.11.2 + '@napi-rs/wasm-runtime': 1.2.4(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2) + optional: true + + '@oxc-resolver/binding-win32-arm64-msvc@11.24.2': + optional: true + + '@oxc-resolver/binding-win32-x64-msvc@11.24.2': + optional: true + + '@oxlint/binding-android-arm-eabi@1.79.0': + optional: true + + '@oxlint/binding-android-arm64@1.79.0': + optional: true + + '@oxlint/binding-darwin-arm64@1.79.0': + optional: true + + '@oxlint/binding-darwin-x64@1.79.0': + optional: true + + '@oxlint/binding-freebsd-x64@1.79.0': + optional: true + + '@oxlint/binding-linux-arm-gnueabihf@1.79.0': + optional: true + + '@oxlint/binding-linux-arm-musleabihf@1.79.0': + optional: true + + '@oxlint/binding-linux-arm64-gnu@1.79.0': + optional: true + + '@oxlint/binding-linux-arm64-musl@1.79.0': + optional: true + + '@oxlint/binding-linux-ppc64-gnu@1.79.0': + optional: true + + '@oxlint/binding-linux-riscv64-gnu@1.79.0': + optional: true + + '@oxlint/binding-linux-riscv64-musl@1.79.0': + optional: true + + '@oxlint/binding-linux-s390x-gnu@1.79.0': + optional: true + + '@oxlint/binding-linux-x64-gnu@1.79.0': + optional: true + + '@oxlint/binding-linux-x64-musl@1.79.0': + optional: true + + '@oxlint/binding-openharmony-arm64@1.79.0': + optional: true + + '@oxlint/binding-win32-arm64-msvc@1.79.0': + optional: true + + '@oxlint/binding-win32-ia32-msvc@1.79.0': + optional: true + + '@oxlint/binding-win32-x64-msvc@1.79.0': + optional: true + + '@sentry/conventions@0.16.0': {} + + '@sentry/core@10.74.0': + dependencies: + '@sentry/conventions': 0.16.0 + + '@sentry/node-core@10.74.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1))(@opentelemetry/instrumentation@0.220.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.11.0(@opentelemetry/api@1.9.1))': + dependencies: + '@sentry/conventions': 0.16.0 + '@sentry/core': 10.74.0 + '@sentry/opentelemetry': 10.74.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.11.0(@opentelemetry/api@1.9.1)) + import-in-the-middle: 3.5.0 + optionalDependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.220.0(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-trace-base': 2.11.0(@opentelemetry/api@1.9.1) + + '@sentry/node@10.74.0(@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1))': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.220.0(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-trace-base': 2.11.0(@opentelemetry/api@1.9.1) + '@sentry/conventions': 0.16.0 + '@sentry/core': 10.74.0 + '@sentry/node-core': 10.74.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1))(@opentelemetry/instrumentation@0.220.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.11.0(@opentelemetry/api@1.9.1)) + '@sentry/opentelemetry': 10.74.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.11.0(@opentelemetry/api@1.9.1)) + '@sentry/server-utils': 10.74.0 + import-in-the-middle: 3.5.0 + transitivePeerDependencies: + - '@opentelemetry/core' + - '@opentelemetry/exporter-trace-otlp-http' + - supports-color + + '@sentry/opentelemetry@10.74.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.11.0(@opentelemetry/api@1.9.1))': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-trace-base': 2.11.0(@opentelemetry/api@1.9.1) + '@sentry/conventions': 0.16.0 + '@sentry/core': 10.74.0 + + '@sentry/server-utils@10.74.0': + dependencies: + '@sentry/conventions': 0.16.0 + '@sentry/core': 10.74.0 + + '@shaderfrog/glsl-parser@7.0.1': {} + + '@tybys/wasm-util@0.10.3': + dependencies: + tslib: 2.8.1 + optional: true + + '@types/esrecurse@4.3.1': {} + + '@types/estree@1.0.9': {} + + '@types/json-schema@7.0.15': {} + + '@typescript-eslint/types@8.70.0': {} + + acorn-jsx@5.3.2(acorn@8.18.0): + dependencies: + acorn: 8.18.0 + + acorn@8.18.0: {} + + agent-install@0.0.5: + dependencies: + '@iarna/toml': 2.2.5 + commander: 14.0.3 + jsonc-parser: 3.3.1 + picocolors: 1.1.1 + prompts: 2.4.2 + yaml: 2.9.0 + + ajv-formats@3.0.1(ajv@8.20.0): + optionalDependencies: + ajv: 8.20.0 + + ajv@6.15.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + + ajv@8.20.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.7 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + + atomically@2.1.1: + dependencies: + stubborn-fs: 2.0.0 + when-exit: 2.1.5 + + balanced-match@4.0.4: {} + + baseline-browser-mapping@2.11.21: {} + + bippy@0.6.1(react@19.3.0): + dependencies: + react: 19.3.0 + + brace-expansion@5.0.9: + dependencies: + balanced-match: 4.0.4 + + browserslist@4.28.9: + dependencies: + baseline-browser-mapping: 2.11.21 + caniuse-lite: 1.0.30001810 + electron-to-chromium: 1.5.426 + node-releases: 2.0.55 + update-browserslist-db: 1.3.2(browserslist@4.28.9) + + cacheable@2.5.0: + dependencies: + '@cacheable/memory': 2.2.0 + '@cacheable/utils': 2.5.0 + hookified: 1.15.1 + keyv: 5.6.0 + qified: 0.10.1 + + caniuse-lite@1.0.30001810: {} + + cjs-module-lexer@2.2.1: {} + + commander@14.0.3: {} + + conf@15.1.0: + dependencies: + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + atomically: 2.1.1 + debounce-fn: 6.0.0 + dot-prop: 10.2.0 + env-paths: 3.0.0 + json-schema-typed: 8.0.2 + semver: 7.8.5 + uint8array-extras: 1.5.0 + + confbox@0.2.4: {} + + convert-source-map@2.0.0: {} + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + debounce-fn@6.0.0: + dependencies: + mimic-function: 5.0.1 + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + deep-is@0.1.4: {} + + detect-libc@2.1.2: {} + + dot-prop@10.2.0: + dependencies: + type-fest: 5.9.0 + + electron-to-chromium@1.5.426: {} + + env-paths@3.0.0: {} + + es-module-lexer@3.0.2: {} + + escalade@3.2.0: {} + + escape-string-regexp@4.0.0: {} + + eslint-plugin-react-hooks@7.1.1(eslint@10.10.0(jiti@2.7.0)): + dependencies: + '@babel/core': 7.29.7 + '@babel/parser': 7.29.8 + eslint: 10.10.0(jiti@2.7.0) + hermes-parser: 0.25.1 + zod: 4.6.1 + zod-validation-error: 4.0.2(zod@4.6.1) + transitivePeerDependencies: + - supports-color + + eslint-scope@9.1.2: + dependencies: + '@types/esrecurse': 4.3.1 + '@types/estree': 1.0.9 + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-visitor-keys@3.4.3: {} + + eslint-visitor-keys@5.0.1: {} + + eslint@10.10.0(jiti@2.7.0): + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@10.10.0(jiti@2.7.0)) + '@eslint-community/regexpp': 4.12.2 + '@eslint/config-array': 0.23.5 + '@eslint/config-helpers': 0.7.0 + '@eslint/core': 1.2.1 + '@eslint/plugin-kit': 0.7.3 + '@humanfs/node': 0.16.8 + '@humanwhocodes/module-importer': 1.0.1 + '@humanwhocodes/retry': 0.4.3 + '@types/estree': 1.0.9 + ajv: 6.15.0 + cross-spawn: 7.0.6 + debug: 4.4.3 + escape-string-regexp: 4.0.0 + eslint-scope: 9.1.2 + eslint-visitor-keys: 5.0.1 + espree: 11.2.0 + esquery: 1.7.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 11.1.5 + find-up: 5.0.0 + glob-parent: 6.0.2 + ignore: 5.3.2 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + json-stable-stringify-without-jsonify: 1.0.1 + minimatch: 10.2.6 + natural-compare: 1.4.0 + optionator: 0.9.4 + optionalDependencies: + jiti: 2.7.0 + transitivePeerDependencies: + - supports-color + + espree@11.2.0: + dependencies: + acorn: 8.18.0 + acorn-jsx: 5.3.2(acorn@8.18.0) + eslint-visitor-keys: 5.0.1 + + esquery@1.7.0: + dependencies: + estraverse: 5.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@5.3.0: {} + + esutils@2.0.3: {} + + fast-deep-equal@3.1.3: {} + + fast-json-stable-stringify@2.1.0: {} + + fast-levenshtein@2.0.6: {} + + fast-uri@3.1.7: {} + + file-entry-cache@11.1.5: + dependencies: + flat-cache: 6.1.23 + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@6.1.23: + dependencies: + cacheable: 2.5.0 + flatted: 3.4.4 + hookified: 1.15.1 + + flatted@3.4.4: {} + + gensync@1.0.0-beta.2: {} + + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + + hashery@1.5.1: + dependencies: + hookified: 1.15.1 + + hermes-estree@0.25.1: {} + + hermes-parser@0.25.1: + dependencies: + hermes-estree: 0.25.1 + + hookified@1.15.1: {} + + hookified@2.2.0: {} + + ignore@5.3.2: {} + + import-in-the-middle@3.5.0: + dependencies: + cjs-module-lexer: 2.2.1 + es-module-lexer: 3.0.2 + module-details-from-path: 1.0.4 + + imurmurhash@0.1.4: {} + + is-extglob@2.1.1: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-unicode-supported@2.1.0: {} + + isexe@2.0.0: {} + + jiti@2.7.0: {} + + js-tokens@4.0.0: {} + + jsesc@3.1.0: {} + + json-schema-traverse@0.4.1: {} + + json-schema-traverse@1.0.0: {} + + json-schema-typed@8.0.2: {} + + json-stable-stringify-without-jsonify@1.0.1: {} + + json5@2.2.3: {} + + jsonc-parser@3.3.1: {} + + keyv@5.6.0: + dependencies: + '@keyv/serialize': 1.1.1 + + kleur@3.0.3: {} + + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + + lru-cache@5.1.1: + dependencies: + yallist: 3.1.1 + + magicast@0.5.4: + dependencies: + '@babel/parser': 7.29.8 + '@babel/types': 7.29.8 + source-map-js: 1.2.1 + + mimic-function@5.0.1: {} + + minimatch@10.2.6: + dependencies: + brace-expansion: 5.0.9 + + module-details-from-path@1.0.4: {} + + ms@2.1.3: {} + + natural-compare@1.4.0: {} + + node-releases@2.0.55: {} + + optionator@0.9.4: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.5 + + oxc-parser@0.146.0: + dependencies: + '@oxc-project/types': 0.146.0 + optionalDependencies: + '@oxc-parser/binding-android-arm-eabi': 0.146.0 + '@oxc-parser/binding-android-arm64': 0.146.0 + '@oxc-parser/binding-darwin-arm64': 0.146.0 + '@oxc-parser/binding-darwin-x64': 0.146.0 + '@oxc-parser/binding-freebsd-x64': 0.146.0 + '@oxc-parser/binding-linux-arm-gnueabihf': 0.146.0 + '@oxc-parser/binding-linux-arm-musleabihf': 0.146.0 + '@oxc-parser/binding-linux-arm64-gnu': 0.146.0 + '@oxc-parser/binding-linux-arm64-musl': 0.146.0 + '@oxc-parser/binding-linux-ppc64-gnu': 0.146.0 + '@oxc-parser/binding-linux-riscv64-gnu': 0.146.0 + '@oxc-parser/binding-linux-riscv64-musl': 0.146.0 + '@oxc-parser/binding-linux-s390x-gnu': 0.146.0 + '@oxc-parser/binding-linux-x64-gnu': 0.146.0 + '@oxc-parser/binding-linux-x64-musl': 0.146.0 + '@oxc-parser/binding-openharmony-arm64': 0.146.0 + '@oxc-parser/binding-win32-arm64-msvc': 0.146.0 + '@oxc-parser/binding-win32-ia32-msvc': 0.146.0 + '@oxc-parser/binding-win32-x64-msvc': 0.146.0 + + oxc-resolver@11.24.2: + optionalDependencies: + '@oxc-resolver/binding-android-arm-eabi': 11.24.2 + '@oxc-resolver/binding-android-arm64': 11.24.2 + '@oxc-resolver/binding-darwin-arm64': 11.24.2 + '@oxc-resolver/binding-darwin-x64': 11.24.2 + '@oxc-resolver/binding-freebsd-x64': 11.24.2 + '@oxc-resolver/binding-linux-arm-gnueabihf': 11.24.2 + '@oxc-resolver/binding-linux-arm-musleabihf': 11.24.2 + '@oxc-resolver/binding-linux-arm64-gnu': 11.24.2 + '@oxc-resolver/binding-linux-arm64-musl': 11.24.2 + '@oxc-resolver/binding-linux-ppc64-gnu': 11.24.2 + '@oxc-resolver/binding-linux-riscv64-gnu': 11.24.2 + '@oxc-resolver/binding-linux-riscv64-musl': 11.24.2 + '@oxc-resolver/binding-linux-s390x-gnu': 11.24.2 + '@oxc-resolver/binding-linux-x64-gnu': 11.24.2 + '@oxc-resolver/binding-linux-x64-musl': 11.24.2 + '@oxc-resolver/binding-openharmony-arm64': 11.24.2 + '@oxc-resolver/binding-wasm32-wasi': 11.24.2 + '@oxc-resolver/binding-win32-arm64-msvc': 11.24.2 + '@oxc-resolver/binding-win32-x64-msvc': 11.24.2 + + oxlint-plugin-react-doctor@0.9.13: + dependencies: + '@shaderfrog/glsl-parser': 7.0.1 + '@typescript-eslint/types': 8.70.0 + eslint-scope: 9.1.2 + eslint-visitor-keys: 5.0.1 + lightningcss: 1.33.0 + oxc-parser: 0.146.0 + + oxlint@1.79.0: + optionalDependencies: + '@oxlint/binding-android-arm-eabi': 1.79.0 + '@oxlint/binding-android-arm64': 1.79.0 + '@oxlint/binding-darwin-arm64': 1.79.0 + '@oxlint/binding-darwin-x64': 1.79.0 + '@oxlint/binding-freebsd-x64': 1.79.0 + '@oxlint/binding-linux-arm-gnueabihf': 1.79.0 + '@oxlint/binding-linux-arm-musleabihf': 1.79.0 + '@oxlint/binding-linux-arm64-gnu': 1.79.0 + '@oxlint/binding-linux-arm64-musl': 1.79.0 + '@oxlint/binding-linux-ppc64-gnu': 1.79.0 + '@oxlint/binding-linux-riscv64-gnu': 1.79.0 + '@oxlint/binding-linux-riscv64-musl': 1.79.0 + '@oxlint/binding-linux-s390x-gnu': 1.79.0 + '@oxlint/binding-linux-x64-gnu': 1.79.0 + '@oxlint/binding-linux-x64-musl': 1.79.0 + '@oxlint/binding-openharmony-arm64': 1.79.0 + '@oxlint/binding-win32-arm64-msvc': 1.79.0 + '@oxlint/binding-win32-ia32-msvc': 1.79.0 + '@oxlint/binding-win32-x64-msvc': 1.79.0 + + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + + path-exists@4.0.0: {} + + path-key@3.1.1: {} + + picocolors@1.1.1: {} + + playwright-core@1.63.0: {} + + prelude-ls@1.2.1: {} + + prompts@2.4.2: + dependencies: + kleur: 3.0.3 + sisteransi: 1.0.5 + + punycode@2.3.1: {} + + qified@0.10.1: + dependencies: + hookified: 2.2.0 + + react-doctor@0.9.13(@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1))(eslint@10.10.0(jiti@2.7.0))(react@19.3.0): + dependencies: + '@astrojs/compiler': 4.0.0 + '@sentry/node': 10.74.0(@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1)) + agent-install: 0.0.5 + bippy: 0.6.1(react@19.3.0) + conf: 15.1.0 + confbox: 0.2.4 + eslint-plugin-react-hooks: 7.1.1(eslint@10.10.0(jiti@2.7.0)) + is-unicode-supported: 2.1.0 + jiti: 2.7.0 + magicast: 0.5.4 + oxc-parser: 0.146.0 + oxc-resolver: 11.24.2 + oxlint: 1.79.0 + oxlint-plugin-react-doctor: 0.9.13 + playwright-core: 1.63.0 + prompts: 2.4.2 + typescript: 5.9.3 + yaml: 2.9.0 + yoga-layout: 3.2.1 + transitivePeerDependencies: + - '@opentelemetry/core' + - '@opentelemetry/exporter-trace-otlp-http' + - eslint + - oxlint-tsgolint + - react + - supports-color + - vite-plus + + react@19.3.0: {} + + require-from-string@2.0.2: {} + + require-in-the-middle@8.0.1: + dependencies: + debug: 4.4.3 + module-details-from-path: 1.0.4 + transitivePeerDependencies: + - supports-color + + semver@6.3.1: {} + + semver@7.8.5: {} + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + sisteransi@1.0.5: {} + + source-map-js@1.2.1: {} + + stubborn-fs@2.0.0: + dependencies: + stubborn-utils: 1.0.2 + + stubborn-utils@1.0.2: {} + + tagged-tag@1.0.0: {} + + tslib@2.8.1: + optional: true + + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + + type-fest@5.9.0: + dependencies: + tagged-tag: 1.0.0 + + typescript@5.9.3: {} + + uint8array-extras@1.5.0: {} + + update-browserslist-db@1.3.2(browserslist@4.28.9): + dependencies: + browserslist: 4.28.9 + escalade: 3.2.0 + picocolors: 1.1.1 + + uri-js@4.4.1: + dependencies: + punycode: 2.3.1 + + when-exit@2.1.5: {} + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + word-wrap@1.2.5: {} + + yallist@3.1.1: {} + + yaml@2.9.0: {} + + yocto-queue@0.1.0: {} + + yoga-layout@3.2.1: {} + + zod-validation-error@4.0.2(zod@4.6.1): + dependencies: + zod: 4.6.1 + + zod@4.6.1: {} diff --git a/tools/react-doctor/pnpm-workspace.yaml b/tools/react-doctor/pnpm-workspace.yaml new file mode 100644 index 00000000000..65276ae91cd --- /dev/null +++ b/tools/react-doctor/pnpm-workspace.yaml @@ -0,0 +1,5 @@ +# Standalone project, deliberately outside the root workspace: react-doctor's dependencies would +# otherwise re-key every eslint/vite/webpack entry in the root lockfile. See ./CONTEXT.md. +packages: [] + +minimumReleaseAge: 10080 # 1 week, same policy as the root workspace diff --git a/tools/react-doctor/run.sh b/tools/react-doctor/run.sh new file mode 100755 index 00000000000..61d05e2a080 --- /dev/null +++ b/tools/react-doctor/run.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +# Usage: tools/react-doctor/run.sh [react-doctor options] [<path>...] +# tools/react-doctor/run.sh why <file>:<line> +# --scope changed --base origin/main only issues this branch introduces (what CI runs) +# --staged only staged files + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" +BIN="$DIR/node_modules/.bin/react-doctor" + +# The tool lives in its own pnpm project (see CONTEXT.md), so the root install does not cover it. +pnpm --dir "$DIR" install --frozen-lockfile --silent + +cd "$ROOT" + +# Subcommands take their own arguments; only a scan gets a target and the scan flags. +if [ "$1" = "why" ] || [ "$1" = "rules" ]; then + exec "$BIN" "$@" +fi + +# Scan the whole project unless the caller named files. +TARGET=(.) +for arg in "$@"; do + if [ -e "$arg" ]; then TARGET=(); fi +done + +"$BIN" "${TARGET[@]}" --yes --no-telemetry "$@" diff --git a/tools/release/categories.spec.ts b/tools/release/categories.spec.ts new file mode 100644 index 00000000000..c0c818a8b3c --- /dev/null +++ b/tools/release/categories.spec.ts @@ -0,0 +1,69 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +import type { Category } from './categories'; +import { CATEGORIES, CATEGORY_LABELS, DEPENDENCIES_LABEL } from './categories'; + +// The rows of the table whose header is "Section | Labels", the labels read off their backticks. +function parseSectionTable(markdown: string): Array<Category> { + const lines = markdown.replace(/\r\n?/g, '\n').split('\n'); + const header = lines.findIndex((line) => /^\|\s*Section\s*\|\s*Labels\s*\|$/.test(line.trim())); + if (header === -1) { + throw new Error('No "| Section | Labels |" table in docs/RELEASING.md'); + } + const rows: Array<Category> = []; + for (const line of lines.slice(header + 2)) { + const cells = line.trim().split('|').slice(1, -1).map((cell) => cell.trim()); + if (cells.length !== 2) { + break; + } + const [ section, labels ] = cells; + rows.push({ section, labels: [ ...labels.matchAll(/`([^`]+)`/g) ].map(([ , label ]) => label) }); + } + return rows; +} + +describe('CATEGORIES', () => { + it('lists the release-notes sections in order, each with its labels', () => { + expect(CATEGORIES).toEqual([ + { section: 'New Features', labels: [ 'feature', 'enhancement', 'client feature' ] }, + { section: 'Bug Fixes', labels: [ 'bug' ] }, + { section: 'Performance Improvements', labels: [ 'performance' ] }, + { section: 'Dependencies Updates', labels: [ 'dependencies' ] }, + { section: 'Design Updates', labels: [ 'design' ] }, + { section: 'DX & Tooling', labels: [ 'refactoring', 'tech', 'devops' ] }, + { section: 'Other Changes', labels: [ 'chore' ] }, + ]); + }); + + it('maps every label to exactly one section', () => { + const labels = CATEGORIES.flatMap(({ labels }) => labels); + expect(new Set(labels).size).toBe(labels.length); + }); +}); + +describe('CATEGORY_LABELS', () => { + it('is every label of the mapping and nothing else', () => { + expect([ ...CATEGORY_LABELS ].sort()).toEqual([ + 'bug', 'chore', 'client feature', 'dependencies', 'design', 'devops', 'enhancement', 'feature', 'performance', 'refactoring', 'tech', + ]); + }); + + it('includes the dependencies label', () => { + expect(CATEGORY_LABELS.has(DEPENDENCIES_LABEL)).toBe(true); + }); +}); + +describe('docs/RELEASING.md', () => { + const doc = fs.readFileSync(path.resolve(__dirname, '../../docs/RELEASING.md'), 'utf8'); + + it('reproduces the mapping, in section order', () => { + expect(parseSectionTable(doc)).toEqual(CATEGORIES); + }); + + it('names the module as the source of truth', () => { + expect(doc).toContain('`tools/release/categories.ts`'); + }); +}); diff --git a/tools/release/categories.ts b/tools/release/categories.ts new file mode 100644 index 00000000000..6fecd51c25b --- /dev/null +++ b/tools/release/categories.ts @@ -0,0 +1,27 @@ +// The one source of truth for how a PR's category label places it in the release notes. Order is +// section order in the notes; within a section, label order is irrelevant. + +export interface Category { + readonly section: string; + readonly labels: ReadonlyArray<string>; +} + +export const CATEGORIES: ReadonlyArray<Category> = [ + { section: 'New Features', labels: [ 'feature', 'enhancement', 'client feature' ] }, + { section: 'Bug Fixes', labels: [ 'bug' ] }, + { section: 'Performance Improvements', labels: [ 'performance' ] }, + { section: 'Dependencies Updates', labels: [ 'dependencies' ] }, + { section: 'Design Updates', labels: [ 'design' ] }, + { section: 'DX & Tooling', labels: [ 'refactoring', 'tech', 'devops' ] }, + { section: 'Other Changes', labels: [ 'chore' ] }, +]; + +export const CATEGORY_LABELS: ReadonlySet<string> = new Set(CATEGORIES.flatMap(({ labels }) => labels)); + +// Only for PRs whose sole purpose is a package bump, so it never shares a PR with another category. +export const DEPENDENCIES_LABEL = 'dependencies'; + +export const RELEASE_LABEL = 'release'; + +// The section of a PR that carries no category label, e.g. one merged before the PR check existed. +export const CATCH_ALL_LABEL = 'chore'; diff --git a/tools/release/check-pr.spec.ts b/tools/release/check-pr.spec.ts new file mode 100644 index 00000000000..baada395c82 --- /dev/null +++ b/tools/release/check-pr.spec.ts @@ -0,0 +1,132 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +import { checkPr, parseTemplate } from './check-pr'; + +const TEMPLATE = [ + '## Description', + '', + '*[What this pull request changes and why.]*', + '', + '## Environment variables', + '', + '*[List each environment variable, or "None".]*', + '', +].join('\n'); + +const FILLED_BODY = [ + '## Description', + '', + 'Adds the release tool.', + '', + '## Environment variables', + '', + 'None', +].join('\n'); + +describe('parseTemplate', () => { + it('reads each heading with the italic placeholder lines under it', () => { + expect(parseTemplate(TEMPLATE)).toEqual([ + { heading: '## Description', placeholders: [ '*[What this pull request changes and why.]*' ] }, + { heading: '## Environment variables', placeholders: [ '*[List each environment variable, or "None".]*' ] }, + ]); + }); + + it('ignores prose that is not an italic bracketed placeholder', () => { + expect(parseTemplate('## A\nplain text\n*italic*\n[link](x)\n')).toEqual([ { heading: '## A', placeholders: [] } ]); + }); + + it('reads the repository template: every section has a heading and a placeholder', () => { + const template = fs.readFileSync(path.resolve(__dirname, '../../docs/PULL_REQUEST_TEMPLATE.md'), 'utf8'); + const sections = parseTemplate(template); + + expect(sections.map(({ heading }) => heading)).toEqual([ + '## Description', + '## Environment variables', + '## Minimum API version', + '## Breaking or incompatible changes', + '## Additional information', + ]); + expect(sections.every(({ placeholders }) => placeholders.length === 1)).toBe(true); + }); +}); + +describe('checkPr', () => { + it('passes a filled-in body with one category label', () => { + expect(checkPr(FILLED_BODY, [ 'feature' ], TEMPLATE)).toEqual([]); + }); + + it('ignores labels that are not categories', () => { + expect(checkPr(FILLED_BODY, [ 'QA', 'bug', 'skip checks' ], TEMPLATE)).toEqual([]); + }); + + it('accepts a body with CRLF line endings and indented headings', () => { + const body = FILLED_BODY.replace('## Description', ' ## Description ').replace(/\n/g, '\r\n'); + expect(checkPr(body, [ 'chore' ], TEMPLATE)).toEqual([]); + }); + + it('reports each missing template heading', () => { + expect(checkPr('Adds the release tool.', [ 'chore' ], TEMPLATE)).toEqual([ + 'Missing template heading "## Description"', + 'Missing template heading "## Environment variables"', + ]); + }); + + it('does not accept a heading at another level or with different text', () => { + const body = FILLED_BODY.replace('## Description', '### Description').replace('## Environment variables', '## Env vars'); + expect(checkPr(body, [ 'chore' ], TEMPLATE)).toEqual([ + 'Missing template heading "## Description"', + 'Missing template heading "## Environment variables"', + ]); + }); + + it('reports a placeholder left in place, naming its section', () => { + expect(checkPr(TEMPLATE, [ 'chore' ], TEMPLATE)).toEqual([ + 'Placeholder text left under "## Description"', + 'Placeholder text left under "## Environment variables"', + ]); + }); + + it('reports a placeholder with text appended to it on the same line', () => { + const body = FILLED_BODY.replace('None', '*[List each environment variable, or "None".]* None'); + expect(checkPr(body, [ 'chore' ], TEMPLATE)).toEqual([ 'Placeholder text left under "## Environment variables"' ]); + }); + + it('reports a missing category label, listing the allowed ones', () => { + expect(checkPr(FILLED_BODY, [ 'QA' ], TEMPLATE)).toEqual([ + 'No category label; add one of: feature, enhancement, client feature, bug, performance, dependencies, design, refactoring, tech, devops, chore', + ]); + }); + + it('reports labels from more than one category, grouped by category', () => { + expect(checkPr(FILLED_BODY, [ 'chore', 'bug', 'enhancement', 'feature' ], TEMPLATE)).toEqual([ + 'More than one category: New Features (enhancement, feature); Bug Fixes (bug); Other Changes (chore). Keep labels of one category only', + ]); + }); + + it('passes several labels of the same category', () => { + expect(checkPr(FILLED_BODY, [ 'feature', 'enhancement' ], TEMPLATE)).toEqual([]); + expect(checkPr(FILLED_BODY, [ 'tech', 'devops', 'refactoring' ], TEMPLATE)).toEqual([]); + }); + + it('reports dependencies combined with another category instead of the generic count failure', () => { + expect(checkPr(FILLED_BODY, [ 'dependencies', 'bug', 'design' ], TEMPLATE)).toEqual([ + '"dependencies" is only for PRs that just bump a package and cannot be combined with: bug, design', + ]); + }); + + it('passes dependencies on its own', () => { + expect(checkPr(FILLED_BODY, [ 'dependencies' ], TEMPLATE)).toEqual([]); + }); + + it('reports template and category failures together', () => { + expect(checkPr('', [], TEMPLATE)).toHaveLength(3); + }); + + it('exempts a PR labeled release from every rule', () => { + expect(checkPr('', [ 'release' ], TEMPLATE)).toEqual([]); + expect(checkPr(TEMPLATE, [ 'release', 'bug', 'chore' ], TEMPLATE)).toEqual([]); + }); +}); diff --git a/tools/release/check-pr.ts b/tools/release/check-pr.ts new file mode 100644 index 00000000000..038d2bdfb8a --- /dev/null +++ b/tools/release/check-pr.ts @@ -0,0 +1,65 @@ +import { CATEGORIES, CATEGORY_LABELS, DEPENDENCIES_LABEL, RELEASE_LABEL } from './categories'; + +export interface TemplateSection { + readonly heading: string; + readonly placeholders: ReadonlyArray<string>; +} + +const HEADING = /^#{1,6}\s/; +const PLACEHOLDER = /^\*\[.*\]\*$/; + +function normalizeNewlines(text: string): string { + return text.replace(/\r\n?/g, '\n'); +} + +export function parseTemplate(template: string): Array<TemplateSection> { + const sections: Array<{ heading: string; placeholders: Array<string> }> = []; + for (const line of normalizeNewlines(template).split('\n').map((line) => line.trim())) { + if (HEADING.test(line)) { + sections.push({ heading: line, placeholders: [] }); + } else if (PLACEHOLDER.test(line)) { + sections.at(-1)?.placeholders.push(line); + } + } + return sections; +} + +function templateFailures(body: string, template: string): Array<string> { + const normalizedBody = normalizeNewlines(body); + const bodyLines = new Set(normalizedBody.split('\n').map((line) => line.trim())); + + return parseTemplate(template).flatMap(({ heading, placeholders }) => [ + ...(bodyLines.has(heading) ? [] : [ `Missing template heading "${ heading }"` ]), + ...(placeholders.some((placeholder) => normalizedBody.includes(placeholder)) ? [ `Placeholder text left under "${ heading }"` ] : []), + ]); +} + +function describeCategory(section: string, labels: ReadonlyArray<string>): string { + return `${ section } (${ labels.join(', ') })`; +} + +function categoryFailures(labels: ReadonlyArray<string>): Array<string> { + const matched = CATEGORIES + .map(({ section, labels: sectionLabels }) => ({ section, labels: labels.filter((label) => sectionLabels.includes(label)) })) + .filter((category) => category.labels.length > 0); + + if (matched.length === 0) { + return [ `No category label; add one of: ${ [ ...CATEGORY_LABELS ].join(', ') }` ]; + } + if (matched.length === 1) { + return []; + } + if (labels.includes(DEPENDENCIES_LABEL)) { + const others = matched.flatMap((category) => category.labels).filter((label) => label !== DEPENDENCIES_LABEL); + return [ `"${ DEPENDENCIES_LABEL }" is only for PRs that just bump a package and cannot be combined with: ${ others.join(', ') }` ]; + } + const described = matched.map(({ section, labels: categoryLabels }) => describeCategory(section, categoryLabels)); + return [ `More than one category: ${ described.join('; ') }. Keep labels of one category only` ]; +} + +export function checkPr(body: string, labels: ReadonlyArray<string>, template: string): Array<string> { + if (labels.includes(RELEASE_LABEL)) { + return []; + } + return [ ...templateFailures(body, template), ...categoryFailures(labels) ]; +} diff --git a/tools/release/check-tag.spec.ts b/tools/release/check-tag.spec.ts new file mode 100644 index 00000000000..2e6d0fabd5e --- /dev/null +++ b/tools/release/check-tag.spec.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest'; + +import type { PrLabels } from './check-tag'; +import { bodyPrNumbers, findUpcoming, findVersionedPrs, replaceUpcoming } from './check-tag'; + +describe('findUpcoming', () => { + it('reports every line that still says "upcoming", with its file and line number', () => { + const docs = [ + { path: 'docs/ENVS.md', content: '| Variable | Version |\n| NEXT_PUBLIC_A | v2.12.0+ |\r\n| NEXT_PUBLIC_B | upcoming |\n' }, + { path: 'docs/DEPRECATED_ENVS.md', content: '| NEXT_PUBLIC_C | <Upcoming> |' }, + ]; + + expect(findUpcoming(docs)).toEqual([ + { path: 'docs/ENVS.md', line: 3, text: '| NEXT_PUBLIC_B | upcoming |' }, + { path: 'docs/DEPRECATED_ENVS.md', line: 1, text: '| NEXT_PUBLIC_C | <Upcoming> |' }, + ]); + }); + + it('passes docs whose versions are all released', () => { + expect(findUpcoming([ { path: 'docs/ENVS.md', content: '| NEXT_PUBLIC_A | v2.13.0+ |\n' } ])).toEqual([]); + }); + + it('does not match the word inside another one', () => { + expect(findUpcoming([ { path: 'docs/ENVS.md', content: 'upcomingVersion\nNOT_UPCOMING' } ])).toEqual([]); + }); +}); + +describe('replaceUpcoming', () => { + it('releases every placeholder as the tag and counts them', () => { + const content = '| NEXT_PUBLIC_A | v2.12.0+ |\n| NEXT_PUBLIC_B | upcoming |\n| NEXT_PUBLIC_C | <Upcoming> |\n| NEXT_PUBLIC_D | `upcoming` |\n'; + + expect(replaceUpcoming(content, 'v2.13.0')).toEqual({ + content: '| NEXT_PUBLIC_A | v2.12.0+ |\n| NEXT_PUBLIC_B | v2.13.0+ |\n| NEXT_PUBLIC_C | v2.13.0+ |\n| NEXT_PUBLIC_D | `v2.13.0+` |\n', + count: 3, + }); + }); + + it('leaves the word inside another one alone', () => { + expect(replaceUpcoming('upcomingVersion\nNOT_UPCOMING', 'v2.13.0')).toEqual({ content: 'upcomingVersion\nNOT_UPCOMING', count: 0 }); + }); + + it('leaves nothing for the tag check to flag', () => { + const { content } = replaceUpcoming('| A | upcoming |\n| B | <UPCOMING> |\n| C | Upcoming |', 'v2.13.0'); + + expect(findUpcoming([ { path: 'docs/ENVS.md', content } ])).toEqual([]); + }); +}); + +describe('bodyPrNumbers', () => { + it('reads PR links and ENV entries, once each, in number order', () => { + const body = [ + '- Add the release tool by @tom in https://github.com/blockscout/frontend/pull/3750', + '- Fix a typo by @ann in https://github.com/blockscout/frontend/pull/3701', + '## 🚨 Changes in ENV variables', + '- #3750', + ' - NEXT_PUBLIC_A', + '- #3702\r\n - NEXT_PUBLIC_B', + ].join('\n'); + + expect(bodyPrNumbers(body)).toEqual([ 3701, 3702, 3750 ]); + }); + + it('ignores PR links into other repositories, anchors, and a #N inside a title or copied prose', () => { + const body = [ + '- Revert "Add the badge (#3600)" by @tom in https://github.com/blockscout/frontend/pull/3750', + '## 🚨 Changes in ENV variables', + '- #3750', + ' - NEXT_PUBLIC_A replaces the one from #3600', + ' - #3601 is unrelated', + '## 💑 Compatibility', + 'See https://github.com/blockscout/blockscout/pull/9001', + 'https://github.com/blockscout/frontend/blob/v2.13.0/docs/ENVS.md#L12', + ].join('\n'); + + expect(bodyPrNumbers(body)).toEqual([ 3750 ]); + }); +}); + +describe('findVersionedPrs', () => { + const labels = new Map<number, ReadonlyArray<string>>([ + [ 1, [ 'bug' ] ], + [ 2, [ 'bug', 'v2.12.1' ] ], + [ 3, [ 'feature', 'v2.13.0' ] ], + [ 4, [ 'pre-release', 'backport' ] ], + ]); + const prLabels: PrLabels = (number) => labels.get(number); + + it('reports PRs already carrying the version label of another release', () => { + expect(findVersionedPrs('- #1\n- #2\n- #4', prLabels, 'v2.13.0')).toEqual([ { number: 2, versionLabels: [ 'v2.12.1' ] } ]); + }); + + it('does not count the tag\'s own version label, which the release workflow applies concurrently', () => { + expect(findVersionedPrs('- #3', prLabels, 'v2.13.0')).toEqual([]); + expect(findVersionedPrs('- #3', prLabels, 'v2.13.0-alpha.2')).toEqual([]); + }); + + it('reports the label of an earlier release of the same line', () => { + expect(findVersionedPrs('- #3', prLabels, 'v2.13.1')).toEqual([ { number: 3, versionLabels: [ 'v2.13.0' ] } ]); + }); + + it('skips references that are issues, not PRs', () => { + expect(findVersionedPrs('- #99', prLabels, 'v2.13.0')).toEqual([]); + }); + + it('passes an empty body', () => { + expect(findVersionedPrs('', prLabels, 'v2.13.0')).toEqual([]); + }); +}); diff --git a/tools/release/check-tag.ts b/tools/release/check-tag.ts new file mode 100644 index 00000000000..7cbe69294f2 --- /dev/null +++ b/tools/release/check-tag.ts @@ -0,0 +1,68 @@ +import { isReleasedElsewhere } from './release-prs'; +import { isVersionLabel } from './versions'; + +export interface Doc { + readonly path: string; + readonly content: string; +} + +export interface UpcomingMention { + readonly path: string; + readonly line: number; + readonly text: string; +} + +export interface VersionedPr { + readonly number: number; + readonly versionLabels: ReadonlyArray<string>; +} + +// Undefined when the number is an issue: a `#N` reference can name either. +export type PrLabels = (number: number) => ReadonlyArray<string> | undefined; + +export const ENV_DOCS = [ 'docs/ENVS.md', 'docs/DEPRECATED_ENVS.md' ]; + +const UPCOMING = /\bupcoming\b/i; +// Every mention the check above flags, with the `<upcoming>` spelling swallowed whole. +const UPCOMING_PLACEHOLDER = /<upcoming>|\bupcoming\b/gi; +// Only links into this repository: a backend PR quoted in the notes has a number of its own. +const PR_LINK = /github\.com\/blockscout\/frontend\/pull\/(\d+)\b/g; +// Only the entries the generator writes: a `#N` inside a PR title ("Revert … (#N)") or copied prose names a +// PR the notes do not list. +const ENV_ENTRY = /^- #(\d+)$/gm; + +export function findUpcoming(docs: ReadonlyArray<Doc>): Array<UpcomingMention> { + return docs.flatMap(({ path, content }) => content + .replace(/\r\n?/g, '\n') + .split('\n') + .map((text, index) => ({ path, line: index + 1, text: text.trim() })) + .filter(({ text }) => UPCOMING.test(text))); +} + +export interface UpcomingReplacement { + readonly content: string; + readonly count: number; +} + +export function replaceUpcoming(content: string, tag: string): UpcomingReplacement { + return { + content: content.replace(UPCOMING_PLACEHOLDER, `${ tag }+`), + count: content.match(UPCOMING_PLACEHOLDER)?.length ?? 0, + }; +} + +export function bodyPrNumbers(body: string): Array<number> { + const numbers = [ ...body.matchAll(PR_LINK), ...body.replace(/\r\n?/g, '\n').matchAll(ENV_ENTRY) ].map(([ , number ]) => Number(number)); + return [ ...new Set(numbers) ].sort((a, b) => a - b); +} + +// The tag's own version label does not count: `release.yml` labels the shipped PRs while this check runs. +export function findVersionedPrs(releaseBody: string, prLabels: PrLabels, tag: string): Array<VersionedPr> { + return bodyPrNumbers(releaseBody).flatMap((number) => { + const labels = prLabels(number); + if (labels === undefined || !isReleasedElsewhere(labels, tag)) { + return []; + } + return [ { number, versionLabels: labels.filter(isVersionLabel) } ]; + }); +} diff --git a/tools/release/commands/alpha.spec.ts b/tools/release/commands/alpha.spec.ts new file mode 100644 index 00000000000..0909f9c4234 --- /dev/null +++ b/tools/release/commands/alpha.spec.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; + +import { alphaState, parseAlphaArgs } from './alpha'; + +const HEAD = '0123456789abcdef0123456789abcdef01234567'; +const OTHER = 'fedcba9876543210fedcba9876543210fedcba98'; + +function preRelease(tagName: string, draft = false) { + return { id: 1, tagName, draft, prerelease: true, url: `https://github.com/blockscout/frontend/releases/tag/${ tagName }` }; +} + +describe('alphaState', () => { + it('is new when the tag is not on origin', () => { + expect(alphaState('v2.13.0-alpha.2', 'release/v2.13.0', undefined, HEAD, preRelease('v2.13.0-alpha.1'))).toBe('new'); + }); + + it('resumes a tag at the pushed branch head that the published pre-release points at', () => { + expect(alphaState('v2.13.0-alpha.2', 'release/v2.13.0', HEAD, HEAD, preRelease('v2.13.0-alpha.2'))).toBe('published'); + }); + + it('refuses a tag on origin that is not the pushed branch head', () => { + expect(() => alphaState('v2.13.0-alpha.2', 'release/v2.13.0', OTHER, HEAD, preRelease('v2.13.0-alpha.1'))).toThrow( + 'v2.13.0-alpha.2 is on origin at fedcba9876, not at the head of origin/release/v2.13.0 (0123456789)', + ); + }); + + it('refuses a tag at the branch head that the pre-release does not point at', () => { + expect(() => alphaState('v2.13.0-alpha.2', 'release/v2.13.0', HEAD, HEAD, preRelease('v2.13.0-alpha.1'))).toThrow( + 'v2.13.0-alpha.2 is on origin at the head of origin/release/v2.13.0, but the pre-release still points at v2.13.0-alpha.1 ' + + '(https://github.com/blockscout/frontend/releases/tag/v2.13.0-alpha.1); re-point it to v2.13.0-alpha.2 by hand, or delete the tag from origin and re-run', + ); + }); + + it('refuses a tag at the branch head that a draft pre-release points at', () => { + expect(() => alphaState('v2.13.0-alpha.2', 'release/v2.13.0', HEAD, HEAD, preRelease('v2.13.0-alpha.2', true))).toThrow( + 'v2.13.0-alpha.2 is on origin at the head of origin/release/v2.13.0 and the pre-release points at it, but is still a draft ' + + '(https://github.com/blockscout/frontend/releases/tag/v2.13.0-alpha.2); publish it by hand, or delete the tag from origin and re-run', + ); + }); +}); + +describe('parseAlphaArgs', () => { + it('reads the alpha tag and its version', () => { + expect(parseAlphaArgs([ 'v2.13.1-alpha.2' ])).toEqual({ + tag: 'v2.13.1-alpha.2', + version: { major: 2, minor: 13, patch: 1, prerelease: 'alpha.2' }, + dryRun: false, + }); + }); + + it('reads the dry run', () => { + expect(parseAlphaArgs([ '--dry-run', 'v2.13.0-alpha.1' ])).toMatchObject({ tag: 'v2.13.0-alpha.1', dryRun: true }); + }); + + it.each([ + [ 'no tag', [] ], + [ 'two tags', [ 'v2.13.0-alpha.1', 'v2.13.0-alpha.2' ] ], + ])('rejects %s with the usage', (_, args) => { + expect(() => parseAlphaArgs(args)).toThrow('Usage: pnpm release alpha <vX.Y.Z-alpha.N>'); + }); + + it('rejects a final tag', () => { + expect(() => parseAlphaArgs([ 'v2.13.0' ])).toThrow('Not an alpha tag: "v2.13.0"'); + }); + + it('rejects an unknown flag', () => { + expect(() => parseAlphaArgs([ 'v2.13.0-alpha.1', '--force' ])).toThrow('Unknown flag: --force'); + }); +}); diff --git a/tools/release/commands/alpha.ts b/tools/release/commands/alpha.ts new file mode 100644 index 00000000000..8ba0a69f611 --- /dev/null +++ b/tools/release/commands/alpha.ts @@ -0,0 +1,138 @@ +/* eslint-disable no-console -- CLI subcommand, console output is the interface */ +import { createTag, fetchBranch, hasRemoteRef, push, pushBranch, REMOTE, remoteBranch, resolveCommit } from '../git'; +import { fetchPrLabels, listReleases, publishPreRelease } from '../github'; +import type { ReleaseNotes } from '../notes'; +import { releaseNotes } from '../notes'; +import type { GithubRelease } from '../pre-release'; +import { findReleasePreRelease } from '../pre-release'; +import { releaseSourceAt } from '../release-source'; +import type { Version } from '../versions'; +import { formatVersion, parseAlphaTagOrThrow, releaseBranch } from '../versions'; +import { parsePhaseArgs } from './args'; +import { checkTag } from './check-tag'; +import { readNotesTemplate } from './notes'; +import type { BranchView } from './release-branch'; +import { checkoutBranch, updateReleaseBranch } from './release-branch'; +import type { StepRunner } from './report'; +import { logList, logReleaseNotes, stepRunner } from './report'; +import { assertTagIsNew, watchTagRun } from './tag-run'; + +const USAGE = `Usage: pnpm release alpha <vX.Y.Z-alpha.N> [--dry-run] + + picks the merged "backport" PRs onto release/vX.Y.Z, releases "upcoming" in the ENV docs, tags the head + once it passes the tag check, publishes the release's pre-release re-pointed to the tag with regenerated + notes, which creates the tag on GitHub and fires pre-release.yml, pushes the branch and watches the run`; + +const WORKFLOW = 'pre-release.yml'; + +export interface AlphaArgs { + readonly tag: string; + readonly version: Version; + readonly dryRun: boolean; +} + +export function parseAlphaArgs(args: ReadonlyArray<string>): AlphaArgs { + const { target, dryRun } = parsePhaseArgs(args, USAGE); + return { tag: target, version: parseAlphaTagOrThrow(target), dryRun }; +} + +// The tag on origin is where an earlier run got to: the publish that creates the tag went through and the +// run stopped at the push or the watch, and the re-run does not tag or publish again. It is judged against +// the branch on origin, before the checkout: a "backport" PR merged since is the next alpha's, not this one's. +// A tag elsewhere than that head is not this alpha, and a tag the pre-release does not point at, or points +// at while still a draft, was not made by the publish. +export function alphaState(tag: string, branch: string, taggedSha: string | undefined, pushedHead: string, preRelease: GithubRelease): 'new' | 'published' { + if (taggedSha === undefined) { + return 'new'; + } + if (taggedSha !== pushedHead) { + throw new Error(`${ tag } is on ${ REMOTE } at ${ taggedSha.slice(0, 10) }, not at the head of ${ remoteBranch(branch) } (${ pushedHead.slice(0, 10) })`); + } + if (preRelease.tagName !== tag) { + throw new Error(`${ tag } is on ${ REMOTE } at the head of ${ remoteBranch(branch) }, but the pre-release still points at ${ preRelease.tagName } ` + + `(${ preRelease.url }); re-point it to ${ tag } by hand, or delete the tag from ${ REMOTE } and re-run`); + } + if (preRelease.draft) { + throw new Error(`${ tag } is on ${ REMOTE } at the head of ${ remoteBranch(branch) } and the pre-release points at it, but is still a draft ` + + `(${ preRelease.url }); publish it by hand, or delete the tag from ${ REMOTE } and re-run`); + } + return 'published'; +} + +interface Alpha { + readonly tag: string; + readonly branch: string; + readonly head: string; + readonly notes: ReleaseNotes; + readonly preRelease: GithubRelease; +} + +function checkAlpha({ tag, notes }: Alpha, view: BranchView): boolean { + const { failures } = checkTag(tag, { readDoc: view.readDoc, releaseBodies: () => [ notes.markdown ], prLabels: fetchPrLabels }); + if (failures.length > 0) { + logList(`\nTag ${ tag } fails the tag check, nothing tagged or pushed`, failures); + } + return failures.length === 0; +} + +function alphaSteps(steps: StepRunner, { tag, branch, head, notes, preRelease }: Alpha): void { + const content = { tagName: tag, target: head, body: notes.markdown }; + steps.run(`Tag ${ branch } at ${ head.slice(0, 10) } as ${ tag }`, () => createTag(tag, head)); + // The branch goes first: the publish names the head as the release target, which GitHub must already have. + steps.run(`Push ${ branch } to ${ REMOTE }`, () => pushBranch(branch)); + const publishTitle = `Publish the pre-release ${ preRelease.tagName } re-pointed to ${ tag } with its notes replaced, ` + + `which creates the tag and fires ${ WORKFLOW }: ${ preRelease.url }`; + steps.run(publishTitle, () => { + console.log(publishPreRelease(preRelease.id, content).url); + }); + steps.run(`Push ${ tag } to ${ REMOTE }, a no-op once the publish created it`, () => push(`refs/tags/${ tag }`)); +} + +function watchAlphaRun(steps: StepRunner, tag: string): void { + steps.run(`Watch the ${ WORKFLOW } run of ${ tag }`, () => watchTagRun(WORKFLOW, tag, 'push')); + steps.finish(); +} + +export function alphaCommand(args: ReadonlyArray<string>): number { + const { tag, version, dryRun } = parseAlphaArgs(args); + const releaseTag = formatVersion(version); + const branch = releaseBranch(version); + + if (!hasRemoteRef(`refs/heads/${ branch }`)) { + throw new Error(`${ branch } is not on ${ REMOTE }; cut it with "pnpm release prepare ${ releaseTag }"`); + } + fetchBranch(branch); + fetchBranch('main'); + const pushedHead = resolveCommit(remoteBranch(branch)); + const preRelease = findReleasePreRelease(listReleases(), version); + const state = alphaState(tag, branch, hasRemoteRef(`refs/tags/${ tag }`) ? resolveCommit(tag) : undefined, pushedHead, preRelease); + if (state === 'new') { + assertTagIsNew(tag); + } + + const steps = stepRunner(dryRun); + if (state === 'published') { + console.error(`${ tag } is already on ${ REMOTE } at the head of ${ remoteBranch(branch) } and the pre-release points at it; ` + + `resuming with the ${ WORKFLOW } run.`); + console.log(preRelease.url); + watchAlphaRun(steps, tag); + return 0; + } + + const view = checkoutBranch(steps, branch, dryRun); + updateReleaseBranch(steps, view, releaseTag); + const head = view.head(); + const notes = releaseNotes(tag, releaseSourceAt(head), readNotesTemplate()); + logReleaseNotes(tag, notes); + const alpha: Alpha = { tag, branch, head, notes, preRelease }; + if (!checkAlpha(alpha, view)) { + return 1; + } + alphaSteps(steps, alpha); + watchAlphaRun(steps, tag); + + if (dryRun) { + console.log(notes.markdown); + } + return 0; +} diff --git a/tools/release/commands/args.ts b/tools/release/commands/args.ts new file mode 100644 index 00000000000..5df0a88f9e7 --- /dev/null +++ b/tools/release/commands/args.ts @@ -0,0 +1,25 @@ +import type { FlagSpec } from '../../cli/flags'; +import { parseArgs } from '../../cli/flags'; + +export interface PhaseArgs { + readonly target: string; + readonly dryRun: boolean; +} + +interface Options { + dryRun: boolean; +} + +const FLAGS: ReadonlyMap<string, FlagSpec<Options>> = new Map<string, FlagSpec<Options>>([ + [ '--dry-run', { kind: 'switch', apply: (options) => { + options.dryRun = true; + } } ], +]); + +export function parsePhaseArgs(args: ReadonlyArray<string>, usage: string): PhaseArgs { + const { options, rest } = parseArgs<Options>(args, FLAGS, { dryRun: false }, { kind: 'reject', usage }); + if (rest.length !== 1) { + throw new Error(usage); + } + return { target: rest[0], dryRun: options.dryRun }; +} diff --git a/tools/release/commands/check-pr.spec.ts b/tools/release/commands/check-pr.spec.ts new file mode 100644 index 00000000000..94b300a4e9d --- /dev/null +++ b/tools/release/commands/check-pr.spec.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest'; + +import { parsePrNumber } from './check-pr'; + +const USAGE = 'Usage: pnpm release check-pr <number>'; + +describe('parsePrNumber', () => { + it('reads the PR number', () => { + expect(parsePrNumber([ '3747' ])).toBe(3747); + }); + + it.each([ + [ 'no argument', [] ], + [ 'two arguments', [ '1', '2' ] ], + [ 'a non-number', [ 'abc' ] ], + [ 'a hash-prefixed number', [ '#3747' ] ], + [ 'zero', [ '0' ] ], + ])('rejects %s with the usage', (_, args) => { + expect(() => parsePrNumber(args)).toThrow(USAGE); + }); + + it('rejects an unknown flag', () => { + expect(() => parsePrNumber([ '3747', '--dry-run' ])).toThrow('Unknown flag: --dry-run'); + }); +}); diff --git a/tools/release/commands/check-pr.ts b/tools/release/commands/check-pr.ts new file mode 100644 index 00000000000..2dd6f1012cc --- /dev/null +++ b/tools/release/commands/check-pr.ts @@ -0,0 +1,38 @@ +/* eslint-disable no-console -- CLI subcommand, console output is the interface */ +import fs from 'node:fs'; +import path from 'node:path'; + +import { parseArgs } from '../../cli/flags'; +import { checkPr } from '../check-pr'; +import { repoRoot } from '../git'; +import { fetchPullRequest } from '../github'; + +const USAGE = 'Usage: pnpm release check-pr <number>'; +const TEMPLATE_PATH = 'docs/PULL_REQUEST_TEMPLATE.md'; + +export function parsePrNumber(args: ReadonlyArray<string>): number { + const { rest } = parseArgs(args, new Map(), {}, { kind: 'reject', usage: USAGE }); + if (rest.length !== 1 || !/^[1-9]\d*$/.test(rest[0])) { + throw new Error(USAGE); + } + return Number(rest[0]); +} + +export function checkPrCommand(args: ReadonlyArray<string>): number { + const number = parsePrNumber(args); + const template = fs.readFileSync(path.join(repoRoot(), TEMPLATE_PATH), 'utf8'); + const pr = fetchPullRequest(number); + const failures = checkPr(pr.body, pr.labels, template); + + if (failures.length === 0) { + console.log(`PR #${ number } passes the PR check.`); + return 0; + } + + console.error(`PR #${ number } fails the PR check:`); + for (const failure of failures) { + console.error(` - ${ failure }`); + } + console.error(`\nKeep every heading of ${ TEMPLATE_PATH } with its placeholder replaced, and set exactly one category label.`); + return 1; +} diff --git a/tools/release/commands/check-tag.spec.ts b/tools/release/commands/check-tag.spec.ts new file mode 100644 index 00000000000..7b51deeba38 --- /dev/null +++ b/tools/release/commands/check-tag.spec.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest'; + +import type { TagCheckSource } from './check-tag'; +import { checkTag, parseCheckTagArgs } from './check-tag'; + +describe('parseCheckTagArgs', () => { + it('reads the tag', () => { + expect(parseCheckTagArgs([ 'v2.13.0-alpha.1' ])).toBe('v2.13.0-alpha.1'); + }); + + it.each([ + [ 'no tag', [] ], + [ 'two tags', [ 'v2.13.0', 'v2.13.1' ] ], + ])('rejects %s with the usage', (_, args) => { + expect(() => parseCheckTagArgs(args)).toThrow('Usage: pnpm release check-tag <tag>'); + }); + + it('rejects a tag that is not a release tag', () => { + expect(() => parseCheckTagArgs([ 'main' ])).toThrow('Not a release tag: "main"'); + }); + + it('rejects an unknown flag', () => { + expect(() => parseCheckTagArgs([ 'v2.13.0', '--dry-run' ])).toThrow('Unknown flag: --dry-run'); + }); +}); + +function source(docs: Record<string, string>, bodies: ReadonlyArray<string>): TagCheckSource { + const labels = new Map<number, ReadonlyArray<string>>([ [ 3708, [ 'bug', 'v2.11.2' ] ], [ 3750, [ 'feature' ] ] ]); + return { + readDoc: (docPath) => docs[docPath] ?? '', + releaseBodies: () => bodies, + prLabels: (number) => labels.get(number), + }; +} + +describe('checkTag', () => { + const cleanDocs = { 'docs/ENVS.md': '| A | v2.13.0+ |', 'docs/DEPRECATED_ENVS.md': '| B | v2.12.0+ |' }; + + it('passes released docs and notes of unshipped PRs', () => { + expect(checkTag('v2.13.0', source(cleanDocs, [ '- #3750' ]))).toEqual({ hasRelease: true, failures: [] }); + }); + + it('passes the notes check when the tag has no release', () => { + expect(checkTag('v2.13.0', source(cleanDocs, []))).toEqual({ hasRelease: false, failures: [] }); + }); + + it('reports each stale doc line and each shipped PR, across every release of the tag', () => { + const docs = { 'docs/ENVS.md': '| A | upcoming |', 'docs/DEPRECATED_ENVS.md': '| B | upcoming |' }; + + expect(checkTag('v2.13.0', source(docs, [ '- #3750', 'https://github.com/blockscout/frontend/pull/3708' ]))).toEqual({ + hasRelease: true, + failures: [ + 'docs/ENVS.md:1 still says "upcoming": | A | upcoming |', + 'docs/DEPRECATED_ENVS.md:1 still says "upcoming": | B | upcoming |', + '#3708 is listed in the notes but already shipped in v2.11.2', + ], + }); + }); +}); diff --git a/tools/release/commands/check-tag.ts b/tools/release/commands/check-tag.ts new file mode 100644 index 00000000000..aac13c74030 --- /dev/null +++ b/tools/release/commands/check-tag.ts @@ -0,0 +1,70 @@ +/* eslint-disable no-console -- CLI subcommand, console output is the interface */ +import fs from 'node:fs'; +import path from 'node:path'; + +import { parseArgs } from '../../cli/flags'; +import type { PrLabels } from '../check-tag'; +import { ENV_DOCS, findUpcoming, findVersionedPrs } from '../check-tag'; +import { repoRoot } from '../git'; +import { fetchPrLabels, fetchReleaseBodies } from '../github'; +import { parseTagOrThrow } from '../versions'; + +const USAGE = `Usage: pnpm release check-tag <tag> + + fails when the ENV docs in the checkout still say "upcoming", or when the tag's GitHub release lists a PR + already shipped by another release`; + +export interface TagCheckSource { + readonly readDoc: (path: string) => string; + readonly releaseBodies: (tag: string) => ReadonlyArray<string>; + readonly prLabels: PrLabels; +} + +export interface TagCheck { + readonly hasRelease: boolean; + readonly failures: ReadonlyArray<string>; +} + +export function parseCheckTagArgs(args: ReadonlyArray<string>): string { + const { rest } = parseArgs(args, new Map(), {}, { kind: 'reject', usage: USAGE }); + if (rest.length !== 1) { + throw new Error(USAGE); + } + const [ tag ] = rest; + parseTagOrThrow(tag); + return tag; +} + +export function checkTag(tag: string, source: TagCheckSource): TagCheck { + const docs = ENV_DOCS.map((docPath) => ({ path: docPath, content: source.readDoc(docPath) })); + const bodies = source.releaseBodies(tag); + const upcoming = findUpcoming(docs) + .map(({ path: docPath, line, text }) => `${ docPath }:${ line } still says "upcoming": ${ text }`); + const versioned = findVersionedPrs(bodies.join('\n'), source.prLabels, tag) + .map(({ number, versionLabels }) => `#${ number } is listed in the notes but already shipped in ${ versionLabels.join(', ') }`); + return { hasRelease: bodies.length > 0, failures: [ ...upcoming, ...versioned ] }; +} + +export function checkTagCommand(args: ReadonlyArray<string>): number { + const tag = parseCheckTagArgs(args); + const root = repoRoot(); + const { hasRelease, failures } = checkTag(tag, { + readDoc: (docPath) => fs.readFileSync(path.join(root, docPath), 'utf8'), + releaseBodies: fetchReleaseBodies, + prLabels: fetchPrLabels, + }); + + if (!hasRelease) { + console.error(`No GitHub release for ${ tag }; the notes check is skipped.`); + } + if (failures.length === 0) { + console.log(`Tag ${ tag } passes the tag check.`); + return 0; + } + + console.error(`Tag ${ tag } fails the tag check:`); + for (const failure of failures) { + console.error(` - ${ failure }`); + } + return 1; +} diff --git a/tools/release/commands/label.spec.ts b/tools/release/commands/label.spec.ts new file mode 100644 index 00000000000..e906c072512 --- /dev/null +++ b/tools/release/commands/label.spec.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest'; + +import { parseLabelArgs, shippedBackports } from './label'; + +describe('parseLabelArgs', () => { + it('reads an apply with its label defaults', () => { + expect(parseLabelArgs([ 'v2.13.0', '--label', 'v2.13.0' ])).toEqual({ + tag: 'v2.13.0', + action: { kind: 'apply', label: 'v2.13.0', description: '', color: 'FFFFFF' }, + dryRun: false, + }); + }); + + it('reads the label description, color and dry run', () => { + const args = [ 'v2.13.0-alpha.1', '--label=pre-release', '--description=Tasks in pre-release right now', '--color', '0E8A16', '--dry-run' ]; + + expect(parseLabelArgs(args)).toEqual({ + tag: 'v2.13.0-alpha.1', + action: { kind: 'apply', label: 'pre-release', description: 'Tasks in pre-release right now', color: '0E8A16' }, + dryRun: true, + }); + }); + + it('accepts an empty description', () => { + expect(parseLabelArgs([ 'v2.13.0', '--label=v2.13.0', '--description=' ]).action).toMatchObject({ description: '' }); + }); + + it('reads a removal', () => { + expect(parseLabelArgs([ 'v2.13.0', '--remove', 'pre-release' ])).toEqual({ + tag: 'v2.13.0', + action: { kind: 'remove', label: 'pre-release' }, + dryRun: false, + }); + }); + + it.each([ + [ 'neither --label nor --remove', [ 'v2.13.0' ] ], + [ 'both --label and --remove', [ 'v2.13.0', '--label', 'a', '--remove', 'b' ] ], + ])('rejects %s', (_, args) => { + expect(() => parseLabelArgs(args)).toThrow('Pass exactly one of --label and --remove'); + }); + + it.each([ + [ 'no tag', [ '--label', 'v2.13.0' ] ], + [ 'two tags', [ 'v2.13.0', 'v2.13.1', '--label', 'v2.13.0' ] ], + ])('rejects %s with the usage', (_, args) => { + expect(() => parseLabelArgs(args)).toThrow('Usage: pnpm release label <tag>'); + }); + + it('rejects a tag that is not a release tag', () => { + expect(() => parseLabelArgs([ 'main', '--label', 'v2.13.0' ])).toThrow('Not a release tag: "main"'); + }); + + it('rejects an unknown flag', () => { + expect(() => parseLabelArgs([ 'v2.13.0', '--label', 'v2.13.0', '--force' ])).toThrow('Unknown flag: --force'); + }); +}); + +describe('shippedBackports', () => { + const pr = (number: number, labels: ReadonlyArray<string>) => ({ number, title: '', author: '', url: '', body: '', labels, closingIssues: [] }); + const prs = [ pr(1, [ 'bug', 'backport' ]), pr(2, [ 'feature' ]), pr(3, [ 'backport' ]) ]; + + it('names the shipped PRs that carry "backport" when the label is a version', () => { + expect(shippedBackports(prs, 'v2.13.1')).toEqual([ 1, 3 ]); + }); + + it('drops nothing for a label that is not a version', () => { + expect(shippedBackports(prs, 'pre-release')).toEqual([]); + }); +}); diff --git a/tools/release/commands/label.ts b/tools/release/commands/label.ts new file mode 100644 index 00000000000..492a4143476 --- /dev/null +++ b/tools/release/commands/label.ts @@ -0,0 +1,128 @@ +/* eslint-disable no-console -- CLI subcommand, console output is the interface */ +import type { FlagSpec } from '../../cli/flags'; +import { parseArgs } from '../../cli/flags'; +import { addLabel, BACKPORT_LABEL, ensureLabel, listLabeled, removeLabel } from '../github'; +import type { ReleasePullRequest } from '../release-prs'; +import { issuesToLabel, releasePrs } from '../release-prs'; +import { RELEASE_SOURCE } from '../release-source'; +import { isVersionLabel, parseTagOrThrow } from '../versions'; +import { describePr, logExclusions, logList } from './report'; + +const USAGE = `Usage: pnpm release label <tag> --label <name> [--description <text>] [--color <hex>] [--dry-run] + pnpm release label <tag> --remove <name> [--dry-run] + + --label label the PRs the tag shipped and the issues they close; prints the issue numbers as JSON + --remove remove the label from every PR and issue that carries it`; + +export type LabelAction = + { readonly kind: 'apply'; readonly label: string; readonly description: string; readonly color: string } | + { readonly kind: 'remove'; readonly label: string }; + +export interface LabelArgs { + readonly tag: string; + readonly action: LabelAction; + readonly dryRun: boolean; +} + +interface Options { + label: string | undefined; + remove: string | undefined; + description: string; + color: string; + dryRun: boolean; +} + +const DEFAULT_OPTIONS: Options = { label: undefined, remove: undefined, description: '', color: 'FFFFFF', dryRun: false }; + +const FLAGS: ReadonlyMap<string, FlagSpec<Options>> = new Map<string, FlagSpec<Options>>([ + [ '--label', { kind: 'value', apply: (options, value) => { + options.label = value; + } } ], + [ '--remove', { kind: 'value', apply: (options, value) => { + options.remove = value; + } } ], + [ '--description', { kind: 'value', apply: (options, value) => { + options.description = value; + } } ], + [ '--color', { kind: 'value', apply: (options, value) => { + options.color = value; + } } ], + [ '--dry-run', { kind: 'switch', apply: (options) => { + options.dryRun = true; + } } ], +]); + +function toAction({ label, remove, description, color }: Options): LabelAction { + if (label !== undefined && remove === undefined) { + return { kind: 'apply', label, description, color }; + } + if (remove !== undefined && label === undefined) { + return { kind: 'remove', label: remove }; + } + throw new Error(`Pass exactly one of --label and --remove\n${ USAGE }`); +} + +export function parseLabelArgs(args: ReadonlyArray<string>): LabelArgs { + const { options, rest } = parseArgs<Options>(args, FLAGS, { ...DEFAULT_OPTIONS }, { kind: 'reject', usage: USAGE }); + if (rest.length !== 1) { + throw new Error(USAGE); + } + const [ tag ] = rest; + parseTagOrThrow(tag); + return { tag, action: toAction(options), dryRun: options.dryRun }; +} + +// The version label replaces `backport` on the PRs it ships; a PR that was never picked is not in `prs` +// and keeps it for the next release. +export function shippedBackports(prs: ReadonlyArray<ReleasePullRequest>, label: string): Array<number> { + return isVersionLabel(label) ? prs.filter((pr) => pr.labels.includes(BACKPORT_LABEL)).map(({ number }) => number) : []; +} + +function applyLabel(tag: string, action: Extract<LabelAction, { kind: 'apply' }>, dryRun: boolean): number { + const { previousTag, prs, skipped, unresolved } = releasePrs(tag, RELEASE_SOURCE); + const issues = issuesToLabel(prs, tag); + const backports = shippedBackports(prs, action.label); + + console.error(`Release ${ tag }, compared with ${ previousTag }`); + logList('PRs to label', prs.map(describePr)); + logExclusions(skipped, unresolved); + logList('Issues to label', issues.map((number) => `#${ number }`)); + logList(`PRs to drop "${ BACKPORT_LABEL }" from`, backports.map((number) => `#${ number }`)); + + if (dryRun) { + console.error(`\nDry run: label "${ action.label }" not applied.`); + } else { + console.error(`\nLabel "${ action.label }" ${ ensureLabel(action.label, action.description, action.color) }.`); + for (const number of [ ...prs.map((pr) => pr.number), ...issues ]) { + addLabel(number, action.label); + } + for (const number of backports) { + removeLabel(number, BACKPORT_LABEL); + } + console.error(`Labeled ${ prs.length } PRs and ${ issues.length } issues with "${ action.label }".`); + console.error(`Dropped "${ BACKPORT_LABEL }" from ${ backports.length } PRs.`); + } + + console.log(JSON.stringify(issues)); + return 0; +} + +function removeLabelEverywhere(label: string, dryRun: boolean): number { + const numbers = listLabeled(label); + logList(`PRs and issues labeled "${ label }"`, numbers.map((number) => `#${ number }`)); + + if (dryRun) { + console.error(`\nDry run: label "${ label }" not removed.`); + return 0; + } + for (const number of numbers) { + removeLabel(number, label); + } + console.error(`Removed "${ label }" from ${ numbers.length } PRs and issues.`); + return 0; +} + +export function labelCommand(args: ReadonlyArray<string>): number { + const { tag, action, dryRun } = parseLabelArgs(args); + return action.kind === 'apply' ? applyLabel(tag, action, dryRun) : removeLabelEverywhere(action.label, dryRun); +} diff --git a/tools/release/commands/notes.spec.ts b/tools/release/commands/notes.spec.ts new file mode 100644 index 00000000000..b5690234b4d --- /dev/null +++ b/tools/release/commands/notes.spec.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; + +import { parseNotesArgs } from './notes'; + +describe('parseNotesArgs', () => { + it('reads the tag, printing to stdout by default', () => { + expect(parseNotesArgs([ 'v2.13.0' ])).toEqual({ tag: 'v2.13.0', out: undefined }); + }); + + it('reads the output file', () => { + expect(parseNotesArgs([ 'v2.13.0-alpha.1', '--out', 'notes.md' ])).toEqual({ tag: 'v2.13.0-alpha.1', out: 'notes.md' }); + }); + + it.each([ + [ 'no tag', [] ], + [ 'two tags', [ 'v2.13.0', 'v2.13.1' ] ], + ])('rejects %s with the usage', (_, args) => { + expect(() => parseNotesArgs(args)).toThrow('Usage: pnpm release notes <tag>'); + }); + + it('rejects a tag that is not a release tag', () => { + expect(() => parseNotesArgs([ 'main' ])).toThrow('Not a release tag: "main"'); + }); + + it('rejects an unknown flag', () => { + expect(() => parseNotesArgs([ 'v2.13.0', '--dry-run' ])).toThrow('Unknown flag: --dry-run'); + }); +}); diff --git a/tools/release/commands/notes.ts b/tools/release/commands/notes.ts new file mode 100644 index 00000000000..4edd739fe3d --- /dev/null +++ b/tools/release/commands/notes.ts @@ -0,0 +1,60 @@ +/* eslint-disable no-console -- CLI subcommand, console output is the interface */ +import fs from 'node:fs'; +import path from 'node:path'; + +import type { FlagSpec } from '../../cli/flags'; +import { parseArgs } from '../../cli/flags'; +import { repoRoot } from '../git'; +import { releaseNotes } from '../notes'; +import { RELEASE_SOURCE } from '../release-source'; +import { parseTagOrThrow } from '../versions'; +import { logReleaseNotes } from './report'; + +const USAGE = `Usage: pnpm release notes <tag> [--out <file>] + + prints the release notes of the tag, or writes them to --out`; + +const TEMPLATE_PATH = 'tools/release/notes-template.md'; + +export function readNotesTemplate(): string { + return fs.readFileSync(path.join(repoRoot(), TEMPLATE_PATH), 'utf8'); +} + +export interface NotesArgs { + readonly tag: string; + readonly out: string | undefined; +} + +interface Options { + out: string | undefined; +} + +const FLAGS: ReadonlyMap<string, FlagSpec<Options>> = new Map<string, FlagSpec<Options>>([ + [ '--out', { kind: 'value', apply: (options, value) => { + options.out = value; + } } ], +]); + +export function parseNotesArgs(args: ReadonlyArray<string>): NotesArgs { + const { options, rest } = parseArgs<Options>(args, FLAGS, { out: undefined }, { kind: 'reject', usage: USAGE }); + if (rest.length !== 1) { + throw new Error(USAGE); + } + const [ tag ] = rest; + parseTagOrThrow(tag); + return { tag, out: options.out }; +} + +export function notesCommand(args: ReadonlyArray<string>): number { + const { tag, out } = parseNotesArgs(args); + const notes = releaseNotes(tag, RELEASE_SOURCE, readNotesTemplate()); + logReleaseNotes(tag, notes); + + if (out === undefined) { + console.log(notes.markdown); + } else { + fs.writeFileSync(out, notes.markdown); + console.error(`\nNotes written to ${ path.resolve(out) }.`); + } + return 0; +} diff --git a/tools/release/commands/prepare.spec.ts b/tools/release/commands/prepare.spec.ts new file mode 100644 index 00000000000..67d73906106 --- /dev/null +++ b/tools/release/commands/prepare.spec.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest'; + +import { baseRef, cutStepTitle, isPicksOnly, parsePrepareArgs } from './prepare'; + +describe('parsePrepareArgs', () => { + it('reads the release tag and its version', () => { + expect(parsePrepareArgs([ 'v2.13.1' ])).toEqual({ + tag: 'v2.13.1', + version: { major: 2, minor: 13, patch: 1, prerelease: undefined }, + dryRun: false, + }); + }); + + it('reads the dry run', () => { + expect(parsePrepareArgs([ 'v2.13.0', '--dry-run' ])).toMatchObject({ tag: 'v2.13.0', dryRun: true }); + }); + + it.each([ + [ 'no tag', [] ], + [ 'two tags', [ 'v2.13.0', 'v2.14.0' ] ], + ])('rejects %s with the usage', (_, args) => { + expect(() => parsePrepareArgs(args)).toThrow('Usage: pnpm release prepare <vX.Y.Z>'); + }); + + it('rejects a line in place of a tag', () => { + expect(() => parsePrepareArgs([ 'v2.13' ])).toThrow('Not a release tag: "v2.13"'); + }); + + it('rejects an alpha tag', () => { + expect(() => parsePrepareArgs([ 'v2.13.0-alpha.1' ])).toThrow('Not a final tag: "v2.13.0-alpha.1"'); + }); + + it('rejects an unknown flag', () => { + expect(() => parsePrepareArgs([ 'v2.13.0', '--force' ])).toThrow('Unknown flag: --force'); + }); +}); + +describe('baseRef', () => { + it('reads main from origin for a minor', () => { + expect(baseRef({ kind: 'main' })).toBe('origin/main'); + }); + + it('is the previous tag for a patch', () => { + expect(baseRef({ kind: 'tag', tag: 'v2.13.0' })).toBe('v2.13.0'); + }); +}); + +describe('cutStepTitle', () => { + const SHA = '0123456789abcdef0123456789abcdef01234567'; + + it('cuts a minor from main', () => { + expect(cutStepTitle('release/v2.13.0', 'origin/main', SHA, false)).toBe('Cut release/v2.13.0 at origin/main (0123456789)'); + }); + + it('cuts a patch from the previous tag', () => { + expect(cutStepTitle('release/v2.13.1', 'v2.13.0', SHA, false)).toBe('Cut release/v2.13.1 at v2.13.0 (0123456789)'); + }); + + it('resumes a branch an earlier run left behind', () => { + expect(cutStepTitle('release/v2.13.0', 'origin/main', SHA, true)).toBe( + 'Switch to release/v2.13.0, cut at origin/main (0123456789) by an earlier run that stopped; resuming', + ); + }); +}); + +describe('isPicksOnly', () => { + const pick = { sha: 'a', message: 'Fix the badge (#3600)\n\n(cherry picked from commit 0123456789abcdef0123456789abcdef01234567)' }; + const docs = { sha: 'b', message: 'chore: prepare release v2.13.0' }; + + it('accepts a branch of picks and the docs commit of the release', () => { + expect(isPicksOnly([ pick, docs ], 'v2.13.0')).toBe(true); + }); + + it('accepts a branch with nothing past the fork point', () => { + expect(isPicksOnly([], 'v2.13.0')).toBe(true); + }); + + it('refuses a commit made on the branch by hand', () => { + expect(isPicksOnly([ pick, { sha: 'c', message: 'Fix the badge on the branch' } ], 'v2.13.0')).toBe(false); + }); + + it('refuses the docs commit of another release', () => { + expect(isPicksOnly([ docs ], 'v2.13.1')).toBe(false); + }); +}); diff --git a/tools/release/commands/prepare.ts b/tools/release/commands/prepare.ts new file mode 100644 index 00000000000..f6d0034a703 --- /dev/null +++ b/tools/release/commands/prepare.ts @@ -0,0 +1,138 @@ +/* eslint-disable no-console -- CLI subcommand, console output is the interface */ +import { + createBranchAt, + fetchBranch, + hasLocalRef, + hasRemoteRef, + isAncestor, + listCommits, + listTags, + mergeBase, + pushBranch, + REMOTE, + remoteBranch, + resolveCommit, + switchBranch, +} from '../git'; +import { createDraftPreRelease, listReleases } from '../github'; +import { releaseNotes } from '../notes'; +import { findLinePreRelease } from '../pre-release'; +import type { Commit } from '../release-prs'; +import { cherryPickSources, isDocsCommit } from '../release-prs'; +import { releaseSourceAt } from '../release-source'; +import type { ReleaseBase, Version } from '../versions'; +import { formatLine, parseFinalTagOrThrow, releaseBase, releaseBranch } from '../versions'; +import { parsePhaseArgs } from './args'; +import { readNotesTemplate } from './notes'; +import type { BranchView } from './release-branch'; +import { assertCheckoutReady, checkoutBranch, checkoutView, refView, updateReleaseBranch } from './release-branch'; +import type { StepRunner } from './report'; +import { logReleaseNotes, stepRunner } from './report'; + +const USAGE = `Usage: pnpm release prepare <vX.Y.Z> [--dry-run] + + cuts release/vX.Y.Z from main (Z = 0) or from vX.Y.(Z-1) (a patch), picks the merged "backport" PRs onto + it, releases "upcoming" in the ENV docs as vX.Y.Z+, pushes the branch and creates the draft pre-release + vX.Y.Z with its notes`; + +export interface PrepareArgs { + readonly tag: string; + readonly version: Version; + readonly dryRun: boolean; +} + +export function parsePrepareArgs(args: ReadonlyArray<string>): PrepareArgs { + const { target, dryRun } = parsePhaseArgs(args, USAGE); + return { tag: target, version: parseFinalTagOrThrow(target), dryRun }; +} + +export function baseRef(base: ReleaseBase): string { + return base.kind === 'main' ? remoteBranch('main') : base.tag; +} + +export function cutStepTitle(branch: string, start: string, sha: string, resumed: boolean): string { + const at = `${ start } (${ sha.slice(0, 10) })`; + return resumed ? + `Switch to ${ branch }, cut at ${ at } by an earlier run that stopped; resuming` : + `Cut ${ branch } at ${ at }`; +} + +// Whether the branch is on origin says where a stopped run got to: a push that went through, followed by a +// draft call that did not, leaves the branch there with no pre-release, and the re-run picks up from it. +function releaseState(version: Version, tag: string, branch: string): 'new' | 'pushed' { + if (hasRemoteRef(`refs/tags/${ tag }`)) { + throw new Error(`${ tag } is already released`); + } + const preRelease = findLinePreRelease(listReleases(), version); + if (preRelease !== undefined) { + const open = `${ preRelease.tagName } (${ preRelease.url })`; + throw new Error(`Line ${ formatLine(version) } has the open pre-release ${ open }; publish it before preparing ${ tag }`); + } + return hasRemoteRef(`refs/heads/${ branch }`) ? 'pushed' : 'new'; +} + +// A minor's cut point on main moves on with every merge, so a resumed branch is recognised by what sits +// past its fork point instead: nothing but picks and the release's docs commit. +export function isPicksOnly(commits: ReadonlyArray<Commit>, tag: string): boolean { + return commits.every((commit) => cherryPickSources(commit.message).length > 0 || isDocsCommit(commit, tag)); +} + +interface CutPoint { + readonly sha: string; + readonly resumed: boolean; +} + +function cutPoint(base: ReleaseBase, branch: string, tag: string): CutPoint { + const start = baseRef(base); + if (!hasLocalRef(`refs/heads/${ branch }`)) { + return { sha: resolveCommit(start), resumed: false }; + } + const deleteHint = `delete it with "git branch -D ${ branch }" and re-run`; + if (base.kind === 'tag') { + if (!isAncestor(start, branch)) { + throw new Error(`${ branch } exists locally but does not descend from ${ start }; ${ deleteHint }`); + } + return { sha: resolveCommit(start), resumed: true }; + } + const fork = mergeBase(branch, start); + if (!isPicksOnly(listCommits(fork, branch), tag)) { + throw new Error(`${ branch } exists locally with commits that are neither picks from main nor the docs commit of ${ tag }; ${ deleteHint }`); + } + return { sha: fork, resumed: true }; +} + +function cutReleaseBranch(steps: StepRunner, base: ReleaseBase, branch: string, tag: string, dryRun: boolean): BranchView { + const start = baseRef(base); + const { sha, resumed } = cutPoint(base, branch, tag); + if (!dryRun) { + assertCheckoutReady(); + } + steps.run(cutStepTitle(branch, start, sha, resumed), () => resumed ? switchBranch(branch) : createBranchAt(branch, start)); + return dryRun ? refView(resumed ? branch : start) : checkoutView(); +} + +export function prepareCommand(args: ReadonlyArray<string>): number { + const { tag, version, dryRun } = parsePrepareArgs(args); + const branch = releaseBranch(version); + + fetchBranch('main'); + const state = releaseState(version, tag, branch); + const base = releaseBase(version, listTags()); + + const steps = stepRunner(dryRun); + const view = state === 'pushed' ? checkoutBranch(steps, branch, dryRun) : cutReleaseBranch(steps, base, branch, tag, dryRun); + updateReleaseBranch(steps, view, tag); + const notes = releaseNotes(tag, releaseSourceAt(view.head()), readNotesTemplate()); + logReleaseNotes(tag, notes); + + steps.run(`Push ${ branch } to ${ REMOTE }`, () => pushBranch(branch)); + steps.run(`Create the draft pre-release ${ tag } on ${ branch } with the notes`, () => { + console.log(createDraftPreRelease({ tagName: tag, target: branch, body: notes.markdown }).url); + }); + steps.finish(); + + if (dryRun) { + console.log(notes.markdown); + } + return 0; +} diff --git a/tools/release/commands/publish.spec.ts b/tools/release/commands/publish.spec.ts new file mode 100644 index 00000000000..743315c9514 --- /dev/null +++ b/tools/release/commands/publish.spec.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from 'vitest'; + +import { approvedAlpha, describeCommit, docsConflictMessage, foreignMainCommits, needsMainPush, parsePublishArgs, publishState } from './publish'; + +const HEAD = '0123456789abcdef0123456789abcdef01234567'; +const OTHER = 'fedcba9876543210fedcba9876543210fedcba98'; + +describe('parsePublishArgs', () => { + it('reads the release tag and its version', () => { + expect(parsePublishArgs([ 'v2.13.1' ])).toEqual({ + tag: 'v2.13.1', + version: { major: 2, minor: 13, patch: 1, prerelease: undefined }, + dryRun: false, + }); + }); + + it('reads the dry run', () => { + expect(parsePublishArgs([ '--dry-run', 'v2.13.0' ])).toMatchObject({ tag: 'v2.13.0', dryRun: true }); + }); + + it.each([ + [ 'no tag', [] ], + [ 'two tags', [ 'v2.13.0', 'v2.13.1' ] ], + ])('rejects %s with the usage', (_, args) => { + expect(() => parsePublishArgs(args)).toThrow('Usage: pnpm release publish <vX.Y.Z>'); + }); + + it('rejects an alpha tag', () => { + expect(() => parsePublishArgs([ 'v2.13.0-alpha.1' ])).toThrow('Not a final tag: "v2.13.0-alpha.1"'); + }); + + it('rejects an unknown flag', () => { + expect(() => parsePublishArgs([ 'v2.13.0', '--force' ])).toThrow('Unknown flag: --force'); + }); +}); + +describe('approvedAlpha', () => { + const BRANCH = 'release/v2.13.0'; + + it('is the latest alpha when it tags the branch head', () => { + expect(approvedAlpha('v2.13.0', BRANCH, HEAD, 'v2.13.0-alpha.2', HEAD)).toBe('v2.13.0-alpha.2'); + }); + + it('refuses a release without an alpha', () => { + expect(() => approvedAlpha('v2.13.0', BRANCH, HEAD, undefined, undefined)).toThrow( + 'v2.13.0 has no alpha tag; cut one with "pnpm release alpha v2.13.0-alpha.1"', + ); + }); + + it('refuses an alpha that is not on the branch', () => { + expect(() => approvedAlpha('v2.13.0', BRANCH, HEAD, 'v2.13.0-alpha.2', undefined)).toThrow( + 'v2.13.0-alpha.2 is not on release/v2.13.0; cut another alpha of what is there', + ); + }); + + it('refuses a branch that moved past its latest alpha', () => { + expect(() => approvedAlpha('v2.13.0', BRANCH, HEAD, 'v2.13.0-alpha.2', OTHER)).toThrow( + 'release/v2.13.0 has moved past v2.13.0-alpha.2 (fedcba9876) to 0123456789; cut another alpha of what is there', + ); + }); +}); + +describe('describeCommit', () => { + it('shows the short sha and the subject', () => { + expect(describeCommit({ sha: HEAD, message: 'chore: prepare release v2.13.0\n\nBody.' })).toBe('0123456789 chore: prepare release v2.13.0'); + }); +}); + +describe('docsConflictMessage', () => { + it('names the commit and the conflicted files, and how to resume', () => { + const commit = { sha: HEAD, message: 'chore: prepare release v2.13.0' }; + + expect(docsConflictMessage(commit, [ 'docs/ENVS.md' ])).toBe( + 'Cherry-picking the docs commit 0123456789 chore: prepare release v2.13.0 onto main conflicts in docs/ENVS.md; ' + + 'resolve the conflicts, run "git cherry-pick --continue" and re-run the command, which resumes after this commit', + ); + }); +}); + +describe('publishState', () => { + it('is new when the tag is not on origin', () => { + expect(publishState('v2.13.0', 'release/v2.13.0', undefined, HEAD)).toBe('new'); + }); + + it('resumes a published tag at the branch head', () => { + expect(publishState('v2.13.0', 'release/v2.13.0', HEAD, HEAD)).toBe('published'); + }); + + it('refuses a tag on origin that is not the branch head', () => { + expect(() => publishState('v2.13.0', 'release/v2.13.0', OTHER, HEAD)).toThrow( + 'v2.13.0 is on origin at fedcba9876, not at the head of release/v2.13.0 (0123456789)', + ); + }); +}); + +describe('needsMainPush', () => { + const commit = { sha: HEAD, message: 'chore: prepare release v2.13.0' }; + + it('pushes when a docs commit is left to pick', () => { + expect(needsMainPush({ picks: [ commit ], skipped: [] }, 'current')).toBe(true); + }); + + it('pushes a local main ahead of origin with a continued pick, nothing left to pick', () => { + expect(needsMainPush({ picks: [], skipped: [ { commit, sha: OTHER } ] }, 'ahead')).toBe(true); + }); + + it.each([ 'missing', 'current', 'behind' ] as const)('leaves main alone when every docs commit is on origin and the local branch is %s', (state) => { + expect(needsMainPush({ picks: [], skipped: [ { commit, sha: OTHER } ] }, state)).toBe(false); + }); +}); + +describe('foreignMainCommits', () => { + const docs = { sha: HEAD, message: 'chore: prepare release v2.13.0' }; + const picked = { sha: OTHER, message: 'chore: prepare release v2.13.0\n\n(cherry picked from commit ' + HEAD + ')' }; + const wip = { sha: 'abc'.padEnd(40, '0'), message: 'wip: something local' }; + + it('passes a main ahead with only the continued picks of the release', () => { + expect(foreignMainCommits([ picked ], { picks: [], skipped: [ { commit: docs, sha: OTHER } ] })).toEqual([]); + }); + + it('returns the ahead commits that are not picks of the release', () => { + expect(foreignMainCommits([ picked, wip ], { picks: [], skipped: [ { commit: docs, sha: OTHER } ] })).toEqual([ wip ]); + }); + + it('returns every ahead commit when the release has nothing picked', () => { + expect(foreignMainCommits([ wip ], { picks: [ docs ], skipped: [] })).toEqual([ wip ]); + }); +}); diff --git a/tools/release/commands/publish.ts b/tools/release/commands/publish.ts new file mode 100644 index 00000000000..5cb0875ae22 --- /dev/null +++ b/tools/release/commands/publish.ts @@ -0,0 +1,209 @@ +/* eslint-disable no-console -- CLI subcommand, console output is the interface */ +import type { DocsPickPlan } from '../docs-picks'; +import { docsCommits, planDocsPicks } from '../docs-picks'; +import { + createTag, + fetchBranch, + hasRemoteRef, + isAncestor, + listCommits, + listTags, + mergeBase, + push, + pushBranch, + REMOTE, + remoteBranch, + resolveCommit, + showFile, +} from '../git'; +import { fetchPrLabels, listReleases, publishRelease } from '../github'; +import type { ReleaseNotes } from '../notes'; +import { releaseNotes } from '../notes'; +import { findReleasePreRelease } from '../pre-release'; +import type { Commit } from '../release-prs'; +import { releaseSourceAt } from '../release-source'; +import type { Version } from '../versions'; +import { latestAlphaTag, parseFinalTagOrThrow, releaseBranch } from '../versions'; +import { parsePhaseArgs } from './args'; +import { checkTag } from './check-tag'; +import { readNotesTemplate } from './notes'; +import type { LocalBranchState } from './release-branch'; +import { checkoutBranch, checkoutPlan, pickCommit, readLocalBranchState } from './release-branch'; +import type { StepRunner } from './report'; +import { logList, logReleaseNotes, stepRunner } from './report'; +import { assertTagIsNew, watchTagRun } from './tag-run'; + +const USAGE = `Usage: pnpm release publish <vX.Y.Z> [--dry-run] + + tags the latest alpha of release/vX.Y.Z as vX.Y.Z once it passes the tag check, pushes the tag, turns the + release's pre-release into the final release marked latest with regenerated notes, cherry-picks the + release's docs commits onto main and watches the release.yml run`; + +const WORKFLOW = 'release.yml'; +const MAIN = 'main'; + +export interface PublishArgs { + readonly tag: string; + readonly version: Version; + readonly dryRun: boolean; +} + +export function parsePublishArgs(args: ReadonlyArray<string>): PublishArgs { + const { target, dryRun } = parsePhaseArgs(args, USAGE); + return { tag: target, version: parseFinalTagOrThrow(target), dryRun }; +} + +export function describeCommit({ sha, message }: Commit): string { + return `${ sha.slice(0, 10) } ${ message.split('\n', 1)[0] }`; +} + +export function docsConflictMessage(commit: Commit, files: ReadonlyArray<string>): string { + return `Cherry-picking the docs commit ${ describeCommit(commit) } onto ${ MAIN } conflicts in ${ files.join(', ') }; ` + + 'resolve the conflicts, run "git cherry-pick --continue" and re-run the command, which resumes after this commit'; +} + +// The approved alpha is the branch head: anything after it never ran on staging. +export function approvedAlpha(tag: string, branch: string, head: string, alphaTag: string | undefined, alphaSha: string | undefined): string { + if (alphaTag === undefined) { + throw new Error(`${ tag } has no alpha tag; cut one with "pnpm release alpha ${ tag }-alpha.1"`); + } + if (alphaSha === undefined) { + throw new Error(`${ alphaTag } is not on ${ branch }; cut another alpha of what is there`); + } + if (alphaSha !== head) { + throw new Error(`${ branch } has moved past ${ alphaTag } (${ alphaSha.slice(0, 10) }) to ${ head.slice(0, 10) }; cut another alpha of what is there`); + } + return alphaTag; +} + +// The tag on origin is where an earlier run got to: it published and stopped at the docs picks or the main +// push, and the re-run does not tag or publish again. A tag elsewhere than the head is not this release. +export function publishState(tag: string, branch: string, taggedSha: string | undefined, head: string): 'new' | 'published' { + if (taggedSha === undefined) { + return 'new'; + } + if (taggedSha !== head) { + throw new Error(`${ tag } is on ${ REMOTE } at ${ taggedSha.slice(0, 10) }, not at the head of ${ branch } (${ head.slice(0, 10) })`); + } + return 'published'; +} + +function logDocsPlan({ picks, skipped }: DocsPickPlan): void { + logList(`Docs commits to cherry-pick onto ${ MAIN }`, picks.map(describeCommit)); + logList(`Docs commits already on ${ MAIN }`, skipped.map(({ commit, sha }) => `${ describeCommit(commit) }: picked as ${ sha.slice(0, 10) }`)); +} + +// Planned against the main the checkout will use: after the operator continued a stopped pick, the local main +// is ahead of origin with that commit, which its trailer then skips rather than picks onto itself again. +function docsPlanAt(head: string, previousTag: string, tag: string, main: string): DocsPickPlan { + const docs = docsCommits(listCommits(previousTag, head), tag); + return planDocsPicks(docs, listCommits(mergeBase(head, main), main)); +} + +// A local main ahead of origin holds a continued pick that is not pushed yet, so it goes even with nothing +// left to pick. +export function needsMainPush({ picks }: DocsPickPlan, mainState: LocalBranchState): boolean { + return picks.length > 0 || mainState === 'ahead'; +} + +// Whatever a local main is ahead of origin with goes along with the push, so only this release's continued +// picks may be there: a release's docs commit on main is a skipped pick, anything else is the operator's. +export function foreignMainCommits(ahead: ReadonlyArray<Commit>, { skipped }: DocsPickPlan): Array<Commit> { + const picked = new Set(skipped.map(({ sha }) => sha)); + return ahead.filter(({ sha }) => !picked.has(sha)); +} + +function assertMainAheadWithDocsOnly(tag: string, plan: DocsPickPlan, mainState: LocalBranchState): void { + if (mainState !== 'ahead') { + return; + } + const foreign = foreignMainCommits(listCommits(remoteBranch(MAIN), MAIN), plan); + if (foreign.length > 0) { + throw new Error(`${ MAIN } is ahead of ${ remoteBranch(MAIN) } with commits that are not docs commits of ${ tag }: ` + + `${ foreign.map(describeCommit).join(', ') }; push or drop them by hand and re-run`); + } +} + +function returnDocsToMain(steps: StepRunner, plan: DocsPickPlan, mainState: LocalBranchState, dryRun: boolean): void { + if (!needsMainPush(plan, mainState)) { + return; + } + checkoutBranch(steps, MAIN, dryRun); + for (const commit of plan.picks) { + steps.run(`Cherry-pick ${ describeCommit(commit) } onto ${ MAIN }`, () => pickCommit(commit.sha, (files) => docsConflictMessage(commit, files))); + } + steps.run(`Push ${ MAIN } to ${ REMOTE }`, () => pushBranch(MAIN)); +} + +interface Release { + readonly tag: string; + readonly version: Version; + readonly branch: string; + readonly head: string; + readonly notes: ReleaseNotes; +} + +function checkRelease({ tag, head, notes }: Release): boolean { + const { failures } = checkTag(tag, { readDoc: (docPath) => showFile(head, docPath), releaseBodies: () => [ notes.markdown ], prLabels: fetchPrLabels }); + if (failures.length > 0) { + logList(`\nTag ${ tag } fails the tag check, nothing tagged or published`, failures); + } + return failures.length === 0; +} + +function releaseSteps(steps: StepRunner, { tag, version, branch, head, notes }: Release): void { + const alpha = latestAlphaTag(version, listTags()); + const alphaSha = alpha !== undefined && isAncestor(alpha, head) ? resolveCommit(alpha) : undefined; + const alphaTag = approvedAlpha(tag, branch, head, alpha, alphaSha); + const preRelease = findReleasePreRelease(listReleases(), version); + + steps.run(`Tag ${ branch } at ${ head.slice(0, 10) } (${ alphaTag }) as ${ tag }`, () => createTag(tag, head)); + steps.run(`Push ${ tag } to ${ REMOTE }`, () => push(`refs/tags/${ tag }`)); + const publishTitle = `Publish the pre-release ${ preRelease.tagName } as the final release ${ tag } marked latest, with the notes regenerated, ` + + `which fires ${ WORKFLOW }: ${ preRelease.url }`; + steps.run(publishTitle, () => { + console.log(publishRelease(preRelease.id, { tagName: tag, target: head, body: notes.markdown }).url); + }); +} + +export function publishCommand(args: ReadonlyArray<string>): number { + const { tag, version, dryRun } = parsePublishArgs(args); + const branch = releaseBranch(version); + + if (!hasRemoteRef(`refs/heads/${ branch }`)) { + throw new Error(`${ branch } is not on ${ REMOTE }; cut it with "pnpm release prepare ${ tag }"`); + } + fetchBranch(branch); + fetchBranch(MAIN); + const head = resolveCommit(remoteBranch(branch)); + const state = publishState(tag, branch, hasRemoteRef(`refs/tags/${ tag }`) ? resolveCommit(tag) : undefined, head); + if (state === 'new') { + assertTagIsNew(tag); + } + + const notes = releaseNotes(tag, releaseSourceAt(head), readNotesTemplate()); + logReleaseNotes(tag, notes); + const release: Release = { tag, version, branch, head, notes }; + if (state === 'new' && !checkRelease(release)) { + return 1; + } + const mainState = readLocalBranchState(MAIN); + const docsPlan = docsPlanAt(head, notes.previousTag, tag, checkoutPlan(MAIN, mainState).ref); + assertMainAheadWithDocsOnly(tag, docsPlan, mainState); + logDocsPlan(docsPlan); + + const steps = stepRunner(dryRun); + if (state === 'new') { + releaseSteps(steps, release); + } else { + console.error(`${ tag } is already on ${ REMOTE } at the head of ${ branch } and published; resuming with the docs commits.`); + } + returnDocsToMain(steps, docsPlan, mainState, dryRun); + steps.run(`Watch the ${ WORKFLOW } run of ${ tag }`, () => watchTagRun(WORKFLOW, tag, 'release')); + steps.finish(); + + if (dryRun) { + console.log(notes.markdown); + } + return 0; +} diff --git a/tools/release/commands/release-branch.spec.ts b/tools/release/commands/release-branch.spec.ts new file mode 100644 index 00000000000..14e09c20f94 --- /dev/null +++ b/tools/release/commands/release-branch.spec.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest'; + +import { checkoutPlan, envDocsStepTitle, localBranchState, pickConflictMessage, releaseEnvDocs } from './release-branch'; + +describe('localBranchState', () => { + it('is missing without a local branch, whatever origin has', () => { + expect(localBranchState(false, { remoteInLocal: false, localInRemote: false })).toBe('missing'); + }); + + it.each([ + [ 'current', { remoteInLocal: true, localInRemote: true } ], + [ 'ahead', { remoteInLocal: true, localInRemote: false } ], + [ 'behind', { remoteInLocal: false, localInRemote: true } ], + [ 'diverged', { remoteInLocal: false, localInRemote: false } ], + ] as const)('is %s', (state, relation) => { + expect(localBranchState(true, relation)).toBe(state); + }); +}); + +describe('checkoutPlan', () => { + const BRANCH = 'release/v2.13.0'; + + it('checks a missing branch out from origin and reads origin', () => { + const plan = checkoutPlan(BRANCH, 'missing'); + + expect(plan.title).toBe('Check out release/v2.13.0 from origin'); + expect(plan.ref).toBe('origin/release/v2.13.0'); + }); + + it('reads the local branch when it is current', () => { + const plan = checkoutPlan(BRANCH, 'current'); + + expect(plan.title).toBe('Switch to release/v2.13.0, at the head of origin/release/v2.13.0'); + expect(plan.ref).toBe(BRANCH); + }); + + it('reads the local branch when it is ahead, which is a resumed pick', () => { + const plan = checkoutPlan(BRANCH, 'ahead'); + + expect(plan.title).toBe('Switch to release/v2.13.0, which is ahead of origin/release/v2.13.0 with commits not pushed yet'); + expect(plan.ref).toBe(BRANCH); + }); + + it('fast-forwards a branch that lags and reads origin', () => { + const plan = checkoutPlan(BRANCH, 'behind'); + + expect(plan.title).toBe('Switch to release/v2.13.0 and fast-forward it to origin/release/v2.13.0'); + expect(plan.ref).toBe('origin/release/v2.13.0'); + }); + + it('refuses a diverged branch', () => { + expect(() => checkoutPlan(BRANCH, 'diverged')).toThrow( + 'release/v2.13.0 has diverged from origin/release/v2.13.0; reconcile them by hand and re-run', + ); + }); +}); + +describe('pickConflictMessage', () => { + it('names the PR and the conflicted files, and how to resume', () => { + const pr = { number: 3708, title: 'Fix the thing', labels: [ 'backport' ], mergeSha: '0123456789abcdef0123456789abcdef01234567' }; + + expect(pickConflictMessage(pr, [ 'src/a.ts', 'src/b.ts' ])).toBe( + 'Picking #3708 Fix the thing (0123456789) conflicts in src/a.ts, src/b.ts; resolve the conflicts, ' + + 'run "git cherry-pick --continue" and re-run the command, which resumes after this pick', + ); + }); +}); + +describe('releaseEnvDocs', () => { + it('releases "upcoming" in each ENV doc that has it, leaving out the others', () => { + const docs: Record<string, string> = { + 'docs/ENVS.md': '| A | upcoming |\n| B | v2.12.0+ |\n| C | <upcoming> |\n', + 'docs/DEPRECATED_ENVS.md': '| D | v2.11.0+ |\n', + }; + + expect(releaseEnvDocs((docPath) => docs[docPath], 'v2.13.0')).toEqual([ + { path: 'docs/ENVS.md', content: '| A | v2.13.0+ |\n| B | v2.12.0+ |\n| C | v2.13.0+ |\n', count: 2 }, + ]); + }); +}); + +describe('envDocsStepTitle', () => { + it('names the docs and the counts the branch has before the picks', () => { + const docs = [ { path: 'docs/ENVS.md', content: '', count: 2 }, { path: 'docs/DEPRECATED_ENVS.md', content: '', count: 1 } ]; + + expect(envDocsStepTitle(docs, 'v2.13.0', 'origin/main')).toBe( + 'Commit "chore: prepare release v2.13.0" with "upcoming" → v2.13.0+ in the ENV docs, when any is left after the picks; ' + + 'at origin/main before them: docs/ENVS.md (2), docs/DEPRECATED_ENVS.md (1)', + ); + }); + + it('says so when the branch has none yet', () => { + expect(envDocsStepTitle([], 'v2.13.1', 'HEAD')).toBe( + 'Commit "chore: prepare release v2.13.1" with "upcoming" → v2.13.1+ in the ENV docs, when any is left after the picks; ' + + 'at HEAD before them: none', + ); + }); +}); diff --git a/tools/release/commands/release-branch.ts b/tools/release/commands/release-branch.ts new file mode 100644 index 00000000000..ce32115868e --- /dev/null +++ b/tools/release/commands/release-branch.ts @@ -0,0 +1,195 @@ +/* eslint-disable no-console -- CLI subcommand, console output is the interface */ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; + +import { ENV_DOCS, replaceUpcoming } from '../check-tag'; +import type { FileChange } from '../git'; +import { + cherryPick, + fastForward, + hasCherryPickInProgress, + hasCleanWorkingTree, + hasLocalRef, + isAncestor, + listCommits, + listShas, + mergeBase, + REMOTE, + remoteBranch, + repoRoot, + resolveCommit, + showFile, + switchBranch, + trackRemoteBranch, + unmergedFiles, + writeAndCommit, +} from '../git'; +import { listBackportPrs } from '../github'; +import type { BackportPullRequest, PickPlan } from '../picks'; +import { planPicks } from '../picks'; +import { prepareCommitMessage } from '../release-prs'; +import type { StepRunner } from './report'; +import { describeBackportPr, logPickPlan } from './report'; + +// Where a command reads the branch from: a ref in a dry run, the checkout in a real one, so the ENV docs +// a real run sees are the ones the picks just changed. +export interface BranchView { + readonly ref: string; + readonly head: () => string; + readonly readDoc: (docPath: string) => string; +} + +export function refView(ref: string): BranchView { + return { ref, head: () => resolveCommit(ref), readDoc: (docPath) => showFile(ref, docPath) }; +} + +export function checkoutView(): BranchView { + return { ref: 'HEAD', head: () => resolveCommit('HEAD'), readDoc: (docPath) => fs.readFileSync(path.join(repoRoot(), docPath), 'utf8') }; +} + +export type LocalBranchState = 'missing' | 'current' | 'ahead' | 'behind' | 'diverged'; + +export interface BranchRelation { + readonly remoteInLocal: boolean; + readonly localInRemote: boolean; +} + +export function localBranchState(hasLocal: boolean, { remoteInLocal, localInRemote }: BranchRelation): LocalBranchState { + if (!hasLocal) { + return 'missing'; + } + if (remoteInLocal) { + return localInRemote ? 'current' : 'ahead'; + } + return localInRemote ? 'behind' : 'diverged'; +} + +export interface CheckoutPlan { + readonly title: string; + readonly ref: string; + readonly run: () => void; +} + +// The local branch counts when it carries everything origin has: it is ahead after the operator continued a +// stopped pick, and that work is what the command resumes. +export function checkoutPlan(branch: string, state: LocalBranchState): CheckoutPlan { + const remote = remoteBranch(branch); + switch (state) { + case 'missing': + return { title: `Check out ${ branch } from ${ REMOTE }`, ref: remote, run: () => trackRemoteBranch(branch) }; + case 'current': + return { title: `Switch to ${ branch }, at the head of ${ remote }`, ref: branch, run: () => switchBranch(branch) }; + case 'ahead': + return { title: `Switch to ${ branch }, which is ahead of ${ remote } with commits not pushed yet`, ref: branch, run: () => switchBranch(branch) }; + case 'behind': + return { + title: `Switch to ${ branch } and fast-forward it to ${ remote }`, + ref: remote, + run: () => { + switchBranch(branch); + fastForward(remote); + }, + }; + case 'diverged': + throw new Error(`${ branch } has diverged from ${ remote }; reconcile them by hand and re-run`); + } +} + +export function readLocalBranchState(branch: string): LocalBranchState { + const remote = remoteBranch(branch); + if (!hasLocalRef(`refs/heads/${ branch }`)) { + return 'missing'; + } + return localBranchState(true, { remoteInLocal: isAncestor(remote, branch), localInRemote: isAncestor(branch, remote) }); +} + +export function assertCheckoutReady(): void { + if (hasCherryPickInProgress()) { + throw new Error('A cherry-pick is in progress; resolve it, run "git cherry-pick --continue" (or --abort) and re-run'); + } + if (!hasCleanWorkingTree()) { + throw new Error('The working tree has uncommitted changes; commit or discard them and re-run'); + } +} + +// Switches the operator's checkout to the branch in a real run; a dry run only picks the ref to read. +export function checkoutBranch(steps: StepRunner, branch: string, dryRun: boolean): BranchView { + const plan = checkoutPlan(branch, readLocalBranchState(branch)); + if (!dryRun) { + assertCheckoutReady(); + } + steps.run(plan.title, plan.run); + return dryRun ? refView(plan.ref) : checkoutView(); +} + +export function pickPlanAt(head: string): PickPlan { + const main = remoteBranch('main'); + const fork = mergeBase(head, main); + return planPicks(listBackportPrs(), { mainCommits: listShas(fork, main), branchCommits: listCommits(fork, head) }); +} + +export function pickConflictMessage(pr: BackportPullRequest, files: ReadonlyArray<string>): string { + return `Picking ${ describeBackportPr(pr) } conflicts in ${ files.join(', ') }; resolve the conflicts, ` + + 'run "git cherry-pick --continue" and re-run the command, which resumes after this pick'; +} + +// A conflict is the operator's to resolve: the cherry-pick stays in progress and the error says how to go on. +export function pickCommit(sha: string, conflictMessage: (files: ReadonlyArray<string>) => string): void { + try { + cherryPick(sha); + } catch (error) { + const files = unmergedFiles(); + throw files.length === 0 ? error : new Error(conflictMessage(files)); + } +} + +export interface EnvDocUpdate extends FileChange { + readonly count: number; +} + +export function releaseEnvDocs(readDoc: (docPath: string) => string, tag: string): Array<EnvDocUpdate> { + return ENV_DOCS + .map((docPath) => ({ path: docPath, ...replaceUpcoming(readDoc(docPath), tag) })) + .filter(({ count }) => count > 0); +} + +export function describeEnvDocs(docs: ReadonlyArray<EnvDocUpdate>): string { + return docs.length === 0 ? 'none' : docs.map(({ path: docPath, count }) => `${ docPath } (${ count })`).join(', '); +} + +// Titled with what the docs say before the picks, since a picked PR may bring "upcoming" of its own. +export function envDocsStepTitle(docs: ReadonlyArray<EnvDocUpdate>, tag: string, ref: string): string { + return `Commit "${ prepareCommitMessage(tag) }" with "upcoming" → ${ tag }+ in the ENV docs, when any is left after the picks; ` + + `at ${ ref } before them: ${ describeEnvDocs(docs) }`; +} + +function commitEnvDocs(tag: string): void { + const docs = releaseEnvDocs(checkoutView().readDoc, tag); + if (docs.length === 0) { + console.error(' The ENV docs say "upcoming" nowhere, so no docs commit.'); + return; + } + const sha = writeAndCommit(docs, prepareCommitMessage(tag)); + console.error(` ${ sha.slice(0, 10) }: ${ describeEnvDocs(docs) }`); +} + +function runTypeCheck(): void { + try { + execFileSync('pnpm', [ 'lint:tsc' ], { cwd: repoRoot(), stdio: 'inherit' }); + } catch { + throw new Error('"pnpm lint:tsc" fails on the release branch; fix it there and re-run'); + } +} + +// Picks every "backport" PR the branch lacks, releases "upcoming", and type-checks: the branch is ready to +// push after this. A stopped pick leaves the cherry-pick in progress for the operator. +export function updateReleaseBranch(steps: StepRunner, view: BranchView, tag: string): void { + const plan = pickPlanAt(view.head()); + logPickPlan(plan); + for (const pr of plan.picks) { + steps.run(`Pick ${ describeBackportPr(pr) }`, () => pickCommit(pr.mergeSha, (files) => pickConflictMessage(pr, files))); + } + steps.run(envDocsStepTitle(releaseEnvDocs(view.readDoc, tag), tag, view.ref), () => commitEnvDocs(tag)); + steps.run('Run "pnpm lint:tsc"', runTypeCheck); +} diff --git a/tools/release/commands/report.ts b/tools/release/commands/report.ts new file mode 100644 index 00000000000..dfb882b0c8c --- /dev/null +++ b/tools/release/commands/report.ts @@ -0,0 +1,78 @@ +/* eslint-disable no-console -- CLI subcommand, console output is the interface */ +import type { ReleaseNotes } from '../notes'; +import { API_VERSION_HEADING, unreadableApiVersions } from '../notes-sections'; +import type { BackportPullRequest, PickPlan, Skip } from '../picks'; +import type { Commit, ReleasePullRequest } from '../release-prs'; + +// Reports go to stderr, keeping stdout for what a workflow step or a pipe consumes. + +export function describePr({ number, title }: ReleasePullRequest): string { + return `#${ number } ${ title }`; +} + +export function logList(heading: string, items: ReadonlyArray<string>): void { + console.error(`${ heading } (${ items.length }):`); + for (const item of items) { + console.error(` ${ item }`); + } +} + +export function logExclusions(skipped: ReadonlyArray<ReleasePullRequest>, unresolved: ReadonlyArray<Commit>): void { + logList('Skipped, already in another release', skipped.map((pr) => `${ describePr(pr) } [${ pr.labels.join(', ') }]`)); + logList('Commits without a PR', unresolved.map(({ sha, message }) => `${ sha.slice(0, 10) } ${ message.split('\n', 1)[0] }`)); +} + +export function logReleaseNotes(tag: string, { previousTag, prs, skipped, unresolved }: ReleaseNotes): void { + console.error(`Release ${ tag }, compared with ${ previousTag }`); + logList('PRs in the notes', prs.map(describePr)); + logExclusions(skipped, unresolved); + const unreadable = unreadableApiVersions(prs); + if (unreadable.length > 0) { + logList(`Not in Compatibility, "${ API_VERSION_HEADING }" names no "<service> v<version>"; check by hand`, unreadable.map((number) => `#${ number }`)); + } +} + +export function describeBackportPr({ number, title, mergeSha }: BackportPullRequest): string { + return `#${ number } ${ title } (${ mergeSha.slice(0, 10) })`; +} + +function describeSkip(skip: Skip): string { + switch (skip.reason) { + case 'released': + return `${ describeBackportPr(skip.pr) }: already shipped in ${ skip.versionLabels.join(', ') }`; + case 'before-fork': + return `${ describeBackportPr(skip.pr) }: merged before the fork, so already on the branch`; + case 'picked': + return `${ describeBackportPr(skip.pr) }: picked as ${ skip.sha.slice(0, 10) }`; + } +} + +export function logPickPlan({ picks, skipped }: PickPlan): void { + logList('"backport" PRs to pick, in main order', picks.map(describeBackportPr)); + logList('"backport" PRs skipped', skipped.map(describeSkip)); +} + +export interface StepRunner { + readonly run: (title: string, action: () => void) => void; + readonly finish: () => void; +} + +// A dry run prints the very steps a real run takes, so its output is the plan to review. +export function stepRunner(dryRun: boolean): StepRunner { + let count = 0; + console.error(''); + return { + run: (title, action) => { + count += 1; + console.error(`${ count }. ${ title }`); + if (!dryRun) { + action(); + } + }, + finish: () => { + if (dryRun) { + console.error('\nDry run: nothing written.'); + } + }, + }; +} diff --git a/tools/release/commands/tag-run.ts b/tools/release/commands/tag-run.ts new file mode 100644 index 00000000000..c94726f3c92 --- /dev/null +++ b/tools/release/commands/tag-run.ts @@ -0,0 +1,42 @@ +/* eslint-disable no-console -- CLI subcommand, console output is the interface */ +import { hasLocalRef, hasRemoteRef, REMOTE } from '../git'; +import type { RunEvent, WorkflowRun } from '../github'; +import { findTagRun, watchRun } from '../github'; + +// GitHub queues the run a few seconds after the push; a minute without one means it never fired. +const RUN_POLL_ATTEMPTS = 12; +const RUN_POLL_INTERVAL_MS = 5_000; + +export function assertTagIsNew(tag: string): void { + const ref = `refs/tags/${ tag }`; + if (hasRemoteRef(ref)) { + throw new Error(`Tag ${ tag } is already on ${ REMOTE }`); + } + if (hasLocalRef(ref)) { + throw new Error(`Tag ${ tag } exists locally only, likely left by a failed run; delete it with "git tag -d ${ tag }" and re-run`); + } +} + +function sleep(ms: number): void { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} + +function waitForTagRun(workflow: string, tag: string, event: RunEvent): WorkflowRun { + for (let attempt = 0; attempt < RUN_POLL_ATTEMPTS; attempt++) { + const run = findTagRun(workflow, tag, event); + if (run !== undefined) { + return run; + } + sleep(RUN_POLL_INTERVAL_MS); + } + throw new Error(`No ${ workflow } run of ${ tag } showed up; look for it in the repository's Actions tab`); +} + +export function watchTagRun(workflow: string, tag: string, event: RunEvent): void { + const run = waitForTagRun(workflow, tag, event); + console.log(run.url); + if (!watchRun(run.id)) { + throw new Error(`The ${ workflow } run of ${ tag } failed: ${ run.url }`); + } + console.error(`The ${ workflow } run of ${ tag } passed: ${ run.url }`); +} diff --git a/tools/release/docs-picks.spec.ts b/tools/release/docs-picks.spec.ts new file mode 100644 index 00000000000..6d54a6199b3 --- /dev/null +++ b/tools/release/docs-picks.spec.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from 'vitest'; + +import { docsCommits, planDocsPicks } from './docs-picks'; + +const SHA = { + docsA: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + docsB: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + pick: 'cccccccccccccccccccccccccccccccccccccccc', + pickOfA: 'dddddddddddddddddddddddddddddddddddddddd', +}; + +const DOCS_A = { sha: SHA.docsA, message: 'chore: prepare release v2.13.0' }; +const DOCS_B = { sha: SHA.docsB, message: 'chore: prepare release v2.13.0\n\nSecond alpha.' }; + +describe('docsCommits', () => { + it('keeps the commits whose subject is the docs commit of the release, in order', () => { + const commits = [ + DOCS_A, + { sha: SHA.pick, message: 'Fix the thing (#3708)\n\n(cherry picked from commit 0123456789abcdef)' }, + { sha: SHA.docsB, message: 'chore: prepare release v2.12.3' }, + DOCS_B, + ]; + + expect(docsCommits(commits, 'v2.13.0')).toEqual([ DOCS_A, DOCS_B ]); + }); + + it('matches the subject only, not a body line', () => { + const commit = { sha: SHA.pick, message: 'Fix (#1)\n\nchore: prepare release v2.13.0' }; + + expect(docsCommits([ commit ], 'v2.13.0')).toEqual([]); + }); +}); + +describe('planDocsPicks', () => { + it('picks every docs commit main lacks, in order', () => { + expect(planDocsPicks([ DOCS_A, DOCS_B ], [])).toEqual({ picks: [ DOCS_A, DOCS_B ], skipped: [] }); + }); + + it('skips a docs commit a main commit names in its trailer', () => { + const main = [ { sha: SHA.pickOfA, message: `chore: prepare release v2.13.0\n\n(cherry picked from commit ${ SHA.docsA })` } ]; + + expect(planDocsPicks([ DOCS_A, DOCS_B ], main)).toEqual({ picks: [ DOCS_B ], skipped: [ { commit: DOCS_A, sha: SHA.pickOfA } ] }); + }); + + it('matches an abbreviated trailer by prefix', () => { + const main = [ { sha: SHA.pickOfA, message: `chore: prepare release v2.13.0\n\n(cherry picked from commit ${ SHA.docsA.slice(0, 7) })` } ]; + + expect(planDocsPicks([ DOCS_A ], main).picks).toEqual([]); + }); + + it('plans nothing without docs commits', () => { + expect(planDocsPicks([], [])).toEqual({ picks: [], skipped: [] }); + }); +}); diff --git a/tools/release/docs-picks.ts b/tools/release/docs-picks.ts new file mode 100644 index 00000000000..b9df8b177f2 --- /dev/null +++ b/tools/release/docs-picks.ts @@ -0,0 +1,36 @@ +import type { Commit } from './release-prs'; +import { cherryPickSources, isDocsCommit } from './release-prs'; + +export function docsCommits(commits: ReadonlyArray<Commit>, tag: string): Array<Commit> { + return commits.filter((commit) => isDocsCommit(commit, tag)); +} + +export interface DocsSkip { + readonly commit: Commit; + readonly sha: string; +} + +export interface DocsPickPlan { + readonly picks: ReadonlyArray<Commit>; + readonly skipped: ReadonlyArray<DocsSkip>; +} + +function pickOf(sha: string, mainCommits: ReadonlyArray<Commit>): Commit | undefined { + return mainCommits.find(({ message }) => cherryPickSources(message).some((source) => sha.startsWith(source))); +} + +// A docs commit already on main by its trailer is skipped, so a run stopped by a conflict or a failed push +// resumes with the ones left. +export function planDocsPicks(docs: ReadonlyArray<Commit>, mainCommits: ReadonlyArray<Commit>): DocsPickPlan { + const picks: Array<Commit> = []; + const skipped: Array<DocsSkip> = []; + for (const commit of docs) { + const pick = pickOf(commit.sha, mainCommits); + if (pick === undefined) { + picks.push(commit); + } else { + skipped.push({ commit, sha: pick.sha }); + } + } + return { picks, skipped }; +} diff --git a/tools/release/git.spec.ts b/tools/release/git.spec.ts new file mode 100644 index 00000000000..3bc1af44c97 --- /dev/null +++ b/tools/release/git.spec.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; + +import { parseLog } from './git'; + +describe('parseLog', () => { + it('splits records into sha and full message', () => { + const log = 'aaa\x1fAdd the badge (#10)\n\nBody line.\n\x1e\nbbb\x1fFix (#11)\n\n(cherry picked from commit ccc)\n\x1e\n'; + + expect(parseLog(log)).toEqual([ + { sha: 'aaa', message: 'Add the badge (#10)\n\nBody line.' }, + { sha: 'bbb', message: 'Fix (#11)\n\n(cherry picked from commit ccc)' }, + ]); + }); + + it('reads an empty range as no commits', () => { + expect(parseLog('')).toEqual([]); + }); +}); diff --git a/tools/release/git.ts b/tools/release/git.ts new file mode 100644 index 00000000000..00379f950d1 --- /dev/null +++ b/tools/release/git.ts @@ -0,0 +1,159 @@ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; + +import { EXEC_MAX_BUFFER } from '../cli/exec'; +import type { Commit } from './release-prs'; + +export const REMOTE = 'origin'; + +interface GitOptions { + readonly cwd?: string; + readonly env?: typeof process.env; + readonly input?: string; +} + +export function git(args: ReadonlyArray<string>, { cwd = process.cwd(), env, input }: GitOptions = {}): string { + return execFileSync('git', args as Array<string>, { cwd, env, input, encoding: 'utf8', maxBuffer: EXEC_MAX_BUFFER }); +} + +// Resolved from this file's directory, not counted off it: the entry runs compiled from ./dist, so its +// depth below the repo root is not the source's. +export function repoRoot(): string { + return git([ 'rev-parse', '--show-toplevel' ], { cwd: __dirname }).trim(); +} + +export function listTags(): Array<string> { + return git([ 'tag', '--list', 'v*' ]).split('\n').filter(Boolean); +} + +const FIELD_SEPARATOR = '\x1f'; +const RECORD_SEPARATOR = '\x1e'; + +export function parseLog(log: string): Array<Commit> { + return log + .split(RECORD_SEPARATOR) + .map((record) => record.replace(/^\n/, '')) + .filter(Boolean) + .map((record) => { + const [ sha, message ] = record.split(FIELD_SEPARATOR); + return { sha, message: message.trim() }; + }); +} + +// `from..to` is the commit set of GitHub's `compare/from...to`: what `to` has beyond the merge base. +export function listCommits(from: string, to: string): Array<Commit> { + return parseLog(git([ 'log', '--reverse', `--format=%H${ FIELD_SEPARATOR }%B${ RECORD_SEPARATOR }`, `${ from }..${ to }` ])); +} + +export function listShas(from: string, to: string): Array<string> { + return git([ 'rev-list', '--reverse', `${ from }..${ to }` ]).split('\n').filter(Boolean); +} + +export function commitMessage(sha: string): string { + return git([ 'log', '-1', '--format=%B', sha ]).trim(); +} + +// The tags come along so `previousTag` and the notes see every release, whichever branch it is on. +export function fetchBranch(branch: string): void { + git([ 'fetch', '--quiet', '--tags', REMOTE, branch ]); +} + +export function remoteBranch(branch: string): string { + return `${ REMOTE }/${ branch }`; +} + +export function resolveCommit(ref: string): string { + return git([ 'rev-parse', '--verify', `${ ref }^{commit}` ]).trim(); +} + +export function mergeBase(a: string, b: string): string { + return git([ 'merge-base', a, b ]).trim(); +} + +export function isAncestor(ancestor: string, descendant: string): boolean { + try { + git([ 'merge-base', '--is-ancestor', ancestor, descendant ]); + return true; + } catch { + return false; + } +} + +export function hasLocalRef(ref: string): boolean { + try { + git([ 'rev-parse', '--verify', '--quiet', ref ]); + return true; + } catch { + return false; + } +} + +export function hasRemoteRef(ref: string): boolean { + return git([ 'ls-remote', REMOTE, ref ]).trim() !== ''; +} + +export function showFile(ref: string, filePath: string): string { + return git([ 'show', `${ ref }:${ filePath }` ]); +} + +export function hasCleanWorkingTree(): boolean { + return git([ 'status', '--porcelain', '--untracked-files=no' ]).trim() === ''; +} + +export function hasCherryPickInProgress(): boolean { + return hasLocalRef('CHERRY_PICK_HEAD'); +} + +export function switchBranch(branch: string): void { + git([ 'switch', '--quiet', branch ]); +} + +export function createBranchAt(branch: string, start: string): void { + git([ 'switch', '--quiet', '--no-track', '--create', branch, start ]); +} + +export function trackRemoteBranch(branch: string): void { + git([ 'switch', '--quiet', '--track', '--create', branch, remoteBranch(branch) ]); +} + +export function fastForward(ref: string): void { + git([ 'merge', '--quiet', '--ff-only', ref ]); +} + +export function cherryPick(sha: string): void { + git([ 'cherry-pick', '-x', sha ]); +} + +export function unmergedFiles(): Array<string> { + return git([ 'diff', '--name-only', '--diff-filter=U' ]).split('\n').filter(Boolean); +} + +export interface FileChange { + readonly path: string; + readonly content: string; +} + +// Through the checkout and with explicit paths: the release branch is checked out while this runs, and +// nothing else the operator may have lying around belongs in a docs commit. +export function writeAndCommit(files: ReadonlyArray<FileChange>, message: string): string { + const root = repoRoot(); + for (const file of files) { + fs.writeFileSync(path.join(root, file.path), file.content); + } + git([ 'add', '--', ...files.map((file) => file.path) ], { cwd: root }); + git([ 'commit', '--quiet', '-m', message ], { cwd: root }); + return resolveCommit('HEAD'); +} + +export function createTag(tag: string, sha: string): void { + git([ 'tag', tag, sha ]); +} + +export function push(ref: string): void { + git([ 'push', '--quiet', REMOTE, ref ]); +} + +export function pushBranch(branch: string): void { + git([ 'push', '--quiet', '--set-upstream', REMOTE, branch ]); +} diff --git a/tools/release/github.ts b/tools/release/github.ts new file mode 100644 index 00000000000..8372c5ff603 --- /dev/null +++ b/tools/release/github.ts @@ -0,0 +1,284 @@ +import { execFileSync } from 'node:child_process'; + +import { EXEC_MAX_BUFFER } from '../cli/exec'; +import type { BackportPullRequest } from './picks'; +import type { GithubRelease } from './pre-release'; +import type { ReleasePullRequest } from './release-prs'; + +// Every GitHub call goes through the `gh` CLI, which reads GH_TOKEN in CI and the operator's own +// `gh auth` session locally, so the tool carries no token handling and no HTTP client of its own. +// `{owner}/{repo}` in an API path is filled in by `gh` from the checkout's remote (or GH_REPO). + +export function gh(args: ReadonlyArray<string>, input?: string): string { + return execFileSync('gh', args as Array<string>, { input, encoding: 'utf8', maxBuffer: EXEC_MAX_BUFFER }); +} + +export function ghApi<TResponse>(path: string): TResponse { + return JSON.parse(gh([ 'api', path ])) as TResponse; +} + +function ghGraphql<TResponse>(query: string, variables: Record<string, string | number>): TResponse { + const fields = Object.entries(variables).flatMap(([ name, value ]) => [ '-F', `${ name }=${ value }` ]); + return JSON.parse(gh([ 'api', 'graphql', '-f', `query=${ query }`, '-F', 'owner={owner}', '-F', 'repo={repo}', ...fields ])) as TResponse; +} + +export interface PullRequest { + readonly number: number; + readonly body: string; + readonly labels: ReadonlyArray<string>; +} + +interface PullRequestResponse { + readonly number: number; + readonly body: string | null; + readonly labels: ReadonlyArray<{ readonly name: string }>; +} + +export function fetchPullRequest(number: number): PullRequest { + const response = ghApi<PullRequestResponse>(`repos/{owner}/{repo}/pulls/${ number }`); + return { + number: response.number, + body: response.body ?? '', + labels: response.labels.map(({ name }) => name), + }; +} + +interface LabelsConnection { + readonly nodes: ReadonlyArray<{ readonly name: string }>; +} + +interface ReleasePullRequestResponse { + readonly data: { + readonly repository: { + readonly nameWithOwner: string; + readonly pullRequest: { + readonly number: number; + readonly title: string; + readonly url: string; + readonly body: string; + readonly author: { readonly login: string } | null; + readonly labels: LabelsConnection; + readonly closingIssuesReferences: { + readonly nodes: ReadonlyArray<{ + readonly number: number; + readonly repository: { readonly nameWithOwner: string }; + readonly labels: LabelsConnection; + }>; + }; + }; + }; + }; +} + +const RELEASE_PULL_REQUEST_QUERY = ` + query ($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + nameWithOwner + pullRequest(number: $number) { + number + title + url + body + author { login } + labels(first: 100) { nodes { name } } + closingIssuesReferences(first: 50) { + nodes { + number + repository { nameWithOwner } + labels(first: 100) { nodes { name } } + } + } + } + } + } +`; + +function labelNames({ nodes }: LabelsConnection): Array<string> { + return nodes.map(({ name }) => name); +} + +// A PR can close an issue in another repository; labeling it by number here would hit the wrong issue. +export function fetchReleasePullRequest(number: number): ReleasePullRequest { + const { data: { repository } } = ghGraphql<ReleasePullRequestResponse>(RELEASE_PULL_REQUEST_QUERY, { number }); + const { pullRequest } = repository; + return { + number: pullRequest.number, + title: pullRequest.title, + // A deleted account leaves a PR without an author; GitHub shows it as this placeholder user. + author: pullRequest.author?.login ?? 'ghost', + url: pullRequest.url, + body: pullRequest.body, + labels: labelNames(pullRequest.labels), + closingIssues: pullRequest.closingIssuesReferences.nodes + .filter((issue) => issue.repository.nameWithOwner === repository.nameWithOwner) + .map((issue) => ({ number: issue.number, labels: labelNames(issue.labels) })), + }; +} + +export function fetchAssociatedPr(sha: string): number | undefined { + const pulls = ghApi<ReadonlyArray<{ readonly number: number; readonly merged_at: string | null }>>(`repos/{owner}/{repo}/commits/${ sha }/pulls`); + return pulls.find(({ merged_at: mergedAt }) => mergedAt !== null)?.number; +} + +// The issues endpoint answers for PRs and issues alike, so a `#N` naming an issue reads as "not a PR" +// instead of a 404. +interface IssueResponse { + readonly labels: ReadonlyArray<{ readonly name: string }>; + readonly pull_request?: object; +} + +export function fetchPrLabels(number: number): ReadonlyArray<string> | undefined { + const issue = ghApi<IssueResponse>(`repos/{owner}/{repo}/issues/${ number }`); + return issue.pull_request === undefined ? undefined : issue.labels.map(({ name }) => name); +} + +interface BackportPullRequestResponse { + readonly number: number; + readonly title: string; + readonly labels: ReadonlyArray<{ readonly name: string }>; + readonly mergeCommit: { readonly oid: string } | null; +} + +export const BACKPORT_LABEL = 'backport'; +const BACKPORT_PR_LIMIT = 200; + +// Only PRs merged to main: a PR merged elsewhere has no main commit to pick. +export function listBackportPrs(): Array<BackportPullRequest> { + const prs = JSON.parse(gh([ + 'pr', 'list', '--state', 'merged', '--base', 'main', '--label', BACKPORT_LABEL, '--limit', String(BACKPORT_PR_LIMIT), + '--json', 'number,title,labels,mergeCommit', + ])) as ReadonlyArray<BackportPullRequestResponse>; + if (prs.length >= BACKPORT_PR_LIMIT) { + throw new Error(`More than ${ BACKPORT_PR_LIMIT } merged "${ BACKPORT_LABEL }" PRs; the list is cut off, so raise BACKPORT_PR_LIMIT`); + } + return prs.map(({ number, title, labels, mergeCommit }) => { + if (mergeCommit === null) { + throw new Error(`PR #${ number } is merged but GitHub reports no merge commit`); + } + return { number, title, labels: labels.map(({ name }) => name), mergeSha: mergeCommit.oid }; + }); +} + +// Listed rather than fetched by tag: `releases/tags/<tag>` answers 404 for a tag without a release, which +// the check treats as a skip, not a failure. +export function fetchReleaseBodies(tag: string): Array<string> { + const jq = `.[] | select(.tag_name == ${ JSON.stringify(tag) }) | .body // "" | @json`; + return gh([ 'api', '--paginate', 'repos/{owner}/{repo}/releases', '--jq', jq ]) + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line) as string); +} + +function labelPath(name: string): string { + return `repos/{owner}/{repo}/labels/${ encodeURIComponent(name) }`; +} + +export function ensureLabel(name: string, description: string, color: string): 'created' | 'exists' { + try { + ghApi(labelPath(name)); + return 'exists'; + } catch { + gh([ 'label', 'create', name, '--description', description, '--color', color ]); + return 'created'; + } +} + +// PRs are issues to the labels API, so one call shape labels both. +export function addLabel(number: number, name: string): void { + gh([ 'api', '--method', 'POST', `repos/{owner}/{repo}/issues/${ number }/labels`, '-f', `labels[]=${ name }` ]); +} + +export function removeLabel(number: number, name: string): void { + gh([ 'api', '--method', 'DELETE', `repos/{owner}/{repo}/issues/${ number }/labels/${ encodeURIComponent(name) }` ]); +} + +export function listLabeled(name: string): Array<number> { + const path = `repos/{owner}/{repo}/issues?labels=${ encodeURIComponent(name) }&state=all&per_page=100`; + return gh([ 'api', '--paginate', path, '--jq', '.[].number' ]).split('\n').filter(Boolean).map(Number); +} + +// Only for its "New Contributors" list: GitHub knows who contributed before, the checkout does not. +// A tag not pushed yet needs the commit it will name as its target. +export function generateReleaseNotes(tag: string, previousTag: string, target?: string): string { + const targetField = target === undefined ? [] : [ '-f', `target_commitish=${ target }` ]; + return gh([ + 'api', '--method', 'POST', 'repos/{owner}/{repo}/releases/generate-notes', + '-f', `tag_name=${ tag }`, '-f', `previous_tag_name=${ previousTag }`, ...targetField, '--jq', '.body', + ]); +} + +// Sent as a JSON body on stdin: release notes outgrow what fits in a `-f` argument. +function ghSend<TResponse>(method: 'POST' | 'PATCH', apiPath: string, payload: object): TResponse { + return JSON.parse(gh([ 'api', '--method', method, apiPath, '--input', '-' ], JSON.stringify(payload))) as TResponse; +} + +interface ReleaseResponse { + readonly id: number; + readonly tag_name: string; + readonly draft: boolean; + readonly prerelease: boolean; + readonly html_url: string; +} + +function toGithubRelease(release: ReleaseResponse): GithubRelease { + return { id: release.id, tagName: release.tag_name, draft: release.draft, prerelease: release.prerelease, url: release.html_url }; +} + +export function listReleases(): Array<GithubRelease> { + return gh([ 'api', '--paginate', 'repos/{owner}/{repo}/releases', '--jq', '.[] | { id, tag_name, draft, prerelease, html_url } | @json' ]) + .split('\n') + .filter(Boolean) + .map((line) => toGithubRelease(JSON.parse(line) as ReleaseResponse)); +} + +export interface ReleaseContent { + readonly tagName: string; + readonly target: string; + readonly body: string; +} + +function releaseFields({ tagName, target, body }: ReleaseContent): object { + return { tag_name: tagName, target_commitish: target, name: tagName, body }; +} + +export function createDraftPreRelease(content: ReleaseContent): GithubRelease { + return toGithubRelease(ghSend('POST', 'repos/{owner}/{repo}/releases', { ...releaseFields(content), draft: true, prerelease: true })); +} + +// Publishing a release whose tag GitHub does not have yet creates the tag at the target, and that creation +// fires the tag's push event as a `git push` would. +export function publishPreRelease(id: number, content: ReleaseContent): GithubRelease { + const fields = { ...releaseFields(content), draft: false, prerelease: true }; + return toGithubRelease(ghSend('PATCH', `repos/{owner}/{repo}/releases/${ id }`, fields)); +} + +// Turns the pre-release into the final release: published, marked latest, which fires release.yml. +export function publishRelease(id: number, content: ReleaseContent): GithubRelease { + const fields = { ...releaseFields(content), draft: false, prerelease: false, make_latest: 'true' }; + return toGithubRelease(ghSend('PATCH', `repos/{owner}/{repo}/releases/${ id }`, fields)); +} + +export interface WorkflowRun { + readonly id: number; + readonly url: string; +} + +export type RunEvent = 'push' | 'release'; + +// A run of a tag, whether the tag push or the release event fired it, lists the tag as its "branch". +export function findTagRun(workflow: string, tag: string, event: RunEvent): WorkflowRun | undefined { + const runs = JSON.parse(gh([ + 'run', 'list', '--workflow', workflow, '--branch', tag, '--event', event, '--limit', '1', '--json', 'databaseId,url', + ])) as ReadonlyArray<{ readonly databaseId: number; readonly url: string }>; + return runs.map(({ databaseId, url }) => ({ id: databaseId, url }))[0]; +} + +// The live progress goes to stderr, keeping stdout for the command's result. +export function watchRun(id: number): boolean { + try { + execFileSync('gh', [ 'run', 'watch', String(id), '--exit-status' ], { stdio: [ 'ignore', 2, 2 ] }); + return true; + } catch { + return false; + } +} diff --git a/tools/release/index.ts b/tools/release/index.ts new file mode 100644 index 00000000000..fd6fd6c87e9 --- /dev/null +++ b/tools/release/index.ts @@ -0,0 +1,75 @@ +/* eslint-disable no-console -- CLI tool, console output is the interface */ +import type { FlagSpec } from '../cli/flags'; +import { parseArgs } from '../cli/flags'; +import { alphaCommand } from './commands/alpha'; +import { checkPrCommand } from './commands/check-pr'; +import { checkTagCommand } from './commands/check-tag'; +import { labelCommand } from './commands/label'; +import { notesCommand } from './commands/notes'; +import { prepareCommand } from './commands/prepare'; +import { publishCommand } from './commands/publish'; + +const USAGE = `Usage: pnpm release <subcommand> [args] + + prepare <vX.Y.Z> cut release/vX.Y.Z (from main, or from vX.Y.Z-1 for a patch), pick the "backport" PRs + onto it and create the draft pre-release + alpha <tag> pick the "backport" PRs onto release/vX.Y.Z, tag its head as the alpha, publish the + pre-release re-pointed to it and watch its CI run + publish <vX.Y.Z> tag the latest alpha as the final release marked latest, return the docs commits to + main and watch its CI run + check-pr <number> check a PR's body against docs/PULL_REQUEST_TEMPLATE.md and its category labels + check-tag <tag> check that a tag ships no "upcoming" ENV docs and no PR another release shipped + label <tag> label the PRs a tag shipped and their issues, or remove a label everywhere + notes <tag> print the release notes of a tag`; + +type Command = (args: ReadonlyArray<string>) => number; + +const COMMANDS: ReadonlyMap<string, Command> = new Map<string, Command>([ + [ 'prepare', prepareCommand ], + [ 'alpha', alphaCommand ], + [ 'publish', publishCommand ], + [ 'check-pr', checkPrCommand ], + [ 'check-tag', checkTagCommand ], + [ 'label', labelCommand ], + [ 'notes', notesCommand ], +]); + +interface Options { + help: boolean; +} + +const showHelp: FlagSpec<Options> = { kind: 'switch', apply: (options) => { + options.help = true; +} }; + +// Only the global flags live here; everything after the subcommand is passed through for the subcommand +// to parse, so each one owns its own flag surface. +const FLAGS: ReadonlyMap<string, FlagSpec<Options>> = new Map([ + [ '--help', showHelp ], + [ '-h', showHelp ], +]); + +function main(argv: ReadonlyArray<string>): number { + const { options, rest } = parseArgs(argv, FLAGS, { help: false }, { kind: 'passthrough' }); + const [ name, ...args ] = rest; + + if (options.help) { + console.log(USAGE); + return 0; + } + + const command = name === undefined ? undefined : COMMANDS.get(name); + if (command === undefined) { + console.error(name === undefined ? USAGE : `Unknown subcommand: ${ name }\n${ USAGE }`); + return 1; + } + + return command(args); +} + +try { + process.exitCode = main(process.argv.slice(2)); +} catch (error) { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; +} diff --git a/tools/release/notes-sections.spec.ts b/tools/release/notes-sections.spec.ts new file mode 100644 index 00000000000..90eab752f35 --- /dev/null +++ b/tools/release/notes-sections.spec.ts @@ -0,0 +1,184 @@ +import { describe, expect, it } from 'vitest'; + +import { + compatibilityRows, + envChanges, + filledSection, + minimumApiVersions, + newContributors, + parseFirstContributions, + unreadableApiVersions, +} from './notes-sections'; +import type { ReleasePullRequest } from './release-prs'; + +function pr(number: number, body: string): ReleasePullRequest { + const url = `https://github.com/blockscout/frontend/pull/${ number }`; + return { number, title: `PR ${ number }`, author: 'tom2drum', url, body, labels: [], closingIssues: [] }; +} + +function body(sections: Record<string, string>): string { + return Object.entries(sections).map(([ heading, text ]) => `## ${ heading }\n\n${ text }`).join('\n\n'); +} + +describe('filledSection', () => { + it('reads the text under the heading up to the next heading', () => { + const text = body({ Description: 'Adds a badge', 'Environment variables': 'Added `NEXT_PUBLIC_BADGE`', 'Minimum API version': 'None' }); + + expect(filledSection(text, 'Environment variables')).toBe('Added `NEXT_PUBLIC_BADGE`'); + }); + + it('matches the heading at any level and case, and reads to the end of the body', () => { + expect(filledSection('### environment Variables\r\n\r\n- Added `A`\r\n', 'Environment variables')).toBe('- Added `A`'); + }); + + it.each([ + [ 'missing', body({ Description: 'Adds a badge' }) ], + [ 'empty', body({ 'Environment variables': '' }) ], + [ 'None', body({ 'Environment variables': 'None' }) ], + [ 'an emphasized none.', body({ 'Environment variables': '_none._' }) ], + [ 'N/A', body({ 'Environment variables': 'N/A' }) ], + [ 'None with a reason', body({ 'Environment variables': 'None — the feature reuses `NEXT_PUBLIC_OG_ENHANCED_DATA_ENABLED`.' }) ], + [ 'only a comment', body({ 'Environment variables': '<!-- fill me -->' }) ], + [ 'the template placeholder', body({ 'Environment variables': '*[List each environment variable added, changed, or removed, or "None".]*' }) ], + ])('is nothing when the section is %s', (_, text) => { + expect(filledSection(text, 'Environment variables')).toBeUndefined(); + }); +}); + +describe('envChanges', () => { + it('groups each PR\'s changes under its number, as a nested list', () => { + const prs = [ + pr(3005, body({ 'Environment variables': '- Added `NEXT_PUBLIC_AD`\n- Removed the `hype` option' })), + pr(2968, body({ 'Environment variables': 'Added `NEXT_PUBLIC_SOCKET_URL`' })), + ]; + + expect(envChanges(prs)).toBe([ + '- #3005', + ' - Added `NEXT_PUBLIC_AD`', + ' - Removed the `hype` option', + '- #2968', + ' - Added `NEXT_PUBLIC_SOCKET_URL`', + ].join('\n')); + }); + + it('keeps paragraphs and code blocks of a change, nested under the PR', () => { + const section = 'Added `NEXT_PUBLIC_EXPEDITED_REVIEW_HTML`.\n\n**Example value**:\n\n```\nNEXT_PUBLIC_EXPEDITED_REVIEW_HTML=<b>Pay</b>\n```'; + + expect(envChanges([ pr(3644, body({ 'Environment variables': section })) ])).toBe([ + '- #3644', + ' - Added `NEXT_PUBLIC_EXPEDITED_REVIEW_HTML`.', + '', + ' **Example value**:', + '', + ' ```', + ' NEXT_PUBLIC_EXPEDITED_REVIEW_HTML=<b>Pay</b>', + ' ```', + ].join('\n')); + }); + + it('leaves out PRs whose section says None or is missing', () => { + const prs = [ pr(1, body({ 'Environment variables': 'None' })), pr(2, 'Old PR body'), pr(3, body({ 'Environment variables': 'Added `A`' })) ]; + + expect(envChanges(prs)).toBe('- #3\n - Added `A`'); + }); + + it('is empty when every PR says None', () => { + expect(envChanges([ pr(1, body({ 'Environment variables': 'None' })), pr(2, body({ 'Environment variables': 'None.' })) ])).toBe(''); + }); +}); + +describe('minimumApiVersions', () => { + it('maps Core API to the Blockscout API row', () => { + expect(minimumApiVersions(body({ 'Minimum API version': 'Core API v11.2.4+' }))).toEqual([ { service: 'Blockscout API', version: '11.2.4' } ]); + }); + + it('reads several services from a list or one line', () => { + const listed = body({ 'Minimum API version': '- Core API v11.2.4+\n- Stats microservice v2.5.0+' }); + const inline = body({ 'Minimum API version': 'Core API v11.2.4+ and stats v2.5' }); + const expected = [ { service: 'Blockscout API', version: '11.2.4' }, { service: 'Stats microservice API', version: '2.5.0' } ]; + + expect(minimumApiVersions(listed)).toEqual(expected); + expect(minimumApiVersions(inline)).toEqual([ expected[0], { ...expected[1], version: '2.5' } ]); + }); + + it('reads an emphasized version and ignores the explanation around it', () => { + const section = '- `tac-operation-lifecycle` **v1.2.0+** — the service release that serves Read API v2.\n- Core **v11.2.8+** (search, v2 shape)'; + + expect(minimumApiVersions(body({ 'Minimum API version': section }))).toEqual([ + { service: 'Tac-operation-lifecycle microservice API', version: '1.2.0' }, + { service: 'Blockscout API', version: '11.2.8' }, + ]); + }); + + it('does not read a version quoted in prose as a requirement', () => { + const section = 'The endpoint is merged but **not released yet** (latest release is v11.2.6), so the requirement is the next Core API release.'; + + expect(minimumApiVersions(body({ 'Minimum API version': section }))).toEqual([]); + }); + + it('is empty for None and for a PR without the section', () => { + expect(minimumApiVersions(body({ 'Minimum API version': 'None' }))).toEqual([]); + expect(minimumApiVersions('Old PR body')).toEqual([]); + }); +}); + +describe('unreadableApiVersions', () => { + it('lists PRs that fill the section without naming a versioned service', () => { + const prs = [ + pr(1, body({ 'Minimum API version': 'The latest backend' })), + pr(2, body({ 'Minimum API version': 'None' })), + pr(3, body({ 'Minimum API version': 'Core API v11.2.4+' })), + ]; + + expect(unreadableApiVersions(prs)).toEqual([ 1 ]); + }); +}); + +describe('compatibilityRows', () => { + it('lists each raised service once, at the highest version, Blockscout API first', () => { + const prs = [ + pr(1, body({ 'Minimum API version': 'Stats microservice v2.5.0+' })), + pr(2, body({ 'Minimum API version': 'Core API v11.2.4+' })), + pr(3, body({ 'Minimum API version': 'Core API v11.10.0+' })), + pr(4, body({ 'Minimum API version': 'Core API v11.9.9+\n- Bens microservice v1.2.0' })), + ]; + + expect(compatibilityRows(prs)).toBe([ + '| Blockscout API | v11.10.0 |', + '| Bens microservice API | v1.2.0 |', + '| Stats microservice API | v2.5.0 |', + ].join('\n')); + }); + + it('treats a missing patch number as zero', () => { + const prs = [ pr(1, body({ 'Minimum API version': 'Core API v11.2.0' })), pr(2, body({ 'Minimum API version': 'Core API v11.2' })) ]; + + expect(compatibilityRows(prs)).toBe('| Blockscout API | v11.2.0 |'); + }); + + it('is empty when no PR raises a version', () => { + expect(compatibilityRows([ pr(1, body({ 'Minimum API version': 'None' })) ])).toBe(''); + }); +}); + +describe('new contributors', () => { + const generated = [ + '## What\'s Changed', + '* Add the badge by @alice in https://github.com/blockscout/frontend/pull/10', + '', + '## New Contributors', + '* @alice made their first contribution in https://github.com/blockscout/frontend/pull/10', + '* @bob made their first contribution in https://github.com/blockscout/frontend/pull/11', + '', + '**Full Changelog**: https://github.com/blockscout/frontend/compare/v2.12.1...v2.13.0', + ].join('\n'); + + it('reads the first contributions from GitHub\'s generated notes', () => { + expect(parseFirstContributions(generated)).toEqual([ { author: 'alice', number: 10 }, { author: 'bob', number: 11 } ]); + }); + + it('keeps only first contributions made by a PR of these notes', () => { + expect(newContributors([ pr(10, '') ], parseFirstContributions(generated))) + .toBe('- @alice made their first contribution in https://github.com/blockscout/frontend/pull/10'); + }); +}); diff --git a/tools/release/notes-sections.ts b/tools/release/notes-sections.ts new file mode 100644 index 00000000000..9d32cccc025 --- /dev/null +++ b/tools/release/notes-sections.ts @@ -0,0 +1,145 @@ +import { orderBy, upperFirst } from 'es-toolkit'; + +import type { ReleasePullRequest } from './release-prs'; + +export const ENV_HEADING = 'Environment variables'; +export const API_VERSION_HEADING = 'Minimum API version'; + +const HEADING = /^#{1,6}\s+(\S.*)$/; +const HTML_COMMENT = /<!--[\s\S]*?-->/g; +const TEMPLATE_PLACEHOLDER = /^\*\[[\s\S]*\]\*$/; +const NONE = /^(?:none|n\/a)\b/i; +const EMPHASIS = /[*_`]/g; +const LIST_ITEM = /^\s*(?:[-*+]|\d+[.)])\s/; + +function isHeading(line: string, heading?: string): boolean { + const text = HEADING.exec(line.trim())?.[1]; + return text !== undefined && (heading === undefined || text.toLowerCase() === heading.toLowerCase()); +} + +function bodySection(body: string, heading: string): string | undefined { + const lines = body.replace(/\r\n?/g, '\n').split('\n'); + const start = lines.findIndex((line) => isHeading(line, heading)); + if (start === -1) { + return undefined; + } + const end = lines.findIndex((line, index) => index > start && isHeading(line)); + return lines.slice(start + 1, end === -1 ? undefined : end).join('\n'); +} + +function isEmptySection(section: string): boolean { + return section === '' || TEMPLATE_PLACEHOLDER.test(section) || NONE.test(section.replace(EMPHASIS, '')); +} + +// What the author wrote under the heading; nothing when the section is missing (a PR older than the +// template), starts with "None" (often followed by why), or still holds the template's placeholder. +export function filledSection(body: string, heading: string): string | undefined { + const section = bodySection(body, heading)?.replace(HTML_COMMENT, '').trim(); + return section === undefined || isEmptySection(section) ? undefined : section; +} + +// Nested under the PR's item as written, so code blocks and paragraphs survive; prose opens a sub-item +// so that it does not run on into the PR number. +function nestedChanges(section: string): Array<string> { + const lines = section.split('\n').map((line) => (line.trim() === '' ? '' : ` ${ line }`)); + return LIST_ITEM.test(section) ? lines : [ ` - ${ lines[0].trim() }`, ...lines.slice(1) ]; +} + +export function envChanges(prs: ReadonlyArray<ReleasePullRequest>): string { + return prs + .flatMap(({ number, body }) => { + const section = filledSection(body, ENV_HEADING); + return section === undefined ? [] : [ `- #${ number }`, ...nestedChanges(section) ]; + }) + .join('\n'); +} + +export interface ApiVersion { + readonly service: string; + readonly version: string; +} + +const BLOCKSCOUT_API = 'Blockscout API'; +const CORE_API = /\b(?:core|blockscout)\b/i; +const SERVICE_WORDS = /\b(?:microservice|service|api)\b/gi; +const VERSION = /\bv?(\d+(?:\.\d+){1,2})/; +const SEPARATOR = /[\n,;]|\band\b/; +const PARENTHETICAL = /\([^()]*\)/g; +const SERVICE_NAME = /^[a-z][\w-]*(?: [\w-]+){0,3}$/i; + +function serviceName(written: string): string { + if (CORE_API.test(written)) { + return BLOCKSCOUT_API; + } + return `${ upperFirst(written.replace(SERVICE_WORDS, '').replace(/\s+/g, ' ').trim()) } microservice API`; +} + +// Only a short name right before the version counts as a service, so a version quoted in prose ("the +// latest release is v11.2.6") is not mistaken for a requirement. +function serviceVersion(part: string): ApiVersion | undefined { + const text = part.replace(LIST_ITEM, '').replace(/\s+/g, ' '); + const match = VERSION.exec(text); + const service = text.slice(0, match?.index).trim(); + return match === null || !SERVICE_NAME.test(service) ? undefined : { service: serviceName(service), version: match[1] }; +} + +export function minimumApiVersions(body: string): Array<ApiVersion> { + const section = filledSection(body, API_VERSION_HEADING); + if (section === undefined) { + return []; + } + return section + .replace(EMPHASIS, '') + .replace(PARENTHETICAL, '') + .split(SEPARATOR) + .map(serviceVersion) + .filter((apiVersion) => apiVersion !== undefined); +} + +// A section the author filled in that names no `<service> v<version>`; the operator reads these PRs by +// hand rather than the notes silently dropping a requirement. +export function unreadableApiVersions(prs: ReadonlyArray<ReleasePullRequest>): Array<number> { + return prs + .filter(({ body }) => filledSection(body, API_VERSION_HEADING) !== undefined && minimumApiVersions(body).length === 0) + .map(({ number }) => number); +} + +function compareVersions(a: string, b: string): number { + const [ aParts, bParts ] = [ a, b ].map((version) => version.split('.').map(Number)); + const index = [ 0, 1, 2 ].find((position) => (aParts[position] ?? 0) !== (bParts[position] ?? 0)) ?? 0; + return (aParts[index] ?? 0) - (bParts[index] ?? 0); +} + +export function compatibilityRows(prs: ReadonlyArray<ReleasePullRequest>): string { + const highest = new Map<string, string>(); + for (const { service, version } of prs.flatMap(({ body }) => minimumApiVersions(body))) { + const current = highest.get(service); + if (current === undefined || compareVersions(version, current) > 0) { + highest.set(service, version); + } + } + return orderBy([ ...highest ], [ ([ service ]) => service !== BLOCKSCOUT_API, ([ service ]) => service ], [ 'asc', 'asc' ]) + .map(([ service, version ]) => `| ${ service } | v${ version } |`) + .join('\n'); +} + +export interface FirstContribution { + readonly author: string; + readonly number: number; +} + +const FIRST_CONTRIBUTION = /^[*-] @(\S+) made their first contribution in \S*\/pull\/(\d+)/gm; + +export function parseFirstContributions(generatedNotes: string): Array<FirstContribution> { + return [ ...generatedNotes.matchAll(FIRST_CONTRIBUTION) ].map(([ , author, number ]) => ({ author, number: Number(number) })); +} + +// GitHub counts a first contribution over the whole compared range, which for a minor includes PRs an +// earlier patch already shipped and announced; only the PRs of these notes are kept. +export function newContributors(prs: ReadonlyArray<ReleasePullRequest>, contributions: ReadonlyArray<FirstContribution>): string { + const urls = new Map(prs.map(({ number, url }) => [ number, url ])); + return contributions + .filter(({ number }) => urls.has(number)) + .map(({ author, number }) => `- @${ author } made their first contribution in ${ urls.get(number) }`) + .join('\n'); +} diff --git a/tools/release/notes-template.md b/tools/release/notes-template.md new file mode 100644 index 00000000000..ab89482abf3 --- /dev/null +++ b/tools/release/notes-template.md @@ -0,0 +1,45 @@ +<!-- +Template of `pnpm release notes`. A `## ` heading or a `---` line starts a block, and a block is left out of +the notes when any of its placeholders comes out empty. Placeholders: {{tag}}, {{previous_tag}}, +{{prs:<section>}} for each section of tools/release/categories.ts, in its order, {{env_changes}}, +{{compatibility}} and {{new_contributors}}. +--> +## 🚀 New Features +{{prs:New Features}} + +## 🐛 Bug Fixes +{{prs:Bug Fixes}} + +## ⚡ Performance Improvements +{{prs:Performance Improvements}} + +## 📦 Dependencies Updates +{{prs:Dependencies Updates}} + +## 🎨 Design Updates +{{prs:Design Updates}} + +## 🛠️ DX & Tooling +{{prs:DX & Tooling}} + +## ✨ Other Changes +{{prs:Other Changes}} + +## 🚨 Changes in ENV variables +{{env_changes}} + +**Full list of the ENV variables**: [{{tag}}](https://github.com/blockscout/frontend/blob/{{tag}}/docs/ENVS.md) + +## 💑 Compatibility +This release raises the minimum required version of the following API services: + +| Service | Version | +| --- | --- | +{{compatibility}} + +## 🦄 New Contributors +{{new_contributors}} + +--- + +**Full Changelog**: https://github.com/blockscout/frontend/compare/{{previous_tag}}...{{tag}} diff --git a/tools/release/notes.spec.ts b/tools/release/notes.spec.ts new file mode 100644 index 00000000000..e42fd33b73a --- /dev/null +++ b/tools/release/notes.spec.ts @@ -0,0 +1,159 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +import { CATEGORIES } from './categories'; +import type { NotesSource } from './notes'; +import { categoryOf, fillTemplate, releaseNotes, renderNotes } from './notes'; +import type { Commit, ReleasePullRequest } from './release-prs'; + +const TEMPLATE = fs.readFileSync(path.join(__dirname, 'notes-template.md'), 'utf8'); + +function pr(number: number, labels: ReadonlyArray<string>, overrides: Partial<ReleasePullRequest> = {}): ReleasePullRequest { + return { + number, + title: `PR ${ number }`, + author: 'tom2drum', + url: `https://github.com/blockscout/frontend/pull/${ number }`, + body: '', + labels, + closingIssues: [], + ...overrides, + }; +} + +const META = { tag: 'v2.13.0', previousTag: 'v2.12.1', template: TEMPLATE, firstContributions: [] }; +const FULL_CHANGELOG = '---\n\n**Full Changelog**: https://github.com/blockscout/frontend/compare/v2.12.1...v2.13.0\n'; + +describe('the notes template', () => { + it('has one PR list per category, in section order', () => { + const lists = [ ...TEMPLATE.replace(/<!--[\s\S]*?-->/, '').matchAll(/\{\{prs:([^}]+)\}\}/g) ].map(([ , section ]) => section); + + expect(lists).toEqual(CATEGORIES.map(({ section }) => section)); + }); +}); + +describe('categoryOf', () => { + it('places a PR by its category label', () => { + expect(categoryOf([ 'ENVs', 'bug' ]).section).toBe('Bug Fixes'); + }); + + it('places a PR with two category labels in the earlier section, whatever the label order', () => { + expect(categoryOf([ 'refactoring', 'feature' ]).section).toBe('New Features'); + expect(categoryOf([ 'feature', 'refactoring' ]).section).toBe('New Features'); + }); + + it('places a PR without a category label in Other Changes', () => { + expect(categoryOf([ 'ENVs' ]).section).toBe('Other Changes'); + }); +}); + +describe('fillTemplate', () => { + it('drops a block, up to the next heading or rule, when one of its placeholders is empty', () => { + const template = '## A\n{{a}}\n\n## B\n{{b}} and {{c}}\n\n---\n\n{{c}}\n'; + + expect(fillTemplate(template, new Map([ [ 'a', 'one' ], [ 'b', '' ], [ 'c', 'three' ] ]))).toBe('## A\none\n\n---\n\nthree\n'); + }); + + it('strips template comments', () => { + expect(fillTemplate('<!--\nHow to edit\n-->\n## A\n{{a}}\n', new Map([ [ 'a', 'one' ] ]))).toBe('## A\none\n'); + }); + + it('rejects an unknown placeholder', () => { + expect(() => fillTemplate('## A\n{{typo}}\n', new Map())).toThrow('Unknown placeholder {{typo}}'); + }); +}); + +describe('renderNotes', () => { + it('lists each PR once under its section, title capitalised, empty sections dropped', () => { + const prs = [ + pr(10, [ 'feature', 'refactoring' ], { title: 'add the badge', author: 'alice' }), + pr(11, [ 'bug' ]), + pr(12, []), + pr(13, [ 'enhancement' ]), + ]; + + expect(renderNotes(prs, META)).toBe([ + '## 🚀 New Features', + '- Add the badge by @alice in https://github.com/blockscout/frontend/pull/10', + '- PR 13 by @tom2drum in https://github.com/blockscout/frontend/pull/13', + '', + '## 🐛 Bug Fixes', + '- PR 11 by @tom2drum in https://github.com/blockscout/frontend/pull/11', + '', + '## ✨ Other Changes', + '- PR 12 by @tom2drum in https://github.com/blockscout/frontend/pull/12', + '', + FULL_CHANGELOG, + ].join('\n')); + }); + + it('fills the ENV, Compatibility and New Contributors sections', () => { + const prs = [ + pr(10, [ 'feature' ], { + author: 'alice', + body: '## Environment variables\n\nAdded `NEXT_PUBLIC_BADGE`\n\n## Minimum API version\n\nCore API v11.2.4+', + }), + ]; + + expect(renderNotes(prs, { ...META, firstContributions: [ { author: 'alice', number: 10 } ] })).toBe([ + '## 🚀 New Features', + '- PR 10 by @alice in https://github.com/blockscout/frontend/pull/10', + '', + '## 🚨 Changes in ENV variables', + '- #10', + ' - Added `NEXT_PUBLIC_BADGE`', + '', + '**Full list of the ENV variables**: [v2.13.0](https://github.com/blockscout/frontend/blob/v2.13.0/docs/ENVS.md)', + '', + '## 💑 Compatibility', + 'This release raises the minimum required version of the following API services:', + '', + '| Service | Version |', + '| --- | --- |', + '| Blockscout API | v11.2.4 |', + '', + '## 🦄 New Contributors', + '- @alice made their first contribution in https://github.com/blockscout/frontend/pull/10', + '', + FULL_CHANGELOG, + ].join('\n')); + }); +}); + +describe('releaseNotes', () => { + const TAGS = [ 'v2.12.0', 'v2.12.1', 'v2.13.0-alpha.1', 'v2.13.0' ]; + + function source(rangeStart: string, commits: ReadonlyArray<Commit>, pullRequests: ReadonlyArray<ReleasePullRequest>): NotesSource { + return { + tags: () => TAGS, + commits: (from) => (from === rangeStart ? commits : []), + commitMessage: () => '', + associatedPr: () => undefined, + pullRequest: (number) => pullRequests.find((pullRequest) => pullRequest.number === number) ?? pr(number, []), + generatedNotes: (tag, previousTag) => `* @alice made their first contribution in https://github.com/x/y/pull/10 (${ tag }, ${ previousTag })`, + }; + } + + it('lists a minor\'s PRs since the previous minor\'s last release, without those a version already shipped', () => { + const commits = [ { sha: 'c1', message: 'Add the badge (#10)' }, { sha: 'c2', message: 'Fix the gas tracker (#11)' } ]; + const notes = releaseNotes('v2.13.0', source('v2.12.1', commits, [ pr(10, [ 'feature' ]), pr(11, [ 'bug', 'v2.12.1' ]) ]), TEMPLATE); + + expect(notes.previousTag).toBe('v2.12.1'); + expect(notes.skipped.map(({ number }) => number)).toEqual([ 11 ]); + expect(notes.markdown).toContain('/pull/10'); + expect(notes.markdown).not.toContain('/pull/11'); + expect(notes.markdown).toContain('@alice made their first contribution'); + }); + + it('lists a patch\'s PRs picked since the previous patch of its line', () => { + const commits = [ { sha: 'c3', message: `Fix the badge (#12)\n\n(cherry picked from commit ${ 'a'.repeat(40) })` } ]; + const notesSource = { ...source('v2.13.0', commits, [ pr(12, [ 'bug' ]) ]), commitMessage: () => 'Fix the badge (#12)' }; + const notes = releaseNotes('v2.13.1-alpha.1', notesSource, TEMPLATE); + + expect(notes.previousTag).toBe('v2.13.0'); + expect(notes.markdown).toContain('## 🐛 Bug Fixes\n- PR 12 by @tom2drum in https://github.com/blockscout/frontend/pull/12'); + expect(notes.markdown).toContain('compare/v2.13.0...v2.13.1-alpha.1'); + }); +}); diff --git a/tools/release/notes.ts b/tools/release/notes.ts new file mode 100644 index 00000000000..b01014a582b --- /dev/null +++ b/tools/release/notes.ts @@ -0,0 +1,98 @@ +import { upperFirst } from 'es-toolkit'; + +import type { Category } from './categories'; +import { CATCH_ALL_LABEL, CATEGORIES } from './categories'; +import type { FirstContribution } from './notes-sections'; +import { compatibilityRows, envChanges, newContributors, parseFirstContributions } from './notes-sections'; +import type { ReleasePrs, ReleasePullRequest, ReleaseSource } from './release-prs'; +import { releasePrs } from './release-prs'; + +export interface NotesMeta { + readonly tag: string; + readonly previousTag: string; + readonly template: string; + readonly firstContributions: ReadonlyArray<FirstContribution>; +} + +const CATCH_ALL = CATEGORIES.find(({ labels }) => labels.includes(CATCH_ALL_LABEL)) as Category; + +// Walked in section order, not the PR's label order, so a PR labeled with two categories (possible +// before the PR check existed) lands in the same section whatever order GitHub returns its labels in. +export function categoryOf(labels: ReadonlyArray<string>): Category { + return CATEGORIES.find((category) => category.labels.some((label) => labels.includes(label))) ?? CATCH_ALL; +} + +function prLine({ title, author, url }: ReleasePullRequest): string { + return `- ${ upperFirst(title.trim()) } by @${ author } in ${ url }`; +} + +const COMMENT = /<!--[\s\S]*?-->\n?/g; +const BLOCK_START = /^(?:## |---$)/; +const PLACEHOLDER = /\{\{([^{}]+)\}\}/g; + +function templateBlocks(template: string): Array<string> { + const blocks: Array<Array<string>> = [ [] ]; + for (const line of template.replace(/\r\n?/g, '\n').replace(COMMENT, '').split('\n')) { + if (BLOCK_START.test(line)) { + blocks.push([]); + } + blocks[blocks.length - 1].push(line); + } + return blocks.map((lines) => lines.join('\n').trim()).filter((block) => block !== ''); +} + +function placeholderValue(values: ReadonlyMap<string, string>, key: string): string { + const value = values.get(key); + if (value === undefined) { + throw new Error(`Unknown placeholder {{${ key }}} in the release notes template`); + } + return value; +} + +function fillBlock(block: string, values: ReadonlyMap<string, string>): string | undefined { + const keys = [ ...block.matchAll(PLACEHOLDER) ].map(([ , key ]) => key); + if (keys.some((key) => placeholderValue(values, key) === '')) { + return undefined; + } + return block.replace(PLACEHOLDER, (_, key: string) => placeholderValue(values, key)); +} + +export function fillTemplate(template: string, values: ReadonlyMap<string, string>): string { + const blocks = templateBlocks(template) + .map((block) => fillBlock(block, values)) + .filter((block) => block !== undefined); + return `${ blocks.join('\n\n') }\n`; +} + +export function renderNotes(prs: ReadonlyArray<ReleasePullRequest>, meta: NotesMeta): string { + const sections = CATEGORIES.map((category): [ string, string ] => [ + `prs:${ category.section }`, + prs.filter(({ labels }) => categoryOf(labels) === category).map(prLine).join('\n'), + ]); + const values = new Map([ + [ 'tag', meta.tag ], + [ 'previous_tag', meta.previousTag ], + ...sections, + [ 'env_changes', envChanges(prs) ], + [ 'compatibility', compatibilityRows(prs) ], + [ 'new_contributors', newContributors(prs, meta.firstContributions) ], + ]); + return fillTemplate(meta.template, values); +} + +export interface NotesSource extends ReleaseSource { + readonly generatedNotes: (tag: string, previousTag: string) => string; +} + +export interface ReleaseNotes extends ReleasePrs { + readonly markdown: string; +} + +export function releaseNotes(tag: string, source: NotesSource, template: string): ReleaseNotes { + const release = releasePrs(tag, source); + const firstContributions = parseFirstContributions(source.generatedNotes(tag, release.previousTag)); + return { + ...release, + markdown: renderNotes(release.prs, { tag, previousTag: release.previousTag, template, firstContributions }), + }; +} diff --git a/tools/release/picks.spec.ts b/tools/release/picks.spec.ts new file mode 100644 index 00000000000..119e10f005f --- /dev/null +++ b/tools/release/picks.spec.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from 'vitest'; + +import type { BackportPullRequest, BranchState } from './picks'; +import { planPicks } from './picks'; + +const SHA = { + old: '1111111111111111111111111111111111111111', + a: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + b: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + c: 'cccccccccccccccccccccccccccccccccccccccc', + pickOfA: 'dddddddddddddddddddddddddddddddddddddddd', +}; + +function pr(number: number, mergeSha: string, labels: ReadonlyArray<string> = [ 'backport', 'bug' ]): BackportPullRequest { + return { number, title: `Fix ${ number }`, labels, mergeSha }; +} + +const MAIN: BranchState['mainCommits'] = [ SHA.a, SHA.b, SHA.c ]; + +describe('planPicks', () => { + it('picks in main order, whatever order the PRs come in', () => { + const plan = planPicks([ pr(3, SHA.c), pr(1, SHA.a), pr(2, SHA.b) ], { mainCommits: MAIN, branchCommits: [] }); + + expect(plan.picks.map(({ number }) => number)).toEqual([ 1, 2, 3 ]); + expect(plan.skipped).toEqual([]); + }); + + it('skips a PR merged before the fork, which the branch has as an ancestor', () => { + const plan = planPicks([ pr(1, SHA.old), pr(2, SHA.b) ], { mainCommits: MAIN, branchCommits: [] }); + + expect(plan.picks.map(({ number }) => number)).toEqual([ 2 ]); + expect(plan.skipped).toEqual([ { pr: pr(1, SHA.old), reason: 'before-fork' } ]); + }); + + it('skips a PR a branch commit names in its trailer', () => { + const branchCommits = [ { sha: SHA.pickOfA, message: `Fix 1 (#1)\n\n(cherry picked from commit ${ SHA.a })` } ]; + const plan = planPicks([ pr(1, SHA.a), pr(2, SHA.b) ], { mainCommits: MAIN, branchCommits }); + + expect(plan.picks.map(({ number }) => number)).toEqual([ 2 ]); + expect(plan.skipped).toEqual([ { pr: pr(1, SHA.a), reason: 'picked', sha: SHA.pickOfA } ]); + }); + + it('matches an abbreviated trailer by prefix', () => { + const branchCommits = [ { sha: SHA.pickOfA, message: `Fix 1\n\n(cherry picked from commit ${ SHA.a.slice(0, 7) })` } ]; + + expect(planPicks([ pr(1, SHA.a) ], { mainCommits: MAIN, branchCommits }).picks).toEqual([]); + }); + + it('reads every trailer of a pick of a pick', () => { + const message = `Fix 1\n\n(cherry picked from commit ${ SHA.old })\n(cherry picked from commit ${ SHA.a })`; + const branchCommits = [ { sha: SHA.pickOfA, message } ]; + + expect(planPicks([ pr(1, SHA.a) ], { mainCommits: MAIN, branchCommits }).picks).toEqual([]); + }); + + it('skips a PR another release shipped, whatever the branch has', () => { + const released = pr(1, SHA.a, [ 'backport', 'v2.12.3' ]); + + expect(planPicks([ released ], { mainCommits: MAIN, branchCommits: [] }).skipped).toEqual([ + { pr: released, reason: 'released', versionLabels: [ 'v2.12.3' ] }, + ]); + }); + + it('plans nothing when run again after the picks', () => { + const prs = [ pr(1, SHA.a), pr(2, SHA.b) ]; + const first = planPicks(prs, { mainCommits: MAIN, branchCommits: [] }); + const branchCommits = first.picks.map(({ number, mergeSha }, index) => ({ + sha: `${ index }`.repeat(40), + message: `Fix ${ number } (#${ number })\n\n(cherry picked from commit ${ mergeSha })`, + })); + + const second = planPicks(prs, { mainCommits: MAIN, branchCommits }); + + expect(first.picks).toHaveLength(2); + expect(second.picks).toEqual([]); + expect(second.skipped.map(({ reason }) => reason)).toEqual([ 'picked', 'picked' ]); + }); +}); diff --git a/tools/release/picks.ts b/tools/release/picks.ts new file mode 100644 index 00000000000..8c29275dd26 --- /dev/null +++ b/tools/release/picks.ts @@ -0,0 +1,60 @@ +import type { Commit } from './release-prs'; +import { cherryPickSources } from './release-prs'; +import { isVersionLabel } from './versions'; + +export interface BackportPullRequest { + readonly number: number; + readonly title: string; + readonly labels: ReadonlyArray<string>; + readonly mergeSha: string; +} + +// Both sides of the fork point: what main has beyond it, oldest first, and what the branch has. +export interface BranchState { + readonly mainCommits: ReadonlyArray<string>; + readonly branchCommits: ReadonlyArray<Commit>; +} + +export type Skip = + { readonly pr: BackportPullRequest; readonly reason: 'released'; readonly versionLabels: ReadonlyArray<string> } | + { readonly pr: BackportPullRequest; readonly reason: 'before-fork' } | + { readonly pr: BackportPullRequest; readonly reason: 'picked'; readonly sha: string }; + +export interface PickPlan { + readonly picks: ReadonlyArray<BackportPullRequest>; + readonly skipped: ReadonlyArray<Skip>; +} + +// A hand-made trailer may abbreviate the source, so the full sha is matched by prefix. +function pickOf(mergeSha: string, branchCommits: ReadonlyArray<Commit>): Commit | undefined { + return branchCommits.find(({ message }) => cherryPickSources(message).some((source) => mergeSha.startsWith(source))); +} + +function skipOf(pr: BackportPullRequest, branch: BranchState): Skip | undefined { + const versionLabels = pr.labels.filter(isVersionLabel); + if (versionLabels.length > 0) { + return { pr, reason: 'released', versionLabels }; + } + if (!branch.mainCommits.includes(pr.mergeSha)) { + return { pr, reason: 'before-fork' }; + } + const pick = pickOf(pr.mergeSha, branch.branchCommits); + return pick === undefined ? undefined : { pr, reason: 'picked', sha: pick.sha }; +} + +// Picks go in main order, so a later PR lands on top of an earlier one it may depend on. Planning again +// after the picks finds each one by its trailer and plans nothing, which is what lets a stopped run resume. +export function planPicks(prs: ReadonlyArray<BackportPullRequest>, branch: BranchState): PickPlan { + const skipped: Array<Skip> = []; + const picks: Array<BackportPullRequest> = []; + for (const pr of prs) { + const skip = skipOf(pr, branch); + if (skip === undefined) { + picks.push(pr); + } else { + skipped.push(skip); + } + } + picks.sort((a, b) => branch.mainCommits.indexOf(a.mergeSha) - branch.mainCommits.indexOf(b.mergeSha)); + return { picks, skipped }; +} diff --git a/tools/release/pre-release.spec.ts b/tools/release/pre-release.spec.ts new file mode 100644 index 00000000000..e6506530469 --- /dev/null +++ b/tools/release/pre-release.spec.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest'; + +import type { GithubRelease } from './pre-release'; +import { findLinePreRelease, findReleasePreRelease } from './pre-release'; + +function release(id: number, tagName: string, overrides: Partial<GithubRelease> = {}): GithubRelease { + return { id, tagName, draft: false, prerelease: false, url: `https://github.com/blockscout/frontend/releases/tag/${ tagName }`, ...overrides }; +} + +const V2_13 = { major: 2, minor: 13 }; + +describe('findLinePreRelease', () => { + it('finds the draft pre-release of the line, whichever tag of the line it names', () => { + const preRelease = release(3, 'v2.13.1-alpha.2', { draft: true, prerelease: true }); + const releases = [ release(1, 'v2.12.3'), release(2, 'v2.13.0'), preRelease, release(4, 'v2.12.4-alpha.1', { prerelease: true }) ]; + + expect(findLinePreRelease(releases, V2_13)).toBe(preRelease); + }); + + it('finds a published pre-release too', () => { + const preRelease = release(1, 'v2.13.0-alpha.1', { prerelease: true }); + + expect(findLinePreRelease([ preRelease ], V2_13)).toBe(preRelease); + }); + + it('takes neither a final release of the line nor a pre-release of another line', () => { + const releases = [ release(1, 'v2.13.0'), release(2, 'v2.130.0-alpha.1', { prerelease: true }), release(3, 'v3.13.0', { prerelease: true }) ]; + + expect(findLinePreRelease(releases, V2_13)).toBeUndefined(); + }); + + it('skips a release whose tag is not a release tag', () => { + expect(findLinePreRelease([ release(1, 'untagged-v2.13', { draft: true, prerelease: true }) ], V2_13)).toBeUndefined(); + }); + + it('throws when the line has more than one pre-release', () => { + const releases = [ release(1, 'v2.13.0', { draft: true, prerelease: true }), release(2, 'v2.13.0-alpha.1', { prerelease: true }) ]; + + expect(() => findLinePreRelease(releases, V2_13)).toThrow('Line v2.13 has 2 pre-releases (v2.13.0, v2.13.0-alpha.1); delete all but one'); + }); +}); + +describe('findReleasePreRelease', () => { + const V2_13_1 = { major: 2, minor: 13, patch: 1, prerelease: undefined }; + + it('finds the pre-release of the version, whichever of its tags it names', () => { + const preRelease = release(2, 'v2.13.1-alpha.1', { draft: true, prerelease: true }); + + expect(findReleasePreRelease([ release(1, 'v2.13.0'), preRelease ], V2_13_1)).toBe(preRelease); + }); + + it('throws when the version has no pre-release', () => { + expect(() => findReleasePreRelease([ release(1, 'v2.13.0') ], V2_13_1)).toThrow( + 'Release v2.13.1 has no pre-release; create it with "pnpm release prepare v2.13.1"', + ); + }); + + it('never takes over the open pre-release of another version of the line', () => { + const open = release(1, 'v2.13.0', { draft: true, prerelease: true }); + + expect(() => findReleasePreRelease([ open ], V2_13_1)).toThrow( + 'The open pre-release of line v2.13 is v2.13.0 (https://github.com/blockscout/frontend/releases/tag/v2.13.0), not v2.13.1; publish it first', + ); + }); +}); diff --git a/tools/release/pre-release.ts b/tools/release/pre-release.ts new file mode 100644 index 00000000000..081392dc0a9 --- /dev/null +++ b/tools/release/pre-release.ts @@ -0,0 +1,39 @@ +import type { Line, Version } from './versions'; +import { formatLine, formatVersion, isSameLine, parseTag, versionLabel } from './versions'; + +export interface GithubRelease { + readonly id: number; + readonly tagName: string; + readonly draft: boolean; + readonly prerelease: boolean; + readonly url: string; +} + +// A line keeps one pre-release from prepare to publish, re-pointed at each alpha: a second one would let +// the tag check and the operator read different notes. +export function findLinePreRelease(releases: ReadonlyArray<GithubRelease>, line: Line): GithubRelease | undefined { + const found = releases.filter((release) => { + const version = parseTag(release.tagName); + return release.prerelease && version !== undefined && isSameLine(version, line); + }); + + if (found.length > 1) { + const tags = found.map(({ tagName }) => tagName).join(', '); + throw new Error(`Line ${ formatLine(line) } has ${ found.length } pre-releases (${ tags }); delete all but one`); + } + return found[0]; +} + +// An alpha re-points only the pre-release of its own version: the line's open one may be a release not +// published yet, whose notes and tag the alpha must not take over. +export function findReleasePreRelease(releases: ReadonlyArray<GithubRelease>, version: Version): GithubRelease { + const tag = formatVersion(version); + const preRelease = findLinePreRelease(releases, version); + if (preRelease === undefined) { + throw new Error(`Release ${ tag } has no pre-release; create it with "pnpm release prepare ${ tag }"`); + } + if (versionLabel(preRelease.tagName) !== tag) { + throw new Error(`The open pre-release of line ${ formatLine(version) } is ${ preRelease.tagName } (${ preRelease.url }), not ${ tag }; publish it first`); + } + return preRelease; +} diff --git a/tools/release/release-prs.spec.ts b/tools/release/release-prs.spec.ts new file mode 100644 index 00000000000..0ea1eec15de --- /dev/null +++ b/tools/release/release-prs.spec.ts @@ -0,0 +1,179 @@ +import { describe, expect, it } from 'vitest'; + +import type { Commit, PrResolver, ReleasePullRequest, ReleaseSource } from './release-prs'; +import { isDocsCommit, isReleasedElsewhere, issuesToLabel, prepareCommitMessage, releasePrs, resolvePr } from './release-prs'; + +const SOURCE_SHA = 'a'.repeat(40); + +function resolver(messages: Record<string, string> = {}, associations: Record<string, number> = {}): PrResolver { + return { + commitMessage: (sha) => messages[sha], + associatedPr: (sha) => associations[sha], + }; +} + +function pr(number: number, labels: ReadonlyArray<string> = [], closingIssues: ReleasePullRequest['closingIssues'] = []): ReleasePullRequest { + const url = `https://github.com/blockscout/frontend/pull/${ number }`; + return { number, title: `PR ${ number }`, author: 'tom2drum', url, body: '', labels, closingIssues }; +} + +describe('resolvePr', () => { + it('follows the cherry-pick trailer to the source commit\'s PR reference', () => { + const commit = { sha: 'b1', message: `Fix the gas tracker (#3700)\n\n(cherry picked from commit ${ SOURCE_SHA })` }; + + expect(resolvePr(commit, resolver({ [SOURCE_SHA]: 'Fix the gas tracker (#3708)' }, { [SOURCE_SHA]: 1, b1: 2 }))).toBe(3708); + }); + + it('falls back to the source commit\'s association when its subject has no reference', () => { + const commit = { sha: 'b1', message: `Fix the gas tracker\n\n(cherry picked from commit ${ SOURCE_SHA })` }; + + expect(resolvePr(commit, resolver({ [SOURCE_SHA]: 'Fix the gas tracker' }, { [SOURCE_SHA]: 3708, b1: 1 }))).toBe(3708); + }); + + it('follows a pick of a pick back to the commit on main', () => { + const pickedSha = 'c'.repeat(40); + const commit = { sha: 'b1', message: `Fix\n\n(cherry picked from commit ${ pickedSha })` }; + const messages = { [pickedSha]: `Fix\n\n(cherry picked from commit ${ SOURCE_SHA })`, [SOURCE_SHA]: 'Fix (#3708)' }; + + expect(resolvePr(commit, resolver(messages))).toBe(3708); + }); + + it('reads the last PR reference in the subject', () => { + const commit = { sha: 'b1', message: 'Revert "Add the badge (#3600)" (#3650)\n\nReverts (#3600).' }; + + expect(resolvePr(commit, resolver())).toBe(3650); + }); + + it('ignores a PR reference outside the subject', () => { + const commit = { sha: 'b1', message: 'Fix the badge\n\nFollow-up to (#3600).' }; + + expect(resolvePr(commit, resolver({}, { b1: 3655 }))).toBe(3655); + }); + + it('asks the association lookup when there is neither a trailer nor a reference', () => { + expect(resolvePr({ sha: 'b1', message: 'Merge branch main' }, resolver({}, { b1: 3660, b2: 1 }))).toBe(3660); + }); + + it('resolves to nothing when no step finds a PR', () => { + expect(resolvePr({ sha: 'b1', message: 'Merge branch main' }, resolver())).toBeUndefined(); + }); +}); + +describe('prepareCommitMessage', () => { + it('names the release', () => { + expect(prepareCommitMessage('v2.13.1')).toBe('chore: prepare release v2.13.1'); + }); +}); + +describe('isDocsCommit', () => { + it('matches the subject naming the tag', () => { + expect(isDocsCommit({ sha: 'c1', message: 'chore: prepare release v2.13.0\n\nSecond alpha.' }, 'v2.13.0')).toBe(true); + }); + + it('matches the final tag of an alpha', () => { + expect(isDocsCommit({ sha: 'c1', message: 'chore: prepare release v2.13.0' }, 'v2.13.0-alpha.2')).toBe(true); + }); + + it('does not match another release, a body line, or a pick', () => { + expect(isDocsCommit({ sha: 'c1', message: 'chore: prepare release v2.12.3' }, 'v2.13.0')).toBe(false); + expect(isDocsCommit({ sha: 'c1', message: 'Fix (#1)\n\nchore: prepare release v2.13.0' }, 'v2.13.0')).toBe(false); + expect(isDocsCommit({ sha: 'c1', message: `Fix (#1)\n\n(cherry picked from commit ${ SOURCE_SHA })` }, 'v2.13.0')).toBe(false); + }); +}); + +describe('isReleasedElsewhere', () => { + it('is true for a version label of another release', () => { + expect(isReleasedElsewhere([ 'bug', 'v2.12.1' ], 'v2.13.0')).toBe(true); + }); + + it('is false for the tag\'s own version label, also from its alpha', () => { + expect(isReleasedElsewhere([ 'v2.13.0' ], 'v2.13.0')).toBe(false); + expect(isReleasedElsewhere([ 'v2.13.0' ], 'v2.13.0-alpha.2')).toBe(false); + }); + + it('is false without version labels', () => { + expect(isReleasedElsewhere([ 'pre-release', 'backport' ], 'v2.13.0')).toBe(false); + }); +}); + +describe('releasePrs', () => { + function source(commits: ReadonlyArray<Commit>, pullRequests: ReadonlyArray<ReleasePullRequest>): ReleaseSource { + return { + ...resolver(), + tags: () => [ 'v2.12.0', 'v2.12.1', 'v2.13.0-alpha.1' ], + commits: (from) => (from === 'v2.12.1' ? commits : []), + pullRequest: (number) => pullRequests.find((pullRequest) => pullRequest.number === number) ?? pr(number), + }; + } + + it('compares from the computed previous tag', () => { + const result = releasePrs('v2.13.0-alpha.1', source([ { sha: 'c1', message: 'Add the badge (#10)' } ], [])); + + expect(result.previousTag).toBe('v2.12.1'); + expect(result.prs.map(({ number }) => number)).toEqual([ 10 ]); + }); + + it('excludes PRs already released by another version and reports them as skipped', () => { + const commits = [ + { sha: 'c1', message: 'Add the badge (#10)' }, + { sha: 'c2', message: 'Fix the badge (#11)' }, + { sha: 'c3', message: 'Bump viem (#12)' }, + ]; + const result = releasePrs('v2.13.0', source(commits, [ pr(10, [ 'feature' ]), pr(11, [ 'bug', 'v2.12.1' ]), pr(12, [ 'v2.13.0' ]) ])); + + expect(result.prs.map(({ number }) => number)).toEqual([ 10, 12 ]); + expect(result.skipped.map(({ number }) => number)).toEqual([ 11 ]); + }); + + it('lists a PR once however many commits resolve to it, in commit order', () => { + const commits = [ + { sha: 'c1', message: 'Fix the badge (#11)' }, + { sha: 'c2', message: 'Add the badge (#10)' }, + { sha: 'c3', message: 'Fix the badge again (#11)' }, + ]; + + expect(releasePrs('v2.13.0', source(commits, [])).prs.map(({ number }) => number)).toEqual([ 11, 10 ]); + }); + + it('reports commits that resolve to no PR', () => { + const commit = { sha: 'c1', message: 'Merge branch main' }; + + expect(releasePrs('v2.13.0', source([ commit ], [])).unresolved).toEqual([ commit ]); + }); + + it('leaves the docs commit out without asking GitHub, for the final tag and its alpha', () => { + const docsCommit = { sha: 'c1', message: 'chore: prepare release v2.13.0' }; + const asked: Array<string> = []; + const spied: ReleaseSource = { + ...source([ docsCommit, { sha: 'c2', message: 'Add the badge (#10)' } ], []), + associatedPr: (sha) => { + asked.push(sha); + return undefined; + }, + }; + + for (const tag of [ 'v2.13.0', 'v2.13.0-alpha.1' ]) { + const result = releasePrs(tag, spied); + expect(result.unresolved).toEqual([]); + expect(result.prs.map(({ number }) => number)).toEqual([ 10 ]); + } + expect(asked).toEqual([]); + }); +}); + +describe('issuesToLabel', () => { + it('collects the closing issues of every PR once, sorted', () => { + const prs = [ + pr(10, [], [ { number: 5, labels: [] }, { number: 3, labels: [] } ]), + pr(11, [], [ { number: 3, labels: [] } ]), + ]; + + expect(issuesToLabel(prs, 'v2.13.0')).toEqual([ 3, 5 ]); + }); + + it('leaves out an issue already in another release, keeping the PR\'s other issues', () => { + const prs = [ pr(10, [], [ { number: 5, labels: [ 'v2.12.1' ] }, { number: 6, labels: [ 'v2.13.0', 'bug' ] } ]) ]; + + expect(issuesToLabel(prs, 'v2.13.0')).toEqual([ 6 ]); + }); +}); diff --git a/tools/release/release-prs.ts b/tools/release/release-prs.ts new file mode 100644 index 00000000000..43b145147c8 --- /dev/null +++ b/tools/release/release-prs.ts @@ -0,0 +1,114 @@ +import { isVersionLabel, previousTag, versionLabel } from './versions'; + +export interface Commit { + readonly sha: string; + readonly message: string; +} + +export interface PrResolver { + readonly commitMessage: (sha: string) => string; + readonly associatedPr: (sha: string) => number | undefined; +} + +export interface Issue { + readonly number: number; + readonly labels: ReadonlyArray<string>; +} + +export interface ReleasePullRequest { + readonly number: number; + readonly title: string; + readonly author: string; + readonly url: string; + readonly body: string; + readonly labels: ReadonlyArray<string>; + readonly closingIssues: ReadonlyArray<Issue>; +} + +export interface ReleaseSource extends PrResolver { + readonly tags: () => ReadonlyArray<string>; + readonly commits: (from: string, to: string) => ReadonlyArray<Commit>; + readonly pullRequest: (number: number) => ReleasePullRequest; +} + +export interface ReleasePrs { + readonly previousTag: string; + readonly prs: ReadonlyArray<ReleasePullRequest>; + readonly skipped: ReadonlyArray<ReleasePullRequest>; + readonly unresolved: ReadonlyArray<Commit>; +} + +const CHERRY_PICK_TRAILER = /^\(cherry picked from commit ([0-9a-f]{7,40})\)$/gm; +const PR_REFERENCE = /\(#(\d+)\)/g; + +// Every source a commit names: a pick of a pick carries one trailer per hop. +export function cherryPickSources(message: string): Array<string> { + return [ ...message.matchAll(CHERRY_PICK_TRAILER) ].map(([ , sha ]) => sha); +} + +function subject(message: string): string { + return message.split('\n', 1)[0]; +} + +function subjectPr(message: string): number | undefined { + const reference = [ ...subject(message).matchAll(PR_REFERENCE) ].at(-1); + return reference === undefined ? undefined : Number(reference[1]); +} + +export function prepareCommitMessage(tag: string): string { + return `chore: prepare release ${ tag }`; +} + +// The docs commit of a release is made on its branch, so it has no PR to resolve and, until the branch is +// pushed, is not even known to GitHub. Its subject names the final tag, also when the notes are an alpha's. +export function isDocsCommit(commit: Commit, tag: string): boolean { + return subject(commit.message) === prepareCommitMessage(versionLabel(tag)); +} + +// A picked commit is resolved through its source on `main`, never its own subject, which the operator +// may have edited while resolving a conflict. +export function resolvePr(commit: Commit, resolver: PrResolver): number | undefined { + const [ source ] = cherryPickSources(commit.message); + if (source !== undefined) { + return resolvePr({ sha: source, message: resolver.commitMessage(source) }, resolver); + } + return subjectPr(commit.message) ?? resolver.associatedPr(commit.sha); +} + +// The tag's own version label does not count, so a re-run after a partial failure still sees the PRs +// and issues it labeled the first time. +export function isReleasedElsewhere(labels: ReadonlyArray<string>, tag: string): boolean { + const ownLabel = versionLabel(tag); + return labels.some((label) => isVersionLabel(label) && label !== ownLabel); +} + +export function releasePrs(tag: string, source: ReleaseSource): ReleasePrs { + const previous = previousTag(tag, source.tags()); + const numbers = new Set<number>(); + const unresolved: Array<Commit> = []; + + for (const commit of source.commits(previous, tag).filter((commit) => !isDocsCommit(commit, tag))) { + const number = resolvePr(commit, source); + if (number === undefined) { + unresolved.push(commit); + } else { + numbers.add(number); + } + } + + const pullRequests = [ ...numbers ].map(source.pullRequest); + return { + previousTag: previous, + prs: pullRequests.filter(({ labels }) => !isReleasedElsewhere(labels, tag)), + skipped: pullRequests.filter(({ labels }) => isReleasedElsewhere(labels, tag)), + unresolved, + }; +} + +export function issuesToLabel(prs: ReadonlyArray<ReleasePullRequest>, tag: string): Array<number> { + const numbers = prs + .flatMap(({ closingIssues }) => closingIssues) + .filter(({ labels }) => !isReleasedElsewhere(labels, tag)) + .map(({ number }) => number); + return [ ...new Set(numbers) ].sort((a, b) => a - b); +} diff --git a/tools/release/release-source.ts b/tools/release/release-source.ts new file mode 100644 index 00000000000..c672f819b2f --- /dev/null +++ b/tools/release/release-source.ts @@ -0,0 +1,22 @@ +import { commitMessage, listCommits, listTags } from './git'; +import { fetchAssociatedPr, fetchReleasePullRequest, generateReleaseNotes } from './github'; +import type { NotesSource } from './notes'; + +// Commits and tags come from the checkout, which therefore needs full history and tags (CI: `fetch-depth: 0`). +export const RELEASE_SOURCE: NotesSource = { + tags: listTags, + commits: listCommits, + commitMessage, + associatedPr: fetchAssociatedPr, + pullRequest: fetchReleasePullRequest, + generatedNotes: generateReleaseNotes, +}; + +// For a tag not cut yet: the notes are read up to the commit it is going to name. +export function releaseSourceAt(head: string): NotesSource { + return { + ...RELEASE_SOURCE, + commits: (from) => listCommits(from, head), + generatedNotes: (tag, previousTag) => generateReleaseNotes(tag, previousTag, head), + }; +} diff --git a/tools/release/run.sh b/tools/release/run.sh new file mode 100755 index 00000000000..dca8ffab700 --- /dev/null +++ b/tools/release/run.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# Compile-on-run wrapper for the release tool. +# Resolves its own location, so it can be called from any working directory. +# +# Usage: tools/release/run.sh <subcommand> [args] + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" + +# The tool imports the shared helpers from ../cli, so tsc's rootDir spans the tools folder and the entry +# point lands one level deeper than the outDir. +"$ROOT/node_modules/.bin/tsc" -p "$DIR/tsconfig.json" +node "$DIR/dist/release/index.js" "$@" diff --git a/tools/release/tsconfig.json b/tools/release/tsconfig.json new file mode 100644 index 00000000000..cffc1547b4c --- /dev/null +++ b/tools/release/tsconfig.json @@ -0,0 +1,22 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "node16", + "target": "es2022", + "moduleResolution": "node16", + "resolveJsonModule": false, + "isolatedModules": false, + "noEmit": false, + // Disable incremental (inherited from the root config): dist/ is git-ignored and compiled on + // demand, so a stale .tsbuildinfo must never short-circuit the emit. + "incremental": false, + "rootDir": "..", + "outDir": "./dist" + }, + "include": [ + "./index.ts" + ], + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/tools/release/versions.spec.ts b/tools/release/versions.spec.ts new file mode 100644 index 00000000000..c4ff3b0afcf --- /dev/null +++ b/tools/release/versions.spec.ts @@ -0,0 +1,195 @@ +import { describe, expect, it } from 'vitest'; + +import { + isVersionLabel, + latestAlphaTag, + latestFinalTag, + parseAlphaTagOrThrow, + parseFinalTagOrThrow, + parseTag, + previousTag, + releaseBase, + releaseBranch, + versionLabel, +} from './versions'; + +const TAGS = [ + 'v2.11.0-alpha', 'v2.11.0', 'v2.11.1', 'v2.11.5', + 'v2.12.0-alpha', 'v2.12.0-alpha.1', 'v2.12.0', 'v2.12.1', 'v2.12.2', 'v2.12.3', + 'v2.13.0-alpha.1', 'v2.13.0', + 'not-a-tag', 'v2.14.0-alpha.1', +]; + +describe('parseTag', () => { + it('reads a final tag', () => { + expect(parseTag('v2.13.1')).toEqual({ major: 2, minor: 13, patch: 1, prerelease: undefined }); + }); + + it('reads a pre-release tag', () => { + expect(parseTag('v2.13.0-alpha.2')).toEqual({ major: 2, minor: 13, patch: 0, prerelease: 'alpha.2' }); + }); + + it.each([ '2.13.0', 'v2.13', 'v2.13.0-', 'release/v2.13', 'v2.13.0 ' ])('rejects %j', (tag) => { + expect(parseTag(tag)).toBeUndefined(); + }); +}); + +describe('versionLabel', () => { + it('is the final version, also for a pre-release tag', () => { + expect(versionLabel('v2.13.0')).toBe('v2.13.0'); + expect(versionLabel('v2.13.1-alpha.3')).toBe('v2.13.1'); + }); + + it('throws on a non-tag', () => { + expect(() => versionLabel('main')).toThrow('Not a release tag: "main"'); + }); +}); + +describe('isVersionLabel', () => { + it.each([ 'v1.4.0', 'v2.13.10' ])('accepts %s', (label) => { + expect(isVersionLabel(label)).toBe(true); + }); + + it.each([ 'pre-release', 'v2.13.0-alpha.1', 'version', 'bug' ])('rejects %s', (label) => { + expect(isVersionLabel(label)).toBe(false); + }); +}); + +describe('previousTag', () => { + it('steps back one patch within the line', () => { + expect(previousTag('v2.12.3', TAGS)).toBe('v2.12.2'); + }); + + it('skips a patch missing from the tag list', () => { + expect(previousTag('v2.11.5', TAGS)).toBe('v2.11.1'); + }); + + it('takes the highest final of an earlier minor for a minor release', () => { + expect(previousTag('v2.13.0', TAGS)).toBe('v2.12.3'); + }); + + it('crosses a major boundary for the first minor of a major', () => { + expect(previousTag('v3.0.0', TAGS)).toBe('v2.13.0'); + }); + + it('resolves an alpha as its final would', () => { + expect(previousTag('v2.13.0-alpha.1', TAGS)).toBe('v2.12.3'); + expect(previousTag('v2.13.1-alpha.1', TAGS)).toBe('v2.13.0'); + }); + + it('never picks a pre-release tag', () => { + expect(previousTag('v2.15.0', TAGS)).toBe('v2.13.0'); + }); + + it('does not depend on the order of the tag list', () => { + expect(previousTag('v2.13.0', [ ...TAGS ].reverse())).toBe('v2.12.3'); + }); + + it('stays within an older line for a hotfix on it', () => { + expect(previousTag('v2.11.6', TAGS)).toBe('v2.11.5'); + }); + + it('never leaves the major for a patch, whichever side the other major is on', () => { + expect(previousTag('v2.12.3', [ 'v1.12.2', 'v2.12.2', 'v3.12.2' ])).toBe('v2.12.2'); + }); + + it('never takes a later major for a minor', () => { + expect(previousTag('v2.13.0', [ 'v2.12.3', 'v3.0.0', 'v3.1.0' ])).toBe('v2.12.3'); + }); + + it('throws when nothing precedes the tag', () => { + expect(() => previousTag('v2.11.0', [ 'v2.11.0' ])).toThrow('No release precedes v2.11.0'); + }); +}); + +describe('parseAlphaTagOrThrow', () => { + it('reads an alpha tag', () => { + expect(parseAlphaTagOrThrow('v2.13.1-alpha.2')).toEqual({ major: 2, minor: 13, patch: 1, prerelease: 'alpha.2' }); + }); + + it.each([ 'v2.13.1', 'v2.13.0-alpha', 'v2.13.0-beta.1', 'v2.13.0-alpha.1.1' ])('rejects %s', (tag) => { + expect(() => parseAlphaTagOrThrow(tag)).toThrow(`Not an alpha tag: "${ tag }"; expected vX.Y.Z-alpha.N`); + }); + + it('rejects a non-tag as a non-tag', () => { + expect(() => parseAlphaTagOrThrow('main')).toThrow('Not a release tag: "main"'); + }); +}); + +describe('parseFinalTagOrThrow', () => { + it('reads a final tag', () => { + expect(parseFinalTagOrThrow('v2.13.1')).toEqual({ major: 2, minor: 13, patch: 1, prerelease: undefined }); + }); + + it('rejects a pre-release tag', () => { + expect(() => parseFinalTagOrThrow('v2.13.0-alpha.1')).toThrow('Not a final tag: "v2.13.0-alpha.1"; expected vX.Y.Z'); + }); + + it('rejects a non-tag as a non-tag', () => { + expect(() => parseFinalTagOrThrow('v2.13')).toThrow('Not a release tag: "v2.13"'); + }); +}); + +describe('releaseBranch', () => { + it('gives every release its own branch', () => { + expect(releaseBranch(parseFinalTagOrThrow('v2.13.0'))).toBe('release/v2.13.0'); + expect(releaseBranch(parseFinalTagOrThrow('v2.13.1'))).toBe('release/v2.13.1'); + }); + + it('infers the branch of an alpha tag, a hotfix alpha included', () => { + expect(releaseBranch(parseAlphaTagOrThrow('v2.13.0-alpha.1'))).toBe('release/v2.13.0'); + expect(releaseBranch(parseAlphaTagOrThrow('v2.13.1-alpha.2'))).toBe('release/v2.13.1'); + expect(releaseBranch(parseAlphaTagOrThrow('v3.0.4-alpha.1'))).toBe('release/v3.0.4'); + }); +}); + +describe('latestFinalTag', () => { + it('is the highest final tag of the line', () => { + expect(latestFinalTag({ major: 2, minor: 12 }, TAGS)).toBe('v2.12.3'); + }); + + it('ignores pre-release tags', () => { + expect(latestFinalTag({ major: 2, minor: 14 }, TAGS)).toBeUndefined(); + }); +}); + +describe('latestAlphaTag', () => { + it('is the highest-numbered alpha of the version', () => { + const tags = [ 'v2.13.0-alpha.1', 'v2.13.0-alpha.10', 'v2.13.0-alpha.2', 'v2.13.1-alpha.11', 'v2.13.0' ]; + + expect(latestAlphaTag(parseFinalTagOrThrow('v2.13.0'), tags)).toBe('v2.13.0-alpha.10'); + }); + + it('ignores an unnumbered pre-release and the alphas of other versions', () => { + expect(latestAlphaTag(parseFinalTagOrThrow('v2.12.0'), TAGS)).toBe('v2.12.0-alpha.1'); + expect(latestAlphaTag(parseFinalTagOrThrow('v2.11.0'), TAGS)).toBeUndefined(); + }); +}); + +describe('releaseBase', () => { + it('cuts a minor from main', () => { + expect(releaseBase(parseFinalTagOrThrow('v2.14.0'), TAGS)).toEqual({ kind: 'main' }); + }); + + it('cuts a patch from the previous release of the line', () => { + expect(releaseBase(parseFinalTagOrThrow('v2.12.4'), TAGS)).toEqual({ kind: 'tag', tag: 'v2.12.3' }); + }); + + it('refuses a patch that skips a release', () => { + expect(() => releaseBase(parseFinalTagOrThrow('v2.12.5'), TAGS)).toThrow( + 'v2.12.5 must follow v2.12.4 as the line\'s latest release; the latest is v2.12.3', + ); + }); + + it('refuses a patch of a release already followed by another', () => { + expect(() => releaseBase(parseFinalTagOrThrow('v2.12.2'), TAGS)).toThrow( + 'v2.12.2 must follow v2.12.1 as the line\'s latest release; the latest is v2.12.3', + ); + }); + + it('refuses a patch of a line that has no release', () => { + expect(() => releaseBase(parseFinalTagOrThrow('v2.14.1'), TAGS)).toThrow( + 'v2.14.1 must follow v2.14.0 as the line\'s latest release; line v2.14 has no release yet', + ); + }); +}); diff --git a/tools/release/versions.ts b/tools/release/versions.ts new file mode 100644 index 00000000000..17d19acc1bb --- /dev/null +++ b/tools/release/versions.ts @@ -0,0 +1,136 @@ +export interface Version { + readonly major: number; + readonly minor: number; + readonly patch: number; + readonly prerelease: string | undefined; +} + +// A release line: the minor every `vX.Y.*` tag belongs to; a line keeps one open pre-release at a time. +export interface Line { + readonly major: number; + readonly minor: number; +} + +const TAG = /^v(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/; +const VERSION_LABEL = /^v\d+\.\d+\.\d+$/; +const ALPHA_TAG = /^(v\d+\.\d+\.\d+)-alpha\.(\d+)$/; + +export function parseTag(tag: string): Version | undefined { + const match = TAG.exec(tag); + if (match === null) { + return undefined; + } + const [ , major, minor, patch, prerelease ] = match; + return { major: Number(major), minor: Number(minor), patch: Number(patch), prerelease }; +} + +export function parseTagOrThrow(tag: string): Version { + const version = parseTag(tag); + if (version === undefined) { + throw new Error(`Not a release tag: "${ tag }"; expected vX.Y.Z or vX.Y.Z-<pre-release>`); + } + return version; +} + +export function parseAlphaTagOrThrow(tag: string): Version { + const version = parseTagOrThrow(tag); + if (!ALPHA_TAG.test(tag)) { + throw new Error(`Not an alpha tag: "${ tag }"; expected vX.Y.Z-alpha.N`); + } + return version; +} + +export function parseFinalTagOrThrow(tag: string): Version { + const version = parseTagOrThrow(tag); + if (version.prerelease !== undefined) { + throw new Error(`Not a final tag: "${ tag }"; expected vX.Y.Z`); + } + return version; +} + +export function formatLine({ major, minor }: Line): string { + return `v${ major }.${ minor }`; +} + +export function isSameLine(a: Line, b: Line): boolean { + return a.major === b.major && a.minor === b.minor; +} + +export function formatVersion({ major, minor, patch }: Version): string { + return `v${ major }.${ minor }.${ patch }`; +} + +// Every release has its own branch, so an alpha of a patch never lands on the branch of the minor. +export function releaseBranch(version: Version): string { + return `release/${ formatVersion(version) }`; +} + +// The label a release stamps on what it shipped is its final version, also when the tag is an alpha of it. +export function versionLabel(tag: string): string { + return formatVersion(parseTagOrThrow(tag)); +} + +export function isVersionLabel(label: string): boolean { + return VERSION_LABEL.test(label); +} + +function compareVersions(a: Version, b: Version): number { + return a.major - b.major || a.minor - b.minor || a.patch - b.patch; +} + +function isEarlierRelease(candidate: Version, current: Version): boolean { + if (current.patch > 0) { + return candidate.major === current.major && candidate.minor === current.minor && candidate.patch < current.patch; + } + return candidate.major < current.major || (candidate.major === current.major && candidate.minor < current.minor); +} + +function finalVersionsLatestFirst(tags: ReadonlyArray<string>): Array<Version> { + return tags + .map(parseTag) + .filter((version): version is Version => version !== undefined && version.prerelease === undefined) + .sort((a, b) => compareVersions(b, a)); +} + +// Read off the tag list rather than release dates, so a hotfix on an older line resolves within that line. +export function previousTag(tag: string, tags: ReadonlyArray<string>): string { + const [ previous ] = finalVersionsLatestFirst(tags).filter((version) => isEarlierRelease(version, parseTagOrThrow(tag))); + + if (previous === undefined) { + throw new Error(`No release precedes ${ tag }`); + } + return formatVersion(previous); +} + +export function latestFinalTag(line: Line, tags: ReadonlyArray<string>): string | undefined { + const [ latest ] = finalVersionsLatestFirst(tags).filter((version) => isSameLine(version, line)); + return latest === undefined ? undefined : formatVersion(latest); +} + +export function latestAlphaTag(version: Version, tags: ReadonlyArray<string>): string | undefined { + const final = formatVersion(version); + const numbers = tags + .map((tag) => ALPHA_TAG.exec(tag)) + .filter((match): match is RegExpExecArray => match !== null && match[1] === final) + .map((match) => Number(match[2])); + return numbers.length === 0 ? undefined : `${ final }-alpha.${ Math.max(...numbers) }`; +} + +export type ReleaseBase = + { readonly kind: 'main' } | + { readonly kind: 'tag'; readonly tag: string }; + +// A minor forks from main; a patch continues from the line's latest release, so the line stays a single +// chain of picks and the previous tag is always an ancestor of the next. +export function releaseBase(version: Version, tags: ReadonlyArray<string>): ReleaseBase { + if (version.patch === 0) { + return { kind: 'main' }; + } + const previous = formatVersion({ ...version, patch: version.patch - 1 }); + const latest = latestFinalTag(version, tags); + if (latest !== previous) { + const actual = latest === undefined ? `line ${ formatLine(version) } has no release yet` : `the latest is ${ latest }`; + throw new Error(`${ formatVersion(version) } must follow ${ previous } as the line's latest release; ${ actual }`); + } + return { kind: 'tag', tag: previous }; +} diff --git a/tools/review-screen/CONTEXT.md b/tools/review-screen/CONTEXT.md new file mode 100644 index 00000000000..b24a2057c42 --- /dev/null +++ b/tools/review-screen/CONTEXT.md @@ -0,0 +1,139 @@ +# Review screen — context + +A pilot, not a gate. Before the agent code review's axes read a change, this tool scores every rubric rule +against every touched file with Jev (TypeSafe's typed-judgment model) and prints the cells over threshold +as *suspects* — a rule id, a file, a line and a probability. When the change has a task spec it also +scores every Functional Requirement against every touched file, and a requirement no file seems to +address becomes a suspect too — a requirement id, the best-scoring file, `—` for the line, and the +probability. It sets no severity and writes no claim: a subagent in `review-changes` opens each suspect +and decides. The task spec behind the pilot: +`.agents/tasks/3720-jev-review-screen/spec.md`. + +## Where to look + +| Question | Answer lives in | +| --- | --- | +| How do I run it? What do the flags do? | `pnpm review:screen --help` | +| What does the model get asked? | `./rubric.ts` — the rules, their globs, questions and counterexamples | +| Where do the thresholds, the cap and the window budget live? | `./config.ts` | +| Where does a run's record go? | `<main checkout>/.ai/jev/`, one JSON per run; `./sidecar.ts` names it | +| How is a change turned into model state? | `./select/hunks.ts` | +| How are the base, the files and the spec resolved? | `./select/change.ts` | +| Where does a standards cell become a suspect? | `./grid/standards.ts` | +| Where does a requirement become a suspect? Where is the cap shared? | `./grid/spec.ts` | +| How are the Functional Requirements read out of a spec? | `./select/spec.ts` | +| After a review: how does a suspect get its fate, a finding its origin? | `./origins/match.ts` (`--origins`) | +| What does `--findings` accept? | `pnpm review:screen --help`; the two readers in `./origins/parse.ts` | +| After the pilot: what is the keep-or-kill table made of? | `./report/aggregate.ts` (`--report`), printed by `./report/render.ts` | +| How is it wired into the review? | `.agents/skills/review-changes/axes.md`, the `jev` axis brief | + +## What an editor here must keep true + +- **A tool failure never fails a review.** No key, an API error, a diff with nothing to score: all exit 0 + with the status and reason in the JSON, and every one of them still writes a sidecar. Only invalid + arguments (a bad `--scope`, a stray argument, flags that do not go together) or a bug in the tool exit + non-zero, and those write no sidecar. The `jev` axis brief relies on this. +- **Explicit inputs are never re-derived.** `--base` and `--spec` are used verbatim, because the review that + passes them has already pinned its base and the two must agree. +- **The sidecar keeps every cell, not only the suspects.** Re-tuning a threshold in `./config.ts` is an + offline read of the sidecars; if cells under threshold were dropped it would take a re-run per diff. +- **The sidecar lives in the main checkout**, resolved through the git common dir. A worktree's own files + vanish with the worktree, and task folders are pruned at land. +- **The API key is the tool's concern only.** The SDK reads it from the environment; no agent instruction + names the variable. Keep it that way — an agent told the variable's name will try to set it. +- **The spec grid's comparison is inverted, and that lives in `./grid/spec.ts` only.** Its question is + phrased so a high value means "this file addresses the requirement", so a suspect is a requirement whose + best score is *below* `SPEC_THRESHOLD`, ranked lowest first. Everything downstream — the JSON, the + sidecar, the `jev` brief — sees suspects and scores and never needs to know which way the threshold + points. Keep it that way when tuning: change the threshold, not the direction. +- **The `spec` block in the output has its own status.** `no-spec` when there is nothing to score; + `skipped` when there is a spec but no client; `failed` when an explicit `--spec` points nowhere, the spec + has no `## Functional requirements` list, or the API failed while scoring it. Only the API failure also + fails the run: a bad spec path still gets the review its standards grid. +- **Line ids are new-side line numbers.** Under `--scope uncommitted` they match the working tree; under + `--scope branch` too, because both diff against the working tree, never a commit. +- **`--origins` matches mechanically, never by reading code.** A finding meets a standards suspect when + it sits in the same file inside the suspect's window — the line span the sidecar records under + `windows`, since by then the diff may be gone — and a spec suspect when its location is the same + `FR<n>`. The `jev` axis's drop list is the only other input; a suspect named by neither is `dropped` + with reason `not reported`. Keep it that way: the subagent that runs it forwards the table and nothing + else, so any judgement added here would be a judgement made without the code in front of it. +- **A finding's rule label is the reviewer's, never derived here.** `--origins` stores the `rule` + column as given, and a `—` or an empty cell is stored as no label; a label guessed from the claim's + wording would make the near-miss and sweep rows measure the guess instead of Jev. +- **The tuning rows score a finding's file by the same max-over-windows cell the threshold sees.** + Switching to the window containing the line would make the near-miss spread explain a decision the + screen never made. +- **A calibration run is not a pilot review.** A past diff screened to tune `./config.ts` is run with + `--calibration`, which sets `calibration: true` in its sidecar; `--report` filters on that + field, so a calibration sidecar in `.ai/jev/` never inflates the pilot's counts. Screen such a diff from + a detached worktree at the commit under review with `--base` its merge-base, and give it a `--ticket` + that names the PR, or the same-day runs overwrite one another. +- **`--report` counts a review only once `--origins` has run on it.** Without fates every suspect in + a sidecar would read as dropped and drag the rule's precision down, so such a sidecar is listed as + *pending origins* and counts nowhere — not in the rule rows, not in the timings. A `skipped` or + `failed` review with an `origins` block counts in the rule rows and the timings: its findings are all + `axis`, its added time is zero, which is the honest number for a review the screen contributed nothing + to. It stays out of the tuning rows, which read only `ok` sidecars: a skipped run has no cells, so + every labelled finding would read as a glob miss, and a failed run keeps a partial grid whose max + would read as a miss where a later window was never scored. +- **`--report` computes nothing a review would need.** It is an offline read of the sidecars, run by + the developer when deciding keep or kill; no review step calls it, and the `jev` brief never + mentions it. +- **`jev` membership comes from `sources`, not from `axis`.** A finding's `axis` is its label + (`standards`, `spec`, …); which sides raised it is the orchestrator's `sources` list. A `jev`-sourced + finding with an axis alongside is `both`, and its suspect is `merged` rather than `confirmed`. + +## Gotchas + +- **Rerunning on the same day, branch and scope overwrites the sidecar.** The name carries no time of day. + A calibration or dry run that should survive the next run needs a different `--ticket` or a copied file; + a detached checkout has no branch name and gets `detached`, so two PRs screened the same day collide + unless `--ticket` tells them apart. + A rerun also drops the sidecar's `origins` block — run `--origins` again if the review's table still + stands. Running `--origins` twice replaces the block; it never appends. +- **A sidecar whose `origins` predates the location field counts in the fate rows and in none of the + tuning rows.** The coverage line reports it as `no location recorded`; re-running `--origins` from the + kept `.findings.md` recovers the location, never the label. +- **A `merged` suspect is not a `confirmed` one in the table.** The rule rows keep the two apart: + `confirmed` is a finding only the `jev` axis raised, `merged` one an axis also found. Both are + hits for the rule's precision; only `confirmed` is unique contribution. +- **A spec finding must carry its `FR<n>` in `location` to match a spec suspect.** The review's table + writes `—` for a finding with no line; a spec suspect has no line either, so the requirement id is the + only handle. Without it the suspect is `not reported` even when the finding came from it. +- **The task folder is excluded from the spec grid** (`SPEC_GRID_EXCLUDE`). A branch that adds its own + `spec.md` and ticket specs would otherwise score every requirement high — the spec *states* each one — + and hide the requirements no code addresses yet. The standards grid still sees those files. +- **A requirement about things outside the diff scores low everywhere.** A requirement that names docs, + a PR description or a later ticket will be a suspect on every run by construction, and so will one + about code the change *removes*, since the state carries new-side lines only. That is expected; the + `jev` axis drops such a suspect with that reason. +- **A `choice` question takes at most 255 options**, so a window never carries more changed lines than + that even when it fits the character budget. A huge single hunk therefore becomes several windows, and + the file's cell is the max across them. +- **The rubric's `EntryType` is the SDK's.** `./rubric.spec.ts` still requires arrays of short strings; an + object-shaped example the SDK would accept fails that spec on purpose. + +## File map + +- `./index.ts` — flags, orchestration, the `skipped | failed | ok` status, the JSON on stdout; flag + mechanics shared with the sibling tools in `../cli/flags.ts` +- `./config.ts` — model pin, thresholds for both grids, the shared suspect cap, window budget, sidecar folder +- `./rubric.ts` — the standards rules +- `./select/change.ts` — scope, base, touched and untracked files, spec path, ticket +- `./select/hunks.ts` — `git diff -U<n>` → hunks → line-id state → windows +- `./select/spec.ts` — the spec's `## Functional requirements` list → `FR<n>` ids and text +- `./grid/shared.ts` — the client surface, the bounded pool, the per-call record both grids write +- `./grid/standards.ts` — `noul` batch per window, `choice` locate per suspect, threshold and cap +- `./grid/spec.ts` — `noul` batch per window over the requirements, max over files, the inverted threshold, + the cap shared with the standards grid +- `./origins/parse.ts` — the findings table and the drop list, from a JSON array or Markdown tables +- `./origins/match.ts` — fate per suspect, origin per finding, the window and requirement matching +- `./report/aggregate.ts` — the pilot table's numbers: per-rule fates, finding origins, added seconds + and tokens per review, the calibration and pending filters +- `./report/tuning.ts` — per rule, the near misses, the threshold sweep and the coverage counts, from the + kept cells and the labelled findings +- `./report/render.ts` — the table as text, and as JSON under `--json` +- `./sidecar.ts` — file naming, the record shape, reading one back; the main-checkout resolution it + uses is shared with the sibling tools in `../cli/checkout.ts` +- `./run.sh`, `./tsconfig.json` — compile-on-run wrapper; the compiled output is git-ignored diff --git a/tools/review-screen/config.ts b/tools/review-screen/config.ts new file mode 100644 index 00000000000..96cbb2f7377 --- /dev/null +++ b/tools/review-screen/config.ts @@ -0,0 +1,37 @@ +// The model is pinned so every sidecar in a pilot is comparable; the response's own `model` field is +// what the sidecar records. +export const MODEL = 'jev-1.13.0'; + +export const DEFAULT_STANDARDS_THRESHOLD = 0.7; +export const STANDARDS_THRESHOLD_OVERRIDES: Readonly<Record<string, number>> = { + // Real breaches of this rule score in the low 0.6s, where the other rules only produce noise. + 'inline-empty-default': 0.6, + // Over the pilot's first 16 reviews the standards axis raised six comment findings; Jev scored those + // files 0.40–0.82, and the only two cells above 0.5 without a finding were tests. + 'explanatory-comment': 0.5, +}; +export const SWEEP_THRESHOLDS: ReadonlyArray<number> = [ 0.4, 0.5, 0.6, 0.7 ]; +// The spec grid asks "does this file address the requirement", so a requirement is a suspect when +// its best score stays *below* this. +export const SPEC_THRESHOLD = 0.7; +// The task folder describes the requirements rather than implementing them, so its files would score +// every requirement high and hide the real gaps; the spec grid never sees them. +export const SPEC_GRID_EXCLUDE = '.agents/tasks/**'; +// One cap for both grids, split evenly when both overflow. +export const MAX_SUSPECTS = 12; + +export const DEFAULT_BASE_BRANCH = 'main'; + +// Lines of unchanged code kept around each hunk (`git diff -U<n>`). +export const CONTEXT_LINES = 3; + +// The SDK exposes no token counter, so the window budget is in characters: ~100k chars ≈ 25k tokens, +// under the model's 32k limit for state plus the longest question. +export const MAX_STATE_CHARS = 100_000; + +// A `choice` question takes at most 255 options, and the locate call offers one per changed line. +export const MAX_CHANGED_LINES_PER_WINDOW = 255; + +export const CONCURRENT_REQUESTS = 4; + +export const SIDECAR_DIR = '.ai/jev'; diff --git a/tools/review-screen/grid/shared.ts b/tools/review-screen/grid/shared.ts new file mode 100644 index 00000000000..36b8e563ffe --- /dev/null +++ b/tools/review-screen/grid/shared.ts @@ -0,0 +1,69 @@ +import type { Questions, SystemOneResult, TypeSafeClient, Usage } from '@typesafe-ai/sdk'; +import { TypeSafeError } from '@typesafe-ai/sdk'; + +import type { Window } from '../select/hunks'; + +export type ScreenClient = Pick<TypeSafeClient, 'systemOne'>; + +export interface CallRecord { + readonly kind: 'noul' | 'choice'; + readonly file: string; + readonly window: number; + readonly ms: number; + readonly usage: Usage; +} + +// A bounded worker pool. Once one task fails nothing new starts, but the tasks already in flight +// finish and record their cells; the first failure is what the caller reports. +export async function runPool(tasks: ReadonlyArray<() => Promise<void>>, concurrency: number): Promise<TypeSafeError | undefined> { + let next = 0; + let failure: TypeSafeError | undefined; + async function worker(): Promise<void> { + while (next < tasks.length && failure === undefined) { + const task = tasks[next]; + next += 1; + try { + await task(); + } catch (error) { + if (!(error instanceof TypeSafeError)) throw error; + failure ??= error; + } + } + } + await Promise.all(Array.from({ length: Math.max(1, concurrency) }, worker)); + return failure; +} + +// Cells arrive in completion order; sorting on code-point order is enough to make a rerun rank the +// same way, and the shared collator in src/ sits outside this tool's tsconfig rootDir. +export function compareText(a: string, b: string): number { + if (a === b) return 0; + return a < b ? -1 : 1; +} + +export function describeFailure(failure: TypeSafeError | undefined): string | undefined { + return failure === undefined ? undefined : `${ failure.name }: ${ failure.message }`; +} + +export function stateOf(file: string, window: Window): { readonly file: string; readonly changes: string } { + return { file, changes: window.state }; +} + +export class Recorder<TCell> { + readonly cells: Array<TCell> = []; + readonly calls: Array<CallRecord> = []; + model: string | undefined = undefined; + + async timed<TQuestions extends Questions>( + kind: CallRecord['kind'], + file: string, + window: number, + call: () => Promise<SystemOneResult<TQuestions>>, + ): Promise<SystemOneResult<TQuestions>> { + const started = performance.now(); + const result = await call(); + this.calls.push({ kind, file, window, ms: Math.round(performance.now() - started), usage: result.usage }); + this.model ??= result.model; + return result; + } +} diff --git a/tools/review-screen/grid/spec.spec.ts b/tools/review-screen/grid/spec.spec.ts new file mode 100644 index 00000000000..a7c7fd0ce83 --- /dev/null +++ b/tools/review-screen/grid/spec.spec.ts @@ -0,0 +1,216 @@ +import { TypeSafeClient } from '@typesafe-ai/sdk'; + +import { describe, expect, it } from 'vitest'; + +import type { FileWindows, Window } from '../select/hunks'; +import type { Requirement } from '../select/spec'; +import type { SpecConfig } from './spec'; +import { bestByRequirement, NO_LINE, screenSpec, selectSpecSuspects, shareCap, specGridFiles, splitCap } from './spec'; + +// As in standards.spec.ts, the SDK runs for real down to `fetch`; the fake scores a requirement by +// its id and the changes text so one file can cover a requirement better than another. + +interface RequestBody { + readonly model: string; + readonly state: { readonly file: string; readonly changes: string }; + readonly questions: Record<string, { readonly type: 'noul'; readonly instructions: string; readonly criteria: Record<string, unknown> }>; +} + +const USAGE = { input_tokens: 300, output_tokens: 20 }; +const REPORTED_MODEL = 'jev-1.13.0-fake'; + +type Score = (requirement: string, file: string, changes: string) => number; + +type Fail = (body: RequestBody) => Response | undefined; + +function fakeClient(score: Score = () => 0, fail: Fail = () => undefined): { readonly client: TypeSafeClient; readonly requests: Array<RequestBody> } { + const requests: Array<RequestBody> = []; + const client = new TypeSafeClient({ + apiKey: 'test', + logLevel: 'off', + retry: { maxRetries: 0 }, + fetch: async(_url, init) => { + const body = JSON.parse(String(init?.body)) as RequestBody; + requests.push(body); + const failure = fail(body); + if (failure !== undefined) return failure; + const answers = Object.fromEntries(Object.keys(body.questions).map((name) => [ + name, + { type: 'noul', noul: score(name, body.state.file, body.state.changes) }, + ])); + return Response.json({ model: REPORTED_MODEL, answers, usage: USAGE }); + }, + }); + return { client, requests }; +} + +function requirement(n: number): Requirement { + return { id: `FR${ n }`, text: `Requirement number ${ n }.` }; +} + +function window(index: number, state: string = `window ${ index }`): Window { + return { index, state, changedIds: [ 'L1' ], firstLine: 1, lastLine: 1 }; +} + +function target(file: string, ...windows: Array<Window>): FileWindows { + return { file, windows }; +} + +const CONFIG: SpecConfig = { model: 'jev-1.13.0', threshold: 0.3, maxSuspects: 10, concurrency: 2 }; +const REQUIREMENTS = [ requirement(1), requirement(2), requirement(3) ]; + +describe('specGridFiles', () => { + it('drops the files under the excluded glob and keeps the rest', () => { + const files = [ + target('.agents/tasks/1-x/spec.md', window(0)), + target('.agents/tasks/1-x/tickets/01-a/spec.md', window(0)), + target('src/a.ts', window(0)), + ]; + expect(specGridFiles(files, '.agents/tasks/**').map((file) => file.file)).toEqual([ 'src/a.ts' ]); + }); +}); + +describe('bestByRequirement', () => { + it('keeps the highest-scoring cell per requirement, the first in grid order on a tie whatever order they arrived in', () => { + const cells = [ + { requirement: 'FR2', file: 'a', window: 1, score: 0.5 }, + { requirement: 'FR1', file: 'c', window: 0, score: 0.9 }, + { requirement: 'FR1', file: 'b', window: 0, score: 0.9 }, + { requirement: 'FR1', file: 'a', window: 0, score: 0.2 }, + ]; + expect(bestByRequirement(cells)).toEqual([ cells[2], cells[0] ]); + }); + + it('breaks a tie within one file on the lowest window', () => { + const cells = [ + { requirement: 'FR1', file: 'a', window: 2, score: 0.5 }, + { requirement: 'FR1', file: 'a', window: 0, score: 0.5 }, + { requirement: 'FR1', file: 'a', window: 1, score: 0.5 }, + ]; + expect(bestByRequirement(cells)).toEqual([ cells[1] ]); + }); +}); + +describe('selectSpecSuspects', () => { + it('takes the requirements under the threshold, least covered first, capped with a cut count', () => { + const best = [ + { requirement: 'FR1', file: 'a', window: 0, score: 0.25 }, + { requirement: 'FR2', file: 'b', window: 0, score: 0.9 }, + { requirement: 'FR3', file: 'c', window: 0, score: 0.05 }, + { requirement: 'FR4', file: 'd', window: 0, score: 0.3 }, + { requirement: 'FR5', file: 'e', window: 0, score: 0.1 }, + ]; + expect(selectSpecSuspects(best, 0.3, 2)).toEqual({ + suspects: [ + { requirement: 'FR3', file: 'c', line: NO_LINE, score: 0.05 }, + { requirement: 'FR5', file: 'e', line: NO_LINE, score: 0.1 }, + ], + cut: 1, + }); + }); +}); + +describe('splitCap', () => { + it('keeps both whole while they fit together', () => { + expect(splitCap(5, 7, 12)).toEqual({ standards: 5, spec: 7 }); + expect(splitCap(2, 3, 12)).toEqual({ standards: 2, spec: 3 }); + }); + + it('gives a grid within its half the room the other does not need', () => { + expect(splitCap(2, 20, 12)).toEqual({ standards: 2, spec: 10 }); + expect(splitCap(20, 4, 12)).toEqual({ standards: 8, spec: 4 }); + }); + + it('splits evenly when both overflow, the standards grid taking the odd slot', () => { + expect(splitCap(20, 20, 12)).toEqual({ standards: 6, spec: 6 }); + expect(splitCap(20, 20, 11)).toEqual({ standards: 6, spec: 5 }); + }); +}); + +describe('shareCap', () => { + it('trims two ranked lists to the split and counts the cut from each grid total', () => { + const standards = { suspects: [ 's1', 's2', 's3', 's4' ], cut: 4 }; + const spec = { suspects: [ 'r1', 'r2', 'r3', 'r4' ], cut: 0 }; + expect(shareCap(standards, spec, 4)).toEqual({ + standards: { suspects: [ 's1', 's2' ], cut: 6 }, + spec: { suspects: [ 'r1', 'r2' ], cut: 2 }, + }); + }); + + it('counts a cut the grid already made into that grid\'s total', () => { + const standards = { suspects: [ 's1' ], cut: 0 }; + const spec = { suspects: [ 'r1', 'r2', 'r3', 'r4' ], cut: 2 }; + expect(shareCap(standards, spec, 4)).toEqual({ + standards: { suspects: [ 's1' ], cut: 0 }, + spec: { suspects: [ 'r1', 'r2', 'r3' ], cut: 3 }, + }); + }); + + it('changes nothing while the two fit', () => { + const standards = { suspects: [ 's1' ], cut: 0 }; + const spec = { suspects: [ 'r1', 'r2' ], cut: 0 }; + expect(shareCap(standards, spec, 4)).toEqual({ standards, spec }); + }); +}); + +describe('screenSpec', () => { + it('asks every requirement of every file window in one request each, phrased so high means addressed', async() => { + const { client, requests } = fakeClient(); + const files = [ target('src/a.ts', window(0), window(1)), target('docs/b.md', window(0)) ]; + + const result = await screenSpec(files, REQUIREMENTS, client, CONFIG); + + expect(requests).toHaveLength(3); + expect(requests.map((request) => request.model)).toEqual([ 'jev-1.13.0', 'jev-1.13.0', 'jev-1.13.0' ]); + expect(requests.map((request) => request.state.file).sort()).toEqual([ 'docs/b.md', 'src/a.ts', 'src/a.ts' ]); + expect(Object.keys(requests[0].questions)).toEqual([ 'FR1', 'FR2', 'FR3' ]); + expect(requests[0].questions.FR2.instructions).toBe('Do the changes in this file implement or contribute to the requirement: Requirement number 2.'); + expect(result.cells).toHaveLength(9); + expect(result.model).toBe(REPORTED_MODEL); + expect(result.calls.map((call) => call.kind)).toEqual([ 'noul', 'noul', 'noul' ]); + expect(result.failure).toBeUndefined(); + }); + + it('scores a requirement by its max over files and windows and names the best file on a suspect', async() => { + const { client } = fakeClient((id, file, changes) => { + if (id === 'FR1') return file === 'src/b.ts' ? 0.8 : 0.1; + if (id === 'FR2') return changes === 'window 1' ? 0.2 : 0.05; + return 0.9; + }); + const files = [ target('src/a.ts', window(0), window(1)), target('src/b.ts', window(0)) ]; + + const result = await screenSpec(files, REQUIREMENTS, client, CONFIG); + + expect(result.suspects).toEqual([ { requirement: 'FR2', file: 'src/a.ts', line: NO_LINE, score: 0.2 } ]); + expect(result.cells).toEqual(expect.arrayContaining([ + { requirement: 'FR1', file: 'src/a.ts', window: 0, score: 0.1 }, + { requirement: 'FR1', file: 'src/b.ts', window: 0, score: 0.8 }, + { requirement: 'FR2', file: 'src/a.ts', window: 1, score: 0.2 }, + ])); + }); + + it('ranks suspects lowest score first and caps them', async() => { + const scores: Record<string, number> = { FR1: 0.2, FR2: 0.01, FR3: 0.1 }; + const { client } = fakeClient((id) => scores[id]); + const result = await screenSpec([ target('src/a.ts', window(0)) ], REQUIREMENTS, client, { ...CONFIG, maxSuspects: 2 }); + expect(result.suspects.map((suspect) => suspect.requirement)).toEqual([ 'FR2', 'FR3' ]); + expect(result.cut).toBe(1); + }); + + it('sends nothing without requirements or without files', async() => { + const { client, requests } = fakeClient(); + const expected = { cells: [], suspects: [], cut: 0, calls: [], model: undefined, failure: undefined }; + expect(await screenSpec([ target('src/a.ts', window(0)) ], [], client, CONFIG)).toEqual(expected); + expect(await screenSpec([], REQUIREMENTS, client, CONFIG)).toEqual(expected); + expect(requests).toEqual([]); + }); + + it('reports an API error as the failure, keeps the cells scored before it and names no suspects', async() => { + const { client } = fakeClient(() => 0.01, (body) => (body.state.file === 'src/b.ts' ? Response.json({ error: 'boom' }, { status: 500 }) : undefined)); + const files = [ target('src/a.ts', window(0)), target('src/b.ts', window(0)) ]; + const result = await screenSpec(files, REQUIREMENTS, client, { ...CONFIG, concurrency: 1 }); + expect(result.failure).toMatch(/^InternalServerError: /); + expect(result.cells.map((cell) => cell.file)).toEqual([ 'src/a.ts', 'src/a.ts', 'src/a.ts' ]); + expect(result.suspects).toEqual([]); + }); +}); diff --git a/tools/review-screen/grid/spec.ts b/tools/review-screen/grid/spec.ts new file mode 100644 index 00000000000..9533dccd3c7 --- /dev/null +++ b/tools/review-screen/grid/spec.ts @@ -0,0 +1,158 @@ +import { matchesGlob } from 'path'; + +import { noul } from '@typesafe-ai/sdk'; + +import type { FileWindows, Window } from '../select/hunks'; +import type { Requirement } from '../select/spec'; +import type { CallRecord, ScreenClient } from './shared'; +import { compareText, describeFailure, Recorder, runPool, stateOf } from './shared'; + +// The spec grid: every Functional Requirement × every touched file. One request per window carries +// every requirement as a named `noul` question phrased so that a high value means "addressed"; a +// requirement's score is its max over files and windows, and it is a suspect when that max stays +// *below* the threshold — the inverse of the standards grid. That asymmetry lives here only: the +// output and the renderer see suspects and scores, never the direction of the comparison. + +export interface SpecConfig { + readonly model: string; + readonly threshold: number; + readonly maxSuspects: number; + readonly concurrency: number; +} + +export interface SpecCell { + readonly requirement: string; + readonly file: string; + readonly window: number; + readonly score: number; +} + +export const NO_LINE = '—' as const; + +export interface SpecSuspect { + readonly requirement: string; + readonly file: string; + readonly line: typeof NO_LINE; + readonly score: number; +} + +export interface SpecResult { + readonly cells: ReadonlyArray<SpecCell>; + readonly suspects: ReadonlyArray<SpecSuspect>; + readonly cut: number; + readonly calls: ReadonlyArray<CallRecord>; + readonly model: string | undefined; + readonly failure: string | undefined; +} + +export function specGridFiles(files: ReadonlyArray<FileWindows>, excludeGlob: string): Array<FileWindows> { + return files.filter((target) => !matchesGlob(target.file, excludeGlob)); +} + +export function requirementQuestion(requirement: Requirement): string { + return `Do the changes in this file implement or contribute to the requirement: ${ requirement.text }`; +} + +const CRITERIA = { + 'true': 'the changed lines add, wire or test something the requirement asks for', + 'false': 'the changed lines are unrelated to the requirement, or only touch it in passing', +}; + +// Per requirement, the best cell over every file and window; ties keep grid order so a rerun ranks +// the same way. +export function bestByRequirement(cells: ReadonlyArray<SpecCell>): Array<SpecCell> { + const best = new Map<string, SpecCell>(); + const ordered = [ ...cells ].sort((a, b) => compareText(a.requirement, b.requirement) || compareText(a.file, b.file) || a.window - b.window); + for (const cell of ordered) { + const current = best.get(cell.requirement); + if (current === undefined || cell.score > current.score) best.set(cell.requirement, cell); + } + return [ ...best.values() ]; +} + +// Lowest score first: the least-covered requirement is the most suspect. +export function selectSpecSuspects( + best: ReadonlyArray<SpecCell>, + threshold: number, + maxSuspects: number, +): { readonly suspects: Array<SpecSuspect>; readonly cut: number } { + const ranked = best + .filter((cell) => cell.score < threshold) + .sort((a, b) => a.score - b.score) + .map((cell): SpecSuspect => ({ requirement: cell.requirement, file: cell.file, line: NO_LINE, score: cell.score })); + return { suspects: ranked.slice(0, maxSuspects), cut: Math.max(0, ranked.length - maxSuspects) }; +} + +// One cap for both grids. Each grid keeps everything while the two fit together; when they do not, +// a grid that stays within its half yields the rest to the other, and two overflowing grids split +// the cap evenly (the standards grid takes the odd slot). +export function splitCap(standardsTotal: number, specTotal: number, maxSuspects: number): { readonly standards: number; readonly spec: number } { + // Stryker disable next-line EqualityOperator: when the two totals add up to the cap exactly, the branches below return the same split + if (standardsTotal + specTotal <= maxSuspects) return { standards: standardsTotal, spec: specTotal }; + const standardsHalf = Math.ceil(maxSuspects / 2); + const specHalf = maxSuspects - standardsHalf; + // Stryker disable next-line EqualityOperator: a grid sitting exactly on its half gets that half either way + if (standardsTotal <= standardsHalf) return { standards: standardsTotal, spec: maxSuspects - standardsTotal }; + // Stryker disable next-line EqualityOperator: a grid sitting exactly on its half gets that half either way + if (specTotal <= specHalf) return { standards: maxSuspects - specTotal, spec: specTotal }; + return { standards: standardsHalf, spec: specHalf }; +} + +interface Capped<T> { + readonly suspects: ReadonlyArray<T>; + readonly cut: number; +} + +// Applies `splitCap` to two already-ranked, individually-capped lists; `cut` counts from the +// grid's own total, so a suspect dropped here is reported the same way as one dropped by the grid. +export function shareCap<TStandards, TSpec>( + standards: Capped<TStandards>, + spec: Capped<TSpec>, + maxSuspects: number, +): { readonly standards: Capped<TStandards>; readonly spec: Capped<TSpec> } { + const standardsTotal = standards.suspects.length + standards.cut; + const specTotal = spec.suspects.length + spec.cut; + const cap = splitCap(standardsTotal, specTotal, maxSuspects); + return { + standards: { suspects: standards.suspects.slice(0, cap.standards), cut: standardsTotal - Math.min(cap.standards, standards.suspects.length) }, + spec: { suspects: spec.suspects.slice(0, cap.spec), cut: specTotal - Math.min(cap.spec, spec.suspects.length) }, + }; +} + +function scoreWindowTask( + target: FileWindows, + window: Window, + requirements: ReadonlyArray<Requirement>, + client: ScreenClient, + config: SpecConfig, + recorder: Recorder<SpecCell>, +): () => Promise<void> { + return async() => { + const questions = Object.fromEntries(requirements.map((requirement) => [ requirement.id, noul(requirementQuestion(requirement), CRITERIA) ])); + const result = await recorder.timed('noul', target.file, window.index, () => client.systemOne({ + state: stateOf(target.file, window), + questions, + model: config.model, + })); + for (const requirement of requirements) { + recorder.cells.push({ requirement: requirement.id, file: target.file, window: window.index, score: result.answers[requirement.id].noul }); + } + }; +} + +export async function screenSpec( + files: ReadonlyArray<FileWindows>, + requirements: ReadonlyArray<Requirement>, + client: ScreenClient, + config: SpecConfig, +): Promise<SpecResult> { + const recorder = new Recorder<SpecCell>(); + const tasks = requirements.length === 0 ? + [] : + files.flatMap((target) => target.windows.map((window) => scoreWindowTask(target, window, requirements, client, config, recorder))); + const failure = await runPool(tasks, config.concurrency); + const { suspects, cut } = failure === undefined ? + selectSpecSuspects(bestByRequirement(recorder.cells), config.threshold, config.maxSuspects) : + { suspects: [], cut: 0 }; + return { cells: recorder.cells, suspects, cut, calls: recorder.calls, model: recorder.model, failure: describeFailure(failure) }; +} diff --git a/tools/review-screen/grid/standards.spec.ts b/tools/review-screen/grid/standards.spec.ts new file mode 100644 index 00000000000..568f33a2d97 --- /dev/null +++ b/tools/review-screen/grid/standards.spec.ts @@ -0,0 +1,270 @@ +import { TypeSafeClient } from '@typesafe-ai/sdk'; + +import { describe, expect, it } from 'vitest'; + +import type { Rule } from '../rubric'; +import type { FileWindows, Window } from '../select/hunks'; +import type { StandardsConfig } from './standards'; +import { inGridOrder, rulesFor, screenStandards, selectSuspects, thresholdFor } from './standards'; + +// The SDK is exercised for real down to `fetch`, which is the system boundary: the fake answers a +// request body the way the API would, and records every body it saw. + +interface RequestBody { + readonly model: string; + readonly state: { readonly file: string; readonly changes: string }; + readonly questions: Record<string, { readonly type: 'noul' | 'choice'; readonly criteria: Record<string, unknown> }>; +} + +// How the fake scores a `noul` cell: by rule id and by the changes text, so a spec can make one +// window score higher than another. A `choice` question picks the given line id. +interface FakeApi { + readonly score: (rule: string, changes: string) => number; + readonly pick: (options: ReadonlyArray<string>) => string; + readonly fail: (body: RequestBody) => Response | Error | undefined; +} + +const USAGE = { input_tokens: 300, output_tokens: 20 }; +const REPORTED_MODEL = 'jev-1.13.0-fake'; + +function respond(body: RequestBody, api: FakeApi): Response { + const answers = Object.fromEntries(Object.entries(body.questions).map(([ name, question ]) => { + if (question.type === 'noul') return [ name, { type: 'noul', noul: api.score(name, body.state.changes) } ]; + const options = Object.keys(question.criteria); + const choice = api.pick(options); + const probabilities = Object.fromEntries(options.map((option) => [ option, option === choice ? 1 : 0 ])); + return [ name, { type: 'choice', choice, confidence: 1, probabilities } ]; + })); + return Response.json({ model: REPORTED_MODEL, answers, usage: USAGE }); +} + +function fakeClient(api: Partial<FakeApi>): { readonly client: TypeSafeClient; readonly requests: Array<RequestBody> } { + const requests: Array<RequestBody> = []; + const full: FakeApi = { score: () => 0, pick: (options) => options[0], fail: () => undefined, ...api }; + const client = new TypeSafeClient({ + apiKey: 'test', + logLevel: 'off', + retry: { maxRetries: 0 }, + fetch: async(_url, init) => { + const body = JSON.parse(String(init?.body)) as RequestBody; + requests.push(body); + const failure = full.fail(body); + if (failure instanceof Error) throw failure; + return failure ?? respond(body, full); + }, + }); + return { client, requests }; +} + +function rule(id: string, glob: string = '**/*.ts'): Rule { + return { id, cites: '.agents/rules/code-quality.md', glob, question: `Does ${ id } hold?`, examples: [ `${ id } yes` ], not_for: [ `${ id } no` ] }; +} + +function window(index: number, changedIds: ReadonlyArray<string>, state: string = `window ${ index }`): Window { + return { index, state, changedIds, firstLine: 10 * (index + 1), lastLine: 10 * (index + 1) + 9 }; +} + +function target(file: string, ...windows: Array<Window>): FileWindows { + return { file, windows }; +} + +const CONFIG: StandardsConfig = { model: 'jev-1.13.0', defaultThreshold: 0.7, thresholdOverrides: {}, maxSuspects: 10, concurrency: 2 }; + +const RULES = [ rule('alpha'), rule('beta'), rule('gamma-tsx', '**/*.tsx') ]; + +describe('rulesFor', () => { + it('keeps the rules whose glob matches the repo-relative path', () => { + expect(rulesFor('src/a.ts', RULES).map((r) => r.id)).toEqual([ 'alpha', 'beta' ]); + expect(rulesFor('src/a.tsx', RULES).map((r) => r.id)).toEqual([ 'gamma-tsx' ]); + expect(rulesFor('README.md', RULES)).toEqual([]); + }); +}); + +describe('inGridOrder', () => { + it('sorts by file, then window, then rule', () => { + const cells = [ + { rule: 'beta', file: 'src/b.ts', window: 0, score: 1 }, + { rule: 'beta', file: 'src/a.ts', window: 1, score: 1 }, + { rule: 'alpha', file: 'src/a.ts', window: 1, score: 1 }, + { rule: 'gamma', file: 'src/a.ts', window: 0, score: 1 }, + ]; + expect(inGridOrder(cells)).toEqual([ cells[3], cells[2], cells[1], cells[0] ]); + }); +}); + +describe('thresholdFor', () => { + it('prefers a per-rule override over the default', () => { + const config = { ...CONFIG, thresholdOverrides: { alpha: 0.9 } }; + expect(thresholdFor('alpha', config)).toBe(0.9); + expect(thresholdFor('beta', config)).toBe(0.7); + }); +}); + +describe('selectSuspects', () => { + it('ranks by score, caps the list and counts what was cut', () => { + const candidates = [ + { rule: 'a', file: 'f', line: 1, score: 0.71, window: 0 }, + { rule: 'b', file: 'f', line: 2, score: 0.99, window: 0 }, + { rule: 'c', file: 'f', line: 3, score: 0.8, window: 0 }, + ]; + expect(selectSuspects(candidates, 2)).toEqual({ + suspects: [ candidates[1], candidates[2] ], + cut: 1, + }); + expect(selectSuspects(candidates, 5).cut).toBe(0); + }); +}); + +describe('screenStandards', () => { + it('sends one request per window carrying every matching rule as a noul question on the pinned model', async() => { + const { client, requests } = fakeClient({}); + const files = [ target('src/a.ts', window(0, [ 'L1' ]), window(1, [ 'L2' ])), target('src/b.tsx', window(0, [ 'L1' ])) ]; + + const result = await screenStandards(files, RULES, client, CONFIG); + + expect(requests).toHaveLength(3); + expect(requests.map((request) => request.model)).toEqual([ 'jev-1.13.0', 'jev-1.13.0', 'jev-1.13.0' ]); + const forA = requests.filter((request) => request.state.file === 'src/a.ts'); + expect(forA.map((request) => request.state.changes).sort()).toEqual([ 'window 0', 'window 1' ]); + expect(Object.keys(forA[0].questions)).toEqual([ 'alpha', 'beta' ]); + expect(forA[0].questions.alpha).toMatchObject({ type: 'noul', criteria: { 'true': [ 'alpha yes' ], 'false': [ 'alpha no' ] } }); + expect(result.cells).toHaveLength(5); + expect(result.suspects).toEqual([]); + expect(result.model).toBe(REPORTED_MODEL); + expect(result.failure).toBeUndefined(); + }); + + it('skips a file no rule matches without a request', async() => { + const { client, requests } = fakeClient({}); + const result = await screenStandards([ target('docs/x.md', window(0, [ 'L1' ])) ], RULES, client, CONFIG); + expect(requests).toEqual([]); + expect(result).toEqual({ cells: [], suspects: [], cut: 0, calls: [], model: undefined, failure: undefined }); + }); + + it('takes the max across windows and locates the line in the winning window with one choice call', async() => { + const { client, requests } = fakeClient({ + score: (ruleId, changes) => (ruleId === 'alpha' && changes === 'window 1' ? 0.95 : 0.2), + pick: () => 'L21', + }); + const files = [ target('src/a.ts', window(0, [ 'L1', 'L2' ]), window(1, [ 'L20', 'L21', 'L22' ])) ]; + + const result = await screenStandards(files, RULES, client, CONFIG); + + expect(result.suspects).toEqual([ { rule: 'alpha', file: 'src/a.ts', line: 21, score: 0.95, window: 1 } ]); + const locate = requests.filter((request) => request.questions.line?.type === 'choice'); + expect(locate).toHaveLength(1); + expect(locate[0].state.changes).toBe('window 1'); + expect(Object.keys(locate[0].questions.line.criteria)).toEqual([ 'L20', 'L21', 'L22' ]); + expect(result.cells).toEqual(expect.arrayContaining([ + { rule: 'alpha', file: 'src/a.ts', window: 0, score: 0.2 }, + { rule: 'alpha', file: 'src/a.ts', window: 1, score: 0.95 }, + ])); + }); + + it('keeps the first window in grid order when a later one ties or scores lower', async() => { + const { client, requests } = fakeClient({ + score: (ruleId, changes) => { + if (ruleId === 'alpha') return changes === 'window 2' ? 0.8 : 0.9; + return changes === 'window 0' ? 0.85 : 0.95; + }, + }); + const files = [ target('src/a.ts', window(0, [ 'L1' ]), window(1, [ 'L11' ]), window(2, [ 'L21' ])) ]; + + const result = await screenStandards(files, RULES, client, { ...CONFIG, concurrency: 1 }); + + expect(result.suspects).toEqual([ + { rule: 'beta', file: 'src/a.ts', line: 11, score: 0.95, window: 1 }, + { rule: 'alpha', file: 'src/a.ts', line: 1, score: 0.9, window: 0 }, + ]); + const locate = requests.filter((request) => request.questions.line?.type === 'choice'); + expect(locate.map((request) => request.state.changes)).toEqual([ 'window 0', 'window 1' ]); + }); + + it('applies a per-rule threshold override', async() => { + const { client } = fakeClient({ score: () => 0.75 }); + const config = { ...CONFIG, thresholdOverrides: { alpha: 0.8 } }; + const result = await screenStandards([ target('src/a.ts', window(0, [ 'L1' ])) ], RULES, client, config); + expect(result.suspects.map((suspect) => suspect.rule)).toEqual([ 'beta' ]); + }); + + it('takes a cell sitting exactly on its threshold as a suspect', async() => { + const { client } = fakeClient({ score: (ruleId) => (ruleId === 'alpha' ? 0.8 : 0.7) }); + const config = { ...CONFIG, thresholdOverrides: { alpha: 0.8 } }; + const result = await screenStandards([ target('src/a.ts', window(0, [ 'L1' ])) ], RULES, client, config); + expect(result.suspects.map((suspect) => suspect.rule)).toEqual([ 'alpha', 'beta' ]); + }); + + it('falls back to the window start when a suspect window has no changed line, and when the model names an id outside the window', async() => { + const { client, requests } = fakeClient({ score: () => 0.9, pick: (options) => (options.includes('L1') ? 'nonsense' : 'L999') }); + const files = [ target('src/a.ts', window(0, [])), target('src/b.ts', window(0, [ 'L1' ])), target('src/c.ts', window(0, [ 'L5' ])) ]; + const result = await screenStandards(files, [ rule('alpha') ], client, CONFIG); + expect(result.suspects).toEqual(expect.arrayContaining([ + { rule: 'alpha', file: 'src/a.ts', line: 10, score: 0.9, window: 0 }, + { rule: 'alpha', file: 'src/b.ts', line: 10, score: 0.9, window: 0 }, + { rule: 'alpha', file: 'src/c.ts', line: 10, score: 0.9, window: 0 }, + ])); + expect(requests.filter((request) => request.questions.line?.type === 'choice')).toHaveLength(2); + }); + + it('ranks tied scores in grid order, not in the order the files were listed or finished', async() => { + const { client } = fakeClient({ score: () => 0.9 }); + const files = [ target('src/b.ts', window(0, [ 'L10' ], 'b first')), target('src/a.ts', window(0, [ 'L20' ], 'a second')) ]; + const result = await screenStandards(files, [ rule('beta'), rule('alpha') ], client, { ...CONFIG, maxSuspects: 2 }); + expect(result.suspects.map((suspect) => `${ suspect.file } ${ suspect.rule }`)).toEqual([ 'src/a.ts alpha', 'src/a.ts beta' ]); + expect(result.cut).toBe(2); + }); + + it('names no suspects when a locate call fails, even the ones located before it, keeping the cells', async() => { + const { client, requests } = fakeClient({ + score: () => 0.9, + fail: (body) => { + const isSecondLocate = body.questions.line?.type === 'choice' && body.state.file === 'src/b.ts'; + return isSecondLocate ? Response.json({ error: 'boom' }, { status: 500 }) : undefined; + }, + }); + const files = [ target('src/a.ts', window(0, [ 'L1' ])), target('src/b.ts', window(0, [ 'L1' ])) ]; + const result = await screenStandards(files, [ rule('alpha') ], client, { ...CONFIG, concurrency: 1 }); + expect(result.failure).toMatch(/^InternalServerError: /); + expect(result.cells).toHaveLength(2); + expect(requests.filter((request) => request.questions.line?.type === 'choice')).toHaveLength(2); + expect(result.suspects).toEqual([]); + expect(result.cut).toBe(0); + }); + + it('caps the suspects at maxSuspects, highest score first, and reports the cut', async() => { + const scores: Record<string, number> = { alpha: 0.8, beta: 0.99 }; + const { client } = fakeClient({ score: (ruleId) => scores[ruleId] }); + const result = await screenStandards([ target('src/a.ts', window(0, [ 'L1' ])) ], RULES, client, { ...CONFIG, maxSuspects: 1 }); + expect(result.suspects.map((suspect) => suspect.rule)).toEqual([ 'beta' ]); + expect(result.cut).toBe(1); + }); + + it('records a timing, the usage and the model per call', async() => { + const { client } = fakeClient({ score: () => 0.9 }); + const result = await screenStandards([ target('src/a.ts', window(0, [ 'L1' ])) ], [ rule('alpha') ], client, CONFIG); + expect(result.calls.map((call) => call.kind)).toEqual([ 'noul', 'choice' ]); + expect(result.calls[0]).toMatchObject({ file: 'src/a.ts', window: 0, usage: USAGE }); + expect(result.calls[0].ms).toBeGreaterThanOrEqual(0); + expect(result.model).toBe(REPORTED_MODEL); + }); + + it('reports an API error as the failure and keeps the cells scored before it, without locating', async() => { + const { client, requests } = fakeClient({ + score: () => 0.9, + fail: (body) => (body.state.file === 'src/b.ts' ? Response.json({ error: 'boom' }, { status: 500 }) : undefined), + }); + const files = [ target('src/a.ts', window(0, [ 'L1' ])), target('src/b.ts', window(0, [ 'L1' ])) ]; + const result = await screenStandards(files, [ rule('alpha') ], client, { ...CONFIG, concurrency: 1 }); + expect(result.failure).toMatch(/^InternalServerError: /); + expect(result.cells).toEqual([ { rule: 'alpha', file: 'src/a.ts', window: 0, score: 0.9 } ]); + expect(result.suspects).toEqual([]); + expect(requests.filter((request) => request.questions.line?.type === 'choice')).toEqual([]); + }); + + it('reports a connection failure the same way', async() => { + const { client } = fakeClient({ fail: () => new TypeError('fetch failed') }); + const result = await screenStandards([ target('src/a.ts', window(0, [ 'L1' ])) ], [ rule('alpha') ], client, CONFIG); + expect(result.failure).toMatch(/^APIConnectionError: /); + expect(result.cells).toEqual([]); + }); +}); diff --git a/tools/review-screen/grid/standards.ts b/tools/review-screen/grid/standards.ts new file mode 100644 index 00000000000..f503b4784db --- /dev/null +++ b/tools/review-screen/grid/standards.ts @@ -0,0 +1,168 @@ +import { matchesGlob } from 'path'; + +import { choice, noul } from '@typesafe-ai/sdk'; + +import type { Rule } from '../rubric'; +import type { FileWindows, Window } from '../select/hunks'; +import { parseLineId } from '../select/hunks'; +import type { CallRecord, ScreenClient } from './shared'; +import { compareText, describeFailure, Recorder, runPool, stateOf } from './shared'; + +// The standards grid: every rubric rule × every touched file its glob matches. One request per +// window carries all of the file's rules as named `noul` questions; a cell over its threshold gets a +// second, `choice` request over the window's changed line ids to name the line. The model returns +// probabilities only — this module sets no severity and writes no claim. + +export interface StandardsConfig { + readonly model: string; + readonly defaultThreshold: number; + readonly thresholdOverrides: Readonly<Record<string, number>>; + readonly maxSuspects: number; + readonly concurrency: number; +} + +export interface Cell { + readonly rule: string; + readonly file: string; + readonly window: number; + readonly score: number; +} + +// `window` names the window the score came from; `--origins` matches a review finding to the suspect +// by that window's line span, which the sidecar records. +export interface Suspect { + readonly rule: string; + readonly file: string; + readonly line: number; + readonly score: number; + readonly window: number; +} + +export interface StandardsResult { + readonly cells: ReadonlyArray<Cell>; + readonly suspects: ReadonlyArray<Suspect>; + readonly cut: number; + readonly calls: ReadonlyArray<CallRecord>; + readonly model: string | undefined; + // The SDK error that stopped the run, after its own retries; the cells scored before it stay. + readonly failure: string | undefined; +} + +interface Candidate extends Cell { + readonly windowRef: Window; +} + +export function thresholdFor(rule: string, config: StandardsConfig): number { + return config.thresholdOverrides[rule] ?? config.defaultThreshold; +} + +export function rulesFor(file: string, rules: ReadonlyArray<Rule>): Array<Rule> { + return rules.filter((rule) => matchesGlob(file, rule.glob)); +} + +// Highest score first; ties keep grid order so a rerun ranks the same way. +export function selectSuspects<T extends Suspect>(candidates: ReadonlyArray<T>, maxSuspects: number): { readonly suspects: Array<T>; readonly cut: number } { + const ranked = [ ...candidates ].sort((a, b) => b.score - a.score); + return { suspects: ranked.slice(0, maxSuspects), cut: Math.max(0, ranked.length - maxSuspects) }; +} + +interface ScreenContext { + readonly client: ScreenClient; + readonly config: StandardsConfig; + readonly recorder: Recorder<Cell>; +} + +function scoreWindowTask(target: FileWindows, window: Window, rules: ReadonlyArray<Rule>, context: ScreenContext): () => Promise<void> { + return async() => { + const { client, config, recorder } = context; + const questions = Object.fromEntries(rules.map((rule) => [ rule.id, noul(rule.question, { 'true': rule.examples, 'false': rule.not_for }) ])); + const result = await recorder.timed('noul', target.file, window.index, () => client.systemOne({ + state: stateOf(target.file, window), + questions, + model: config.model, + })); + for (const rule of rules) { + recorder.cells.push({ rule: rule.id, file: target.file, window: window.index, score: result.answers[rule.id].noul }); + } + }; +} + +// Cells and located suspects arrive in completion order, which the pool does not fix; grid order +// (file, window, rule) is what a tie-break and the cap must see so a rerun ranks the same way. +export function inGridOrder<T extends { readonly file: string; readonly window: number; readonly rule: string }>(items: ReadonlyArray<T>): Array<T> { + return [ ...items ].sort((a, b) => compareText(a.file, b.file) || a.window - b.window || compareText(a.rule, b.rule)); +} + +// Per rule × file, the window with the highest score is the cell; the others are kept in `cells` +// for the sidecar but never become suspects on their own. +function bestCells(cells: ReadonlyArray<Cell>, files: ReadonlyArray<FileWindows>): Array<Candidate> { + const best = new Map<string, Candidate>(); + const windowsByFile = new Map(files.map((target) => [ target.file, target.windows ] as const)); + for (const cell of inGridOrder(cells)) { + const key = `${ cell.rule }\0${ cell.file }`; + const current = best.get(key); + if (current !== undefined && current.score >= cell.score) continue; + const windowRef = windowsByFile.get(cell.file)?.[cell.window]; + // Stryker disable next-line ConditionalExpression: every cell was scored from a window of `files`, so the lookup narrows the type and never misses + if (windowRef !== undefined) best.set(key, { ...cell, windowRef }); + } + return [ ...best.values() ]; +} + +function locateTask(candidate: Candidate, rule: Rule, context: ScreenContext, located: Array<Suspect>): () => Promise<void> { + return async() => { + const { client, config, recorder } = context; + const { windowRef, ...cell } = candidate; + if (windowRef.changedIds.length === 0) { + located.push({ rule: cell.rule, file: cell.file, line: windowRef.firstLine, score: cell.score, window: cell.window }); + return; + } + const question = { question: `Which changed line is where this holds: ${ rule.question }`, examples: rule.examples }; + const options = Object.fromEntries(windowRef.changedIds.map((id) => [ id, null ])); + const result = await recorder.timed('choice', cell.file, cell.window, () => client.systemOne({ + state: stateOf(cell.file, windowRef), + questions: { line: choice(question, options) }, + model: config.model, + })); + const chosen = result.answers.line.choice; + const line = (windowRef.changedIds.includes(chosen) ? parseLineId(chosen) : undefined) ?? windowRef.firstLine; + located.push({ rule: cell.rule, file: cell.file, line, score: cell.score, window: cell.window }); + }; +} + +export async function screenStandards( + files: ReadonlyArray<FileWindows>, + rules: ReadonlyArray<Rule>, + client: ScreenClient, + config: StandardsConfig, +): Promise<StandardsResult> { + const recorder = new Recorder<Cell>(); + const context: ScreenContext = { client, config, recorder }; + const rulesByFile = new Map(files.map((target) => [ target.file, rulesFor(target.file, rules) ] as const)); + + const scoreTasks = files.flatMap((target) => { + const fileRules = rulesByFile.get(target.file) ?? []; + if (fileRules.length === 0) return []; + return target.windows.map((window) => scoreWindowTask(target, window, fileRules, context)); + }); + const scoreFailure = await runPool(scoreTasks, config.concurrency); + + const located: Array<Suspect> = []; + const overThreshold = bestCells(recorder.cells, files).filter((candidate) => candidate.score >= thresholdFor(candidate.rule, config)); + const ruleById = new Map(rules.map((rule) => [ rule.id, rule ] as const)); + const locateTasks = scoreFailure === undefined ? + overThreshold.map((candidate) => locateTask(candidate, ruleById.get(candidate.rule) as Rule, context, located)) : + []; + const locateFailure = await runPool(locateTasks, config.concurrency); + + // A locate failure leaves the list partial, so nothing is ranked — the same as a score failure. + const { suspects, cut } = locateFailure === undefined ? selectSuspects(inGridOrder(located), config.maxSuspects) : { suspects: [], cut: 0 }; + return { + cells: recorder.cells, + suspects, + cut, + calls: recorder.calls, + model: recorder.model, + failure: describeFailure(scoreFailure ?? locateFailure), + }; +} diff --git a/tools/review-screen/index.spec.ts b/tools/review-screen/index.spec.ts new file mode 100644 index 00000000000..103a1c49df2 --- /dev/null +++ b/tools/review-screen/index.spec.ts @@ -0,0 +1,243 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { TypeSafeClient } from '@typesafe-ai/sdk'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import type { Screened } from './index'; +import { parseArgs, printReport, recordOrigins, specRecordOf } from './index'; +import type { SidecarRecord } from './sidecar'; +import { readSidecar, writeSidecar } from './sidecar'; + +interface OriginsOutput { + readonly findings: ReadonlyArray<{ readonly id: string; readonly origin: string }>; + readonly suspects: ReadonlyArray<Record<string, string>>; +} + +function runOrigins(sidecar: string, findings: string): OriginsOutput { + return recordOrigins(sidecar, () => findings) as OriginsOutput; +} + +describe('parseArgs', () => { + it('defaults to the branch scope with nothing explicit', () => { + expect(parseArgs([])).toEqual({ + scope: 'branch', + base: undefined, + spec: undefined, + ticket: undefined, + origins: undefined, + findings: undefined, + calibration: false, + report: false, + json: false, + }); + }); + + it('reads every flag in both the separate-token and inline forms', () => { + expect(parseArgs([ '--scope', 'uncommitted', '--base', 'abc123', '--spec', 's.md', '--ticket', '02' ])).toEqual({ + scope: 'uncommitted', + base: 'abc123', + spec: 's.md', + ticket: '02', + origins: undefined, + findings: undefined, + calibration: false, + report: false, + json: false, + }); + expect(parseArgs([ '--scope=uncommitted', '--base=abc123' ])).toMatchObject({ scope: 'uncommitted', base: 'abc123' }); + }); + + it('marks a calibration run with the bare switch', () => { + expect(parseArgs([ '--calibration', '--base', 'abc123' ])).toMatchObject({ calibration: true, base: 'abc123' }); + expect(() => parseArgs([ '--calibration=yes' ])).toThrow('--calibration takes no value'); + }); + + it('reads --origins with --findings, and rejects one without the other', () => { + expect(parseArgs([ '--origins', '.ai/jev/x.json', '--findings', '-' ])).toMatchObject({ origins: '.ai/jev/x.json', findings: '-' }); + expect(() => parseArgs([ '--origins', '.ai/jev/x.json' ])).toThrow(/--origins and --findings go together\nUsage:/); + expect(() => parseArgs([ '--findings', 'f.md' ])).toThrow('--origins and --findings go together'); + }); + + it('reads --report with an optional --json, and rejects --json on its own', () => { + expect(parseArgs([ '--report' ])).toMatchObject({ report: true, json: false }); + expect(parseArgs([ '--report', '--json' ])).toMatchObject({ report: true, json: true }); + expect(() => parseArgs([ '--json' ])).toThrow(/--json goes with --report\nUsage:/); + }); + + it('accepts both scopes by name and rejects any other', () => { + expect(parseArgs([ '--scope', 'branch' ])).toMatchObject({ scope: 'branch' }); + expect(parseArgs([ '--scope', 'uncommitted' ])).toMatchObject({ scope: 'uncommitted' }); + expect(() => parseArgs([ '--scope', 'pr' ])).toThrow('Invalid value for --scope: pr'); + }); + + it('rejects an unknown flag, a missing value and a stray positional, with the usage attached', () => { + expect(() => parseArgs([ '--nope' ])).toThrow(/Unknown flag: --nope\nUsage:/); + expect(() => parseArgs([ '--base' ])).toThrow('Missing value for --base'); + expect(() => parseArgs([ 'src/a.ts' ])).toThrow(/Unexpected argument: src\/a.ts\nUsage:/); + }); +}); + +describe('specRecordOf', () => { + const client: Screened['client'] = { ok: true, client: new TypeSafeClient({ apiKey: 'test' }) }; + const empty = { cells: [], suspects: [], cut: 0, calls: [], model: undefined, failure: undefined }; + const source: Screened['source'] = { status: 'ok', path: 'spec.md', requirements: [ { id: 'FR1', text: 'one' } ] }; + + it('skips the spec grid, saying why, when the task-folder exclusion leaves no file to score', () => { + const screened: Screened = { client, source, windows: [], specFiles: 0, standards: empty, spec: empty, elapsedMs: 0 }; + expect(specRecordOf(screened)).toEqual({ status: 'skipped', reason: 'no touched file outside .agents/tasks/** to score' }); + }); + + it('reports every requirement covered only when at least one file was scored', () => { + const screened: Screened = { client, source, windows: [], specFiles: 1, standards: empty, spec: empty, elapsedMs: 0 }; + expect(specRecordOf(screened)).toEqual({ status: 'ok', requirements: source.requirements, cells: [], suspects: [], cut: 0 }); + }); + + it('passes a missing spec through and turns an unreadable one into a failed record with nothing scored', () => { + const noSpec: Screened = { client, source: { status: 'no-spec' }, windows: [], specFiles: 1, standards: empty, spec: empty, elapsedMs: 0 }; + expect(specRecordOf(noSpec)).toEqual({ status: 'no-spec' }); + const unreadable: Screened['source'] = { status: 'failed', reason: 'no such file' }; + const failed: Screened = { client, source: unreadable, windows: [], specFiles: 1, standards: empty, spec: empty, elapsedMs: 0 }; + expect(specRecordOf(failed)).toEqual({ status: 'failed', reason: 'no such file', requirements: [], cells: [] }); + }); + + it('skips the grid with the client reason when there is no client', () => { + const screened: Screened = { client: { ok: false, reason: 'no key' }, source, windows: [], specFiles: 1, standards: empty, spec: empty, elapsedMs: 0 }; + expect(specRecordOf(screened)).toEqual({ status: 'skipped', reason: 'no key' }); + }); + + it('reports an API failure with the requirements and the cells scored before it', () => { + const cells = [ { requirement: 'FR1', file: 'src/a.ts', window: 0, score: 0.4 } ]; + const spec = { ...empty, cells, failure: 'InternalServerError: boom' }; + const screened: Screened = { client, source, windows: [], specFiles: 1, standards: empty, spec, elapsedMs: 0 }; + expect(specRecordOf(screened)).toEqual({ status: 'failed', reason: 'InternalServerError: boom', requirements: source.requirements, cells }); + }); +}); + +describe('--origins', () => { + let tmp = ''; + + afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; + }); + + it('rewrites the sidecar with an origins block, and a second run replaces it rather than appending', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'review-screen-origins-')); + const sidecar = path.join(tmp, 'x.json'); + const record: SidecarRecord = { + version: 1, + createdAt: '2026-09-28T23:30:00.000Z', + status: 'ok', + reason: undefined, + calibration: false, + model: 'jev-1.13.0', + inputs: { scope: 'branch', base: 'abc', branch: 'issue-1', ticket: undefined, spec: undefined, files: [ { path: 'src/a.ts', untracked: false } ] }, + windows: [ { file: 'src/a.ts', window: 0, firstLine: 1, lastLine: 20 } ], + standards: { cells: [], suspects: [ { rule: 'no-comments', file: 'src/a.ts', line: 4, score: 0.9, window: 0 } ], cut: 0 }, + spec: { status: 'no-spec' }, + calls: [], + elapsedMs: undefined, + origins: undefined, + }; + writeSidecar(sidecar, record); + + const first = runOrigins(sidecar, '| id | axis | location | sources |\n| --- | --- | --- | --- |\n| F1 | standards | `src/a.ts:6` | jev |\n'); + expect(first.suspects).toEqual([ { suspect: 'no-comments src/a.ts:4', fate: 'confirmed', finding: 'F1' } ]); + const afterFirst = readSidecar(sidecar); + expect(afterFirst).toMatchObject({ + status: 'ok', + windows: record.windows, + standards: record.standards, + origins: { findings: [ { id: 'F1', origin: 'jev' } ], suspects: [ { fate: 'confirmed', finding: 'F1' } ] }, + }); + + const second = runOrigins(sidecar, JSON.stringify([ { id: 'F9', axis: 'spec', location: '—', sources: [ 'spec' ] } ])); + expect(second.findings).toEqual([ { id: 'F9', origin: 'axis' } ]); + expect(second.suspects).toEqual([ { suspect: 'no-comments src/a.ts:4', fate: 'dropped', reason: 'not reported' } ]); + const afterSecond = readSidecar(sidecar); + expect(afterSecond.origins?.findings).toEqual([ { id: 'F9', axis: 'spec', sources: [ 'spec' ], origin: 'axis', location: { kind: 'none' } } ]); + expect(afterSecond.origins?.suspects).toEqual([ + { suspect: { kind: 'standards', rule: 'no-comments', file: 'src/a.ts', line: 4 }, score: 0.9, fate: 'dropped', reason: 'not reported' }, + ]); + expect(Object.keys(afterSecond)).toEqual(Object.keys(afterFirst)); + }); +}); + +describe('--report', () => { + let tmp = ''; + + afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; + }); + + function pilotRecord(overrides: Partial<SidecarRecord>): SidecarRecord { + return { + version: 1, + createdAt: '2026-09-28T23:30:00.000Z', + status: 'ok', + reason: undefined, + calibration: false, + model: 'jev-1.13.0', + inputs: { scope: 'branch', base: 'abc', branch: 'issue-1', ticket: undefined, spec: undefined, files: [] }, + windows: [], + standards: { cells: [], suspects: [], cut: 0 }, + spec: { status: 'no-spec' }, + calls: [ { kind: 'noul', file: 'src/a.ts', window: 0, ms: 2000, usage: { input_tokens: 500, output_tokens: 10 } } ], + elapsedMs: 2000, + origins: undefined, + ...overrides, + }; + } + + it('prints an empty table when the sidecar folder does not exist yet', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'review-screen-report-')); + const output = printReport(path.join(tmp, 'missing'), false); + expect(output).toContain('reviews: 0 counted · 0 pending origins'); + expect(output).toMatch(/^explanatory-comment\s+0\s+0\s+0\s+0\s+—$/m); + }); + + it('reads every sidecar in the folder, in name order, and prints the same data as text or JSON', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'review-screen-report-')); + writeSidecar(path.join(tmp, '2026-09-28-b-branch.json'), pilotRecord({})); + writeSidecar(path.join(tmp, '2026-09-27-a-branch.json'), pilotRecord({ origins: { + recordedAt: '2026-09-27T00:00:00.000Z', + findings: [ { + id: 'F1', axis: 'standards', sources: [ 'jev' ], origin: 'jev', + location: { kind: 'line', file: 'src/a.ts', line: 4 }, rule: 'magic-number', claim: 'A bare 4.', + } ], + suspects: [ { suspect: { kind: 'standards', rule: 'magic-number', file: 'src/a.ts', line: 4 }, score: 0.9, fate: 'confirmed', finding: 'F1' } ], + } })); + writeSidecar(path.join(tmp, 'calibration.json'), pilotRecord({ calibration: true })); + fs.writeFileSync(path.join(tmp, 'notes.txt'), 'ignored'); + + const text = printReport(tmp, false); + expect(text).toMatch(/^magic-number\s+1\s+1\s+0\s+0\s+—$/m); + expect(text).toContain('reviews: 1 counted · 1 pending origins'); + expect(text).toContain('findings: jev 1 / axis 0 / both 0'); + expect(text).toContain('added seconds per review: mean 2.0 · max 2.0'); + expect(text).toContain('input tokens per review: mean 500'); + expect(text).toContain(' 2026-09-28-b-branch.json'); + expect(text).toMatch(/^magic-number\s+1\s+1\s+—$/m); + expect(text).toMatch(/^magic-number\s+0\.7\s+0\/0\/0\s+0\/0\/0\s+0\/0\/0\s+0\/0\/0$/m); + expect(text).toMatch(/^explanatory-comment\s+0\.5\s+/m); + expect(text).toContain('coverage: 1 standards findings · 1 in a file with no cell · 0 on a line outside every window · 0 with no location recorded'); + + expect(JSON.parse(printReport(tmp, true))).toMatchObject({ + rules: expect.arrayContaining([ { rule: 'magic-number', sent: 1, confirmed: 1, merged: 0, dropped: 0, topDropReason: undefined } ]), + nearMisses: expect.arrayContaining([ { rule: 'magic-number', labelled: 1, noCell: 1 } ]), + sweep: expect.arrayContaining([ { rule: 'inline-empty-default', threshold: 0.6, at: [ + { threshold: 0.4, hit: 0, noise: 0, missed: 0 }, + { threshold: 0.5, hit: 0, noise: 0, missed: 0 }, + { threshold: 0.6, hit: 0, noise: 0, missed: 0 }, + { threshold: 0.7, hit: 0, noise: 0, missed: 0 }, + ] } ]), + coverage: { standardsFindings: 1, noCell: 1, outsideWindows: 0, unlocated: 0 }, + totals: { reviews: 1, pending: 1, findings: { jev: 1, axis: 0, both: 0 }, addedSeconds: { mean: 2, max: 2 }, meanInputTokens: 500 }, + pending: [ '2026-09-28-b-branch.json' ], + }); + }); +}); diff --git a/tools/review-screen/index.ts b/tools/review-screen/index.ts new file mode 100644 index 00000000000..0b5347de8d2 --- /dev/null +++ b/tools/review-screen/index.ts @@ -0,0 +1,358 @@ +/* eslint-disable no-console -- this is a CLI whose entire job is to print a JSON report to stdout */ +import fs from 'fs'; +import path from 'path'; + +import { TypeSafeClient, TypeSafeError } from '@typesafe-ai/sdk'; + +import { resolveMainCheckout } from '../cli/checkout'; +import type { FlagSpec } from '../cli/flags'; +import { parseArgs as parseFlags } from '../cli/flags'; +import { + CONCURRENT_REQUESTS, CONTEXT_LINES, DEFAULT_STANDARDS_THRESHOLD, MAX_CHANGED_LINES_PER_WINDOW, MAX_STATE_CHARS, MAX_SUSPECTS, MODEL, + SIDECAR_DIR, SPEC_GRID_EXCLUDE, SPEC_THRESHOLD, STANDARDS_THRESHOLD_OVERRIDES, SWEEP_THRESHOLDS, +} from './config'; +import type { CallRecord, ScreenClient } from './grid/shared'; +import type { SpecResult } from './grid/spec'; +import { screenSpec, shareCap, specGridFiles } from './grid/spec'; +import type { StandardsConfig, StandardsResult } from './grid/standards'; +import { screenStandards, thresholdFor } from './grid/standards'; +import type { SuspectFateRecord } from './origins/match'; +import { assignOrigins } from './origins/match'; +import { formatSuspectRef, parseOriginsInput } from './origins/parse'; +import type { SidecarFile } from './report/aggregate'; +import { aggregateReport } from './report/aggregate'; +import { renderReport, renderReportJson } from './report/render'; +import { RULES } from './rubric'; +import type { Change, Scope } from './select/change'; +import { resolveChange } from './select/change'; +import type { FileWindows } from './select/hunks'; +import { buildWindows, readHunks } from './select/hunks'; +import type { SpecSource } from './select/spec'; +import { readSpec } from './select/spec'; +import type { RunStatus, SidecarRecord, SpecRecord } from './sidecar'; +import { readSidecar, sidecarFileName, windowSpans, writeSidecar } from './sidecar'; + +// The screen never fails a review: a missing key or an API error still exits 0, with the status and +// reason in the JSON, and every run writes its sidecar. Only invalid arguments or a bug in the tool +// itself exit non-zero, and those write no sidecar. + +export interface CliOptions { + scope: Scope; + base: string | undefined; + spec: string | undefined; + ticket: string | undefined; + origins: string | undefined; + findings: string | undefined; + calibration: boolean; + report: boolean; + json: boolean; +} + +const STDIN = '-'; + +const USAGE = `Usage: + review:screen [--scope branch|uncommitted] [--base <ref>] [--spec <path>] [--ticket <NN>] + review:screen --origins <sidecar> --findings <path|-> + review:screen --report [--json] + + Screens a change with Jev — every rubric rule against every touched file, and, when the change has + a task spec, every Functional Requirement against every touched file — and prints the suspects as + JSON on stdout. Every run writes a sidecar with every cell score to <main checkout>/.ai/jev/. + + --scope branch (default) diff from the merge-base with main; untracked files included + --scope uncommitted diff HEAD against the working tree; untracked files included + --base <ref> use this base verbatim instead of deriving it from the scope + --spec <path> use this task spec verbatim instead of resolving it from the issue branch + --ticket <NN> name the ticket in the sidecar file; under --scope uncommitted it defaults to + the first unchecked box in the task's progress.md + --calibration mark the sidecar as a calibration run (a past diff screened to tune the + thresholds), so --report leaves it out of the pilot's numbers + + Without TYPESAFE_API_KEY in the environment the run is skipped; an API failure is reported as failed. + Both exit 0. + + --origins <sidecar> after the review is published: record each suspect's fate and each finding's + origin (axis | jev | both) into that sidecar, replacing any earlier record + --findings <path|-> the review's final findings and the jev axis's drop list, as a JSON array or as + Markdown tables; - reads stdin + finding: { id, axis, location: "<path>:<line>" | "FR<n>" | "—", sources: [...], + rule: "<rubric rule id>" | "—", claim: "<first sentence>" } + drop: { suspect: "<rule> <path>:<line>" | "FR<n>", fate: "dropped", reason } + tables: | id | axis | rule | location | sources | claim | and | suspect | fate | reason | + rule and claim are optional; the sidecar keeps location, rule and claim per finding + + --report the pilot tables over every sidecar in <main checkout>/.ai/jev/: per rule, suspects + sent / confirmed / merged / dropped with the top drop reason; per rule, the near + misses — reviewer findings labelled with the rule, how many sat in a file the rule + had no cell for, and the min / median / max of the rule's cell on their files; per + rule, a threshold sweep — hit / noise / missed cells at ${ SWEEP_THRESHOLDS.join(' / ') }, where a hit + is a cell over the threshold on a file with a labelled finding, noise one without, + and missed a cell under it on a labelled file; the jev / axis / both finding counts; + added seconds and input tokens per review; a coverage line — standards findings in + a file with no cell, or on a line outside every window. Calibration runs are left + out; a sidecar --origins has not been run on is listed as pending and not counted. + Nothing is computed during a review. + --json with --report: print the same data as JSON`; + +function readScope(raw: string): Scope { + if (raw === 'branch' || raw === 'uncommitted') return raw; + throw new Error(`Invalid value for --scope: ${ raw }\n${ USAGE }`); +} + +const FLAGS: ReadonlyMap<string, FlagSpec<CliOptions>> = new Map<string, FlagSpec<CliOptions>>([ + [ '--help', { kind: 'switch', apply: () => { + console.log(USAGE); + process.exit(0); + } } ], + [ '-h', { kind: 'switch', apply: () => { + console.log(USAGE); + process.exit(0); + } } ], + [ '--scope', { kind: 'value', apply: (options, value) => { + options.scope = readScope(value); + } } ], + [ '--base', { kind: 'value', apply: (options, value) => { + options.base = value; + } } ], + [ '--spec', { kind: 'value', apply: (options, value) => { + options.spec = value; + } } ], + [ '--ticket', { kind: 'value', apply: (options, value) => { + options.ticket = value; + } } ], + [ '--origins', { kind: 'value', apply: (options, value) => { + options.origins = value; + } } ], + [ '--findings', { kind: 'value', apply: (options, value) => { + options.findings = value; + } } ], + [ '--calibration', { kind: 'switch', apply: (options) => { + options.calibration = true; + } } ], + [ '--report', { kind: 'switch', apply: (options) => { + options.report = true; + } } ], + [ '--json', { kind: 'switch', apply: (options) => { + options.json = true; + } } ], +]); + +export function parseArgs(argv: ReadonlyArray<string>): CliOptions { + const { options, rest } = parseFlags<CliOptions>(argv, FLAGS, { + scope: 'branch', + base: undefined, + spec: undefined, + ticket: undefined, + origins: undefined, + findings: undefined, + calibration: false, + report: false, + json: false, + }, { kind: 'reject', usage: USAGE }); + if (rest.length > 0) throw new Error(`Unexpected argument: ${ rest[0] }\n${ USAGE }`); + if ((options.origins === undefined) !== (options.findings === undefined)) throw new Error(`--origins and --findings go together\n${ USAGE }`); + if (options.json && !options.report) throw new Error(`--json goes with --report\n${ USAGE }`); + return options; +} + +export type ClientOutcome = + { readonly ok: true; readonly client: ScreenClient } | + { readonly ok: false; readonly reason: string }; + +// The SDK reads the key itself; a missing one surfaces as the constructor throwing, which is the +// `skipped` outcome rather than a crash. +function createClient(): ClientOutcome { + try { + return { ok: true, client: new TypeSafeClient({ defaultModel: MODEL }) }; + } catch (error) { + if (error instanceof TypeSafeError) return { ok: false, reason: error.message }; + throw error; + } +} + +function windowsOf(change: Change, cwd: string): Array<FileWindows> { + const limits = { maxChars: MAX_STATE_CHARS, maxChangedLines: MAX_CHANGED_LINES_PER_WINDOW }; + return change.files + .map((file) => ({ file: file.path, windows: buildWindows(readHunks(file.path, file.untracked, change.base, CONTEXT_LINES, cwd), limits) })) + .filter((target) => target.windows.length > 0); +} + +const STANDARDS_CONFIG: StandardsConfig = { + model: MODEL, + defaultThreshold: DEFAULT_STANDARDS_THRESHOLD, + thresholdOverrides: STANDARDS_THRESHOLD_OVERRIDES, + maxSuspects: MAX_SUSPECTS, + concurrency: CONCURRENT_REQUESTS, +}; + +const EMPTY_STANDARDS: StandardsResult = { cells: [], suspects: [], cut: 0, calls: [], model: undefined, failure: undefined }; +const EMPTY_SPEC: SpecResult = { cells: [], suspects: [], cut: 0, calls: [], model: undefined, failure: undefined }; + +export interface Screened { + readonly client: ClientOutcome; + readonly source: SpecSource; + readonly windows: ReadonlyArray<FileWindows>; + // What the spec grid scores once the task folder is excluded; none means the grid is skipped. + readonly specFiles: number; + readonly standards: StandardsResult; + readonly spec: SpecResult; + readonly elapsedMs: number; +} + +function statusOf(screened: Screened): { readonly status: RunStatus; readonly reason: string | undefined } { + if (!screened.client.ok) return { status: 'skipped', reason: screened.client.reason }; + const failure = screened.standards.failure ?? screened.spec.failure; + if (failure !== undefined) return { status: 'failed', reason: failure }; + return { status: 'ok', reason: undefined }; +} + +export function specRecordOf(screened: Screened): SpecRecord { + const { client, source, spec } = screened; + if (source.status !== 'ok') return source.status === 'no-spec' ? source : { status: 'failed', reason: source.reason, requirements: [], cells: [] }; + if (!client.ok) return { status: 'skipped', reason: client.reason }; + if (screened.specFiles === 0) return { status: 'skipped', reason: `no touched file outside ${ SPEC_GRID_EXCLUDE } to score` }; + if (spec.failure !== undefined) return { status: 'failed', reason: spec.failure, requirements: source.requirements, cells: spec.cells }; + return { status: 'ok', requirements: source.requirements, cells: spec.cells, suspects: spec.suspects, cut: spec.cut }; +} + +function buildRecord(change: Change, screened: Screened, calibration: boolean): SidecarRecord { + const calls: Array<CallRecord> = [ ...screened.standards.calls, ...screened.spec.calls ]; + return { + version: 1, + createdAt: new Date().toISOString(), + ...statusOf(screened), + calibration, + model: screened.standards.model ?? screened.spec.model, + inputs: { scope: change.scope, base: change.base, branch: change.branch, ticket: change.ticket, spec: change.spec, files: change.files }, + windows: windowSpans(screened.windows), + standards: { cells: screened.standards.cells, suspects: screened.standards.suspects, cut: screened.standards.cut }, + spec: specRecordOf(screened), + calls, + elapsedMs: screened.elapsedMs, + origins: undefined, + }; +} + +// The two grids run one after the other so a single pool bounds the request rate, and the cap is +// shared once both have ranked their own suspects. +async function screen(change: Change, client: ClientOutcome, source: SpecSource, cwd: string): Promise<Screened> { + const windows = windowsOf(change, cwd); + const specFiles = specGridFiles(windows, SPEC_GRID_EXCLUDE); + const base = { client, source, windows, specFiles: specFiles.length }; + if (!client.ok) return { ...base, standards: EMPTY_STANDARDS, spec: EMPTY_SPEC, elapsedMs: 0 }; + const started = performance.now(); + const standards = await screenStandards(windows, RULES, client.client, STANDARDS_CONFIG); + const spec = source.status === 'ok' ? + await screenSpec(specFiles, source.requirements, client.client, { + model: MODEL, + threshold: SPEC_THRESHOLD, + maxSuspects: MAX_SUSPECTS, + concurrency: CONCURRENT_REQUESTS, + }) : + EMPTY_SPEC; + const elapsedMs = Math.round(performance.now() - started); + const capped = shareCap(standards, spec, MAX_SUSPECTS); + return { ...base, standards: { ...standards, ...capped.standards }, spec: { ...spec, ...capped.spec }, elapsedMs }; +} + +function printSpec(record: SpecRecord): unknown { + switch (record.status) { + case 'ok': + return { status: record.status, requirements: record.requirements.length, cells: record.cells.length, suspects: record.suspects, cut: record.cut }; + case 'failed': + return { status: record.status, reason: record.reason, requirements: record.requirements.length, cells: record.cells.length }; + default: + return record; + } +} + +function readFindings(source: string): string { + return fs.readFileSync(source === STDIN ? process.stdin.fd : source, 'utf8'); +} + +function printFate(entry: SuspectFateRecord): Record<string, string> { + const suspect = formatSuspectRef(entry.suspect); + return entry.fate === 'dropped' ? + { suspect, fate: entry.fate, reason: entry.reason } : + { suspect, fate: entry.fate, finding: entry.finding }; +} + +export function recordOrigins(sidecar: string, readInput: () => string): unknown { + const input = parseOriginsInput(readInput()); + const record = readSidecar(sidecar); + const origins = assignOrigins(record, input, new Date().toISOString()); + writeSidecar(sidecar, { ...record, origins }); + return { + sidecar, + status: record.status, + findings: origins.findings.map(({ id, origin }) => ({ id, origin })), + suspects: origins.suspects.map(printFate), + }; +} + +export function readSidecarDir(dir: string): Array<SidecarFile> { + if (!fs.existsSync(dir)) return []; + return fs.readdirSync(dir) + .filter((file) => file.endsWith('.json')) + .sort() + .map((file) => ({ file, record: readSidecar(path.join(dir, file)) })); +} + +export function printReport(dir: string, json: boolean): string { + const report = aggregateReport(readSidecarDir(dir), { + ids: RULES.map((rule) => rule.id), + thresholdOf: (rule) => thresholdFor(rule, STANDARDS_CONFIG), + sweepThresholds: SWEEP_THRESHOLDS, + }); + return json ? renderReportJson(report) : renderReport(report); +} + +async function main(): Promise<void> { + const options = parseArgs(process.argv.slice(2)); + const cwd = process.cwd(); + if (options.report) { + console.log(printReport(path.join(resolveMainCheckout(cwd), SIDECAR_DIR), options.json)); + return; + } + if (options.origins !== undefined && options.findings !== undefined) { + const findings = options.findings; + console.log(JSON.stringify(recordOrigins(path.resolve(cwd, options.origins), () => readFindings(findings)), null, 2)); + return; + } + const change = resolveChange(options, cwd); + const screened = await screen(change, createClient(), readSpec(change.spec, cwd), cwd); + + const record = buildRecord(change, screened, options.calibration); + const sidecar = path.join(resolveMainCheckout(cwd), SIDECAR_DIR, sidecarFileName({ + date: new Date(record.createdAt), + branch: change.branch, + scope: change.scope, + ticket: change.ticket, + })); + writeSidecar(sidecar, record); + + console.log(JSON.stringify({ + status: record.status, + reason: record.reason, + model: record.model, + sidecar, + standards: { cells: record.standards.cells.length, suspects: record.standards.suspects, cut: record.standards.cut }, + spec: printSpec(record.spec), + }, null, 2)); +} + +// run.sh always executes the compiled `tools/review-screen/dist/review-screen/index.js`, so that path +// is what marks this module as the process entry point; under vitest the entry is vitest's own binary. +const CLI_ENTRY_PATH = 'review-screen/dist/review-screen/index.js'; + +function isProcessEntryPoint(): boolean { + const entry = process.argv[1]?.replace(/\\/g, '/'); + return entry !== undefined && entry.endsWith(CLI_ENTRY_PATH); +} + +if (isProcessEntryPoint()) { + main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + }); +} diff --git a/tools/review-screen/origins/match.spec.ts b/tools/review-screen/origins/match.spec.ts new file mode 100644 index 00000000000..c9cbff1a329 --- /dev/null +++ b/tools/review-screen/origins/match.spec.ts @@ -0,0 +1,194 @@ +import { describe, expect, it } from 'vitest'; + +import type { SidecarRecord } from '../sidecar'; +import { assignOrigins, originOf } from './match'; +import type { FindingRow, OriginsInput } from './parse'; +import { parseLocation } from './parse'; + +const RECORDED_AT = '2026-09-28T23:30:00.000Z'; + +function finding(id: string, location: string, sources: ReadonlyArray<string>, axis: string = 'standards'): FindingRow { + return { id, axis, location: parseLocation(location), sources, rule: undefined, claim: undefined }; +} + +function record(overrides: Partial<SidecarRecord> = {}): SidecarRecord { + return { + version: 1, + createdAt: RECORDED_AT, + status: 'ok', + reason: undefined, + model: 'jev-1.13.0', + inputs: { scope: 'branch', base: 'abc', branch: 'issue-1', ticket: undefined, spec: undefined, files: [] }, + windows: [ + { file: 'src/a.ts', window: 0, firstLine: 10, lastLine: 30 }, + { file: 'src/a.ts', window: 1, firstLine: 80, lastLine: 95 }, + { file: 'src/b.ts', window: 0, firstLine: 1, lastLine: 12 }, + ], + standards: { + cells: [], + suspects: [ + { rule: 'no-comments', file: 'src/a.ts', line: 12, score: 0.91, window: 0 }, + { rule: 'magic-number', file: 'src/a.ts', line: 90, score: 0.8, window: 1 }, + { rule: 'no-comments', file: 'src/b.ts', line: 3, score: 0.75, window: 0 }, + ], + cut: 0, + }, + spec: { + status: 'ok', + requirements: [ { id: 'FR1', text: 'one' }, { id: 'FR2', text: 'two' } ], + cells: [], + suspects: [ + { requirement: 'FR1', file: 'src/a.ts', line: '—', score: 0.1 }, + { requirement: 'FR2', file: 'src/b.ts', line: '—', score: 0.2 }, + ], + cut: 0, + }, + calls: [], + elapsedMs: undefined, + origins: undefined, + calibration: false, + ...overrides, + }; +} + +describe('originOf', () => { + it('is jev when only jev raised it, axis when jev did not, both otherwise', () => { + expect(originOf([ 'jev' ])).toBe('jev'); + expect(originOf([ 'jev', 'jev' ])).toBe('jev'); + expect(originOf([ 'standards' ])).toBe('axis'); + expect(originOf([])).toBe('axis'); + expect(originOf([ 'standards', 'jev' ])).toBe('both'); + }); +}); + +describe('assignOrigins', () => { + it('confirms a suspect a jev-only finding lands in its window, merges one shared with an axis, and drops the rest', () => { + const input: OriginsInput = { + findings: [ + finding('F1', 'src/a.ts:25', [ 'jev' ]), + finding('F2', 'src/a.ts:85', [ 'standards', 'jev' ]), + finding('F3', 'src/b.ts:3', [ 'standards' ]), + finding('F4', 'FR1', [ 'jev' ], 'spec'), + ], + drops: [ { suspect: { kind: 'spec', requirement: 'FR2' }, reason: 'covered by the PR description' } ], + }; + const origins = assignOrigins(record(), input, RECORDED_AT); + expect(origins.recordedAt).toBe(RECORDED_AT); + const unlabelled = { rule: undefined, claim: undefined }; + expect(origins.findings).toEqual([ + { id: 'F1', axis: 'standards', sources: [ 'jev' ], origin: 'jev', location: { kind: 'line', file: 'src/a.ts', line: 25 }, ...unlabelled }, + { id: 'F2', axis: 'standards', sources: [ 'standards', 'jev' ], origin: 'both', location: { kind: 'line', file: 'src/a.ts', line: 85 }, ...unlabelled }, + { id: 'F3', axis: 'standards', sources: [ 'standards' ], origin: 'axis', location: { kind: 'line', file: 'src/b.ts', line: 3 }, ...unlabelled }, + { id: 'F4', axis: 'spec', sources: [ 'jev' ], origin: 'jev', location: { kind: 'requirement', requirement: 'FR1' }, ...unlabelled }, + ]); + expect(origins.suspects).toEqual([ + { suspect: { kind: 'standards', rule: 'no-comments', file: 'src/a.ts', line: 12 }, score: 0.91, fate: 'confirmed', finding: 'F1' }, + { suspect: { kind: 'standards', rule: 'magic-number', file: 'src/a.ts', line: 90 }, score: 0.8, fate: 'merged', finding: 'F2' }, + { suspect: { kind: 'standards', rule: 'no-comments', file: 'src/b.ts', line: 3 }, score: 0.75, fate: 'dropped', reason: 'not reported' }, + { suspect: { kind: 'spec', requirement: 'FR1' }, score: 0.1, fate: 'confirmed', finding: 'F4' }, + { suspect: { kind: 'spec', requirement: 'FR2' }, score: 0.2, fate: 'dropped', reason: 'covered by the PR description' }, + ]); + }); + + it('gives each finding to one suspect only, the nearest by located line, when two suspects share a window', () => { + const shared = record({ + standards: { + cells: [], + suspects: [ + { rule: 'no-comments', file: 'src/a.ts', line: 12, score: 0.91, window: 0 }, + { rule: 'magic-number', file: 'src/a.ts', line: 28, score: 0.8, window: 0 }, + ], + cut: 0, + }, + spec: { status: 'no-spec' }, + }); + // For the first suspect (line 12): F1 is 15 away, F2 and F3 both 2 away, F4 is 4 away. The nearest + // wins regardless of its position in the list, and an earlier row wins a tie. + const input: OriginsInput = { + findings: [ + finding('F1', 'src/a.ts:27', [ 'standards', 'jev' ]), + finding('F2', 'src/a.ts:14', [ 'jev' ]), + finding('F3', 'src/a.ts:10', [ 'jev' ]), + finding('F4', 'src/a.ts:16', [ 'jev' ]), + ], + drops: [], + }; + const fates = assignOrigins(shared, input, RECORDED_AT).suspects; + expect(fates).toEqual([ + { suspect: { kind: 'standards', rule: 'no-comments', file: 'src/a.ts', line: 12 }, score: 0.91, fate: 'confirmed', finding: 'F2' }, + { suspect: { kind: 'standards', rule: 'magic-number', file: 'src/a.ts', line: 28 }, score: 0.8, fate: 'merged', finding: 'F1' }, + ]); + + const oneFinding: OriginsInput = { findings: [ finding('F1', 'src/a.ts:20', [ 'jev' ]) ], drops: [] }; + expect(assignOrigins(shared, oneFinding, RECORDED_AT).suspects.map((entry) => entry.fate)).toEqual([ 'confirmed', 'dropped' ]); + }); + + it('matches by the window span, not the located line, and never across files', () => { + // F2 sits inside src/a.ts window 0 by line number only: it is in another file, so it belongs to no + // src/a.ts suspect, and it is outside src/b.ts window 0, so it belongs to no src/b.ts suspect either. + const input: OriginsInput = { + findings: [ finding('F1', 'src/a.ts:30', [ 'jev' ]), finding('F2', 'src/b.ts:20', [ 'jev' ]), finding('F3', 'src/b.ts:5', [ 'jev' ]) ], + drops: [], + }; + const fates = assignOrigins(record(), input, RECORDED_AT).suspects; + expect(fates).toMatchObject([ + { fate: 'confirmed', finding: 'F1' }, + { fate: 'dropped', reason: 'not reported' }, + { fate: 'confirmed', finding: 'F3' }, + { fate: 'dropped', reason: 'not reported' }, + { fate: 'dropped', reason: 'not reported' }, + ]); + + // Alone, F2 is still past the end of src/b.ts window 0, and one on its last line is in. + const past: OriginsInput = { findings: [ finding('F2', 'src/b.ts:20', [ 'jev' ]) ], drops: [] }; + expect(assignOrigins(record(), past, RECORDED_AT).suspects[2]).toMatchObject({ fate: 'dropped', reason: 'not reported' }); + const last: OriginsInput = { findings: [ finding('F2', 'src/b.ts:12', [ 'jev' ]) ], drops: [] }; + expect(assignOrigins(record(), last, RECORDED_AT).suspects[2]).toMatchObject({ fate: 'confirmed', finding: 'F2' }); + }); + + it('matches a spec suspect on its requirement id only, never on a line finding', () => { + const input: OriginsInput = { + findings: [ finding('F1', 'FR2', [ 'jev' ], 'spec'), finding('F2', 'FR1', [ 'jev' ], 'spec'), finding('F3', 'src/b.ts:3', [ 'jev' ]) ], + drops: [], + }; + const fates = assignOrigins(record(), input, RECORDED_AT).suspects; + expect(fates.slice(3)).toMatchObject([ + { suspect: { kind: 'spec', requirement: 'FR1' }, fate: 'confirmed', finding: 'F2' }, + { suspect: { kind: 'spec', requirement: 'FR2' }, fate: 'confirmed', finding: 'F1' }, + ]); + }); + + it('matches on the exact line when the sidecar has no window spans', () => { + const input: OriginsInput = { findings: [ finding('F1', 'src/a.ts:12', [ 'jev' ]), finding('F2', 'src/a.ts:13', [ 'jev' ]) ], drops: [] }; + const fates = assignOrigins(record({ windows: [] }), input, RECORDED_AT).suspects; + expect(fates[0]).toMatchObject({ fate: 'confirmed', finding: 'F1' }); + expect(fates[1]).toMatchObject({ fate: 'dropped', reason: 'not reported' }); + }); + + it('records the drop reason over a matching finding, and an empty reason as given', () => { + const input: OriginsInput = { + findings: [ finding('F1', 'src/a.ts:12', [ 'jev' ]) ], + drops: [ { suspect: { kind: 'standards', rule: 'no-comments', file: 'src/a.ts', line: 12 }, reason: '' } ], + }; + expect(assignOrigins(record(), input, RECORDED_AT).suspects[0]).toMatchObject({ fate: 'dropped', reason: '' }); + }); + + it('keeps the rule label and the claim a finding came with', () => { + const labelled: FindingRow = { ...finding('F1', 'src/a.ts:25', [ 'standards' ]), rule: 'no-comments', claim: 'The comment restates the line.' }; + const origins = assignOrigins(record(), { findings: [ labelled ], drops: [] }, RECORDED_AT); + expect(origins.findings[0]).toMatchObject({ id: 'F1', rule: 'no-comments', claim: 'The comment restates the line.' }); + }); + + it('still classifies every finding as axis on a skipped run with no suspects', () => { + const skipped = record({ + status: 'skipped', + reason: 'no key', + standards: { cells: [], suspects: [], cut: 0 }, + spec: { status: 'skipped', reason: 'no key' }, + }); + const input: OriginsInput = { findings: [ finding('F1', 'src/a.ts:12', [ 'standards' ]), finding('F2', '—', [ 'spec' ], 'spec') ], drops: [] }; + const origins = assignOrigins(skipped, input, RECORDED_AT); + expect(origins.findings.map((entry) => entry.origin)).toEqual([ 'axis', 'axis' ]); + expect(origins.suspects).toEqual([]); + }); +}); diff --git a/tools/review-screen/origins/match.ts b/tools/review-screen/origins/match.ts new file mode 100644 index 00000000000..719fc0f39e7 --- /dev/null +++ b/tools/review-screen/origins/match.ts @@ -0,0 +1,147 @@ +import type { SpecSuspect } from '../grid/spec'; +import type { Suspect } from '../grid/standards'; +import type { SidecarRecord, WindowSpan } from '../sidecar'; +import type { DropEntry, FindingLocation, FindingRow, OriginsInput, SuspectRef } from './parse'; +import { formatSuspectRef, JEV_SOURCE } from './parse'; + +// Which side raised each published finding, and what became of each suspect the screen sent. The +// match is mechanical: same file and a line inside the suspect's window, or the same requirement id. + +export type FindingOrigin = 'axis' | 'jev' | 'both'; + +export interface FindingOriginRecord { + readonly id: string; + readonly axis: string; + readonly sources: ReadonlyArray<string>; + readonly origin: FindingOrigin; + readonly location: FindingLocation | undefined; + readonly rule: string | undefined; + readonly claim: string | undefined; +} + +export type SuspectFate = + { readonly fate: 'confirmed'; readonly finding: string } | + { readonly fate: 'merged'; readonly finding: string } | + { readonly fate: 'dropped'; readonly reason: string }; + +interface ScoredSuspect { + readonly suspect: SuspectRef; + readonly score: number; +} + +interface ConfirmedSuspect extends ScoredSuspect { + readonly fate: 'confirmed'; + readonly finding: string; +} + +interface MergedSuspect extends ScoredSuspect { + readonly fate: 'merged'; + readonly finding: string; +} + +interface DroppedSuspect extends ScoredSuspect { + readonly fate: 'dropped'; + readonly reason: string; +} + +export type SuspectFateRecord = ConfirmedSuspect | MergedSuspect | DroppedSuspect; + +export interface OriginsRecord { + readonly recordedAt: string; + readonly findings: ReadonlyArray<FindingOriginRecord>; + readonly suspects: ReadonlyArray<SuspectFateRecord>; +} + +export const NOT_REPORTED = 'not reported'; + +export function originOf(sources: ReadonlyArray<string>): FindingOrigin { + const hasJev = sources.includes(JEV_SOURCE); + if (!hasJev) return 'axis'; + return sources.every((source) => source === JEV_SOURCE) ? 'jev' : 'both'; +} + +function spanOf(suspect: Suspect, spans: ReadonlyArray<WindowSpan>): { readonly firstLine: number; readonly lastLine: number } { + const span = spans.find((candidate) => candidate.file === suspect.file && candidate.window === suspect.window); + return span ?? { firstLine: suspect.line, lastLine: suspect.line }; +} + +// How far a finding sits from the suspect, or `undefined` when it does not match at all. Two suspects +// in one window (two rules, one file) each get their own finding: the nearest unclaimed one wins. +export type Distance = (finding: FindingRow) => number | undefined; + +export function standardsDistance(finding: FindingRow, suspect: Suspect, spans: ReadonlyArray<WindowSpan>): number | undefined { + // Stryker disable next-line ConditionalExpression: the kind check only narrows; a non-line location has no `file`, so the file check alone returns undefined + if (finding.location.kind !== 'line' || finding.location.file !== suspect.file) return undefined; + const { firstLine, lastLine } = spanOf(suspect, spans); + const inside = finding.location.line >= firstLine && finding.location.line <= lastLine; + return inside ? Math.abs(finding.location.line - suspect.line) : undefined; +} + +export function specDistance(finding: FindingRow, suspect: SpecSuspect): number | undefined { + // Stryker disable next-line ConditionalExpression: the kind check only narrows; a non-requirement location has no `requirement`, so the id check alone fails + return finding.location.kind === 'requirement' && finding.location.requirement === suspect.requirement ? 0 : undefined; +} + +function sameSuspect(ref: SuspectRef, suspect: SuspectRef): boolean { + return formatSuspectRef(ref) === formatSuspectRef(suspect); +} + +function nearestUnclaimed(input: OriginsInput, distanceOf: Distance, claimed: Set<string>): FindingRow | undefined { + let best: { readonly finding: FindingRow; readonly distance: number } | undefined; + for (const candidate of input.findings) { + if (claimed.has(candidate.id) || !candidate.sources.includes(JEV_SOURCE)) continue; + const distance = distanceOf(candidate); + if (distance === undefined) continue; + if (best === undefined || distance < best.distance) best = { finding: candidate, distance }; + } + return best?.finding; +} + +function fateOf(ref: SuspectRef, distanceOf: Distance, input: OriginsInput, claimed: Set<string>): SuspectFate { + const drop = input.drops.find((entry: DropEntry) => sameSuspect(entry.suspect, ref)); + if (drop !== undefined) return { fate: 'dropped', reason: drop.reason }; + const finding = nearestUnclaimed(input, distanceOf, claimed); + if (finding === undefined) return { fate: 'dropped', reason: NOT_REPORTED }; + claimed.add(finding.id); + return originOf(finding.sources) === 'both' ? { fate: 'merged', finding: finding.id } : { fate: 'confirmed', finding: finding.id }; +} + +function specSuspects(record: SidecarRecord): ReadonlyArray<SpecSuspect> { + return record.spec.status === 'ok' ? record.spec.suspects : []; +} + +function withFate(scored: ScoredSuspect, fate: SuspectFate): SuspectFateRecord { + switch (fate.fate) { + case 'confirmed': + return { ...scored, fate: 'confirmed', finding: fate.finding }; + case 'merged': + return { ...scored, fate: 'merged', finding: fate.finding }; + case 'dropped': + return { ...scored, fate: 'dropped', reason: fate.reason }; + } +} + +export function assignOrigins(record: SidecarRecord, input: OriginsInput, recordedAt: string): OriginsRecord { + const claimed = new Set<string>(); + const standards = record.standards.suspects.map((suspect) => { + const ref: SuspectRef = { kind: 'standards', rule: suspect.rule, file: suspect.file, line: suspect.line }; + return withFate({ suspect: ref, score: suspect.score }, fateOf(ref, (finding) => standardsDistance(finding, suspect, record.windows), input, claimed)); + }); + const spec = specSuspects(record).map((suspect) => { + const ref: SuspectRef = { kind: 'spec', requirement: suspect.requirement }; + return withFate({ suspect: ref, score: suspect.score }, fateOf(ref, (finding) => specDistance(finding, suspect), input, claimed)); + }); + return { + recordedAt, + findings: input.findings.map((finding) => ({ + id: finding.id, + axis: finding.axis, + sources: finding.sources, + origin: originOf(finding.sources), + location: finding.location, + rule: finding.rule, + claim: finding.claim, + })), + suspects: [ ...standards, ...spec ], + }; +} diff --git a/tools/review-screen/origins/parse.spec.ts b/tools/review-screen/origins/parse.spec.ts new file mode 100644 index 00000000000..4882d264930 --- /dev/null +++ b/tools/review-screen/origins/parse.spec.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from 'vitest'; + +import { formatSuspectRef, parseLocation, parseOriginsInput, parseSuspectRef } from './parse'; + +const MARKDOWN = `## Findings + +| id | axis | location | sources | +| --- | --- | --- | --- | +| F1 | correctness | \`src/a.ts:41\` | correctness, jev | +| F2 | standards | \`src/b.ts:7\` | standards | +| F3 | spec | FR3 | jev | +| F4 | spec | — | spec | + +Some prose between the tables. + +| suspect | fate | reason | +| --- | --- | --- | +| \`no-comments src/c.ts:12\` | dropped | the comment explains a workaround | +| FR5 | dropped | addressed in the PR description | +| \`no-comments src/a.ts:41\` | confirmed | F1 | +`; + +const JSON_INPUT = JSON.stringify([ + { id: 'F1', axis: 'correctness', location: 'src/a.ts:41', sources: [ 'correctness', 'jev' ] }, + { id: 'F2', axis: 'standards', location: 'src/b.ts:7', sources: 'standards' }, + { id: 'F3', axis: 'spec', location: 'FR3', sources: [ 'jev' ] }, + { id: 'F4', axis: 'spec', location: '—', sources: [ 'spec' ] }, + { suspect: 'no-comments src/c.ts:12', fate: 'dropped', reason: 'the comment explains a workaround' }, + { suspect: 'FR5', fate: 'dropped', reason: 'addressed in the PR description' }, + { suspect: 'no-comments src/a.ts:41', fate: 'confirmed', finding: 'F1' }, +]); + +const UNLABELLED = { rule: undefined, claim: undefined }; + +const EXPECTED = { + findings: [ + { id: 'F1', axis: 'correctness', location: { kind: 'line', file: 'src/a.ts', line: 41 }, sources: [ 'correctness', 'jev' ], ...UNLABELLED }, + { id: 'F2', axis: 'standards', location: { kind: 'line', file: 'src/b.ts', line: 7 }, sources: [ 'standards' ], ...UNLABELLED }, + { id: 'F3', axis: 'spec', location: { kind: 'requirement', requirement: 'FR3' }, sources: [ 'jev' ], ...UNLABELLED }, + { id: 'F4', axis: 'spec', location: { kind: 'none' }, sources: [ 'spec' ], ...UNLABELLED }, + ], + drops: [ + { suspect: { kind: 'standards', rule: 'no-comments', file: 'src/c.ts', line: 12 }, reason: 'the comment explains a workaround' }, + { suspect: { kind: 'spec', requirement: 'FR5' }, reason: 'addressed in the PR description' }, + ], +}; + +describe('parseOriginsInput', () => { + it('reads the findings table and the drop list from Markdown, ignoring prose and confirmed rows', () => { + expect(parseOriginsInput(MARKDOWN)).toEqual(EXPECTED); + }); + + it('reads the same two lists from a JSON array', () => { + expect(parseOriginsInput(JSON_INPUT)).toEqual(EXPECTED); + }); + + it('accepts a findings table with no rows and no drop table', () => { + expect(parseOriginsInput('| id | axis | location | sources |\n| --- | --- | --- | --- |\n')).toEqual({ findings: [], drops: [] }); + expect(parseOriginsInput('[]')).toEqual({ findings: [], drops: [] }); + }); + + it('reads a numeric id as text, missing sources as none, and drops empty or dash sources from a list or a cell', () => { + const json = JSON.stringify([ + { id: 7, axis: 'spec', location: 'FR1', sources: [ 'jev', '', ' ' ] }, + { id: 'F2', axis: 'spec', location: 'FR2' }, + { suspect: 'FR5', fate: 'dropped' }, + ]); + expect(parseOriginsInput(json)).toEqual({ + findings: [ + { id: '7', axis: 'spec', location: { kind: 'requirement', requirement: 'FR1' }, sources: [ 'jev' ], ...UNLABELLED }, + { id: 'F2', axis: 'spec', location: { kind: 'requirement', requirement: 'FR2' }, sources: [], ...UNLABELLED }, + ], + drops: [ { suspect: { kind: 'spec', requirement: 'FR5' }, reason: '' } ], + }); + + const markdown = '| id | axis | location | sources |\n| --- | --- | --- | --- |\n| F1 | spec | FR1 | — |\n| F2 | spec | FR2 | `, jev` |\n'; + expect(parseOriginsInput(markdown).findings.map((row) => row.sources)).toEqual([ [], [ 'jev' ] ]); + }); + + it('reads the rule label and the claim when the table carries them, a dash or an empty cell as none', () => { + const markdown = [ + '| id | axis | rule | location | sources | claim |', + '| --- | --- | --- | --- | --- | --- |', + '| F1 | standards | `explanatory-comment` | src/a.ts:3 | standards | The comment restates the line below. |', + '| F2 | standards | — | src/b.ts:9 | standards | |', + '| F3 | correctness | | src/c.ts:1 | correctness | — |', + ].join('\n'); + expect(parseOriginsInput(markdown).findings.map(({ rule, claim }) => ({ rule, claim }))).toEqual([ + { rule: 'explanatory-comment', claim: 'The comment restates the line below.' }, + { rule: undefined, claim: undefined }, + { rule: undefined, claim: undefined }, + ]); + + const json = JSON.stringify([ { id: 'F1', axis: 'standards', location: 'src/a.ts:3', sources: [ 'standards' ], rule: 'magic-number', claim: 7 } ]); + expect(parseOriginsInput(json).findings[0]).toMatchObject({ rule: 'magic-number', claim: undefined }); + }); + + it('rejects Markdown without a findings table, a JSON value that is not an array, and a row missing a column', () => { + expect(() => parseOriginsInput('| suspect | fate | reason |\n| --- | --- | --- |\n')).toThrow('No findings table'); + expect(() => parseOriginsInput('{ "id": "F1" }')).toThrow('No findings table'); + expect(() => parseOriginsInput('[ { "id": "F1", "axis": "spec" } ]')).toThrow('Missing "location"'); + expect(() => parseOriginsInput('[ 1 ]')).toThrow('Expected an object'); + expect(() => parseOriginsInput('[ null ]')).toThrow('Expected an object'); + expect(() => parseOriginsInput('[ [] ]')).toThrow('Expected an object'); + }); + + it('does not take a pipe block for a table without a separator row under the header', () => { + expect(() => parseOriginsInput('| id | axis | location | sources |\n| F1 | spec | FR1 | jev |\n')).toThrow('No findings table'); + }); +}); + +describe('parseLocation', () => { + it('reads a file and line, a requirement id, and the no-location dash, with or without backticks', () => { + expect(parseLocation('`src/slices/token/pages/Holders.tsx:41`')).toEqual({ kind: 'line', file: 'src/slices/token/pages/Holders.tsx', line: 41 }); + expect(parseLocation('FR12')).toEqual({ kind: 'requirement', requirement: 'FR12' }); + expect(parseLocation('—')).toEqual({ kind: 'none' }); + expect(parseLocation('')).toEqual({ kind: 'none' }); + }); + + it('rejects a path with no line', () => { + expect(() => parseLocation('src/a.ts')).toThrow('Cannot read finding location: src/a.ts'); + }); +}); + +describe('parseSuspectRef', () => { + it('round-trips through formatSuspectRef', () => { + const standards = parseSuspectRef('rule-without-mechanism .agents/rules/x.md:3'); + expect(standards).toEqual({ kind: 'standards', rule: 'rule-without-mechanism', file: '.agents/rules/x.md', line: 3 }); + expect(formatSuspectRef(standards)).toBe('rule-without-mechanism .agents/rules/x.md:3'); + expect(formatSuspectRef(parseSuspectRef('FR2'))).toBe('FR2'); + }); + + it('rejects a reference without a rule or without a line', () => { + expect(() => parseSuspectRef('src/a.ts:3')).toThrow('Cannot read suspect reference'); + expect(() => parseSuspectRef('no-comments src/a.ts')).toThrow('Cannot read suspect reference'); + }); +}); diff --git a/tools/review-screen/origins/parse.ts b/tools/review-screen/origins/parse.ts new file mode 100644 index 00000000000..ebac3789a90 --- /dev/null +++ b/tools/review-screen/origins/parse.ts @@ -0,0 +1,197 @@ +// The review's final findings table plus the `jev` axis's drop list, from one input: a JSON array or the +// Markdown tables the review publishes. Whatever the form, the output is the same two lists, so the +// matching in `./match.ts` never sees the format. + +export const JEV_SOURCE = 'jev'; + +export type FindingLocation = + { readonly kind: 'line'; readonly file: string; readonly line: number } | + { readonly kind: 'requirement'; readonly requirement: string } | + { readonly kind: 'none' }; + +export interface FindingRow { + readonly id: string; + readonly axis: string; + readonly location: FindingLocation; + readonly sources: ReadonlyArray<string>; + readonly rule: string | undefined; + readonly claim: string | undefined; +} + +export type SuspectRef = + { readonly kind: 'standards'; readonly rule: string; readonly file: string; readonly line: number } | + { readonly kind: 'spec'; readonly requirement: string }; + +export interface DropEntry { + readonly suspect: SuspectRef; + readonly reason: string; +} + +export interface OriginsInput { + readonly findings: ReadonlyArray<FindingRow>; + readonly drops: ReadonlyArray<DropEntry>; +} + +const NO_LOCATION = '—'; +const REQUIREMENT_ID = /^FR\d+$/; +const FILE_AND_LINE = /^(.+):(\d+)$/; +const FINDING_COLUMNS = [ 'id', 'axis', 'location', 'sources' ] as const; +const DROP_COLUMNS = [ 'suspect', 'fate', 'reason' ] as const; + +function isRecord(value: unknown): value is Record<string, unknown> { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function unquote(cell: string): string { + return cell.trim().replace(/^`(.*)`$/, '$1').trim(); +} + +export function parseLocation(raw: string): FindingLocation { + const text = unquote(raw); + if (text === '' || text === NO_LOCATION) return { kind: 'none' }; + if (REQUIREMENT_ID.test(text)) return { kind: 'requirement', requirement: text }; + const match = FILE_AND_LINE.exec(text); + if (match === null) throw new Error(`Cannot read finding location: ${ raw }`); + return { kind: 'line', file: match[1], line: Number(match[2]) }; +} + +// A standards suspect is named `<rule> <file>:<line>`, a spec suspect by its requirement id. +export function parseSuspectRef(raw: string): SuspectRef { + const text = unquote(raw); + if (REQUIREMENT_ID.test(text)) return { kind: 'spec', requirement: text }; + const space = text.lastIndexOf(' '); + const match = space === -1 ? null : FILE_AND_LINE.exec(text.slice(space + 1)); + if (match === null) throw new Error(`Cannot read suspect reference (expected "<rule> <file>:<line>" or "FR<n>"): ${ raw }`); + return { kind: 'standards', rule: text.slice(0, space).trim(), file: match[1], line: Number(match[2]) }; +} + +export function formatSuspectRef(ref: SuspectRef): string { + return ref.kind === 'spec' ? ref.requirement : `${ ref.rule } ${ ref.file }:${ ref.line }`; +} + +function parseSources(raw: unknown): Array<string> { + if (Array.isArray(raw)) return raw.map((source) => String(source).trim()).filter((source) => source !== ''); + if (typeof raw === 'string') return unquote(raw).split(/[,\s]+/).map((source) => source.trim()).filter((source) => source !== '' && source !== NO_LOCATION); + return []; +} + +function readString(row: Record<string, unknown>, key: string): string { + const value = row[key]; + if (typeof value !== 'string' && typeof value !== 'number') throw new Error(`Missing "${ key }" in ${ JSON.stringify(row) }`); + return String(value); +} + +function readOptional(row: Record<string, unknown>, key: string): string | undefined { + const value = row[key]; + if (typeof value !== 'string') return undefined; + const text = unquote(value); + return text === '' || text === NO_LOCATION ? undefined : text; +} + +function findingOf(row: Record<string, unknown>): FindingRow { + return { + id: readString(row, 'id').trim(), + axis: unquote(readString(row, 'axis')), + location: parseLocation(readString(row, 'location')), + sources: parseSources(row.sources), + rule: readOptional(row, 'rule'), + claim: readOptional(row, 'claim'), + }; +} + +// A confirmed suspect reaches the tool as a finding, so only `dropped` rows carry information here. +function dropOf(row: Record<string, unknown>): DropEntry | undefined { + if (unquote(readString(row, 'fate')) !== 'dropped') return undefined; + return { + suspect: parseSuspectRef(readString(row, 'suspect')), + reason: typeof row.reason === 'string' ? unquote(row.reason) : '', + }; +} + +function collect(rows: ReadonlyArray<Record<string, unknown>>): OriginsInput { + const findings: Array<FindingRow> = []; + const drops: Array<DropEntry> = []; + for (const row of rows) { + if ('fate' in row) { + const drop = dropOf(row); + if (drop !== undefined) drops.push(drop); + } else { + findings.push(findingOf(row)); + } + } + return { findings, drops }; +} + +function fromJson(entries: ReadonlyArray<unknown>): OriginsInput { + const rows = entries.map((entry) => { + if (!isRecord(entry)) throw new Error(`Expected an object, got ${ JSON.stringify(entry) }`); + return entry; + }); + return collect(rows); +} + +function splitRow(line: string): Array<string> { + return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell) => cell.trim()); +} + +function isSeparatorRow(cells: ReadonlyArray<string>): boolean { + return cells.every((cell) => /^:?-+:?$/.test(cell)); +} + +interface MarkdownTable { + readonly header: ReadonlyArray<string>; + readonly rows: Array<Record<string, string>>; +} + +function hasColumns(table: MarkdownTable, columns: ReadonlyArray<string>): boolean { + return columns.every((column) => table.header.includes(column)); +} + +// Every pipe table in the text, its rows keyed by the lower-cased header cells. +function markdownTables(text: string): Array<MarkdownTable> { + const tables: Array<MarkdownTable> = []; + let header: Array<string> | undefined; + let table: MarkdownTable | undefined; + for (const line of text.split('\n')) { + if (!line.trim().startsWith('|')) { + header = undefined; + table = undefined; + continue; + } + const cells = splitRow(line); + if (header === undefined) { + header = cells.map((cell) => cell.toLowerCase()); + continue; + } + if (table === undefined) { + if (isSeparatorRow(cells)) { + table = { header, rows: [] }; + tables.push(table); + } else { + header = undefined; + } + continue; + } + table.rows.push(Object.fromEntries(header.map((column, index) => [ column, cells[index] ?? '' ]))); + } + return tables; +} + +function fromMarkdown(text: string): OriginsInput { + const tables = markdownTables(text); + const findingTables = tables.filter((table) => hasColumns(table, FINDING_COLUMNS)); + const dropTables = tables.filter((table) => hasColumns(table, DROP_COLUMNS)); + if (findingTables.length === 0) throw new Error('No findings table (| id | axis | location | sources |) in the input'); + return collect([ ...findingTables, ...dropTables ].flatMap((table) => table.rows)); +} + +export function parseOriginsInput(text: string): OriginsInput { + const trimmed = text.trim(); + if (trimmed.startsWith('[')) { + const parsed: unknown = JSON.parse(trimmed); + // Stryker disable next-line ConditionalExpression: JSON text that starts with "[" parses to an array or throws, so this guard only narrows the type + if (!Array.isArray(parsed)) throw new Error('A JSON findings input must be an array'); + return fromJson(parsed); + } + return fromMarkdown(trimmed); +} diff --git a/tools/review-screen/report/aggregate.spec.ts b/tools/review-screen/report/aggregate.spec.ts new file mode 100644 index 00000000000..c960d4d77e8 --- /dev/null +++ b/tools/review-screen/report/aggregate.spec.ts @@ -0,0 +1,249 @@ +import { describe, expect, it } from 'vitest'; + +import type { OriginsRecord, SuspectFateRecord } from '../origins/match'; +import type { SidecarRecord } from '../sidecar'; +import type { SidecarFile } from './aggregate'; +import { addedSecondsOf, aggregateReport, inputTokensOf } from './aggregate'; + +const RULES = { + ids: [ 'explanatory-comment', 'magic-number' ], + thresholdOf: (rule: string) => rule === 'magic-number' ? 0.6 : 0.7, + sweepThresholds: [ 0.5, 0.7 ], +}; + +function call(ms: number, inputTokens: number): SidecarRecord['calls'][number] { + return { kind: 'noul', file: 'src/a.ts', window: 0, ms, usage: { input_tokens: inputTokens, output_tokens: 10 } }; +} + +function standardsSuspect(rule: string, fate: SuspectFateRecord['fate'], reasonOrFinding: string = 'F1'): SuspectFateRecord { + const suspect = { kind: 'standards' as const, rule, file: 'src/a.ts', line: 5 }; + if (fate === 'dropped') return { suspect, score: 0.8, fate, reason: reasonOrFinding }; + return { suspect, score: 0.8, fate, finding: reasonOrFinding }; +} + +function specSuspect(fate: SuspectFateRecord['fate'], reasonOrFinding: string = 'F1'): SuspectFateRecord { + const suspect = { kind: 'spec' as const, requirement: 'FR1' }; + if (fate === 'dropped') return { suspect, score: 0.3, fate, reason: reasonOrFinding }; + return { suspect, score: 0.3, fate, finding: reasonOrFinding }; +} + +function origins( + suspects: ReadonlyArray<SuspectFateRecord>, + findingOrigins: ReadonlyArray<OriginsRecord['findings'][number]['origin']> = [], +): OriginsRecord { + return { + recordedAt: '2026-09-28T12:00:00.000Z', + findings: findingOrigins.map((origin, index) => ({ + id: `F${ index + 1 }`, + axis: 'standards', + sources: [ 'jev' ], + origin, + location: undefined, + rule: undefined, + claim: undefined, + })), + suspects, + }; +} + +function sidecar(file: string, overrides: Partial<SidecarRecord> = {}): SidecarFile { + return { + file, + record: { + version: 1, + createdAt: '2026-09-28T11:00:00.000Z', + status: 'ok', + reason: undefined, + calibration: false, + model: 'jev-1.13.0', + inputs: { scope: 'branch', base: 'abc', branch: 'issue-1', ticket: undefined, spec: undefined, files: [] }, + windows: [], + standards: { cells: [], suspects: [], cut: 0 }, + spec: { status: 'no-spec' }, + calls: [], + elapsedMs: undefined, + origins: undefined, + ...overrides, + }, + }; +} + +describe('aggregateReport', () => { + it('leaves calibration runs out and lists reviews without origins as pending, counting neither', () => { + const report = aggregateReport([ + sidecar('calibration.json', { + calibration: true, + origins: origins([ standardsSuspect('magic-number', 'confirmed') ], [ 'jev' ]), + calls: [ call(9000, 100) ], + }), + sidecar('pending.json', { calls: [ call(9000, 100) ] }), + sidecar('calibration-pending.json', { calibration: true }), + sidecar('counted.json', { origins: origins([]) }), + ], RULES); + + expect(report.pending).toEqual([ 'pending.json' ]); + expect(report.totals).toEqual({ + reviews: 1, + pending: 1, + findings: { jev: 0, axis: 0, both: 0 }, + addedSeconds: { mean: 0, max: 0 }, + meanInputTokens: 0, + }); + expect(report.rules.every((row) => row.sent === 0)).toBe(true); + }); + + it('aggregates fates per rule across reviews, spec suspects as one row, with the most frequent drop reason', () => { + const report = aggregateReport([ + sidecar('one.json', { origins: origins([ + standardsSuspect('magic-number', 'confirmed'), + standardsSuspect('magic-number', 'dropped', 'pre-existing'), + standardsSuspect('magic-number', 'dropped', 'not reported'), + specSuspect('dropped', 'outside the diff'), + ]) }), + sidecar('two.json', { origins: origins([ + standardsSuspect('magic-number', 'dropped', 'pre-existing'), + standardsSuspect('magic-number', 'merged'), + standardsSuspect('legacy-rule', 'confirmed'), + specSuspect('confirmed'), + ]) }), + ], RULES); + + expect(report.rules).toEqual([ + { rule: 'explanatory-comment', sent: 0, confirmed: 0, merged: 0, dropped: 0, topDropReason: undefined }, + { rule: 'magic-number', sent: 5, confirmed: 1, merged: 1, dropped: 3, topDropReason: 'pre-existing' }, + { rule: 'legacy-rule', sent: 1, confirmed: 1, merged: 0, dropped: 0, topDropReason: undefined }, + { rule: 'spec', sent: 2, confirmed: 1, merged: 0, dropped: 1, topDropReason: 'outside the diff' }, + ]); + }); + + it('picks the most frequent drop reason even when it is seen after a rarer one', () => { + const report = aggregateReport([ + sidecar('one.json', { origins: origins([ + standardsSuspect('magic-number', 'dropped', 'rare'), + standardsSuspect('magic-number', 'dropped', 'common'), + standardsSuspect('magic-number', 'dropped', 'common'), + ]) }), + ], RULES); + + expect(report.rules[1].topDropReason).toBe('common'); + }); + + it('keeps the first-seen reason when drop reasons tie', () => { + const report = aggregateReport([ + sidecar('one.json', { origins: origins([ + standardsSuspect('magic-number', 'dropped', 'second'), + standardsSuspect('magic-number', 'dropped', 'first'), + standardsSuspect('magic-number', 'dropped', 'first'), + standardsSuspect('magic-number', 'dropped', 'second'), + ]) }), + ], RULES); + + expect(report.rules[1].topDropReason).toBe('second'); + }); + + it('counts finding origins across reviews, including a skipped review whose findings are all axis', () => { + const report = aggregateReport([ + sidecar('one.json', { origins: origins([], [ 'jev', 'both', 'axis' ]) }), + sidecar('skipped.json', { status: 'skipped', reason: 'no key', origins: origins([], [ 'axis', 'axis' ]) }), + ], RULES); + + expect(report.totals.reviews).toBe(2); + expect(report.totals.findings).toEqual({ jev: 1, axis: 3, both: 1 }); + }); + + it('reports zero seconds and tokens when no review is counted', () => { + const report = aggregateReport([ sidecar('pending.json', { calls: [ call(9000, 100) ] }) ], RULES); + + expect(report.totals).toEqual({ + reviews: 0, + pending: 1, + findings: { jev: 0, axis: 0, both: 0 }, + addedSeconds: { mean: 0, max: 0 }, + meanInputTokens: 0, + }); + }); + + it('reports the wall-clock seconds per review as mean and max, and the mean input tokens', () => { + const report = aggregateReport([ + sidecar('one.json', { origins: origins([]), elapsedMs: 2000, calls: [ call(1500, 600), call(1500, 400) ] }), + sidecar('two.json', { origins: origins([]), elapsedMs: 6000, calls: [ call(6000, 3000) ] }), + sidecar('skipped.json', { status: 'skipped', reason: 'no key', origins: origins([]) }), + ], RULES); + + expect(report.totals.addedSeconds).toEqual({ mean: (2 + 6 + 0) / 3, max: 6 }); + expect(report.totals.meanInputTokens).toBe((1000 + 3000 + 0) / 3); + }); +}); + +function labelledFinding(id: string, file: string, claim: string | undefined): OriginsRecord['findings'][number] { + return { id, axis: 'standards', sources: [ 'standards' ], origin: 'axis', location: { kind: 'line', file, line: 5 }, rule: 'magic-number', claim }; +} + +describe('aggregateReport tuning rows', () => { + it('carries the per-rule near misses, the sweep at the given thresholds and the coverage totals', () => { + const report = aggregateReport([ + sidecar('one.json', { + windows: [ { file: 'src/a.ts', window: 0, firstLine: 1, lastLine: 20 } ], + standards: { cells: [ { rule: 'magic-number', file: 'src/a.ts', window: 0, score: 0.55 } ], suspects: [], cut: 0 }, + origins: { + recordedAt: '2026-09-28T12:00:00.000Z', + findings: [ + labelledFinding('F1', 'src/a.ts', 'A bare 4.'), + labelledFinding('F2', 'src/b.ts', undefined), + ], + suspects: [], + }, + }), + ], RULES); + + expect(report.nearMisses).toEqual([ + { rule: 'explanatory-comment', labelled: 0, noCell: 0, scores: undefined }, + { rule: 'magic-number', labelled: 2, noCell: 1, scores: { min: 0.55, median: 0.55, max: 0.55 } }, + ]); + expect(report.sweep).toEqual([ + { rule: 'explanatory-comment', threshold: 0.7, at: [ { threshold: 0.5, hit: 0, noise: 0, missed: 0 }, { threshold: 0.7, hit: 0, noise: 0, missed: 0 } ] }, + { rule: 'magic-number', threshold: 0.6, at: [ { threshold: 0.5, hit: 1, noise: 0, missed: 0 }, { threshold: 0.7, hit: 0, noise: 0, missed: 1 } ] }, + ]); + expect(report.coverage).toEqual({ standardsFindings: 2, noCell: 1, outsideWindows: 0, unlocated: 0 }); + }); + + it('reads only counted reviews into the tuning rows, never a calibration or pending one', () => { + const labelled: OriginsRecord = { recordedAt: '2026-09-28T12:00:00.000Z', findings: [ labelledFinding('F1', 'src/a.ts', undefined) ], suspects: [] }; + const cells = [ { rule: 'magic-number', file: 'src/a.ts', window: 0, score: 0.9 } ]; + const report = aggregateReport([ + sidecar('calibration.json', { calibration: true, origins: labelled, standards: { cells, suspects: [], cut: 0 } }), + sidecar('pending.json', { standards: { cells, suspects: [], cut: 0 } }), + ], RULES); + + expect(report.nearMisses[1]).toEqual({ rule: 'magic-number', labelled: 0, noCell: 0, scores: undefined }); + expect(report.sweep[1].at).toEqual([ { threshold: 0.5, hit: 0, noise: 0, missed: 0 }, { threshold: 0.7, hit: 0, noise: 0, missed: 0 } ]); + expect(report.coverage).toEqual({ standardsFindings: 0, noCell: 0, outsideWindows: 0, unlocated: 0 }); + }); + + it('keeps a skipped or failed review out of the tuning rows while still counting its findings', () => { + const labelled: OriginsRecord = { recordedAt: '2026-09-28T12:00:00.000Z', findings: [ labelledFinding('F1', 'src/a.ts', undefined) ], suspects: [] }; + const partial = [ { rule: 'magic-number', file: 'src/a.ts', window: 0, score: 0.3 } ]; + const report = aggregateReport([ + sidecar('skipped.json', { status: 'skipped', reason: 'no key', origins: labelled }), + sidecar('failed.json', { status: 'failed', reason: 'api', origins: labelled, standards: { cells: partial, suspects: [], cut: 0 } }), + ], RULES); + + expect(report.totals.findings).toEqual({ jev: 0, axis: 2, both: 0 }); + expect(report.nearMisses[1]).toEqual({ rule: 'magic-number', labelled: 0, noCell: 0, scores: undefined }); + expect(report.sweep[1].at).toEqual([ { threshold: 0.5, hit: 0, noise: 0, missed: 0 }, { threshold: 0.7, hit: 0, noise: 0, missed: 0 } ]); + expect(report.coverage).toEqual({ standardsFindings: 0, noCell: 0, outsideWindows: 0, unlocated: 0 }); + }); +}); + +describe('per-review sums', () => { + it('reads the wall-clock span in seconds, not the sum of the overlapping calls', () => { + const { record } = sidecar('one.json', { elapsedMs: 1500, calls: [ call(1000, 100), call(1000, 250) ] }); + expect(addedSecondsOf(record)).toBe(1.5); + expect(inputTokensOf(record)).toBe(350); + }); + + it('falls back to the summed call timings for a sidecar written without a span', () => { + const { record } = sidecar('old.json', { calls: [ call(250, 100), call(750, 250) ] }); + expect(addedSecondsOf(record)).toBe(1); + }); +}); diff --git a/tools/review-screen/report/aggregate.ts b/tools/review-screen/report/aggregate.ts new file mode 100644 index 00000000000..55cc8ee38e1 --- /dev/null +++ b/tools/review-screen/report/aggregate.ts @@ -0,0 +1,160 @@ +import type { OriginsRecord, SuspectFateRecord } from '../origins/match'; +import type { SidecarRecord } from '../sidecar'; +import type { CoverageTotals, NearMissRow, SweepRow } from './tuning'; +import { coverageTotals, nearMissRows, sweepRows } from './tuning'; + +// The pilot table's numbers, from the sidecars alone. A calibration run is left out; a review whose +// `--origins` has not run yet is listed as pending and counts nowhere, because without fates every +// suspect would read as dropped. + +export const SPEC_ROW = 'spec'; + +export interface SidecarFile { + readonly file: string; + readonly record: SidecarRecord; +} + +export interface RuleRow { + readonly rule: string; + readonly sent: number; + readonly confirmed: number; + readonly merged: number; + readonly dropped: number; + readonly topDropReason: string | undefined; +} + +export interface ReportTotals { + readonly reviews: number; + readonly pending: number; + readonly findings: { readonly jev: number; readonly axis: number; readonly both: number }; + readonly addedSeconds: { readonly mean: number; readonly max: number }; + readonly meanInputTokens: number; +} + +export interface PilotReport { + readonly rules: ReadonlyArray<RuleRow>; + readonly nearMisses: ReadonlyArray<NearMissRow>; + readonly sweep: ReadonlyArray<SweepRow>; + readonly coverage: CoverageTotals; + readonly totals: ReportTotals; + readonly pending: ReadonlyArray<string>; +} + +export interface ReportRules { + readonly ids: ReadonlyArray<string>; + readonly thresholdOf: (rule: string) => number; + readonly sweepThresholds: ReadonlyArray<number>; +} + +interface CountedRecord extends SidecarRecord { + readonly origins: OriginsRecord; +} + +interface Counted extends SidecarFile { + readonly record: CountedRecord; +} + +function isCounted(sidecar: SidecarFile): sidecar is Counted { + return sidecar.record.origins !== undefined; +} + +// A skipped run has no cells and a failed one a partial grid (the pool stops at the first error, and the +// sidecar does not say which grid failed), so either would read as glob misses or missed cells. +function isFullyScored(record: CountedRecord): boolean { + return record.status === 'ok'; +} + +function rowKey(entry: SuspectFateRecord): string { + return entry.suspect.kind === 'spec' ? SPEC_ROW : entry.suspect.rule; +} + +function topReason(reasons: ReadonlyArray<string>): string | undefined { + const counts = new Map<string, number>(); + for (const reason of reasons) counts.set(reason, (counts.get(reason) ?? 0) + 1); + let top: string | undefined; + let topCount = 0; + for (const [ reason, count ] of counts) { + if (count > topCount) { + top = reason; + topCount = count; + } + } + return top; +} + +function ruleRow(rule: string, entries: ReadonlyArray<SuspectFateRecord>): RuleRow { + const dropped = entries.filter((entry) => entry.fate === 'dropped'); + return { + rule, + sent: entries.length, + confirmed: entries.filter((entry) => entry.fate === 'confirmed').length, + merged: entries.filter((entry) => entry.fate === 'merged').length, + dropped: dropped.length, + topDropReason: topReason(dropped.map((entry) => entry.reason)), + }; +} + +// Rubric order first, so a rule that never fired still shows its zero row; rules the rubric no +// longer has follow, and the spec grid is always the last row. +function rowOrder(ruleIds: ReadonlyArray<string>, seen: ReadonlySet<string>): Array<string> { + const extra = [ ...seen ].filter((rule) => rule !== SPEC_ROW && !ruleIds.includes(rule)).sort(); + return [ ...ruleIds, ...extra, SPEC_ROW ]; +} + +function ruleRows(counted: ReadonlyArray<Counted>, ruleIds: ReadonlyArray<string>): Array<RuleRow> { + const byRule = new Map<string, Array<SuspectFateRecord>>(); + for (const { record } of counted) { + for (const entry of record.origins.suspects) { + const key = rowKey(entry); + byRule.set(key, [ ...(byRule.get(key) ?? []), entry ]); + } + } + return rowOrder(ruleIds, new Set(byRule.keys())).map((rule) => ruleRow(rule, byRule.get(rule) ?? [])); +} + +function mean(values: ReadonlyArray<number>): number { + return values.length === 0 ? 0 : values.reduce((sum, value) => sum + value, 0) / values.length; +} + +// Milliseconds to seconds; `src/toolkit/utils/consts` sits outside this tool's tsconfig rootDir. +const MS_PER_SECOND = 1_000; + +export function addedSecondsOf(record: SidecarRecord): number { + const ms = record.elapsedMs ?? record.calls.reduce((sum, call) => sum + call.ms, 0); + return ms / MS_PER_SECOND; +} + +export function inputTokensOf(record: SidecarRecord): number { + return record.calls.reduce((sum, call) => sum + call.usage.input_tokens, 0); +} + +function totals(counted: ReadonlyArray<Counted>, pending: number): ReportTotals { + const findings = counted.flatMap(({ record }) => record.origins.findings); + const seconds = counted.map(({ record }) => addedSecondsOf(record)); + return { + reviews: counted.length, + pending, + findings: { + jev: findings.filter((finding) => finding.origin === 'jev').length, + axis: findings.filter((finding) => finding.origin === 'axis').length, + both: findings.filter((finding) => finding.origin === 'both').length, + }, + addedSeconds: { mean: mean(seconds), max: seconds.length === 0 ? 0 : Math.max(...seconds) }, + meanInputTokens: mean(counted.map(({ record }) => inputTokensOf(record))), + }; +} + +export function aggregateReport(sidecars: ReadonlyArray<SidecarFile>, rules: ReportRules): PilotReport { + const pilot = sidecars.filter((sidecar) => !sidecar.record.calibration); + const counted = pilot.filter(isCounted); + const pending = pilot.filter((sidecar) => !isCounted(sidecar)).map((sidecar) => sidecar.file); + const scored = counted.map((sidecar) => sidecar.record).filter(isFullyScored); + return { + rules: ruleRows(counted, rules.ids), + nearMisses: nearMissRows(scored, rules.ids), + sweep: sweepRows(scored, rules.ids, rules.sweepThresholds, rules.thresholdOf), + coverage: coverageTotals(scored), + totals: totals(counted, pending.length), + pending, + }; +} diff --git a/tools/review-screen/report/render.spec.ts b/tools/review-screen/report/render.spec.ts new file mode 100644 index 00000000000..a2ea19faf19 --- /dev/null +++ b/tools/review-screen/report/render.spec.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from 'vitest'; + +import type { PilotReport } from './aggregate'; +import { renderReport, renderReportJson, renderTable } from './render'; + +const REPORT: PilotReport = { + rules: [ + { rule: 'magic-number', sent: 5, confirmed: 1, merged: 1, dropped: 3, topDropReason: 'pre-existing' }, + { rule: 'spec', sent: 0, confirmed: 0, merged: 0, dropped: 0, topDropReason: undefined }, + ], + nearMisses: [ + { rule: 'magic-number', labelled: 3, noCell: 1, scores: { min: 0.4, median: 0.625, max: 0.8 } }, + { rule: 'no-comments', labelled: 0, noCell: 0, scores: undefined }, + ], + sweep: [ + { rule: 'magic-number', threshold: 0.7, at: [ { threshold: 0.5, hit: 2, noise: 1, missed: 0 }, { threshold: 0.7, hit: 1, noise: 0, missed: 1 } ] }, + { rule: 'no-comments', threshold: 0.5, at: [ { threshold: 0.5, hit: 0, noise: 0, missed: 0 }, { threshold: 0.7, hit: 0, noise: 0, missed: 0 } ] }, + ], + coverage: { standardsFindings: 4, noCell: 1, outsideWindows: 1, unlocated: 2 }, + totals: { + reviews: 2, + pending: 1, + findings: { jev: 1, axis: 3, both: 1 }, + addedSeconds: { mean: 4.25, max: 6 }, + meanInputTokens: 1333.4, + }, + pending: [ '2026-09-28-issue-1-branch.json' ], +}; + +describe('renderTable', () => { + it('pads every column to its widest cell and never leaves trailing spaces', () => { + expect(renderTable([ 'a', 'bb' ], [ [ 'xxx', 'y' ] ])).toBe('a bb\n--- --\nxxx y'); + }); +}); + +describe('renderReport', () => { + it('prints the rule table, the totals and the pending list', () => { + expect(renderReport(REPORT)).toBe([ + 'rule sent confirmed merged dropped top drop reason', + '------------ ---- --------- ------ ------- ---------------', + 'magic-number 5 1 1 3 pre-existing', + 'spec 0 0 0 0 —', + '', + 'rule labelled no cell file score min / median / max', + '------------ -------- ------- -----------------------------', + 'magic-number 3 1 0.40 / 0.63 / 0.80', + 'no-comments 0 0 —', + '', + 'rule threshold 0.5 hit/noise/missed 0.7 hit/noise/missed', + '------------ --------- -------------------- --------------------', + 'magic-number 0.7 2/1/0 1/0/1', + 'no-comments 0.5 0/0/0 0/0/0', + '', + 'reviews: 2 counted · 1 pending origins', + 'findings: jev 1 / axis 3 / both 1', + 'added seconds per review: mean 4.3 · max 6.0', + 'input tokens per review: mean 1333', + 'coverage: 4 standards findings · 1 in a file with no cell · 1 on a line outside every window · 2 with no location recorded', + '', + 'pending origins:', + ' 2026-09-28-issue-1-branch.json', + ].join('\n')); + }); + + it('clips a long drop reason and omits the pending section when nothing is pending', () => { + const reason = 'x'.repeat(80); + const output = renderReport({ ...REPORT, pending: [], rules: [ { ...REPORT.rules[0], topDropReason: reason } ] }); + expect(output).toContain(` ${ 'x'.repeat(59) }…\n`); + expect(output).not.toContain(reason); + expect(output).not.toContain('pending origins:'); + }); + + it('keeps a drop reason that just fits and clips one a character longer', () => { + const fits = 'y'.repeat(60); + const longer = 'z'.repeat(61); + const output = renderReport({ ...REPORT, pending: [], rules: [ + { ...REPORT.rules[0], topDropReason: fits }, + { ...REPORT.rules[1], topDropReason: longer }, + ] }); + expect(output).toContain(` ${ fits }\n`); + expect(output).toContain(` ${ 'z'.repeat(59) }…`); + expect(output).not.toContain(longer); + }); +}); + +describe('renderReport with no sweep rows', () => { + it('prints the sweep table header with the rule and threshold columns only', () => { + expect(renderReport({ ...REPORT, sweep: [], pending: [] })).toContain('rule threshold\n---- ---------\n'); + }); +}); + +describe('renderReportJson', () => { + it('is the report itself, pretty-printed', () => { + expect(JSON.parse(renderReportJson(REPORT))).toEqual(REPORT); + }); +}); diff --git a/tools/review-screen/report/render.ts b/tools/review-screen/report/render.ts new file mode 100644 index 00000000000..9f1d0295190 --- /dev/null +++ b/tools/review-screen/report/render.ts @@ -0,0 +1,79 @@ +import type { PilotReport, RuleRow } from './aggregate'; +import type { NearMissRow, SweepRow } from './tuning'; + +const MAX_REASON_CHARS = 60; +const NONE = '—'; + +const RULE_HEADERS = [ 'rule', 'sent', 'confirmed', 'merged', 'dropped', 'top drop reason' ] as const; +const NEAR_MISS_HEADERS = [ 'rule', 'labelled', 'no cell', 'file score min / median / max' ] as const; +const SWEEP_RULE_HEADER = 'rule'; +const SWEEP_THRESHOLD_HEADER = 'threshold'; +const SCORE_DECIMALS = 2; + +function clip(text: string): string { + return text.length <= MAX_REASON_CHARS ? text : `${ text.slice(0, MAX_REASON_CHARS - 1) }…`; +} + +function ruleCells(row: RuleRow): Array<string> { + const reason = row.topDropReason === undefined ? NONE : clip(row.topDropReason); + return [ row.rule, String(row.sent), String(row.confirmed), String(row.merged), String(row.dropped), reason ]; +} + +function score(value: number): string { + return value.toFixed(SCORE_DECIMALS); +} + +function nearMissCells(row: NearMissRow): Array<string> { + const spread = row.scores === undefined ? NONE : `${ score(row.scores.min) } / ${ score(row.scores.median) } / ${ score(row.scores.max) }`; + return [ row.rule, String(row.labelled), String(row.noCell), spread ]; +} + +function sweepHeaders(rows: ReadonlyArray<SweepRow>): Array<string> { + const thresholds = rows[0]?.at.map((count) => `${ count.threshold } hit/noise/missed`) ?? []; + return [ SWEEP_RULE_HEADER, SWEEP_THRESHOLD_HEADER, ...thresholds ]; +} + +function sweepCells(row: SweepRow): Array<string> { + return [ row.rule, String(row.threshold), ...row.at.map((count) => `${ count.hit }/${ count.noise }/${ count.missed }`) ]; +} + +function coverageLine(report: PilotReport): string { + const { coverage } = report; + return [ + `coverage: ${ coverage.standardsFindings } standards findings`, + `${ coverage.noCell } in a file with no cell`, + `${ coverage.outsideWindows } on a line outside every window`, + `${ coverage.unlocated } with no location recorded`, + ].join(' · '); +} + +export function renderTable(headers: ReadonlyArray<string>, rows: ReadonlyArray<ReadonlyArray<string>>): string { + const widths = headers.map((header, column) => Math.max(header.length, ...rows.map((row) => row[column].length))); + const line = (cells: ReadonlyArray<string>): string => cells.map((cell, column) => cell.padEnd(widths[column])).join(' ').trimEnd(); + return [ line(headers), line(widths.map((width) => '-'.repeat(width))), ...rows.map(line) ].join('\n'); +} + +function totalsLines(report: PilotReport): Array<string> { + const { totals } = report; + return [ + `reviews: ${ totals.reviews } counted · ${ totals.pending } pending origins`, + `findings: jev ${ totals.findings.jev } / axis ${ totals.findings.axis } / both ${ totals.findings.both }`, + `added seconds per review: mean ${ totals.addedSeconds.mean.toFixed(1) } · max ${ totals.addedSeconds.max.toFixed(1) }`, + `input tokens per review: mean ${ Math.round(totals.meanInputTokens) }`, + ]; +} + +export function renderReport(report: PilotReport): string { + const sections = [ + renderTable(RULE_HEADERS, report.rules.map(ruleCells)), + renderTable(NEAR_MISS_HEADERS, report.nearMisses.map(nearMissCells)), + renderTable(sweepHeaders(report.sweep), report.sweep.map(sweepCells)), + [ ...totalsLines(report), coverageLine(report) ].join('\n'), + ]; + if (report.pending.length > 0) sections.push([ 'pending origins:', ...report.pending.map((file) => ` ${ file }`) ].join('\n')); + return sections.join('\n\n'); +} + +export function renderReportJson(report: PilotReport): string { + return JSON.stringify(report, null, 2); +} diff --git a/tools/review-screen/report/tuning.spec.ts b/tools/review-screen/report/tuning.spec.ts new file mode 100644 index 00000000000..8ad610fce42 --- /dev/null +++ b/tools/review-screen/report/tuning.spec.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from 'vitest'; + +import type { FindingOriginRecord } from '../origins/match'; +import type { SidecarRecord } from '../sidecar'; +import { bestCellsOf, coverageTotals, nearMissRows, sweepRows } from './tuning'; + +const RULE = 'magic-number'; +const OTHER_RULE = 'no-comments'; + +function labelled(id: string, file: string, line: number, rule: string | undefined = RULE, axis: string = 'standards'): FindingOriginRecord { + return { id, axis, sources: [ 'standards' ], origin: 'axis', location: { kind: 'line', file, line }, rule, claim: undefined }; +} + +function record(overrides: Partial<SidecarRecord>): SidecarRecord { + return { + version: 1, + createdAt: '2026-09-28T11:00:00.000Z', + status: 'ok', + reason: undefined, + calibration: false, + model: 'jev-1.13.0', + inputs: { scope: 'branch', base: 'abc', branch: 'issue-1', ticket: undefined, spec: undefined, files: [] }, + windows: [ { file: 'src/a.ts', window: 0, firstLine: 1, lastLine: 10 }, { file: 'src/a.ts', window: 1, firstLine: 40, lastLine: 60 } ], + standards: { + cells: [ + { rule: RULE, file: 'src/a.ts', window: 0, score: 0.3 }, + { rule: RULE, file: 'src/a.ts', window: 1, score: 0.65 }, + { rule: RULE, file: 'src/b.ts', window: 0, score: 0.8 }, + { rule: RULE, file: 'src/c.ts', window: 0, score: 0.45 }, + { rule: OTHER_RULE, file: 'src/a.ts', window: 0, score: 0.9 }, + { rule: OTHER_RULE, file: 'src/d.ts', window: 0, score: 0.2 }, + ], + suspects: [], + cut: 0, + }, + spec: { status: 'no-spec' }, + calls: [], + elapsedMs: undefined, + origins: undefined, + ...overrides, + }; +} + +function withFindings(findings: ReadonlyArray<FindingOriginRecord>, overrides: Partial<SidecarRecord> = {}): SidecarRecord { + return record({ origins: { recordedAt: '2026-09-28T12:00:00.000Z', findings, suspects: [] }, ...overrides }); +} + +describe('bestCellsOf', () => { + it('keeps the highest window score per rule and file', () => { + const best = bestCellsOf(record({})); + expect(best.get(RULE)?.get('src/a.ts')).toBe(0.65); + expect(best.get(OTHER_RULE)?.get('src/a.ts')).toBe(0.9); + expect(best.get(RULE)?.get('src/d.ts')).toBeUndefined(); + expect(best.get('unused-rule')).toBeUndefined(); + }); +}); + +describe('nearMissRows', () => { + it('counts the findings labelled with the rule, those in a file the rule has no cell for, and the spread of the rest', () => { + const records = [ + withFindings([ labelled('F1', 'src/a.ts', 5), labelled('F2', 'src/b.ts', 1), labelled('F3', 'src/z.ts', 1), labelled('F4', 'src/a.ts', 2, OTHER_RULE) ]), + withFindings([ labelled('F1', 'src/c.ts', 3) ]), + ]; + expect(nearMissRows(records, [ RULE, OTHER_RULE, 'unused-rule' ])).toEqual([ + { rule: RULE, labelled: 4, noCell: 1, scores: { min: 0.45, median: 0.65, max: 0.8 } }, + { rule: OTHER_RULE, labelled: 1, noCell: 0, scores: { min: 0.9, median: 0.9, max: 0.9 } }, + { rule: 'unused-rule', labelled: 0, noCell: 0, scores: undefined }, + ]); + }); + + it('takes the median of an even count as the mean of the middle two', () => { + const records = [ withFindings([ labelled('F1', 'src/c.ts', 3), labelled('F2', 'src/b.ts', 1) ]) ]; + expect(nearMissRows(records, [ RULE ])[0].scores).toEqual({ min: 0.45, median: 0.625, max: 0.8 }); + }); + + it('counts a labelled finding without a line, or one recorded without a location, as none', () => { + const noLine: FindingOriginRecord = { ...labelled('F1', 'src/a.ts', 5), location: { kind: 'none' } }; + const unlocated: FindingOriginRecord = { ...labelled('F2', 'src/a.ts', 5), location: undefined }; + expect(nearMissRows([ withFindings([ noLine, unlocated ]) ], [ RULE ])[0]).toEqual({ rule: RULE, labelled: 0, noCell: 0, scores: undefined }); + }); + + it('reads nothing from a record whose origins were never recorded', () => { + expect(nearMissRows([ record({}) ], [ RULE ])[0]).toEqual({ rule: RULE, labelled: 0, noCell: 0, scores: undefined }); + }); +}); + +describe('sweepRows', () => { + it('splits every best cell of the rule into hit, noise or missed at each threshold', () => { + const records = [ withFindings([ labelled('F1', 'src/a.ts', 5), labelled('F2', 'src/c.ts', 1), labelled('F3', 'src/z.ts', 1) ]) ]; + const thresholdOf = (rule: string): number => rule === RULE ? 0.6 : 0.7; + expect(sweepRows(records, [ RULE, OTHER_RULE ], [ 0.4, 0.5, 0.7 ], thresholdOf)).toEqual([ + { rule: RULE, threshold: 0.6, at: [ + { threshold: 0.4, hit: 2, noise: 1, missed: 0 }, + { threshold: 0.5, hit: 1, noise: 1, missed: 1 }, + { threshold: 0.7, hit: 0, noise: 1, missed: 2 }, + ] }, + { rule: OTHER_RULE, threshold: 0.7, at: [ + { threshold: 0.4, hit: 0, noise: 1, missed: 0 }, + { threshold: 0.5, hit: 0, noise: 1, missed: 0 }, + { threshold: 0.7, hit: 0, noise: 1, missed: 0 }, + ] }, + ]); + }); + + it('counts a cell exactly at the threshold as over it', () => { + const records = [ withFindings([ labelled('F1', 'src/a.ts', 5) ]) ]; + expect(sweepRows(records, [ RULE ], [ 0.65 ], () => 0.7)[0].at[0]).toEqual({ threshold: 0.65, hit: 1, noise: 1, missed: 0 }); + expect(sweepRows(records, [ RULE ], [ 0.1 ], () => 0.7)[0].at[0]).toEqual({ threshold: 0.1, hit: 1, noise: 2, missed: 0 }); + }); + + it('labels a file by a finding of the same rule only, per review', () => { + const first = withFindings([ labelled('F1', 'src/a.ts', 5, OTHER_RULE) ]); + const second = withFindings([ labelled('F1', 'src/a.ts', 5) ]); + expect(sweepRows([ first, second ], [ RULE ], [ 0.6 ], () => 0.7)[0].at[0]).toEqual({ threshold: 0.6, hit: 1, noise: 3, missed: 0 }); + }); +}); + +describe('coverageTotals', () => { + it('counts standards findings in a file with no cell, on a line outside every window, or recorded without a location', () => { + const findings: ReadonlyArray<FindingOriginRecord> = [ + labelled('F1', 'src/a.ts', 5), + labelled('F2', 'src/a.ts', 20), + labelled('F3', 'src/z.ts', 1), + { ...labelled('F4', 'src/a.ts', 5), location: undefined }, + { ...labelled('F5', 'src/a.ts', 5), location: { kind: 'none' } }, + labelled('F6', 'src/z.ts', 1, undefined, 'correctness'), + labelled('F7', 'src/b.ts', 5), + ]; + expect(coverageTotals([ withFindings(findings) ])).toEqual({ standardsFindings: 6, noCell: 1, outsideWindows: 2, unlocated: 1 }); + }); + + it('takes a line on a window edge as inside it', () => { + expect(coverageTotals([ withFindings([ labelled('F1', 'src/a.ts', 10), labelled('F2', 'src/a.ts', 40), labelled('F3', 'src/a.ts', 11) ]) ])) + .toMatchObject({ outsideWindows: 1 }); + }); + + it('is all zero with no counted review', () => { + expect(coverageTotals([])).toEqual({ standardsFindings: 0, noCell: 0, outsideWindows: 0, unlocated: 0 }); + }); +}); diff --git a/tools/review-screen/report/tuning.ts b/tools/review-screen/report/tuning.ts new file mode 100644 index 00000000000..b5d9ceefa7f --- /dev/null +++ b/tools/review-screen/report/tuning.ts @@ -0,0 +1,150 @@ +import { median } from 'es-toolkit'; + +import type { FindingOriginRecord } from '../origins/match'; +import type { FindingLocation } from '../origins/parse'; +import type { SidecarRecord } from '../sidecar'; + +export interface ScoreSpread { + readonly min: number; + readonly median: number; + readonly max: number; +} + +export interface NearMissRow { + readonly rule: string; + readonly labelled: number; + readonly noCell: number; + readonly scores: ScoreSpread | undefined; +} + +export interface SweepCount { + readonly threshold: number; + readonly hit: number; + readonly noise: number; + readonly missed: number; +} + +export interface SweepRow { + readonly rule: string; + readonly threshold: number; + readonly at: ReadonlyArray<SweepCount>; +} + +export interface CoverageTotals { + readonly standardsFindings: number; + readonly noCell: number; + readonly outsideWindows: number; + // Findings recorded before `--origins` kept the location; they count in none of the above. + readonly unlocated: number; +} + +interface LineFinding { + readonly record: SidecarRecord; + readonly finding: FindingOriginRecord; + readonly file: string; + readonly line: number; +} + +// Rule → file → the highest window score, the cell the threshold is applied to. +type BestCells = ReadonlyMap<string, ReadonlyMap<string, number>>; + +export function bestCellsOf(record: SidecarRecord): BestCells { + const best = new Map<string, Map<string, number>>(); + for (const cell of record.standards.cells) { + const files = best.get(cell.rule) ?? new Map<string, number>(); + files.set(cell.file, Math.max(files.get(cell.file) ?? 0, cell.score)); + best.set(cell.rule, files); + } + return best; +} + +function lineFindings(records: ReadonlyArray<SidecarRecord>, keep: (finding: FindingOriginRecord) => boolean): Array<LineFinding> { + return records.flatMap((record) => record.origins === undefined ? [] : record.origins.findings.flatMap((finding) => { + const location: FindingLocation | undefined = finding.location; + if (!keep(finding) || location === undefined || location.kind !== 'line') return []; + return [ { record, finding, file: location.file, line: location.line } ]; + })); +} + +function spreadOf(scores: ReadonlyArray<number>): ScoreSpread | undefined { + if (scores.length === 0) return undefined; + return { min: Math.min(...scores), median: median([ ...scores ]), max: Math.max(...scores) }; +} + +interface LabelledCells { + readonly scores: Array<number>; + readonly noCell: number; +} + +function labelledCells(rule: string, findings: ReadonlyArray<LineFinding>, bestByRecord: ReadonlyMap<SidecarRecord, BestCells>): LabelledCells { + const scores: Array<number> = []; + let noCell = 0; + for (const entry of findings) { + const score = bestByRecord.get(entry.record)?.get(rule)?.get(entry.file); + if (score === undefined) noCell += 1; + else scores.push(score); + } + return { scores, noCell }; +} + +export function nearMissRows(records: ReadonlyArray<SidecarRecord>, ruleIds: ReadonlyArray<string>): Array<NearMissRow> { + const bestByRecord = new Map(records.map((record) => [ record, bestCellsOf(record) ] as const)); + return ruleIds.map((rule) => { + const labelled = lineFindings(records, (finding) => finding.rule === rule); + const { scores, noCell } = labelledCells(rule, labelled, bestByRecord); + return { rule, labelled: labelled.length, noCell, scores: spreadOf(scores) }; + }); +} + +interface SweepCell { + readonly score: number; + readonly labelled: boolean; +} + +function sweepCellsOf(rule: string, record: SidecarRecord): Array<SweepCell> { + const labelledFiles = new Set(lineFindings([ record ], (finding) => finding.rule === rule).map((entry) => entry.file)); + const files = bestCellsOf(record).get(rule) ?? new Map<string, number>(); + return [ ...files ].map(([ file, score ]) => ({ score, labelled: labelledFiles.has(file) })); +} + +function countAt(threshold: number, cells: ReadonlyArray<SweepCell>): SweepCount { + const over = cells.filter((cell) => cell.score >= threshold); + return { + threshold, + hit: over.filter((cell) => cell.labelled).length, + noise: over.filter((cell) => !cell.labelled).length, + missed: cells.filter((cell) => cell.score < threshold && cell.labelled).length, + }; +} + +export function sweepRows( + records: ReadonlyArray<SidecarRecord>, + ruleIds: ReadonlyArray<string>, + thresholds: ReadonlyArray<number>, + thresholdOf: (rule: string) => number, +): Array<SweepRow> { + return ruleIds.map((rule) => { + const cells = records.flatMap((record) => sweepCellsOf(rule, record)); + return { rule, threshold: thresholdOf(rule), at: thresholds.map((threshold) => countAt(threshold, cells)) }; + }); +} + +const STANDARDS_AXIS = 'standards'; + +function isOutsideWindows(entry: LineFinding): boolean { + return !entry.record.windows.some((span) => span.file === entry.file && span.firstLine <= entry.line && entry.line <= span.lastLine); +} + +export function coverageTotals(records: ReadonlyArray<SidecarRecord>): CoverageTotals { + const standards = records.flatMap((record) => record.origins?.findings.filter((finding) => finding.axis === STANDARDS_AXIS) ?? []); + const located = lineFindings(records, (finding) => finding.axis === STANDARDS_AXIS); + const scoredFiles = new Map(records.map((record) => [ record, new Set(record.standards.cells.map((cell) => cell.file)) ] as const)); + const noCell = located.filter((entry) => !scoredFiles.get(entry.record)?.has(entry.file)); + const outsideWindows = located.filter((entry) => scoredFiles.get(entry.record)?.has(entry.file) && isOutsideWindows(entry)); + return { + standardsFindings: standards.length, + noCell: noCell.length, + outsideWindows: outsideWindows.length, + unlocated: standards.filter((finding) => finding.location === undefined).length, + }; +} diff --git a/tools/review-screen/rubric.spec.ts b/tools/review-screen/rubric.spec.ts new file mode 100644 index 00000000000..c4e170d96c5 --- /dev/null +++ b/tools/review-screen/rubric.spec.ts @@ -0,0 +1,65 @@ +import { existsSync } from 'node:fs'; +import { matchesGlob, resolve } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +import type { Rule } from './rubric'; +import { MAX_RULES, MIN_RULES, RULES } from './rubric'; + +const REPO_ROOT = resolve(import.meta.dirname, '../..'); + +const REPO_PATH_SHAPES = [ + 'src/slices/tx/components/TxDetails.tsx', + 'src/api/utils/build-url.ts', + 'tools/review-screen/rubric.ts', + '.agents/rules/code-quality.md', + 'src/api/CONTEXT.md', + 'docs/ENVS.md', + 'tools/cli/README.md', +]; + +const MAX_ENTRY_LENGTH = 160; + +describe('rubric', () => { + it('has between 8 and 10 rules', () => { + expect(MIN_RULES).toBe(8); + expect(MAX_RULES).toBe(10); + expect(RULES.length).toBeGreaterThanOrEqual(MIN_RULES); + expect(RULES.length).toBeLessThanOrEqual(MAX_RULES); + }); + + it('gives every rule a unique id', () => { + const ids = RULES.map((rule) => rule.id); + expect(new Set(ids).size).toBe(ids.length); + }); + + describe.each(RULES.map((rule) => [ rule.id, rule ] as const))('%s', (_id: string, rule: Rule) => { + it('has a kebab-case id', () => { + expect(rule.id).toMatch(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/); + }); + + it('cites a rule file that exists in the repo', () => { + expect(existsSync(resolve(REPO_ROOT, rule.cites))).toBe(true); + }); + + it('uses a valid glob that matches a repo-relative path', () => { + expect(() => matchesGlob('a', rule.glob)).not.toThrow(); + expect(REPO_PATH_SHAPES.filter((path) => matchesGlob(path, rule.glob))).not.toEqual([]); + }); + + it('asks a single affirmative yes/no question', () => { + expect(rule.question).toMatch(/^Does .+\?$/); + expect(rule.question).not.toMatch(/\bnot\b/); + }); + + it('keeps examples and not_for as arrays of short strings', () => { + for (const list of [ rule.examples, rule.not_for ]) { + expect(Array.isArray(list)).toBe(true); + for (const entry of list as Array<unknown>) { + expect(typeof entry).toBe('string'); + expect((entry as string).length).toBeLessThanOrEqual(MAX_ENTRY_LENGTH); + } + } + }); + }); +}); diff --git a/tools/review-screen/rubric.ts b/tools/review-screen/rubric.ts new file mode 100644 index 00000000000..40c54a5a8ba --- /dev/null +++ b/tools/review-screen/rubric.ts @@ -0,0 +1,211 @@ +import type { EntryType } from '@typesafe-ai/sdk'; + +export interface Rule { + readonly id: string; + readonly cites: string; + readonly glob: string; + readonly question: string; + readonly examples: EntryType; + readonly not_for: EntryType; +} + +export const MIN_RULES = 8; +export const MAX_RULES = 10; + +export const RULES: ReadonlyArray<Rule> = [ + { + id: 'explanatory-comment', + cites: '.agents/rules/code-quality.md', + glob: '**/*.{ts,tsx}', + question: 'Does the changed code add a comment that describes what the code does instead of why the obvious approach fails?', + examples: [ + 'a comment that restates the line below it ("memoize the filtered list")', + 'a file-opening or fixture-opening comment that says what the file or object contains ("the shape every phase takes")', + 'a JSDoc block that repeats the function name, its parameter names or its types', + 'diff narration: what the change replaced ("replaces the old useEffect", "previously this used X")', + 'commented-out code', + 'a TODO with no issue link and no concrete follow-up', + 'a section banner ("// helpers", "// types")', + ], + not_for: [ + 'a comment explaining a quirk, workaround or invariant the code cannot show, optionally with an issue link', + 'the reason on an eslint-disable, on a double cast, or on a raw color value', + 'a `TODO (api-data):` scaffold marker', + 'an SPDX license header', + 'a comment that was already present and is only moved or reindented', + ], + }, + { + id: 'magic-number', + cites: '.agents/rules/code-quality.md', + glob: 'src/**/*.{ts,tsx}', + question: 'Does the changed code use a bare literal for a limit, threshold, interval, size or key whose meaning a reader would still have to ask about?', + examples: [ + 'items.slice(0, 4) where 4 is a product limit', + 'setTimeout(handler, 5000) or refetchInterval: 2_000 instead of SECOND / MINUTE from src/toolkit/utils/consts', + 'if (list.length > 20) with no name for 20', + 'a local unit constant such as MS_IN_SECOND = 1_000', + 'a repeated string discriminator or storage key spelled out at several call sites', + ], + not_for: [ + '1 as the first page, 0 as the first index, -1 from indexOf', + 'a URL, a route path, a file name, a label string', + 'CSS-style props: margin, padding, gap, width, font weight, color, border radius, z-index', + 'a literal assigned to an UPPER_SNAKE_CASE constant above the component or function', + 'a constant that only restates the value it names (FIRST_PAGE = 1)', + ], + }, + { + id: 'inline-empty-default', + cites: '.agents/rules/code-quality.md', + glob: 'src/**/*.{ts,tsx}', + question: 'Does the changed code create an empty array or object literal inline as a fallback or default value inside a component or hook body?', + examples: [ + 'const items = data?.items ?? [];', + 'const filters = props.filters || {};', + 'function List({ items = [] }: Props)', + 'useQuery({ ... , placeholderData: [] })', + ], + not_for: [ + 'a module-level constant such as const EMPTY_ITEMS: Array<Item> = []; used as the fallback', + 'useState([]) or useState({}) initial values', + 'an empty literal used once as a local accumulator (reduce, push) and never passed on', + 'code outside a React component or hook: utils, config modules, server code, tests', + ], + }, + { + id: 'derived-array-without-memo', + cites: '.agents/rules/code-quality.md', + glob: 'src/**/*.tsx', + question: 'Does the changed code pass a .filter(), .map() or .reduce() result computed during render as a prop or hook dependency without useMemo?', + examples: [ + 'const filtered = items.filter(isActive); return <List items={ filtered }/>;', + '<Select options={ tokens.map(toOption) }/>', + 'useEffect(() => { ... }, [ items.map(getId) ]);', + ], + not_for: [ + '.map() used directly in JSX to render children', + 'a derived array used only inside the same render body and never passed to a child or a hook', + 'a derived array already wrapped in useMemo or computed in a custom hook that memoizes it', + 'derived arrays computed outside a component or hook', + ], + }, + { + id: 'route-string-concat', + cites: '.agents/rules/code-quality.md', + glob: 'src/**/*.{ts,tsx}', + question: 'Does the changed code build a link to an application page from a string literal, concatenation or template instead of the route utilities?', + examples: [ + 'href={ `/tx/${ hash }` }', + 'router.push(\'/address/\' + address)', + '<Link href="/blocks">', + ], + not_for: [ + 'route({ pathname: \'/tx/[hash]\', query: { hash } }) from src/shared/router/routes', + 'a URL to an external site or to another Blockscout instance', + 'an API path template in src/api/resources or a fetch URL', + 'a pathname compared or matched in server code (middleware, rewrites, CSP)', + 'a URL inside a *.spec.ts / *.spec.tsx / *.pw.tsx file or a mock', + ], + }, + { + id: 'raw-style-value', + cites: '.agents/rules/design-system.md', + glob: 'src/**/*.tsx', + question: 'Does the changed JSX set a style prop to a raw CSS value where the design system defines a token for that property?', + examples: [ + 'color="#1a1a1a", bg="rgb(0, 0, 0)", borderColor="hsl(...)"', + 'fontSize="14px" or lineHeight="20px" instead of textStyle="sm"', + 'borderRadius="12px" instead of borderRadius="md"', + 'fontWeight={ 600 } instead of fontWeight="semibold"', + 'zIndex={ 1000 } instead of zIndex="modal"', + 'boxShadow="0 2px 4px rgba(...)" instead of boxShadow="size.md"', + ], + not_for: [ + 'a token reference: text.secondary, blue.50, github, textStyle="heading.md", borderRadius="lg"', + 'width, height, padding, margin, gap or position values, which have no token table', + 'a raw color value with a comment explaining the third-party embed that requires it', + 'files under src/toolkit/theme/ that define the tokens', + 'CSS overrides for a third-party widget that does not read the theme', + ], + }, + { + id: 'inline-date-format', + cites: '.agents/rules/code-quality.md', + glob: 'src/**/*.tsx', + question: 'Does the changed code format a date or timestamp for display without the shared Time or TimeWithTooltip component?', + examples: [ + 'dayjs(timestamp).format(\'lll\') rendered straight into JSX', + 'new Date(timestamp).toLocaleString() or toLocaleDateString() in a component', + 'dayjs(timestamp).fromNow() as a component\'s own text', + ], + not_for: [ + '<Time timestamp={ ... }/> or <TimeWithTooltip timestamp={ ... }/> from src/shared/date-and-time', + 'dayjs used for arithmetic, comparison or parsing, with no formatted string shown to the user', + 'the source of the Time components themselves under src/shared/date-and-time/', + 'a chart axis or tooltip formatter, a CSV export cell, or a <time dateTime> attribute', + ], + }, + { + id: 'compound-part-spacing', + cites: '.agents/rules/design-system.md', + glob: 'src/**/*.tsx', + question: 'Does the changed JSX set padding or margin on an internal part of a compound component from src/toolkit/chakra?', + examples: [ + '<DialogHeader px={ 6 }> or <DialogBody pt={ 0 }>', + '<MenuItem py={ 2 }> or <MenuContent p={ 4 }>', + '<TabsTrigger px={ 3 }> or <PopoverContent p={ 2 }>', + ], + not_for: [ + 'spacing on the root of a compound component (DialogRoot, MenuRoot, TabsRoot) or on its trigger', + 'spacing on a layout primitive: Box, Flex, Grid, Stack, HStack, VStack', + 'spacing on a plain child placed inside a compound part', + 'the toolkit files under src/toolkit/ that define the compound components', + ], + }, + { + id: 'rule-without-mechanism', + cites: '.agents/skills/review-changes/prose-smells.md', + glob: '.agents/**/*.md', + question: 'Does the changed instruction text state something an agent must ensure without giving the command, file or probe that establishes it?', + examples: [ + '"check whether a PR already exists" with no gh command', + '"make sure the tests pass" with no test command named', + '"verify the component matches the mockup" with no Figma node or fixture named', + '"confirm the endpoint is available" with no URL, skill or curl given', + ], + not_for: [ + 'a statement that points at the skill, file or section that holds the mechanism', + 'a fact, a definition, a rationale or a description of context', + 'a step that names the command, the file to read, or the ordered checks to run', + 'a `[human]` step that a developer does by hand', + 'a spec or ticket file under .agents/tasks/', + ], + }, + { + id: 'code-restating-doc', + cites: '.agents/rules/docs.md', + glob: '{**/CONTEXT.md,docs/**/*.md,**/README.md,.agents/**/*.md}', + question: 'Does the changed documentation text repeat something the code or another doc already states?', + examples: [ + 'a walk-through of control flow: "X runs Y, then Z parses the result and maps it onto W"', + 'a list of a function\'s parameters, props or return type', + 'a restated package.json script or --help output', + 'a procedure, command or recipe copied from another doc or skill, with or without a pointer to it', + 'a sample that is a verbatim copy of a source file', + 'a value the config or workflow file already holds ("after 14 days", "on port 3000")', + 'a directory listing that the file system already gives', + 'a description of what the change replaced', + ], + not_for: [ + 'navigation: which directory or file to open for what', + 'a constraint an editor must keep true, and what breaks if they do not', + 'a gotcha: the surprise and its consequence, not the mechanism', + 'local vocabulary a term means only in this area', + 'a pointer or link to an ADR, a rule file or another doc', + 'a reference table that is the authoritative list, such as the env vars in docs/ENVS.md', + 'a README of a published package that documents a public API for its consumers', + 'a spec or ticket file under .agents/tasks/', + ], + }, +]; diff --git a/tools/review-screen/run.sh b/tools/review-screen/run.sh new file mode 100755 index 00000000000..47899e6533c --- /dev/null +++ b/tools/review-screen/run.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# Usage: tools/review-screen/run.sh [--scope branch|uncommitted] [--base <ref>] [--spec <path>] [--ticket <NN>] [--calibration] +# tools/review-screen/run.sh --origins <sidecar> --findings <path|-> +# tools/review-screen/run.sh --report [--json] + +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" + +# The tool imports the shared flag parser from ../cli and the git plumbing from ../code-complexity, so +# tsc's rootDir spans the tools folder and the entry point lands one level deeper than the outDir. +"$ROOT/node_modules/.bin/tsc" -p "$DIR/tsconfig.json" +node "$DIR/dist/review-screen/index.js" "$@" diff --git a/tools/review-screen/select/change.spec.ts b/tools/review-screen/select/change.spec.ts new file mode 100644 index 00000000000..fa5842bdc5b --- /dev/null +++ b/tools/review-screen/select/change.spec.ts @@ -0,0 +1,133 @@ +import { execFileSync } from 'child_process'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import type { ChangeRequest } from './change'; +import { resolveChange } from './change'; + +// A throwaway repository, addressed by path, so the assertions do not depend on what this branch +// happens to have changed. `git init -b main` because the tool's default base branch is `main`. +let repo = ''; + +afterEach(() => { + if (repo) fs.rmSync(repo, { recursive: true, force: true }); + repo = ''; +}); + +function git(...args: Array<string>): string { + const stdio: Array<'ignore' | 'pipe'> = [ 'ignore', 'pipe', 'ignore' ]; + return execFileSync('git', [ '-c', 'user.email=t@t.t', '-c', 'user.name=t', ...args ], { cwd: repo, encoding: 'utf8', stdio }); +} + +function write(filePath: string, body: string): void { + const target = path.join(repo, filePath); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, body); +} + +// main: src/base.ts, .agents/tasks/12-thing/{spec.md,progress.md}; then src/landed-later.ts after the fork. +// issue-12: commits src/touched.ts and deletes src/base.ts; leaves src/edited.ts modified and +// src/new.ts untracked in the working tree. +function createForkedRepo(): void { + repo = fs.mkdtempSync(path.join(os.tmpdir(), 'review-screen-change-')); + git('init', '-b', 'main'); + write('src/base.ts', 'export const base = 1;\n'); + write('src/edited.ts', 'export const edited = 1;\n'); + write('.agents/tasks/12-thing/spec.md', '# Spec\n'); + write('.agents/tasks/12-thing/progress.md', '- [x] 01 → `tickets/01-a/`\n- [ ] 02 → `tickets/02-b/`\n- [ ] 03 → `tickets/03-c/`\n'); + git('add', '.'); + git('commit', '-m', 'base'); + + git('checkout', '-b', 'issue-12'); + write('src/touched.ts', 'export const touched = 1;\n'); + git('rm', '-q', 'src/base.ts'); + git('add', '.'); + git('commit', '-m', 'feature'); + + git('checkout', 'main'); + write('src/landed-later.ts', 'export const landedLater = 1;\n'); + git('add', '.'); + git('commit', '-m', 'landed later'); + + git('checkout', 'issue-12'); + write('src/edited.ts', 'export const edited = 2;\n'); + write('src/new.ts', 'export const fresh = 1;\n'); +} + +function resolve(overrides: Partial<ChangeRequest>): ReturnType<typeof resolveChange> { + return resolveChange({ scope: 'branch', base: undefined, spec: undefined, ticket: undefined, ...overrides }, repo); +} + +describe('resolveChange', () => { + it('under --scope branch, diffs from the merge-base with main and lists untracked files, never base-branch churn', () => { + createForkedRepo(); + const change = resolve({ scope: 'branch' }); + expect(change.base).toBe(git('merge-base', 'main', 'HEAD').trim()); + expect(change.files).toEqual([ + { path: 'src/edited.ts', untracked: false }, + { path: 'src/new.ts', untracked: true }, + { path: 'src/touched.ts', untracked: false }, + ]); + expect(change.branch).toBe('issue-12'); + }); + + it('under --scope uncommitted, diffs HEAD against the working tree', () => { + createForkedRepo(); + const change = resolve({ scope: 'uncommitted' }); + expect(change.base).toBe('HEAD'); + expect(change.files).toEqual([ + { path: 'src/edited.ts', untracked: false }, + { path: 'src/new.ts', untracked: true }, + ]); + }); + + it('takes an explicit --base verbatim', () => { + createForkedRepo(); + expect(resolve({ base: 'main' }).base).toBe('main'); + expect(resolve({ scope: 'uncommitted', base: 'main~1' }).base).toBe('main~1'); + }); + + it('resolves the task spec from the issue branch, and takes an explicit --spec verbatim', () => { + createForkedRepo(); + expect(resolve({}).spec).toBe('.agents/tasks/12-thing/spec.md'); + expect(resolve({ spec: 'elsewhere/spec.md' }).spec).toBe('elsewhere/spec.md'); + }); + + it('records no spec when the branch has no task folder', () => { + createForkedRepo(); + git('checkout', '-b', 'not-a-task'); + expect(resolve({}).spec).toBeUndefined(); + git('checkout', '-b', 'issue-99'); + expect(resolve({}).spec).toBeUndefined(); + }); + + it('records no spec, without throwing, when the checkout has no tasks directory at all', () => { + createForkedRepo(); + fs.rmSync(path.join(repo, '.agents'), { recursive: true, force: true }); + expect(resolve({}).spec).toBeUndefined(); + }); + + it('infers the ticket in flight from progress.md only under --scope uncommitted', () => { + createForkedRepo(); + expect(resolve({ scope: 'uncommitted' }).ticket).toBe('02'); + expect(resolve({ scope: 'branch' }).ticket).toBeUndefined(); + expect(resolve({ scope: 'branch', ticket: '05' }).ticket).toBe('05'); + }); + + it('records no ticket, without throwing, when there is no task folder or no progress.md to read', () => { + createForkedRepo(); + fs.rmSync(path.join(repo, '.agents/tasks/12-thing/progress.md')); + expect(resolve({ scope: 'uncommitted' }).ticket).toBeUndefined(); + git('checkout', '-b', 'not-a-task'); + expect(resolve({ scope: 'uncommitted' }).ticket).toBeUndefined(); + }); + + it('names a detached HEAD so the sidecar file name stays well-formed', () => { + createForkedRepo(); + git('checkout', '--detach'); + expect(resolve({}).branch).toBe('detached'); + }); +}); diff --git a/tools/review-screen/select/change.ts b/tools/review-screen/select/change.ts new file mode 100644 index 00000000000..0a9c60eb422 --- /dev/null +++ b/tools/review-screen/select/change.ts @@ -0,0 +1,106 @@ +import { execFileSync } from 'child_process'; +import fs from 'fs'; +import path from 'path'; + +import { getChangedFiles, resolveBaseCommit } from '../../code-complexity/select/diff'; +import { DEFAULT_BASE_BRANCH } from '../config'; + +// What a run screens, resolved once up front. Anything the caller passed explicitly (`--base`, +// `--spec`, `--ticket`) is taken verbatim; only the gaps are derived from git and the task folder, +// so the review that already pinned a base never sees a different one here. + +export type Scope = 'branch' | 'uncommitted'; + +export interface ChangeRequest { + readonly scope: Scope; + readonly base: string | undefined; + readonly spec: string | undefined; + readonly ticket: string | undefined; +} + +export interface TouchedFile { + readonly path: string; + readonly untracked: boolean; +} + +export interface Change { + readonly scope: Scope; + readonly base: string; + readonly branch: string; + readonly files: ReadonlyArray<TouchedFile>; + readonly spec: string | undefined; + readonly ticket: string | undefined; +} + +const TASKS_DIR = '.agents/tasks'; +const ISSUE_BRANCH = /^issue-(\d+)$/; +const UNCHECKED_TICKET = /^- \[ \] (\d+)\b/m; + +function git(args: ReadonlyArray<string>, cwd: string): string { + return execFileSync('git', args as Array<string>, { cwd, encoding: 'utf8' }); +} + +// A detached HEAD has no branch name; 'detached' keeps the sidecar name well-formed. +export function currentBranch(cwd: string): string { + return git([ 'branch', '--show-current' ], cwd).trim() || 'detached'; +} + +export function resolveBase(scope: Scope, explicit: string | undefined, cwd: string): string { + if (explicit !== undefined) return explicit; + return scope === 'branch' ? resolveBaseCommit(DEFAULT_BASE_BRANCH, cwd) : 'HEAD'; +} + +function listUntracked(cwd: string): Array<string> { + return git([ 'ls-files', '--others', '--exclude-standard' ], cwd).split('\n').map((line) => line.trim()).filter(Boolean); +} + +// Both scopes diff against the working tree, so uncommitted edits count under either; a file the +// change deleted is dropped because there is nothing left to score. +export function listTouchedFiles(base: string, cwd: string): Array<TouchedFile> { + const untracked = new Set(listUntracked(cwd)); + const tracked = getChangedFiles(base, cwd).filter((file) => !untracked.has(file)); + const files = [ ...tracked.map((file) => ({ path: file, untracked: false })), ...[ ...untracked ].map((file) => ({ path: file, untracked: true })) ] + .filter((file) => fs.existsSync(path.resolve(cwd, file.path))); + // Stryker disable next-line EqualityOperator: git lists each path once and the untracked ones are removed from the tracked list, so no two paths are equal + return files.sort((a, b) => (a.path < b.path ? -1 : 1)); +} + +export function resolveTaskFolder(branch: string, cwd: string): string | undefined { + const match = ISSUE_BRANCH.exec(branch); + if (!match) return undefined; + const tasksDir = path.resolve(cwd, TASKS_DIR); + if (!fs.existsSync(tasksDir)) return undefined; + const folder = fs.readdirSync(tasksDir).find((name) => name.startsWith(`${ match[1] }-`)); + return folder === undefined ? undefined : path.join(TASKS_DIR, folder); +} + +export function resolveSpecPath(explicit: string | undefined, taskFolder: string | undefined, cwd: string): string | undefined { + if (explicit !== undefined) return explicit; + if (taskFolder === undefined) return undefined; + const specPath = path.join(taskFolder, 'spec.md'); + return fs.existsSync(path.resolve(cwd, specPath)) ? specPath : undefined; +} + +// Uncommitted work is by definition the ticket in flight — the first unchecked box in `progress.md`, +// the same reading `review-changes` makes. A `branch` run spans every ticket and names none. +export function resolveTicket(scope: Scope, explicit: string | undefined, taskFolder: string | undefined, cwd: string): string | undefined { + if (explicit !== undefined) return explicit; + if (scope !== 'uncommitted' || taskFolder === undefined) return undefined; + const progressPath = path.resolve(cwd, taskFolder, 'progress.md'); + if (!fs.existsSync(progressPath)) return undefined; + return UNCHECKED_TICKET.exec(fs.readFileSync(progressPath, 'utf8'))?.[1]; +} + +export function resolveChange(request: ChangeRequest, cwd: string): Change { + const branch = currentBranch(cwd); + const base = resolveBase(request.scope, request.base, cwd); + const taskFolder = resolveTaskFolder(branch, cwd); + return { + scope: request.scope, + base, + branch, + files: listTouchedFiles(base, cwd), + spec: resolveSpecPath(request.spec, taskFolder, cwd), + ticket: resolveTicket(request.scope, request.ticket, taskFolder, cwd), + }; +} diff --git a/tools/review-screen/select/hunks.spec.ts b/tools/review-screen/select/hunks.spec.ts new file mode 100644 index 00000000000..d586063ad07 --- /dev/null +++ b/tools/review-screen/select/hunks.spec.ts @@ -0,0 +1,157 @@ +import { describe, expect, it } from 'vitest'; + +import type { Hunk, StateLine } from './hunks'; +import { buildWindows, parseLineId, parseUnifiedDiff, renderLine, wholeFileHunk } from './hunks'; + +const DIFF = [ + 'diff --git a/src/f.ts b/src/f.ts', + 'index 1111111..2222222 100644', + '--- a/src/f.ts', + '+++ b/src/f.ts', + '@@ -3,4 +3,5 @@ function f() {', + ' keep();', + '- old();', + '+ fresh();', + '+ extra();', + ' tail();', + '@@ -40,2 +41,2 @@', + ' before();', + '- gone();', + '+ here();', + '\\ No newline at end of file', +].join('\n'); + +function added(line: number, text: string): StateLine { + return { kind: 'added', line, text }; +} + +// Every line renders to the same width, so limits count lines predictably: `L1 + xxxxxxxxxx` is 15 +// chars plus the newline. +function hunkOfAddedLines(count: number, firstLine: number = 1): Hunk { + return { lines: Array.from({ length: count }, (_, index) => added(firstLine + index, 'xxxxxxxxxx')) }; +} + +const RENDERED_LINE_CHARS = 16; + +describe('parseUnifiedDiff', () => { + it('numbers context and added lines on the new side and leaves removed lines unnumbered', () => { + expect(parseUnifiedDiff(DIFF)).toEqual([ + { lines: [ + { kind: 'context', line: 3, text: ' keep();' }, + { kind: 'removed', text: ' old();' }, + added(4, ' fresh();'), + added(5, ' extra();'), + { kind: 'context', line: 6, text: ' tail();' }, + ] }, + { lines: [ + { kind: 'context', line: 41, text: ' before();' }, + { kind: 'removed', text: ' gone();' }, + added(42, ' here();'), + ] }, + ]); + }); + + it('takes hunk lines only after a hunk header, so a preamble starting with --- or +++ is not a line', () => { + expect(parseUnifiedDiff('--- a/f\n+++ b/f\n@@ -1 +1 @@\n+a\n')).toEqual([ { lines: [ added(1, 'a') ] } ]); + }); + + it('stops a hunk at the next file header instead of reading it as context', () => { + const twoFiles = `${ DIFF }\ndiff --git a/src/g.ts b/src/g.ts\nindex 3333333..4444444 100644\n--- a/src/g.ts\n+++ b/src/g.ts\n@@ -1 +1 @@\n-x\n+y`; + const hunks = parseUnifiedDiff(twoFiles); + expect(hunks).toHaveLength(3); + expect(hunks[1].lines).toHaveLength(3); + expect(hunks[2]).toEqual({ lines: [ { kind: 'removed', text: 'x' }, added(1, 'y') ] }); + }); + + it('yields no hunk for a diff without one', () => { + expect(parseUnifiedDiff('Binary files a/x.png and b/x.png differ\n')).toEqual([]); + expect(parseUnifiedDiff('')).toEqual([]); + }); +}); + +describe('wholeFileHunk', () => { + it('marks every line as added, numbered from 1, without a phantom trailing line', () => { + expect(wholeFileHunk('a\nb\n')).toEqual({ lines: [ added(1, 'a'), added(2, 'b') ] }); + }); +}); + +describe('renderLine', () => { + it('prefixes numbered lines with their id and marks removed lines without one', () => { + expect(renderLine(added(12, 'x')).startsWith('L12 + x')).toBe(true); + expect(renderLine({ kind: 'context', line: 7, text: 'y' })).toMatch(/^L7 {3}y$/); + expect(renderLine({ kind: 'removed', text: 'z' })).toMatch(/^ +- z$/); + }); +}); + +describe('parseLineId', () => { + it('reads the number back from an id and rejects anything else', () => { + expect(parseLineId('L42')).toBe(42); + expect(parseLineId('42')).toBeUndefined(); + expect(parseLineId('Lx')).toBeUndefined(); + }); +}); + +describe('buildWindows', () => { + const roomy = { maxChars: 10_000, maxChangedLines: 1_000 }; + + it('puts every hunk in one window when they fit, with the changed ids and the first line', () => { + const windows = buildWindows(parseUnifiedDiff(DIFF), roomy); + expect(windows).toHaveLength(1); + expect(windows[0]).toMatchObject({ index: 0, changedIds: [ 'L4', 'L5', 'L42' ], firstLine: 3, lastLine: 42 }); + expect(windows[0].state).toContain('L4 + fresh();'); + expect(windows[0].state).toContain('\n@@\n'); + }); + + it('splits on hunk boundaries before cutting a hunk', () => { + const hunks = [ hunkOfAddedLines(3, 1), hunkOfAddedLines(3, 50), hunkOfAddedLines(3, 90) ]; + const windows = buildWindows(hunks, { maxChars: 4 * RENDERED_LINE_CHARS + 2, maxChangedLines: 1_000 }); + expect(windows.map((window) => window.changedIds)).toEqual([ + [ 'L1', 'L2', 'L3' ], + [ 'L50', 'L51', 'L52' ], + [ 'L90', 'L91', 'L92' ], + ]); + expect(windows.map((window) => window.index)).toEqual([ 0, 1, 2 ]); + }); + + it('cuts a hunk on lines when it cannot fit an empty window', () => { + const windows = buildWindows([ hunkOfAddedLines(5) ], { maxChars: 2 * RENDERED_LINE_CHARS, maxChangedLines: 1_000 }); + expect(windows.map((window) => window.changedIds)).toEqual([ [ 'L1', 'L2' ], [ 'L3', 'L4' ], [ 'L5' ] ]); + }); + + it('counts the newline between rendered lines against the character budget', () => { + const windows = buildWindows([ hunkOfAddedLines(2) ], { maxChars: 2 * RENDERED_LINE_CHARS - 1, maxChangedLines: 1_000 }); + expect(windows.map((window) => window.changedIds)).toEqual([ [ 'L1' ], [ 'L2' ] ]); + }); + + it('caps the changed lines per window so the locate step never exceeds the option limit', () => { + const windows = buildWindows([ hunkOfAddedLines(7) ], { maxChars: 10_000, maxChangedLines: 3 }); + expect(windows.map((window) => window.changedIds.length)).toEqual([ 3, 3, 1 ]); + }); + + it('counts added lines only against the changed-lines cap, not context or removed ones', () => { + const mixed: Hunk = { lines: [ + { kind: 'context', line: 1, text: 'a' }, + added(2, 'b'), + { kind: 'removed', text: 'c' }, + { kind: 'context', line: 3, text: 'd' }, + added(4, 'e'), + ] }; + const windows = buildWindows([ mixed ], { maxChars: 10_000, maxChangedLines: 2 }); + expect(windows.map((window) => window.changedIds)).toEqual([ [ 'L2', 'L4' ] ]); + }); + + it('keeps a single line longer than the budget as its own window', () => { + const long: Hunk = { lines: [ added(1, 'x'.repeat(100)), added(2, 'y') ] }; + const windows = buildWindows([ long ], { maxChars: 20, maxChangedLines: 1_000 }); + expect(windows.map((window) => window.changedIds)).toEqual([ [ 'L1' ], [ 'L2' ] ]); + }); + + it('falls back to line 1 for a window with no numbered line', () => { + const removedOnly: Hunk = { lines: [ { kind: 'removed', text: 'x' } ] }; + expect(buildWindows([ removedOnly ], roomy)[0]).toMatchObject({ changedIds: [], firstLine: 1, lastLine: 1 }); + }); + + it('yields no window for no hunks', () => { + expect(buildWindows([], roomy)).toEqual([]); + }); +}); diff --git a/tools/review-screen/select/hunks.ts b/tools/review-screen/select/hunks.ts new file mode 100644 index 00000000000..e5264fbcb04 --- /dev/null +++ b/tools/review-screen/select/hunks.ts @@ -0,0 +1,192 @@ +import { execFileSync } from 'child_process'; +import fs from 'fs'; +import path from 'path'; + +import { EXEC_MAX_BUFFER } from '../../cli/exec'; + +// A file's change as the model sees it: the changed hunks with their surrounding context, every +// new-side line carrying a stable id (`L<line>`) the locate step can hand back. Windowing keeps a +// state under the model's limit — hunks stay whole where they can, and a hunk too big on its own is +// cut on lines. + +export interface NumberedLine { + readonly kind: 'context' | 'added'; + // The new-side line number. + readonly line: number; + readonly text: string; +} + +export interface RemovedLine { + readonly kind: 'removed'; + readonly text: string; +} + +export type StateLine = NumberedLine | RemovedLine; + +export interface Hunk { + readonly lines: ReadonlyArray<StateLine>; +} + +export interface Window { + readonly index: number; + readonly state: string; + readonly changedIds: ReadonlyArray<string>; + readonly firstLine: number; + readonly lastLine: number; +} + +export interface WindowLimits { + readonly maxChars: number; + readonly maxChangedLines: number; +} + +export interface FileWindows { + readonly file: string; + readonly windows: ReadonlyArray<Window>; +} + +const HUNK_HEADER = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/; +const HUNK_SEPARATOR = '@@'; + +export function lineId(line: number): string { + return `L${ line }`; +} + +export function parseLineId(id: string): number | undefined { + const match = /^L(\d+)$/.exec(id); + return match ? Number(match[1]) : undefined; +} + +function flush(lines: Array<StateLine>, hunks: Array<Hunk>): void { + if (lines.length > 0) hunks.push({ lines: [ ...lines ] }); + lines.length = 0; +} + +// The new-side line counter advances on context and added lines only; removed lines are kept for +// what they say about the change but carry no id. +export function parseUnifiedDiff(diffText: string): Array<Hunk> { + const hunks: Array<Hunk> = []; + const lines: Array<StateLine> = []; + let line = 0; + let inHunk = false; + + for (const raw of diffText.split('\n')) { + const header = HUNK_HEADER.exec(raw); + if (header) { + flush(lines, hunks); + line = Number(header[1]); + inHunk = true; + continue; + } + if (!inHunk || raw.startsWith('\\')) continue; + const marker = raw[0]; + if (marker === '+') { + lines.push({ kind: 'added', line, text: raw.slice(1) }); + line += 1; + } else if (marker === '-') { + lines.push({ kind: 'removed', text: raw.slice(1) }); + } else if (marker === ' ') { + lines.push({ kind: 'context', line, text: raw.slice(1) }); + line += 1; + } else { + inHunk = false; + } + } + flush(lines, hunks); + return hunks; +} + +export function wholeFileHunk(content: string): Hunk { + const body = content.endsWith('\n') ? content.slice(0, -1) : content; + return { lines: body.split('\n').map((text, index) => ({ kind: 'added', line: index + 1, text })) }; +} + +function isBinary(buffer: Buffer): boolean { + return buffer.includes(0); +} + +export function readHunks(file: string, untracked: boolean, base: string, contextLines: number, cwd: string): Array<Hunk> { + if (untracked) { + const buffer = fs.readFileSync(path.resolve(cwd, file)); + return isBinary(buffer) ? [] : [ wholeFileHunk(buffer.toString('utf8')) ]; + } + const diff = execFileSync('git', [ 'diff', `--unified=${ contextLines }`, '--no-color', base, '--', file ], { + cwd, + encoding: 'utf8', + maxBuffer: EXEC_MAX_BUFFER, + }); + return parseUnifiedDiff(diff); +} + +export function renderLine(line: StateLine): string { + switch (line.kind) { + case 'added': + return `${ lineId(line.line) } + ${ line.text }`; + case 'context': + return `${ lineId(line.line) } ${ line.text }`; + case 'removed': + return ` - ${ line.text }`; + } +} + +function measure(lines: ReadonlyArray<StateLine>): { readonly chars: number; readonly changed: number } { + let chars = 0; + let changed = 0; + for (const line of lines) { + chars += renderLine(line).length + 1; + if (line.kind === 'added') changed += 1; + } + return { chars, changed }; +} + +function fits(lines: ReadonlyArray<StateLine>, limits: WindowLimits): boolean { + const { chars, changed } = measure(lines); + return chars <= limits.maxChars && changed <= limits.maxChangedLines; +} + +// Cut one oversized hunk on lines. A single line longer than the whole budget still becomes its own +// chunk — the model gets a long line rather than the tool dropping code silently. The hunk is never +// empty: an empty one fits any window and is not split. +function splitHunk(hunk: Hunk, limits: WindowLimits): Array<Hunk> { + const chunks: Array<Hunk> = []; + let current: Array<StateLine> = []; + for (const line of hunk.lines) { + if (current.length > 0 && !fits([ ...current, line ], limits)) { + chunks.push({ lines: current }); + current = []; + } + current.push(line); + } + chunks.push({ lines: current }); + return chunks; +} + +function toWindow(hunks: ReadonlyArray<Hunk>, index: number): Window { + const lines = hunks.flatMap((hunk) => hunk.lines); + const numbered = lines.flatMap((line) => line.kind === 'removed' ? [] : [ line.line ]); + return { + index, + state: hunks.map((hunk) => hunk.lines.map(renderLine).join('\n')).join(`\n${ HUNK_SEPARATOR }\n`), + changedIds: lines.flatMap((line) => line.kind === 'added' ? [ lineId(line.line) ] : []), + firstLine: numbered.length > 0 ? Math.min(...numbered) : 1, + lastLine: numbered.length > 0 ? Math.max(...numbered) : 1, + }; +} + +// Pack hunks into windows on hunk boundaries first; a hunk that cannot fit an empty window is split +// on lines and its pieces packed like any other hunk. +export function buildWindows(hunks: ReadonlyArray<Hunk>, limits: WindowLimits): Array<Window> { + const pieces = hunks.flatMap((hunk) => fits(hunk.lines, limits) ? [ hunk ] : splitHunk(hunk, limits)); + const groups: Array<Array<Hunk>> = []; + let current: Array<Hunk> = []; + for (const piece of pieces) { + const combined = [ ...current, piece ].flatMap((hunk) => hunk.lines); + if (current.length > 0 && !fits(combined, limits)) { + groups.push(current); + current = []; + } + current.push(piece); + } + if (current.length > 0) groups.push(current); + return groups.map(toWindow); +} diff --git a/tools/review-screen/select/spec.spec.ts b/tools/review-screen/select/spec.spec.ts new file mode 100644 index 00000000000..eea051b2aed --- /dev/null +++ b/tools/review-screen/select/spec.spec.ts @@ -0,0 +1,112 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import { parseRequirements, readSpec } from './spec'; + +const FIXTURE = `# Some task + +| | | +| --- | --- | +| Issue | https://github.com/blockscout/frontend/issues/1 | + +## Context & goal + +1. Not a requirement: this list sits outside the section. + +## Functional requirements + +1. A CLI tool under \`tools/\` screens a change and emits suspects as JSON. It resolves the base ref + and the touched files from \`--scope branch|uncommitted\`, or takes them explicitly. +2. **Standards grid.** For each rubric rule and each touched file matching the rule's glob, the tool + scores the probability of a breach. +3. Thresholds live in the tool's config. + +4. A requirement after a blank line. + +## Data & API + +- TypeSafe Jev: POST https://api.typesafe.ai/v1/systemone. + +1. Not a requirement either. +`; + +let tmp = ''; + +afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; +}); + +describe('parseRequirements', () => { + it('reads the numbered list under the Functional requirements heading only', () => { + expect(parseRequirements(FIXTURE).map((requirement) => requirement.id)).toEqual([ 'FR1', 'FR2', 'FR3', 'FR4' ]); + }); + + it('joins a multi-line requirement into one line of text', () => { + const [ first ] = parseRequirements(FIXTURE); + expect(first.text).toBe( + 'A CLI tool under `tools/` screens a change and emits suspects as JSON. It resolves the base ref ' + + 'and the touched files from `--scope branch|uncommitted`, or takes them explicitly.', + ); + }); + + it('keeps a bold lead-in as part of the text, without the markup, and never as the id', () => { + const [ , second ] = parseRequirements(FIXTURE); + expect(second.id).toBe('FR2'); + expect(second.text).toMatch(/^Standards grid\. For each rubric rule/); + expect(second.text).not.toContain('**'); + }); + + it('uses the number as written for the id', () => { + expect(parseRequirements('## Functional requirements\n\n7. Seven.\n9. Nine.\n')).toEqual([ + { id: 'FR7', text: 'Seven.' }, + { id: 'FR9', text: 'Nine.' }, + ]); + }); + + it('keeps the last item when the section ends the file without a trailing newline', () => { + expect(parseRequirements('## Functional requirements\n\n1. One.\n2. Two.')).toEqual([ + { id: 'FR1', text: 'One.' }, + { id: 'FR2', text: 'Two.' }, + ]); + }); + + it('joins an indented line after a blank line, but ends the item at unindented prose', () => { + expect(parseRequirements('## Functional requirements\n\n1. One.\n\n more.\n')).toEqual([ { id: 'FR1', text: 'One. more.' } ]); + expect(parseRequirements('## Functional requirements\n\n1. One.\nProse.\n tail.\n')).toEqual([ { id: 'FR1', text: 'One.' } ]); + }); + + it('ignores an indented line before the first item', () => { + expect(parseRequirements('## Functional requirements\n\n stray.\n1. One.\n')).toEqual([ { id: 'FR1', text: 'One.' } ]); + }); + + it('returns nothing without the section or without a list in it', () => { + expect(parseRequirements('# Title\n\n1. Loose item.\n')).toEqual([]); + expect(parseRequirements('1. Loose item.\n')).toEqual([]); + expect(parseRequirements('## Functional requirements\n\nProse only.\n')).toEqual([]); + }); +}); + +describe('readSpec', () => { + it('is no-spec without a path', () => { + expect(readSpec(undefined, '/nowhere')).toEqual({ status: 'no-spec' }); + }); + + it('parses the requirements of an existing spec', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'review-screen-spec-')); + fs.writeFileSync(path.join(tmp, 'spec.md'), FIXTURE); + const source = readSpec('spec.md', tmp); + expect(source.status).toBe('ok'); + if (source.status === 'ok') expect(source.requirements.map((requirement) => requirement.id)).toEqual([ 'FR1', 'FR2', 'FR3', 'FR4' ]); + }); + + it('fails with a reason, not a throw, when the path points nowhere or the spec has no list', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'review-screen-spec-')); + expect(readSpec('missing.md', tmp)).toEqual({ status: 'failed', reason: 'Spec file not found: missing.md' }); + fs.writeFileSync(path.join(tmp, 'empty.md'), '# Nothing here\n'); + expect(readSpec('empty.md', tmp)).toMatchObject({ status: 'failed', reason: expect.stringContaining('empty.md') }); + }); +}); diff --git a/tools/review-screen/select/spec.ts b/tools/review-screen/select/spec.ts new file mode 100644 index 00000000000..f792bb01e41 --- /dev/null +++ b/tools/review-screen/select/spec.ts @@ -0,0 +1,68 @@ +import fs from 'fs'; +import path from 'path'; + +// The task spec's Functional Requirements, as the spec grid asks about them: one entry per item of +// the numbered list under `## Functional requirements`, id `FR<n>` from the number as written, text +// with its continuation lines joined and bold lead-ins kept as words. + +export interface Requirement { + readonly id: string; + readonly text: string; +} + +export type SpecSource = + { readonly status: 'ok'; readonly path: string; readonly requirements: ReadonlyArray<Requirement> } | + { readonly status: 'no-spec' } | + { readonly status: 'failed'; readonly reason: string }; + +const SECTION_HEADING = /^## +functional requirements *$/i; +const ANY_HEADING = /^#{1,6}\s/; +const LIST_ITEM = /^(\d+)\. +(\S.*)$/; +const CONTINUATION = /^ +(\S.*)$/; +const BOLD = /\*\*/g; + +function sectionLines(specText: string): Array<string> { + const lines = specText.split('\n'); + const start = lines.findIndex((line) => SECTION_HEADING.test(line)); + if (start === -1) return []; + const rest = lines.slice(start + 1); + const end = rest.findIndex((line) => ANY_HEADING.test(line)); + return end === -1 ? rest : rest.slice(0, end); +} + +function normalize(parts: ReadonlyArray<string>): string { + return parts.join(' ').replace(BOLD, '').replace(/\s+/g, ' ').trim(); +} + +export function parseRequirements(specText: string): Array<Requirement> { + const requirements: Array<Requirement> = []; + let current: { id: string; parts: Array<string> } | undefined; + const flush = (): void => { + if (current !== undefined) requirements.push({ id: current.id, text: normalize(current.parts) }); + current = undefined; + }; + for (const line of sectionLines(specText)) { + const item = LIST_ITEM.exec(line); + if (item) { + flush(); + current = { id: `FR${ item[1] }`, parts: [ item[2] ] }; + continue; + } + const continuation = CONTINUATION.exec(line); + if (continuation && current !== undefined) current.parts.push(continuation[1]); + else if (line.trim() !== '') flush(); + } + flush(); + return requirements; +} + +// An explicit `--spec` that points nowhere is the caller's mistake and is reported, not thrown: the +// review passing it still gets its standards grid. +export function readSpec(specPath: string | undefined, cwd: string): SpecSource { + if (specPath === undefined) return { status: 'no-spec' }; + const absolute = path.resolve(cwd, specPath); + if (!fs.existsSync(absolute)) return { status: 'failed', reason: `Spec file not found: ${ specPath }` }; + const requirements = parseRequirements(fs.readFileSync(absolute, 'utf8')); + if (requirements.length === 0) return { status: 'failed', reason: `No "## Functional requirements" numbered list in ${ specPath }` }; + return { status: 'ok', path: specPath, requirements }; +} diff --git a/tools/review-screen/sidecar.spec.ts b/tools/review-screen/sidecar.spec.ts new file mode 100644 index 00000000000..0de22973424 --- /dev/null +++ b/tools/review-screen/sidecar.spec.ts @@ -0,0 +1,90 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import type { SidecarRecord } from './sidecar'; +import { readSidecar, sidecarFileName, writeSidecar } from './sidecar'; + +let tmp = ''; + +afterEach(() => { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + tmp = ''; +}); + +const DATE = new Date('2026-09-28T23:30:00Z'); + +describe('sidecarFileName', () => { + it('joins date, branch and scope, with the ticket only when there is one', () => { + expect(sidecarFileName({ date: DATE, branch: 'issue-3720', scope: 'branch', ticket: undefined })).toBe('2026-09-28-issue-3720-branch.json'); + expect(sidecarFileName({ date: DATE, branch: 'issue-3720', scope: 'uncommitted', ticket: '02' })).toBe('2026-09-28-issue-3720-uncommitted-02.json'); + }); + + it('flattens path separators in a branch name', () => { + expect(sidecarFileName({ date: DATE, branch: 'tom/fix thing', scope: 'branch', ticket: undefined })).toBe('2026-09-28-tom-fix-thing-branch.json'); + }); +}); + +describe('writeSidecar', () => { + it('creates the folder and writes the record as pretty JSON', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'review-screen-sidecar-')); + const record: SidecarRecord = { + version: 1, + createdAt: DATE.toISOString(), + status: 'skipped', + reason: 'no key', + calibration: false, + model: undefined, + inputs: { scope: 'branch', base: 'abc', branch: 'issue-1', ticket: undefined, spec: undefined, files: [] }, + windows: [], + standards: { cells: [], suspects: [], cut: 0 }, + spec: { status: 'no-spec' }, + calls: [], + elapsedMs: undefined, + origins: undefined, + }; + const target = path.join(tmp, '.ai', 'jev', 'x.json'); + writeSidecar(target, record); + expect(JSON.parse(fs.readFileSync(target, 'utf8'))).toEqual({ + version: 1, + createdAt: '2026-09-28T23:30:00.000Z', + status: 'skipped', + reason: 'no key', + calibration: false, + inputs: { scope: 'branch', base: 'abc', branch: 'issue-1', files: [] }, + windows: [], + standards: { cells: [], suspects: [], cut: 0 }, + spec: { status: 'no-spec' }, + calls: [], + }); + expect(readSidecar(target)).toEqual({ ...record, reason: 'no key' }); + }); +}); + +describe('readSidecar', () => { + it('rejects a file that is not a sidecar of the current version', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'review-screen-sidecar-')); + const target = path.join(tmp, 'x.json'); + fs.writeFileSync(target, JSON.stringify({ version: 99 })); + expect(() => readSidecar(target)).toThrow('Not a review-screen sidecar (version 1)'); + fs.writeFileSync(target, JSON.stringify([])); + expect(() => readSidecar(target)).toThrow('Not a review-screen sidecar'); + fs.writeFileSync(target, JSON.stringify(null)); + expect(() => readSidecar(target)).toThrow('Not a review-screen sidecar'); + }); + + it('fills in an empty window list and a pilot marker for a sidecar written before either was recorded', () => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'review-screen-sidecar-')); + const target = path.join(tmp, 'x.json'); + fs.writeFileSync(target, JSON.stringify({ + version: 1, + status: 'ok', + standards: { cells: [], suspects: [], cut: 0 }, + spec: { status: 'no-spec' }, + calls: [], + })); + expect(readSidecar(target)).toMatchObject({ version: 1, windows: [], calibration: false }); + }); +}); diff --git a/tools/review-screen/sidecar.ts b/tools/review-screen/sidecar.ts new file mode 100644 index 00000000000..2bede024e65 --- /dev/null +++ b/tools/review-screen/sidecar.ts @@ -0,0 +1,122 @@ +import fs from 'fs'; +import path from 'path'; + +import type { CallRecord } from './grid/shared'; +import type { SpecCell, SpecSuspect } from './grid/spec'; +import type { Cell, Suspect } from './grid/standards'; +import type { OriginsRecord } from './origins/match'; +import type { Scope, TouchedFile } from './select/change'; +import type { FileWindows } from './select/hunks'; +import type { Requirement } from './select/spec'; + +// One JSON record per run, in the main checkout's `.ai/jev/` so every worktree adds to the same +// dataset and the file outlives the worktree and the task folder. Every cell score is kept, not +// only the suspects, so thresholds can be re-tuned offline without re-running the model. + +export const SIDECAR_VERSION = 1; + +export type RunStatus = 'ok' | 'skipped' | 'failed'; + +// `no-spec`: nothing to score. `skipped`: a spec, but no client. `failed`: the spec could not be +// read, or the API failed while scoring it (the cells scored before that stay). +export type SpecRecord = + { readonly status: 'no-spec' } | + { readonly status: 'skipped'; readonly reason: string } | + { readonly status: 'failed'; readonly reason: string; readonly requirements: ReadonlyArray<Requirement>; readonly cells: ReadonlyArray<SpecCell> } | + { + readonly status: 'ok'; + readonly requirements: ReadonlyArray<Requirement>; + readonly cells: ReadonlyArray<SpecCell>; + readonly suspects: ReadonlyArray<SpecSuspect>; + readonly cut: number; + }; + +export interface SidecarInputs { + readonly scope: Scope; + readonly base: string; + readonly branch: string; + readonly ticket: string | undefined; + readonly spec: string | undefined; + readonly files: ReadonlyArray<TouchedFile>; +} + +// The line span of one window, keyed by file and window index — what `--origins` needs to say whether a +// finding's line falls inside a suspect's window once the diff itself is gone. +export interface WindowSpan { + readonly file: string; + readonly window: number; + readonly firstLine: number; + readonly lastLine: number; +} + +export interface SidecarRecord { + readonly version: number; + readonly createdAt: string; + readonly status: RunStatus; + readonly reason: string | undefined; + // A past diff screened to tune the thresholds, not a pilot review; `--report` leaves it out. + readonly calibration: boolean; + readonly model: string | undefined; + readonly inputs: SidecarInputs; + readonly windows: ReadonlyArray<WindowSpan>; + readonly standards: { + readonly cells: ReadonlyArray<Cell>; + readonly suspects: ReadonlyArray<Suspect>; + readonly cut: number; + }; + readonly spec: SpecRecord; + readonly calls: ReadonlyArray<CallRecord>; + // Wall-clock span of the screen. The calls overlap (`CONCURRENT_REQUESTS`), so their sum overstates + // what a review waited; a sidecar written before this field existed has none and `--report` falls + // back to the sum. + readonly elapsedMs: number | undefined; + readonly origins: OriginsRecord | undefined; +} + +export function windowSpans(files: ReadonlyArray<FileWindows>): Array<WindowSpan> { + return files.flatMap((target) => target.windows.map((window) => ({ + file: target.file, + window: window.index, + firstLine: window.firstLine, + lastLine: window.lastLine, + }))); +} + +export interface SidecarName { + readonly date: Date; + readonly branch: string; + readonly scope: Scope; + readonly ticket: string | undefined; +} + +function sanitize(segment: string): string { + return segment.replace(/[^\w.-]+/g, '-'); +} + +export function sidecarFileName(name: SidecarName): string { + const date = name.date.toISOString().slice(0, 'YYYY-MM-DD'.length); + const ticket = name.ticket === undefined ? '' : `-${ sanitize(name.ticket) }`; + return `${ date }-${ sanitize(name.branch) }-${ name.scope }${ ticket }.json`; +} + +export function writeSidecar(filePath: string, record: SidecarRecord): void { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, `${ JSON.stringify(record, null, 2) }\n`); +} + +function isRecord(value: unknown): value is Record<string, unknown> { + // Stryker disable next-line ConditionalExpression: a primitive reads `version` as undefined and fails readSidecar the same way; the guard only narrows + if (typeof value !== 'object') return false; + return value !== null; +} + +export function readSidecar(filePath: string): SidecarRecord { + const parsed: unknown = JSON.parse(fs.readFileSync(filePath, 'utf8')); + if (!isRecord(parsed) || parsed.version !== SIDECAR_VERSION) throw new Error(`Not a review-screen sidecar (version ${ SIDECAR_VERSION }): ${ filePath }`); + // Only this tool writes the folder, and the version check above is the one field an edited file + // could drift on; validating every cell of a record we wrote ourselves would double the module. + const record = parsed as unknown as SidecarRecord; + // A sidecar written before `windows`, `calibration` or `elapsedMs` existed still reads: its suspects + // match on the exact line, and it counts as a pilot review. + return { ...record, calibration: record.calibration ?? false, windows: record.windows ?? [], elapsedMs: record.elapsedMs, origins: record.origins }; +} diff --git a/tools/review-screen/tsconfig.json b/tools/review-screen/tsconfig.json new file mode 100644 index 00000000000..a34d8336541 --- /dev/null +++ b/tools/review-screen/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "node16", + "target": "es2022", + "moduleResolution": "node16", + "resolveJsonModule": true, + "isolatedModules": false, + "noEmit": false, + "incremental": false, + "rootDir": "..", + "outDir": "./dist" + }, + "include": [ + "./index.ts" + ], + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/tools/scripts/build.docker.sh b/tools/scripts/build.docker.sh deleted file mode 100755 index 816cfd0aca7..00000000000 --- a/tools/scripts/build.docker.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash - -# remove previous assets -rm -rf ./public/assets/configs -rm -rf ./public/assets/multichain -rm -rf ./public/assets/envs.js - -docker build --progress=plain --build-arg GIT_COMMIT_SHA=$(git rev-parse --short HEAD) --build-arg GIT_TAG=$(git describe --tags --abbrev=0) -t blockscout-frontend:local ./ \ No newline at end of file diff --git a/tools/scripts/check-doc-links.mjs b/tools/scripts/check-doc-links.mjs deleted file mode 100644 index 72064f5bd5f..00000000000 --- a/tools/scripts/check-doc-links.mjs +++ /dev/null @@ -1,211 +0,0 @@ -#!/usr/bin/env node - -// Resolves the cross-references in the agent instruction surface: markdown links, heading anchors, and the -// file and directory paths in backticks. These files instruct agents rather than humans, so a reference that -// no longer resolves does not merely read badly — it sends an agent to a file that is not there, and nothing -// else in the toolchain notices. Kept mechanical on purpose: a review agent should spend its judgement on -// what a rule says, not on whether the rule's target still exists. -// -// These documents also carry paths that are *illustrations* rather than references — a template's output -// column, a kind of file that lives in many slices. Checking those would produce noise that trains everyone -// to ignore the checker, so an illustration is exempt where it carries a mark that cannot be read as a -// reference; `ILLUSTRATION_FORMS` below is the only statement of what those marks are. Each exemption is -// scoped to the path itself rather than to its whole line, so a real reference standing beside an -// illustration is still checked, and anything unmarked is read as a reference and has to resolve. -// -// An `e.g.` is deliberately *not* a mark. Prose that introduces a real file as an example is the common -// case by far, and exempting it would leave those references unprotected against a later rename — the drift -// this script exists to catch. An example that names no real file gets a `<placeholder>` segment instead. - -import { execFileSync } from 'node:child_process'; -import { existsSync } from 'node:fs'; -import { readdir, readFile, realpath } from 'node:fs/promises'; -import path from 'node:path'; - -const ROOT = path.resolve(import.meta.dirname, '../..'); - -// The instruction surface: the agent config directories, plus every per-directory CONTEXT.md wherever it -// lives. Task specs are excluded — they describe files that do not exist yet by design. -const ROOTS = [ '.agents', '.claude', '.cursor' ]; -const EXCLUDED = [ '.agents/tasks', '.claude/worktrees' ]; -const SKIPPED_DIRS = new Set([ 'node_modules', '.git', '.next' ]); - -const PATH_EXTENSIONS = /\.(?:md|mdc|mjs|json|jsonc|ya?ml|sh|tsx?)$/; - -const tracked = execFileSync('git', [ 'ls-files' ], { cwd: ROOT, encoding: 'utf8' }).split('\n').filter(Boolean); - -// Derived rather than listed, so a new top-level directory needs no edit here. A path is only expected to -// resolve when its first segment is one of these: `types/api.ts` names a kind of file, `src/api/types.ts` a -// location. -const TOP_LEVEL = new Set(tracked.filter((f) => f.includes('/')).map((f) => f.split('/')[0])); - -async function collectMarkdown(dir, acc = []) { - let entries; - try { - entries = await readdir(path.join(ROOT, dir), { withFileTypes: true }); - } catch { - return acc; // a root absent from this checkout is not an error - } - - for (const entry of entries) { - const rel = path.join(dir, entry.name); - if (EXCLUDED.some((ex) => rel === ex || rel.startsWith(`${ ex }/`))) continue; - - // A symlinked directory (`.claude/skills` → `../.agents/skills`) is not a directory to `readdir`, so the - // walk skips it — correctly, since the walk over `.agents` reaches those files by their real path. - if (entry.isDirectory()) { - if (!SKIPPED_DIRS.has(entry.name)) await collectMarkdown(rel, acc); - } else if (/\.mdc?$/.test(entry.name)) { - acc.push(rel); - } - } - - return acc; -} - -// GitHub's heading slug: lowercase, drop all but word chars, spaces and hyphens, then spaces to hyphens. -const slugify = (heading) => heading - .toLowerCase() - .replace(/`/g, '') - .replace(/[^\w\s-]/g, '') - .trim() - .replace(/\s+/g, '-'); - -async function headingSlugs(absPath) { - const body = await readFile(absPath, 'utf8'); - return new Set( - body.split('\n') - .filter((line) => /^#{1,6}\s/.test(line)) - .map((line) => slugify(line.replace(/^#{1,6}\s+/, ''))), - ); -} - -// Fenced blocks hold example commands and JSON payloads; neither is a reference. -function withoutFences(body) { - let inFence = false; - return body.split('\n').map((line) => { - if (/^\s*```/.test(line)) { - inFence = !inFence; - return ''; - } - return inFence ? '' : line; - }); -} - -// Stated once, and printed on failure so the convention reaches an author at the moment they trip it rather -// than in a document they would have to know to read. -const ILLUSTRATION_FORMS = 'give it a <placeholder> segment, or place it after a → in a table row as the ' + - 'output of the pattern before it'; - -// Blanks the marked regions and leaves the rest of the line checkable. The arrow form is confined to table -// rows, where a cell pairs a pattern with its filled-in output; in prose an arrow is ordinary punctuation -// and the path after it is a reference like any other. The `<placeholder>` form is per-path, below. -const withoutIllustrations = (line) => (/^\s*\|/.test(line) ? line.replace(/→[^|]*/g, '') : line); - -const isPlaceholder = (target) => /[<>{}*]|__/.test(target); - -// Resolved against the file's realpath, so a symlinked entry point (`.claude/CLAUDE.md` → `.agents/AGENTS.md`) -// resolves its relative links from where the file really lives. -function resolves(realDir, target) { - const clean = target.replace(/^\.\//, ''); - return [ path.resolve(realDir, clean), path.resolve(ROOT, clean) ].find((c) => existsSync(c)); -} - -// A path that resolves nowhere may still name a real file written short — `toolkit/theme/theme.ts` for -// `src/toolkit/theme/theme.ts`. Reported only when exactly one tracked file ends with it, which makes the -// intended file certain; `types/api.ts` matches thirty of them and so asserts no single location to check. -// Files only: a bare directory such as `hooks/` names a convention every slice follows, not one location, -// and nothing distinguishes that from shorthand. -function shorthandFor(target) { - const matches = tracked.filter((f) => f.endsWith(`/${ target }`)); - return matches.length === 1 ? matches[0] : undefined; -} - -// A path whose parent directory sits beside the file was written relative to it — `components/Provider.tsx` -// in a CONTEXT.md is a reference to a neighbour, and its absence is a break. Without this the whole relative -// class goes unprotected: once broken, such a path is indistinguishable from `types/api.ts` naming a kind of -// file, so a renamed neighbour would fail silently. -function nearby(realDir, target) { - const parent = path.dirname(target); - return parent !== '.' && !target.endsWith('/') && existsSync(path.resolve(realDir, parent)); -} - -async function checkFile(fileRel, failures) { - const realDir = path.dirname(await realpath(path.join(ROOT, fileRel))); - const lines = withoutFences(await readFile(path.join(ROOT, fileRel), 'utf8')); - - for (const [ index, rawLine ] of lines.entries()) { - const report = (message) => failures.push({ file: fileRel, line: index + 1, message }); - const checkable = withoutIllustrations(rawLine); - - // Backtick paths. Collected first, then stripped, so an inline code span holding a markdown-link - // example — `[Link Text](URL)` — is not read as a link. - const spans = [ ...checkable.matchAll(/`([^`]+)`/g) ].map((m) => m[1]); - const line = checkable.replace(/`[^`]+`/g, ''); - - for (const target of spans) { - if (/\s/.test(target) || isPlaceholder(target) || !target.includes('/')) continue; - // A trailing slash marks a directory, a known extension marks a file. Anything else in backticks — a - // config key, a dotted token, a fragment of prose — is not a path. - if (!target.endsWith('/') && !PATH_EXTENSIONS.test(target)) continue; - if (resolves(realDir, target)) continue; - - const full = shorthandFor(target); - if (full) { - report(`${ target } is shorthand; write it in full: ${ full }`); - } else if (target.startsWith('./') || TOP_LEVEL.has(target.split('/')[0]) || nearby(realDir, target)) { - report(`path reference does not exist: ${ target }`); - } - } - - // Markdown links, with an optional heading anchor. - for (const [ , target ] of line.matchAll(/\[[^\]]*\]\(([^)\s]+)\)/g)) { - if (/^(?:https?:|mailto:|#)/.test(target) || isPlaceholder(target)) continue; - - const [ filePart, anchor ] = target.split('#'); - // A link with neither a slash nor a file extension is prose in brackets, not a path. - if (!filePart.includes('/') && !PATH_EXTENSIONS.test(filePart)) continue; - - const resolved = resolves(realDir, filePart); - if (!resolved) { - report(`link target does not exist: ${ target }`); - } else if (anchor && resolved.endsWith('.md')) { - const slugs = await headingSlugs(resolved); - if (!slugs.has(anchor.toLowerCase())) report(`heading anchor not found in target: ${ target }`); - } - } - } -} - -const walked = (await Promise.all(ROOTS.map((r) => collectMarkdown(r)))).flat(); -const contexts = tracked.filter((f) => path.basename(f) === 'CONTEXT.md'); - -// One entry per real file. `.cursor/rules/*.mdc` and `.claude/CLAUDE.md` are symlinks onto files the walk -// already reached under `.agents`, and checking a file twice reports each of its findings twice. -const seen = new Map(); -for (const rel of [ ...walked, ...contexts ]) { - const real = await realpath(path.join(ROOT, rel)); - if (!seen.has(real)) seen.set(real, rel); -} -const files = [ ...seen.values() ]; - -const failures = []; -for (const file of files) { - await checkFile(file, failures); -} - -if (failures.length > 0) { - for (const { file, line, message } of failures) { - // eslint-disable-next-line no-console - console.error(`${ file }:${ line } — ${ message }`); - } - // eslint-disable-next-line no-console - console.error( - `\n${ failures.length } unresolved reference(s) across ${ files.length } file(s).\n` + - `A path naming a shape rather than a file has to be marked as one, or it is read as a reference: ${ ILLUSTRATION_FORMS }.`, - ); - process.exit(1); -} - -// eslint-disable-next-line no-console -console.log(`Doc links: ${ files.length } files checked, every reference resolves.`); diff --git a/tools/scripts/dev.sh b/tools/scripts/dev.sh deleted file mode 100755 index 1d2606efc83..00000000000 --- a/tools/scripts/dev.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash - -# remove previous assets -rm -rf ./public/assets/configs -rm -rf ./public/assets/multichain -rm -rf ./public/assets/envs.js - -# download assets for the running instance -dotenv \ - -e .env.development.local \ - -e .env.local \ - -e .env.development \ - -e .env \ - -- bash -c './deploy/scripts/download_assets.sh ./public/assets/configs' - -source ./deploy/scripts/build_sprite.sh -echo "" - -# generate routes -pnpm routes:generate -echo "" - -# generate envs.js file and run the app -dotenv \ - -v NEXT_PUBLIC_GIT_COMMIT_SHA=$(git rev-parse --short HEAD) \ - -v NEXT_PUBLIC_GIT_TAG=$(git describe --tags --abbrev=0) \ - -v NEXT_PUBLIC_ICON_SPRITE_HASH="${NEXT_PUBLIC_ICON_SPRITE_HASH}" \ - -e .env.secrets \ - -e .env.development.local \ - -e .env.local \ - -e .env.development \ - -e .env \ - -- bash -c './deploy/scripts/make_envs_script.sh && next dev -p $NEXT_PUBLIC_APP_PORT' | -pino-pretty \ No newline at end of file diff --git a/tools/scripts/docker.preset.sh b/tools/scripts/docker.preset.sh deleted file mode 100755 index 3df5b237440..00000000000 --- a/tools/scripts/docker.preset.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/bash - -if [ "$#" -ne 1 ]; then - echo "Usage: pnpm start:docker:preset <preset_name>" - exit 1 -fi - -preset_name="$1" -secrets_file="./.env.secrets" - -# Fetch the instance config into ./.env.tmp (raw KEY=value, docker --env-file compatible) -./tools/dev-server/fetch.sh "$preset_name" || exit 1 - -if [ ! -f "$secrets_file" ]; then - echo "Error: File '$secrets_file' not found." - exit 1 -fi - -docker run -p 3000:3000 --env-file ./.env.tmp --env-file $secrets_file blockscout-frontend:local | pino-pretty \ No newline at end of file diff --git a/tools/scripts/favicon-generator.dev.sh b/tools/scripts/favicon-generator.dev.sh deleted file mode 100755 index 53d5cd25f6f..00000000000 --- a/tools/scripts/favicon-generator.dev.sh +++ /dev/null @@ -1,12 +0,0 @@ -favicon_folder="./public/assets/favicon/" -master_url="https://raw.githubusercontent.com/blockscout/frontend/main/tools/scripts/favicon.svg" - -dotenv \ - -v MASTER_URL=$master_url \ - -- bash -c 'cd ./deploy/tools/favicon-generator && node "$(pwd)/index.js"' - -if [ -d "$favicon_folder" ]; then - rm -r "$favicon_folder" -fi -mkdir -p "$favicon_folder" -cp -r ./deploy/tools/favicon-generator/output/* "$favicon_folder" \ No newline at end of file diff --git a/tools/scripts/og-image-generator.dev.sh b/tools/scripts/og-image-generator.dev.sh deleted file mode 100755 index 9c8dcd5e87a..00000000000 --- a/tools/scripts/og-image-generator.dev.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -# use this script for testing the og image generator - -# Fetch a representative instance config (eth) into ./.env.tmp -./tools/dev-server/fetch.sh eth || exit 1 - -dotenv \ - -e ./.env.tmp \ - -- bash -c 'node ./deploy/scripts/og_image_generator.js' diff --git a/tools/scripts/pw.docker.deps.sh b/tools/scripts/pw.docker.deps.sh deleted file mode 100755 index d3b485c470d..00000000000 --- a/tools/scripts/pw.docker.deps.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash - -# Install build tools required for native dependencies -apt-get update && apt-get install -y \ - build-essential \ - python3 \ - cmake \ - pkg-config \ - libssl-dev \ - && rm -rf /var/lib/apt/lists/* - -# Enable pnpm in the container (Playwright image has Node but not pnpm) -corepack enable -corepack prepare pnpm@11.5.1 --activate - -# Set environment variables to help with native compilation -export npm_config_build_from_source=false -export npm_config_prefer_offline=true - -# Non-interactive install in Docker (pnpm 11 may prompt to purge node_modules otherwise). -export CI=true -pnpm install --modules-dir node_modules_linux --store-dir /pnpm-store --config.confirm-modules-purge=true \ No newline at end of file diff --git a/tools/scripts/pw.docker.sh b/tools/scripts/pw.docker.sh deleted file mode 100755 index 7cff6143036..00000000000 --- a/tools/scripts/pw.docker.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -# Enable pnpm in the container (Playwright image has Node but not pnpm) -corepack enable -corepack prepare pnpm@11.5.1 --activate - -# test:pw:docker mounts node_modules_linux over node_modules in the container so -# Node resolves Linux-native optional deps (e.g. @rollup/rollup-linux-arm64-gnu). -if [ ! -f node_modules_linux/.modules.yaml ]; then - echo "Linux dependencies are missing. Install them with: pnpm test:pw:docker:deps" - exit 1 -fi - -export PNPM_CONFIG_VERIFY_DEPS_BEFORE_RUN=false - -pnpm test:pw "$@" diff --git a/tools/scripts/pw.sh b/tools/scripts/pw.sh deleted file mode 100755 index 99ab8365655..00000000000 --- a/tools/scripts/pw.sh +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash - -config_file="./playwright/.env.pw" - -rm -rf ./playwright/.cache - -dotenv \ - -e $config_file \ - -- bash -c './deploy/scripts/make_envs_script.sh ./playwright/envs.js' - -# Important to set this variable here, so the sprite will be built correctly -export NEXT_PUBLIC_APP_ENV=pw -pnpm svg:build-sprite - -# Check if the "--affected" argument is present in the script args -check_affected_flag() { - local affected_flag=false - - for arg in "$@"; do - if [[ "$arg" = "--affected"* ]]; then - # Extract the value after the equals sign - is_affected_value=${is_affected_arg#*=} - - if [ "$is_affected_value" != "false" ]; then - affected_flag=true - fi - - break - fi - done - - echo "$affected_flag" -} - -# Remove the "--affected" argument from the script args -filter_arguments() { - local args=() - - for arg in "$@"; do - if [[ "$arg" != "--affected"* ]]; then - args+=("$arg") - fi - done - - echo "${args[@]}" -} - -get_files_to_run() { - local is_affected=$1 - local files_to_run="" - - if [ "$is_affected" = true ]; then - affected_tests_file="./playwright/affected-tests.txt" - - if [ -f "$affected_tests_file" ]; then - file_content=$(<"$affected_tests_file") - files_to_run="${file_content//$'\n'/$' '}" - - if [ -z "$files_to_run" ]; then - exit 1 - fi - fi - fi - - echo "$files_to_run" -} - -args=$(filter_arguments "$@") -affected_flag=$(check_affected_flag "$@") -files_to_run=$(get_files_to_run "$affected_flag") -if [ $? -eq 1 ]; then - echo "No affected tests found in the file. Exiting..." - exit 0 -fi - -echo "Running Playwright tests with the following arguments: $args" -echo "Affected flag: $affected_flag" -echo "Files to run: $files_to_run" - -dotenv \ - -v NODE_OPTIONS=\"--max-old-space-size=8192\" \ - -e $config_file \ - -- playwright test -c playwright-ct.config.ts $files_to_run $args - diff --git a/tools/scripts/sitemap-generator.dev.sh b/tools/scripts/sitemap-generator.dev.sh deleted file mode 100755 index e51ce0e634b..00000000000 --- a/tools/scripts/sitemap-generator.dev.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash - -# Fetch a representative instance config (eth) into ./.env.tmp -./tools/dev-server/fetch.sh eth || exit 1 - -dotenv \ - -e ./.env.tmp \ - -- bash -c 'cd ./deploy/tools/sitemap-generator && pnpm next-sitemap' diff --git a/tsconfig.json b/tsconfig.json index dbc04cd2c37..f05fdb3450d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -32,6 +32,7 @@ "include": [ "next-types.d.ts", "**/*.ts", + "**/*.mts", "**/*.node.ts", "**/*.tsx", "**/*.pw.tsx", @@ -40,15 +41,14 @@ ], "exclude": [ "node_modules", - "node_modules_linux", + "**/node_modules_linux", // agent worktrees are full checkouts of the repo, with no dependencies installed of their own ".claude/worktrees", - "./deploy/tools/envs-validator", - "./deploy/tools/favicon-generator", - "./deploy/tools/multichain-config-generator", - "./deploy/tools/essential-dapps-chains-config-generator", - "./deploy/tools/llms-txt-generator", - "./deploy/tools/feature-reporter", + // Stryker's sandbox is a copy of the repo, and survives a run it did not finish + "tools/mutation-testing/.stryker-tmp", "./src/toolkit/package", + ".ds-sync", + ".design-sync", + "ds-bundle" ] } diff --git a/vitest.config.ts b/vitest.config.ts index fa56fc1c967..bc9dba4878d 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,5 +1,3 @@ -import tsconfigPaths from 'vite-tsconfig-paths'; - import { defineConfig } from 'vitest/config'; // the Next.js build turns .svg imports into React components via @svgr/webpack; @@ -16,16 +14,25 @@ const svgStub = { export default defineConfig({ plugins: [ - tsconfigPaths({ - ignoreConfigErrors: true, - }), svgStub, ], + resolve: { + tsconfigPaths: true, + }, test: { globalSetup: [ './vitest/global-setup.ts' ], setupFiles: [ './vitest/setup.ts' ], include: [ '**/*.spec.ts', '**/*.spec.tsx' ], - // agent worktrees are full checkouts of the repo; their specs would run a second time - exclude: [ '**/node_modules/**', '**/node_modules_linux/**', '.claude/worktrees/**' ], + // the design-readout calibration set is read with fs, not imported, so a `--changed` run would + // not see an edited entry; its spec is what keeps the committed set green + forceRerunTriggers: [ 'tools/design-readout/calibration/**' ], + // agent worktrees are full checkouts of the repo; their specs would run a second time. + // Stryker's sandbox is a copy of the repo too, and survives a run it did not finish. + exclude: [ + '**/node_modules/**', + '**/node_modules_linux/**', + '.claude/worktrees/**', + 'tools/mutation-testing/.stryker-tmp/**', + ], }, }); diff --git a/vitest/global-setup.ts b/vitest/global-setup.ts index c8b101bdc87..03f92027bb2 100644 --- a/vitest/global-setup.ts +++ b/vitest/global-setup.ts @@ -1,5 +1,5 @@ import dotenv from 'dotenv'; export async function setup() { - dotenv.config({ path: './vitest/.env.vitest' }); + dotenv.config({ path: './vitest/.env.vitest', quiet: true }); } diff --git a/vitest/lib.tsx b/vitest/lib.tsx index e7fd2269fc1..c5ffd817609 100644 --- a/vitest/lib.tsx +++ b/vitest/lib.tsx @@ -7,6 +7,8 @@ import { http } from 'viem'; import { WagmiProvider, createConfig, mock } from 'wagmi'; import { mainnet } from 'wagmi/chains'; +import type { Router, RouterContextValue } from 'src/toolkit/router/types'; + import { SocketProvider } from 'src/api/socket/context'; import { AppContextProvider } from 'src/shell/app/context'; @@ -17,7 +19,12 @@ import { CsvExportContextProvider } from 'src/features/csv-export/utils/context' import { MarketplaceContext } from 'src/features/marketplace/context'; import { RewardsContextProvider } from 'src/features/rewards/context'; +import { NextLink } from 'src/shared/router/NextRouterProvider'; + import { Provider as ChakraProvider } from 'src/toolkit/chakra/provider'; +import { RouterProvider } from 'src/toolkit/router/context'; + +import { buildRouterMock } from './utils/mockRouter'; import 'src/shared/i18n/set-locale'; @@ -52,11 +59,20 @@ const wagmiConfig = createConfig({ interface TestAppProps { children: React.ReactNode; socketUrl?: string; + router?: Partial<Router>; } +const toPathname = (asPath: string): string => new URL(asPath, 'http://localhost').pathname; + // The full app provider stack (mirrors playwright/TestApp.tsx; the wallet client stays inert, and // so does the socket unless `socketUrl` is given) — heavy enough to mount whole page slices in jsdom. -const TestApp = ({ children, socketUrl }: TestAppProps) => { +// The router is a frozen stand-in: `router` overrides the home-page default field by field. +const TestApp = ({ children, socketUrl, router }: TestAppProps) => { + const routerContext = React.useMemo((): RouterContextValue => { + const value = { ...buildRouterMock('/', '/'), ...router }; + return { Link: NextLink, router: value, pathname: toPathname(value.asPath) }; + }, [ router ]); + const [ queryClient ] = React.useState(() => new QueryClient({ defaultOptions: { queries: { @@ -67,27 +83,29 @@ const TestApp = ({ children, socketUrl }: TestAppProps) => { })); return ( - <ChakraProvider> - <QueryClientProvider client={ queryClient }> - <SocketProvider url={ socketUrl }> - <AppContextProvider pageProps={ PAGE_PROPS }> - <MarketplaceContext.Provider value={ marketplaceContext }> - <SettingsContextProvider> - <GrowthBookProvider> - <WagmiProvider config={ wagmiConfig }> - <RewardsContextProvider> - <CsvExportContextProvider> - { children } - </CsvExportContextProvider> - </RewardsContextProvider> - </WagmiProvider> - </GrowthBookProvider> - </SettingsContextProvider> - </MarketplaceContext.Provider> - </AppContextProvider> - </SocketProvider> - </QueryClientProvider> - </ChakraProvider> + <RouterProvider value={ routerContext }> + <ChakraProvider> + <QueryClientProvider client={ queryClient }> + <SocketProvider url={ socketUrl }> + <AppContextProvider pageProps={ PAGE_PROPS }> + <MarketplaceContext.Provider value={ marketplaceContext }> + <SettingsContextProvider> + <GrowthBookProvider> + <WagmiProvider config={ wagmiConfig }> + <RewardsContextProvider> + <CsvExportContextProvider> + { children } + </CsvExportContextProvider> + </RewardsContextProvider> + </WagmiProvider> + </GrowthBookProvider> + </SettingsContextProvider> + </MarketplaceContext.Provider> + </AppContextProvider> + </SocketProvider> + </QueryClientProvider> + </ChakraProvider> + </RouterProvider> ); }; diff --git a/vitest/setup.ts b/vitest/setup.ts index 5892916c3a6..bd326a19024 100644 --- a/vitest/setup.ts +++ b/vitest/setup.ts @@ -3,7 +3,7 @@ import dotenv from 'dotenv'; import { vi } from 'vitest'; import createFetchMock from 'vitest-fetch-mock'; -const envs = dotenv.config({ path: './vitest/.env.vitest' }); +const envs = dotenv.config({ path: './vitest/.env.vitest', quiet: true }); const fetchMocker = createFetchMock(vi); fetchMocker.enableMocks(); @@ -19,16 +19,6 @@ vi.mock('use-font-face-observer', () => ({ 'default': () => true, })); -// Default next/router so vitest/lib's TestApp. -vi.mock('next/router', async() => { - const { buildRouterMock } = await import('./utils/mockRouter'); - const router = buildRouterMock('/', '/'); - return { - useRouter: () => router, - 'default': router, - }; -}); - // browser APIs that jsdom does not implement but app components rely on if (typeof window !== 'undefined') { if (!window.matchMedia) { diff --git a/vitest/utils/checkPrimedRequests.tsx b/vitest/utils/checkPrimedRequests.tsx index 5bcae06e480..64bec601d93 100644 --- a/vitest/utils/checkPrimedRequests.tsx +++ b/vitest/utils/checkPrimedRequests.tsx @@ -8,7 +8,7 @@ import { expect, it, vi } from 'vitest'; import flushPromises from './flushPromises'; import withEnvs from './mockEnvs'; -import { mockNextRouter } from './mockRouter'; +import { buildRouterMock } from './mockRouter'; import { mockSocket, MOCK_SOCKET_URL } from './mockSocket'; // Drift check for the early-fetch primer (src/server/primedRequests): asserts that every @@ -56,9 +56,6 @@ export default function checkPrimedRequests(params: CheckPrimedRequestsParams) { try { await withEnvs(params.envs, async() => { - // register the router mock AFTER withEnvs' resetModules so the subsequent dynamic - // imports of Layout / page components pick it up (doMock before resetModules races) - mockNextRouter(params.page, params.url); // pages gate some queries on their socket channel joining; the mock joins right away so // those requests belong to the first render here, as they effectively do in a browser mockSocket(); @@ -90,7 +87,8 @@ export default function checkPrimedRequests(params: CheckPrimedRequestsParams) { params.loadComponent(), ]); - const { unmount } = render(<TestApp socketUrl={ MOCK_SOCKET_URL }><Component/></TestApp>); + const router = buildRouterMock(params.page, params.url); + const { unmount } = render(<TestApp socketUrl={ MOCK_SOCKET_URL } router={ router }><Component/></TestApp>); try { // let mount effects fire their queries and any second-wave queries subscribe @@ -123,7 +121,6 @@ export default function checkPrimedRequests(params: CheckPrimedRequestsParams) { } }); } finally { - vi.doUnmock('next/router'); vi.doUnmock('phoenix'); fetchMock.resetMocks(); window.__primedFetches = undefined; diff --git a/vitest/utils/mockJsonRpc.ts b/vitest/utils/mockJsonRpc.ts new file mode 100644 index 00000000000..ecf248b688c --- /dev/null +++ b/vitest/utils/mockJsonRpc.ts @@ -0,0 +1,73 @@ +/* global fetchMock -- provided by vitest-fetch-mock in vitest/setup.ts */ + +// Routes the global fetch mock between the REST API and the JSON-RPC node. +// +// viem's http transport posts `{ jsonrpc, id, method, params }` through the global `fetch`, so the same +// `vitest-fetch-mock` that serves API responses can answer RPC calls. Every RPC method not listed in +// `rpc` answers `null`, which viem turns into its *NotFound errors (transaction, receipt, block). +// +// mockApiAndRpc({ +// api: (url) => url.includes('/transactions/') ? { status: 404, body: '{"message":"Not found"}' } : undefined, +// rpc: { eth_getTransactionByHash: RPC_TX }, +// }); + +interface ApiResponse { + status?: number; + body: string; +} + +interface Params { + api: (url: string) => ApiResponse | Promise<ApiResponse> | undefined; + rpc?: Record<string, unknown>; +} + +const JSON_HEADERS = { 'Content-Type': 'application/json' }; + +function parseRpcMethod(body: unknown): string | undefined { + if (typeof body !== 'string') { + return; + } + + try { + const parsed = JSON.parse(body) as { jsonrpc?: string; method?: string }; + return parsed.jsonrpc ? parsed.method : undefined; + } catch { + return; + } +} + +export function mockApiAndRpc({ api, rpc = {} }: Params) { + fetchMock.mockResponse(async(request) => { + const text = request.method === 'POST' ? await request.text() : undefined; + const rpcMethod = parseRpcMethod(text); + + if (rpcMethod) { + const { id } = JSON.parse(text as string) as { id: number }; + return { + status: 200, + headers: JSON_HEADERS, + body: JSON.stringify({ jsonrpc: '2.0', id, result: rpc[rpcMethod] ?? null }), + }; + } + + const response = await api(request.url); + + if (!response) { + throw new Error(`Unexpected API request: ${ request.url }`); + } + + return { status: response.status ?? 200, headers: JSON_HEADERS, body: response.body }; + }); +} + +export function rpcRequests(): Array<string> { + return fetchMock.mock.calls + .map(([ , init ]) => parseRpcMethod(init?.body)) + .filter((method): method is string => Boolean(method)); +} + +export function apiRequests(): Array<string> { + return fetchMock.mock.calls + .filter(([ , init ]) => !parseRpcMethod(init?.body)) + .map(([ input ]) => input instanceof Request ? input.url : String(input)); +} diff --git a/vitest/utils/mockRouter.ts b/vitest/utils/mockRouter.ts index d3acca9c419..d538824017e 100644 --- a/vitest/utils/mockRouter.ts +++ b/vitest/utils/mockRouter.ts @@ -1,17 +1,28 @@ +import type { Router } from 'src/toolkit/router/types'; + import { vi } from 'vitest'; -// next/router mocking for Vitest. +// A frozen router value for Vitest, installed through the toolkit router provider. +// +// Default: `vitest/lib`'s TestApp mounts the provider with `buildRouterMock('/', '/')`, so a suite +// mounts without wiring the router. Suites that need a specific route/query pass the `router` prop +// (`<TestApp router={ buildRouterMock('/tx/[hash]', '/tx/0xabc') }>`), or a `Partial<Router>` with just +// the fields the component reads; the primed drift tests (checkPrimedRequests.tsx) do the former. // -// Default: vitest/setup.ts registers a home-page mock via `vi.mock` so TestApp mounts -// without each suite wiring the router. Suites that need a specific route/query should -// override with their own top-level `vi.mock('next/router', …)` (see useQueryWithPages.spec). +// The provider only reaches a component from the same module graph. `withEnvs` (mockEnvs.ts) calls +// `vi.resetModules()`, so a component imported inside its callback holds a fresh router context that a +// statically imported `render` / `wrapper` never feeds: the component sees the no-provider default +// (`pathname: ''`, no-op `push`). Import `vitest/lib` (or routerStandIn.ts) inside the callback too. // -// Primed drift tests: `mockNextRouter` uses `vi.doMock`, which applies only to modules -// imported AFTER the call — pair it with `resetModules` + dynamic imports -// (checkPrimedRequests.tsx), and clean up with `vi.doUnmock('next/router')`. -// `buildRouterMock` is the shared shape used by both paths. +// `query` never changes after a `push`/`replace` — the calls are `vi.fn` spies to assert on. A hook +// that must observe the URL it pushed uses the live stand-in in routerStandIn.ts instead. + +export interface RouterMock extends Router { + push: ReturnType<typeof vi.fn<Router['push']>>; + replace: ReturnType<typeof vi.fn<Router['replace']>>; +} -export function buildRouterMock(page: string, url: string) { +export function buildRouterMock(page: string, url: string): RouterMock { const { pathname, searchParams } = new URL(url, 'http://localhost'); const query: Record<string, string> = Object.fromEntries(searchParams.entries()); @@ -26,25 +37,8 @@ export function buildRouterMock(page: string, url: string) { return { query, pathname: page, - route: page, asPath: url, - basePath: '', - isReady: true, - push: vi.fn(() => Promise.resolve(true)), - replace: vi.fn(() => Promise.resolve(true)), - prefetch: vi.fn(() => Promise.resolve()), - back: vi.fn(), - events: { on: vi.fn(), off: vi.fn(), emit: vi.fn() }, + push: vi.fn<Router['push']>(() => Promise.resolve(true)), + replace: vi.fn<Router['replace']>(() => Promise.resolve(true)), }; } - -export function mockNextRouter(page: string, url: string) { - const router = buildRouterMock(page, url); - - vi.doMock('next/router', () => ({ - useRouter: () => router, - 'default': router, - })); - - return router; -} diff --git a/vitest/utils/mockSocket.ts b/vitest/utils/mockSocket.ts index 4332b2d9ce4..8309f19ff96 100644 --- a/vitest/utils/mockSocket.ts +++ b/vitest/utils/mockSocket.ts @@ -1,20 +1,13 @@ import { vi } from 'vitest'; -// Phoenix socket mocking for Vitest. -// -// Replaces the transport only — `SocketProvider`, `useSocketChannel` and `useSocketMessage` stay -// real. Channels join successfully, so the queries a page enables from an `onJoin` callback run -// here the way they do in a browser. Server-sent events are not simulated: subscriptions made via -// `channel.on` are accepted and never fire. -// -// Uses `vi.doMock`, which applies only to modules imported AFTER the call — pair it with -// `resetModules` + dynamic imports (checkPrimedRequests.tsx), and clean up with -// `vi.doUnmock('phoenix')`. Mounting under `vitest/lib`'s TestApp additionally requires passing -// `socketUrl={ MOCK_SOCKET_URL }`, since the provider skips socket creation without a url. - /** any non-empty url works — the mocked socket never opens a connection */ export const MOCK_SOCKET_URL = 'wss://localhost/socket'; +type MessageHandler = (payload: unknown) => void; +type ChannelSubscriptions = Map<string, Map<number, MessageHandler>>; + +const subscriptionsByTopic = new Map<string, ChannelSubscriptions>(); + interface MockPush { receive: (status: string, callback: (response: unknown) => void) => MockPush; } @@ -34,31 +27,66 @@ function createMockPush(): MockPush { return push; } -function createMockChannel() { +interface MockChannel { + join: () => MockPush; + leave: () => MockPush; + push: () => MockPush; + on: (event: string, handler: MessageHandler) => number; + off: (event: string, ref: number) => void; +} + +function createMockChannel(topic: string): MockChannel { let nextHandlerRef = 0; + const subscriptions: ChannelSubscriptions = new Map(); + subscriptionsByTopic.set(topic, subscriptions); return { join: createMockPush, - leave: createMockPush, + leave: () => { + subscriptionsByTopic.delete(topic); + return createMockPush(); + }, push: createMockPush, - on: () => nextHandlerRef++, - off: () => {}, + on: (event: string, handler: MessageHandler) => { + const ref = nextHandlerRef++; + const handlers = subscriptions.get(event) ?? new Map<number, MessageHandler>(); + handlers.set(ref, handler); + subscriptions.set(event, handlers); + return ref; + }, + off: (event: string, ref: number) => { + subscriptions.get(event)?.delete(ref); + }, }; } +let nextListenerRef = 0; +const createListenerRef = () => String(nextListenerRef++); + +class MockSocketClass { + connect() {} + disconnect() {} + onOpen = createListenerRef; + onClose = createListenerRef; + onError = createListenerRef; + off() {} + channel = createMockChannel; +} + +export const phoenixModule = { Socket: MockSocketClass }; + export function mockSocket() { - let nextListenerRef = 0; - const createListenerRef = () => String(nextListenerRef++); - - class MockSocketClass { - connect() {} - disconnect() {} - onOpen = createListenerRef; - onClose = createListenerRef; - onError = createListenerRef; - off() {} - channel = createMockChannel; + vi.doMock('phoenix', () => phoenixModule); +} + +// throws on a topic or event nobody listens to, so a test cannot pass on a message that went nowhere; +// the handlers update React state, so wrap the call in `act` +export function sendSocketMessage(topic: string, event: string, payload: unknown): void { + const handlers = [ ...(subscriptionsByTopic.get(topic)?.get(event)?.values() ?? []) ]; + + if (handlers.length === 0) { + throw new Error(`No socket subscription for "${ event }" on "${ topic }"`); } - vi.doMock('phoenix', () => ({ Socket: MockSocketClass })); + handlers.forEach((handler) => handler(payload)); } diff --git a/vitest/utils/routerStandIn.spec.ts b/vitest/utils/routerStandIn.spec.ts new file mode 100644 index 00000000000..6d8c569adce --- /dev/null +++ b/vitest/utils/routerStandIn.spec.ts @@ -0,0 +1,141 @@ +// @vitest-environment jsdom + +import { useRouter } from 'src/shared/router/useRouter'; + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { renderHook, act, cleanup } from 'vitest/lib'; + +import { routerStandIn } from './routerStandIn'; + +beforeEach(() => { + routerStandIn.reset({ pathname: '/blocks', query: { tab: 'txs' } }); +}); + +afterEach(cleanup); + +function renderRouterConsumer() { + let renderCount = 0; + const hook = renderHook(() => { + renderCount++; + return useRouter(); + }, { wrapper: routerStandIn.wrapper }); + return { ...hook, getRenderCount: () => renderCount }; +} + +it('installs through the router provider and exposes the reset location', () => { + const { result } = renderRouterConsumer(); + + expect(result.current.pathname).toBe('/blocks'); + expect(result.current.query).toEqual({ tab: 'txs' }); + expect(result.current.asPath).toBe('/blocks?tab=txs'); +}); + +describe('push', () => { + it('replaces the query, re-renders consumers and resolves', async() => { + const { result, getRenderCount } = renderRouterConsumer(); + + let resolved: boolean | undefined; + await act(async() => { + resolved = await result.current.push({ pathname: '/blocks', query: { page: '2' } }, { shallow: true }); + }); + + expect(resolved).toBe(true); + expect(getRenderCount()).toBe(2); + expect(result.current.query).toEqual({ page: '2' }); + expect(routerStandIn.query).toEqual({ page: '2' }); + expect(routerStandIn.push).toHaveBeenCalledTimes(1); + }); + + it('resolves only after consumers have rendered the new location', async() => { + const { result } = renderRouterConsumer(); + let queryWhenResolved: unknown; + + await act(async() => { + await result.current.push({ pathname: '/blocks', query: { page: '3' } }); + queryWhenResolved = result.current.query; + }); + + expect(queryWhenResolved).toEqual({ page: '3' }); + }); + + it('accepts a string url and keeps the pathname when the url object omits it', async() => { + const { result } = renderRouterConsumer(); + + await act(async() => { + await routerStandIn.push('/txs?filter=from&sort=val-desc'); + }); + expect(result.current.pathname).toBe('/txs'); + expect(result.current.query).toEqual({ filter: 'from', sort: 'val-desc' }); + + await act(async() => { + await routerStandIn.push({ query: { page: 2, items: [ 'a', 'b' ], skipped: undefined } }); + }); + expect(result.current.pathname).toBe('/txs'); + expect(result.current.query).toEqual({ page: '2', items: [ 'a', 'b' ] }); + }); + + it('resolves even when nothing renders useRouter', async() => { + await expect(routerStandIn.push({ pathname: '/', query: {} })).resolves.toBe(true); + expect(routerStandIn.query).toEqual({}); + }); +}); + +describe('setQuery', () => { + it('re-renders consumers without counting as a push', () => { + const { result, getRenderCount } = renderRouterConsumer(); + + act(() => { + routerStandIn.setQuery({ tab: 'internal_txs' }); + }); + + expect(getRenderCount()).toBe(2); + expect(result.current.query).toEqual({ tab: 'internal_txs' }); + expect(routerStandIn.push).not.toHaveBeenCalled(); + }); +}); + +describe('router identity', () => { + it('is stable across unrelated re-renders and changes on navigation', async() => { + const { result, rerender } = renderRouterConsumer(); + const initial = result.current; + + rerender(); + expect(result.current).toBe(initial); + expect(result.current.query).toBe(initial.query); + + await act(async() => { + await result.current.push({ pathname: '/blocks', query: { page: '2' } }); + }); + expect(result.current).not.toBe(initial); + }); +}); + +describe('reset', () => { + it('clears push history and re-renders consumers with the new location', async() => { + const { result } = renderRouterConsumer(); + await act(async() => { + await result.current.push({ pathname: '/blocks', query: { page: '2' } }); + }); + + act(() => { + routerStandIn.reset(); + }); + + expect(routerStandIn.push).not.toHaveBeenCalled(); + expect(result.current.pathname).toBe('/'); + expect(result.current.query).toEqual({}); + }); +}); + +it('re-renders every mounted consumer', async() => { + const first = renderRouterConsumer(); + const second = renderRouterConsumer(); + + await act(async() => { + await first.result.current.push({ pathname: '/blocks', query: { page: '5' } }); + }); + + expect(first.getRenderCount()).toBe(2); + expect(second.getRenderCount()).toBe(2); + expect(second.result.current.query).toEqual({ page: '5' }); +}); diff --git a/vitest/utils/routerStandIn.ts b/vitest/utils/routerStandIn.ts new file mode 100644 index 00000000000..22db6defbc4 --- /dev/null +++ b/vitest/utils/routerStandIn.ts @@ -0,0 +1,182 @@ +import React from 'react'; + +import type { Router, RouterContextValue } from 'src/toolkit/router/types'; + +import { RouterProvider } from 'src/toolkit/router/context'; +import { DefaultLink } from 'src/toolkit/router/defaults'; + +import { vi } from 'vitest'; +import { wrapper as TestApp } from 'vitest/lib'; + +// A live router stand-in for Vitest, installed through the toolkit router provider. +// +// `buildRouterMock` (mockRouter.ts) freezes `query`, so a hook under test never sees the URL it +// pushed. This one holds `pathname` and `query` in a store: every `useRouter` consumer re-renders +// on `push`/`replace`/`setQuery`, and `push` resolves only after that render has committed — the +// same ordering the real pages router gives `.then` callbacks — so a spec can count requests and +// renders per user action, not just check the final state. +// +// Install from the spec with the `wrapper`; it is the innermost provider, so it wins over the frozen +// `buildRouterMock` value that `vitest/lib`'s TestApp mounts when the two are nested: +// +// import { routerStandIn } from 'vitest/utils/routerStandIn'; +// +// beforeEach(() => routerStandIn.reset({ pathname: '/blocks', query: {} })); +// afterEach(cleanup); // RTL does not auto-unmount without vitest globals; stale consumers would re-render on reset +// renderHook(() => useMyHook(), { wrapper: routerStandIn.wrapper }); +// renderHook(() => useMyQuery(), { wrapper: routerStandIn.appWrapper }); // inside the TestApp stack +// render(<RouterStandInProvider><MyPage/></RouterStandInProvider>); // inside vitest/lib's render() +// act(() => routerStandIn.setQuery({ tab: 'txs' })); // external URL change (tab switch, back button) +// expect(routerStandIn.query).toEqual({ page: '2' }); + +type Query = Router['query']; + +interface RouterLocation { + readonly pathname: string; + readonly query: Query; +} + +interface RouterSnapshot extends RouterLocation { + readonly version: number; +} + +interface PendingTransition { + readonly version: number; + readonly resolve: (value: boolean) => void; +} + +type UrlInput = string | { readonly pathname?: string; readonly query?: Record<string, unknown> | null }; + +const INITIAL_LOCATION: RouterLocation = { pathname: '/', query: {} }; + +let snapshot: RouterSnapshot = { ...INITIAL_LOCATION, version: 0 }; +const listeners = new Set<() => void>(); +const pendingTransitions: Array<PendingTransition> = []; + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +function getSnapshot(): RouterSnapshot { + return snapshot; +} + +function commit(location: RouterLocation): number { + snapshot = { ...location, version: snapshot.version + 1 }; + listeners.forEach((listener) => listener()); + return snapshot.version; +} + +function settle(renderedVersion: number): void { + for (let index = pendingTransitions.length - 1; index >= 0; index--) { + const transition = pendingTransitions[index]; + if (transition.version <= renderedVersion) { + pendingTransitions.splice(index, 1); + transition.resolve(true); + } + } +} + +function normalizeQuery(query: Record<string, unknown> | null | undefined): Query { + const result: Record<string, string | Array<string>> = {}; + for (const [ key, value ] of Object.entries(query ?? {})) { + if (value === undefined || value === null) { + continue; + } + result[key] = Array.isArray(value) ? value.map(String) : String(value); + } + return result; +} + +function toLocation(url: UrlInput): RouterLocation { + if (typeof url === 'string') { + const { pathname, searchParams } = new URL(url, 'http://localhost'); + return { pathname, query: Object.fromEntries(searchParams.entries()) }; + } + + return { + pathname: url.pathname ?? snapshot.pathname, + query: normalizeQuery(url.query), + }; +} + +function transition(url: UrlInput): Promise<boolean> { + const version = commit(toLocation(url)); + return new Promise<boolean>((resolve) => { + pendingTransitions.push({ version, resolve }); + // nobody rendering `useRouter` means nobody settles the transition; a real router resolves anyway + setTimeout(() => settle(version)); + }); +} + +function toAsPath({ pathname, query }: RouterLocation): string { + const searchParams = new URLSearchParams(); + for (const [ key, value ] of Object.entries(query)) { + (Array.isArray(value) ? value : [ value ]).forEach((item) => item !== undefined && searchParams.append(key, item)); + } + const search = searchParams.toString(); + return search ? `${ pathname }?${ search }` : pathname; +} + +const push = vi.fn((url: UrlInput) => transition(url)); +const replace = vi.fn((url: UrlInput) => transition(url)); + +function useRouter(): Router { + const current = React.useSyncExternalStore(subscribe, getSnapshot, getSnapshot); + + React.useLayoutEffect(() => { + settle(current.version); + }, [ current ]); + + return React.useMemo(() => ({ + pathname: current.pathname, + query: current.query, + asPath: toAsPath(current), + push, + replace, + }), [ current ]); +} + +export function RouterStandInProvider({ children }: { children: React.ReactNode }) { + const router = useRouter(); + const value = React.useMemo((): RouterContextValue => ({ + Link: DefaultLink, + router, + pathname: new URL(router.asPath, 'http://localhost').pathname, + }), [ router ]); + + return React.createElement(RouterProvider, { value, children }); +} + +function RouterStandInAppProvider({ children }: { children: React.ReactNode }) { + return React.createElement(TestApp, { children: React.createElement(RouterStandInProvider, { children }) }); +} + +export const routerStandIn = { + get pathname(): string { + return snapshot.pathname; + }, + get query(): Query { + return snapshot.query; + }, + push, + replace, + setQuery(query: Query): void { + commit({ pathname: snapshot.pathname, query }); + }, + setPathname(pathname: string): void { + commit({ pathname, query: snapshot.query }); + }, + reset(location: Partial<RouterLocation> = {}): void { + push.mockClear(); + replace.mockClear(); + pendingTransitions.length = 0; + commit({ ...INITIAL_LOCATION, ...location }); + }, + useRouter, + wrapper: RouterStandInProvider, + appWrapper: RouterStandInAppProvider, +};